Compare commits

..

160 Commits

Author SHA1 Message Date
Jiaxin Peng
e9355aaf92 docs: enhance auto sync documentation with frontmatter key configuration and examples 2025-11-06 16:50:50 +00:00
Jiaxin Peng
943ec6af6d Merge pull request #68 from jxpeng98/autosync-filter
Autosync filter
2025-11-06 16:44:58 +00:00
Jiaxin Peng
bb4b75c82e feat: add auto sync frontmatter key configuration and update related messages 2025-11-06 16:43:24 +00:00
Jiaxin Peng
ae4488546c feat: add auto sync database list handling and notifications for missing entries 2025-11-06 16:27:24 +00:00
Jiaxin Peng
7661bc94c7 fix: update changelog to reflect version v2.8.0-beta.1 release 2025-11-01 00:44:35 +00:00
Jiaxin Peng
e8a9594ea1 fix: refine tag patterns for release triggers in workflow 2025-11-01 00:42:01 +00:00
Jiaxin Peng
bb211543f5 fix: remove branch trigger for prerelease workflow 2025-11-01 00:38:25 +00:00
Jiaxin Peng
c52f84232d Merge pull request #67 from jxpeng98/automate-sync
Automate sync
2025-11-01 00:35:52 +00:00
Jiaxin Peng
3730b7645a chore: update changelog with detailed auto sync feature description and improvements 2025-11-01 00:34:23 +00:00
Jiaxin Peng
e2a965e3d6 fix: update autoSyncTimeout type and ensure window context for setTimeout calls 2025-11-01 00:32:35 +00:00
Jiaxin Peng
2738498dc2 fix: clean up formatting in auto sync logic for better readability 2025-11-01 00:30:39 +00:00
Jiaxin Peng
6df5e21f3d feat: implement enhanced frontmatter change detection and caching for auto sync 2025-11-01 00:30:09 +00:00
Jiaxin Peng
d660a088e3 feat: add GitHub Actions workflow for prerelease builds and asset uploads 2025-10-31 23:44:53 +00:00
Jiaxin Peng
83d4f1e48c feat: enhance auto sync functionality to support multiple databases and improved user notifications 2025-10-31 23:36:57 +00:00
Jiaxin Peng
7c841f3db3 feat: update UI text to use internationalization configuration for modals and notices 2025-10-31 23:36:49 +00:00
Jiaxin Peng
fab3acdc21 feat: add auto sync messages and database management labels in English, Japanese, and Chinese locales 2025-10-31 23:35:28 +00:00
Jiaxin Peng
59fa32b5e5 docs: enhance auto sync documentation with detailed setup, scenarios, and troubleshooting guidance 2025-10-31 23:35:16 +00:00
Jiaxin Peng
e5f906bba2 feat: migrate settings for auto sync feature and add user notification 2025-10-31 21:57:21 +00:00
Jiaxin Peng
c369c291a7 feat: add auto sync functionality with configurable delay in settings 2025-10-31 21:42:48 +00:00
Jiaxin Peng
33f0848b32 docs: add changelog and roadmap links to English and Chinese index files 2025-10-31 21:21:50 +00:00
Jiaxin Peng
a33e63a219 docs: add changelog and roadmap files in English and Chinese 2025-10-31 17:00:26 +00:00
Jiaxin Peng
99a40375f5 docs: update documentation website link in README files 2025-10-31 14:27:39 +00:00
Jiaxin Peng
7282fc6955 chore: Switch to pnpm and create individual package for docs 2025-10-31 13:46:31 +00:00
Jiaxin Peng
770061e826 chore: remove unused image files from documentation 2025-10-31 11:14:43 +00:00
Jiaxin Peng
de7b7dd28d Merge pull request #65 from jxpeng98/docs
add doc website
2025-10-31 11:03:19 +00:00
Jiaxin Peng
1c6c3fb0d9 chore: add vitepress package 2025-10-31 10:57:37 +00:00
Jiaxin Peng
ca0935bfe8 docs: update README to reflect new features and improved database support 2025-10-31 10:56:47 +00:00
Jiaxin Peng
e944721415 docs: add documentation for Obsidian to NotionNext plugin setup and usage 2025-10-31 10:47:34 +00:00
Jiaxin Peng
db66ef137c Update version to 2.7.0 2025-10-27 23:21:30 +00:00
Jiaxin Peng
a152201510 Merge pull request #64 from jxpeng98/callout-support
feat: callout support
2025-10-27 23:20:27 +00:00
Jiaxin Peng
abb699fe4d docs: add support for converting Obsidian callouts to Notion callout blocks 2025-10-27 23:17:55 +00:00
Jiaxin Peng
cf6c80df0f update yarn.lock 2025-10-27 23:14:43 +00:00
Jiaxin Peng
cf884de554 refactor: remove redundant debug logs from upload commands and base class 2025-10-27 23:12:25 +00:00
Jiaxin Peng
8eb4694342 refactor: removing redundant debug logs 2025-10-27 22:57:28 +00:00
Jiaxin Peng
6c0f6cea30 feat: enhance logging and error handling in upload commands and base class 2025-10-27 22:34:46 +00:00
Jiaxin Peng
8af4816f87 chore: update martian dependency version to 1.3.1 2025-10-27 20:44:23 +00:00
Jiaxin Peng
f6d24daa52 chore: bump martian dependency version to 1.3.0 2025-10-27 13:40:42 +00:00
Jiaxin Peng
da72846903 Update version to 2.6.0 2025-10-06 23:25:29 +01:00
Jiaxin Peng
8e08c4325d Update version to 2.6.0 2025-10-06 23:22:00 +01:00
Jiaxin Peng
ebb7a290e8 Merge pull request #61 from jxpeng98/unify-upload-functions
unify three databases with single upload file
2025-10-06 23:19:55 +01:00
Jiaxin Peng
24e68fc798 unify three databases with single upload file 2025-10-06 23:18:01 +01:00
Jiaxin Peng
78d2a29c8a Update README.md img links 2025-07-20 12:19:10 +01:00
Jiaxin Peng
1156bd3809 Merge pull request #58 from jxpeng98/notion-relation
update img links
2025-07-20 12:17:56 +01:00
Jiaxin Peng
b46e24f1ed update img links 2025-07-20 12:16:10 +01:00
Jiaxin Peng
a950e2e301 Update version to 2.5.0 2024-11-20 22:19:38 +00:00
Jiaxin Peng
aac7bc154a feat: consistent sync function (requestUrl) for desktop and mobile 2024-11-20 22:19:03 +00:00
Jiaxin Peng
a573ef728d chore: remove node-fetch and change the platform back to browser. 2024-11-20 22:17:49 +00:00
Jiaxin Peng
1344c14933 Update version to 2.4.3 2024-10-22 10:29:09 +01:00
Jiaxin Peng
c1f4ecd14b Update version to 2.4.3 2024-10-22 10:27:49 +01:00
Jiaxin Peng
5942876c92 fix: cannot parse title from front matter 2024-10-22 10:27:33 +01:00
Jiaxin Peng
3218eb9fba Update version to 2.4.2 2024-09-19 13:50:51 +01:00
Jiaxin Peng
48566eca20 Merge pull request #37 from jxpeng98/pluggin-does-not-appear-on-mac
fix: obsidian language not set in English, Chinese and Japanese
2024-09-19 13:49:08 +01:00
Jiaxin Peng
8bd8346423 fix: obsidian language not set in English, Chinese and Japanese 2024-09-19 13:47:57 +01:00
Jiaxin Peng
00411e9599 Merge pull request #35 from jxpeng98/mobile-fail-to-start
feat: separate mobile sync from desktop version
2024-09-03 12:19:23 +01:00
Jiaxin Peng
296125f6b4 chore: remove process from dependencies 2024-09-03 12:15:36 +01:00
Jiaxin Peng
1b385ccd0a solve: the fail to load of mobile caused by the node version 2024-09-01 23:26:22 +01:00
Jiaxin Peng
a90e4871bb Backup mobile requesturl after version 2.4.1 2024-09-01 22:57:03 +01:00
Jiaxin Peng
885ccba027 fix: test the desktop function for next and general 2024-08-31 23:43:19 +01:00
Jiaxin Peng
f282dde1b7 fix: test the desktop function of custom database
with platform function
2024-08-31 00:00:09 +01:00
Jiaxin Peng
bc166d8db1 Update version to 2.4.1 2024-08-28 20:31:28 +01:00
Jiaxin Peng
7612637951 Merge pull request #34 from jxpeng98/code-highlight-issue
fix code highlight issue
2024-08-28 20:30:49 +01:00
Jiaxin Peng
e8b1617916 fix item type error for iteration 2024-08-28 20:30:05 +01:00
Jiaxin Peng
fd29ed820e fix code highlight issue 2024-08-28 20:26:06 +01:00
Jiaxin Peng
1f58670906 Update version to 2.4.0 2024-08-19 11:24:23 +01:00
Jiaxin Peng
fc47d36e8d Merge pull request #32 from jxpeng98/long-notes-support
Long notes support
2024-08-18 22:39:00 +01:00
Jiaxin Peng
cd4e610c46 modify type of pageProperties 2024-08-18 18:42:59 +01:00
Jiaxin Peng
b05c248c44 feat: support long notes syncing 2024-08-18 17:16:08 +01:00
Jiaxin Peng
800e218dee Update version to 2.3.5 2024-08-18 13:08:04 +01:00
Jiaxin Peng
3b774552af update martian 2024-08-18 13:07:52 +01:00
b8a02c49f1 Update version to 2.3.4 2024-07-28 01:13:39 +01:00
Jiaxin Peng
046a67f22c Merge pull request #29 from jxpeng98/debug-general
General: use node-fetch to post notes
2024-07-28 01:08:08 +01:00
426f05dfbd General: use node-fetch to post notes 2024-07-28 01:07:35 +01:00
Jiaxin Peng
0addaa0d7f Merge pull request #28 from jxpeng98/debug-next
Next: use node-fetch to post notes for a better debug
2024-07-28 00:54:05 +01:00
1d5792c966 Next: use node-fetch to post notes for a better debug 2024-07-28 00:52:27 +01:00
Jiaxin Peng
193d3f6f87 Merge pull request #27 from jxpeng98/better-debug
custom: node-fetch replaces requestUrl
2024-07-27 23:37:27 +01:00
e9c2b4aada Custom: use node-fetch to post notes rather than requestUrl for better debug 2024-07-27 23:36:00 +01:00
b5ac42e6e3 use node-fetch to post notes for a better debug 2024-07-27 22:28:21 +01:00
60d002677b use json to parse the error information 2024-07-27 21:38:09 +01:00
3c3ec6881e Update version to 2.3.3 2024-07-15 14:19:11 +01:00
Jiaxin Peng
a80155fafc Merge pull request #26 from jxpeng98/notice-info
change the success notice colour
2024-07-15 14:17:01 +01:00
3a814b8390 feat: change the success notice colour 2024-07-15 14:15:10 +01:00
bb522db9a2 fix: readme gif link update 2024-07-15 14:13:09 +01:00
201f72ae0e update notice 2024-07-14 23:57:01 +01:00
be6f192dd8 Update readme file 2024-07-14 21:51:53 +01:00
4ce1019094 Update Readme links 2024-07-14 20:27:02 +01:00
095c608511 update readme with new instruction 2024-07-14 17:58:21 +01:00
2d8d7fb11a Update version to 2.3.2 2024-07-14 17:52:59 +01:00
36725cb699 fix: Text property in custom database 2024-07-14 17:52:43 +01:00
Jiaxin Peng
654e7e854d 更新 README.md 2024-07-10 00:32:00 +01:00
Jiaxin Peng
fa67f08512 Update version to 2.3.1 2024-07-05 09:50:31 +01:00
Jiaxin Peng
7e42ef49a7 Merge pull request #24 from jxpeng98/notion-link
feat: add notion link display
2024-07-05 09:49:27 +01:00
Jiaxin Peng
5a95aa0acc feat: add notion link display 2024-07-05 09:48:35 +01:00
Jiaxin Peng
ded01ce678 Update version to 2.3.0 2024-07-04 20:57:35 +01:00
Jiaxin Peng
3535d9fc70 Merge pull request #23 from jxpeng98/edit-modal
edit modal update for customised database
2024-07-04 20:55:41 +01:00
Jiaxin Peng
9c93e38aff reformat code and update readme file 2024-07-04 20:51:07 +01:00
Jiaxin Peng
bfde5dfe1a finish the edit modal 2024-07-04 20:28:28 +01:00
Jiaxin Peng
d8eb3c8984 feat: cancel function works well 2024-07-04 18:12:31 +01:00
Jiaxin Peng
1cee2b67a6 update edit modal with better display setting. 2024-07-04 17:06:23 +01:00
Jiaxin Peng
82529ce56a back up for edit modal 2024-07-04 10:00:46 +01:00
Jiaxin Peng
70f30f0713 Add support for notion link display in the front matter. 2024-07-03 22:35:47 +01:00
Jiaxin Peng
24ebb0bf8a Back up edit modal 2024-07-03 22:01:46 +01:00
Jiaxin Peng
d7372c7c55 Improve preview function for customised database 2024-07-03 16:05:24 +01:00
Jiaxin Peng
f7bcf71020 create retrieve function to get all created properties for customised database 2024-07-03 14:26:02 +01:00
Jiaxin Peng
72146afe48 update settingModal.ts refactor the customise database and improve the creating logic 2024-07-03 13:39:56 +01:00
Jiaxin Peng
9bcdb42edb settingmodal save mapping for reference 2024-07-03 11:06:54 +01:00
Jiaxin Peng
16e0827991 update the basic function of edit modal 2024-07-03 08:47:33 +01:00
Jiaxin Peng
863a6fb0dc more clear logic customised database setting code 2024-07-02 23:56:35 +01:00
Jiaxin Peng
5799ffe79b Update custom function and adjust the custom interface ui 2024-07-02 23:48:37 +01:00
Jiaxin Peng
a8ebab7fcb change tags titleicon and summary to optional function in next database 2024-03-17 14:36:55 +00:00
Jiaxin Peng
e0ec27ad07 update readme 2024-03-12 22:04:34 +00:00
Jiaxin Peng
85220105b0 update README 2024-03-08 15:23:17 +00:00
Jiaxin Peng
9afdb24a82 typo 2024-02-26 11:57:28 +00:00
Jiaxin Peng
3c7ab13995 update readme 2024-02-26 11:53:02 +00:00
Jiaxin Peng
31b72f3bd3 Update version to 2.2.4 2024-02-19 23:08:47 +00:00
Jiaxin Peng
ee5aada1b9 Update version to 2.2.3 2024-02-19 20:51:47 +00:00
Jiaxin Peng
9e15044f6a Update version to 2.2.2 2024-02-16 23:10:22 +00:00
Jiaxin Peng
9d891dae55 Update version to 2.2.1 2024-01-29 20:43:14 +00:00
Jiaxin Peng
bc665253ec Update version to 2.2.0 2024-01-29 19:03:09 +00:00
Jiaxin Peng
125c75f7c0 Merge pull request #13 from jxpeng98/custom
add the customisation function
2024-01-29 19:01:37 +00:00
Jiaxin Peng
8248640b5f fix the extra argument in the uploadcommand 2024-01-29 11:55:52 +00:00
Jiaxin Peng
0198898086 update the readme and changelog 2024-01-29 11:53:18 +00:00
Jiaxin Peng
8c6aea8250 Complete the basic function of customisation 2024-01-29 11:12:07 +00:00
Jiaxin Peng
a179d3da52 almost finish the structure 2024-01-29 00:55:06 +00:00
Jiaxin Peng
569d8eb699 fix the error of the display of title custom button 2024-01-28 00:26:58 +00:00
Jiaxin Peng
2a58dd3258 complete the custom ui design 2024-01-28 00:11:11 +00:00
Jiaxin Peng
8c65e471eb Update version to 2.1.2 2024-01-09 11:44:40 +00:00
Jiaxin Peng
388693d5b4 Update version to 2.1.1 2024-01-09 11:38:03 +00:00
Jiaxin Peng
dda6710fe9 remove redundant settingtabs 2024-01-09 11:37:47 +00:00
Jiaxin Peng
76ea9a4aee Update version to 2.1.0 2024-01-09 11:34:11 +00:00
Jiaxin Peng
856f83e8a1 Add confirmation delete button and modify edit modal interface. 2024-01-09 11:33:39 +00:00
Jiaxin Peng
f670dd972a Update version to 2.0.1 2024-01-03 00:37:47 +00:00
Jiaxin Peng
e6de2d036a add preview and edit function 2024-01-03 00:37:34 +00:00
Jiaxin Peng
dd131f5df1 readme update 2023-12-29 00:41:02 +00:00
Jiaxin Peng
a9fb81fc1b readme error 2023-12-29 00:39:18 +00:00
Jiaxin Peng
4f21e3ff91 Update version to 2.0.0 2023-12-29 00:36:48 +00:00
Jiaxin Peng
4abbbecd37 modify the notionapi variable 2023-12-29 00:36:29 +00:00
Jiaxin Peng
35746f1c51 Merge pull request #12 from jxpeng98/add-button
rebuild the plugin and add new button for multi database support
2023-12-29 00:26:16 +00:00
Jiaxin Peng
9ac64268fc Merge branch 'master' into add-button 2023-12-29 00:26:02 +00:00
Jiaxin Peng
3123d91e97 complete the new version for add button 2023-12-29 00:21:21 +00:00
Jiaxin Peng
cf08703fea complete the basic notionnext function 2023-12-28 00:55:06 +00:00
Jiaxin Peng
fb463ceaae modify language map 2023-12-27 00:48:39 +00:00
Jiaxin Peng
306573d81e merge 1.1.2 2023-12-27 00:37:54 +00:00
Jiaxin Peng
fb5f7b502d finish some command coding 2023-12-27 00:27:32 +00:00
Jiaxin Peng
59c15f1206 modify setting modal 2023-12-26 21:19:24 +00:00
Jiaxin Peng
370444fb94 basic display of modal 2023-12-26 09:03:29 +00:00
Jiaxin Peng
11aaf14c0b update general tabs 2023-12-25 22:47:24 +00:00
Jiaxin Peng
f3fb251cf7 set the class next tabs 2023-12-25 22:43:11 +00:00
Jiaxin Peng
913fa4dd03 Update version to 1.1.2 2023-12-06 15:22:53 +00:00
Jiaxin Peng
f638310f31 modify workflow 2023-12-06 15:22:09 +00:00
Jiaxin Peng
c2421f7a84 add the property 'status' for NotionNext 2023-12-06 15:19:57 +00:00
Jiaxin Peng
6c30d0c2b4 adjust the limitation of blocks 2023-12-06 14:40:15 +00:00
Jiaxin Peng
ccb5a20abe add custom frontmatter 2023-11-23 22:11:04 +00:00
Jiaxin Peng
630e3a20c2 Update version to 1.1.1 2023-11-23 11:54:50 +00:00
Jiaxin Peng
040b72b760 Update version to 1.1.0 2023-11-20 22:01:20 +00:00
Jiaxin Peng
7df4b5e9c8 Merge pull request #9 from jxpeng98/package-test
package update and add tag syncing button
2023-11-20 21:59:53 +00:00
Jiaxin Peng
3f35a56b6e rebuild the locale file and add tag button to control tag syncing function 2023-11-20 21:57:30 +00:00
Jiaxin Peng
3c7e266a35 setting tab bug fix 2023-11-20 17:07:04 +00:00
Jiaxin Peng
8201c706ea remove block limit and update packages 2023-11-16 21:09:31 +00:00
Jiaxin Peng
4433ea449d Update version to 1.0.1 2023-11-16 13:55:14 +00:00
Jiaxin Peng
96126d1334 Jump to version 1.0.0 2023-11-16 13:32:07 +00:00
72 changed files with 8781 additions and 3251 deletions

111
.github/workflows/prerelease.yml vendored Normal file
View File

@@ -0,0 +1,111 @@
name: Prerelease
on:
push:
tags:
- "*-beta*"
- "*-rc*"
- "*-alpha*"
- "*-test*"
env:
PLUGIN_NAME: share-to-notionnext
CHANGELOG_FILENAME: CHANGELOG.md
jobs:
build:
name: prerelease
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- name: Build
id: build
run: |
npm install
npm run build
mkdir ${{ env.PLUGIN_NAME }}
cp main.js manifest.json ${{ env.PLUGIN_NAME }}
zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }}
ls
echo "tag_name=$(git tag --sort version:refname | tail -n 1)" >> $GITHUB_OUTPUT
- name: Create Prerelease
id: create_prerelease
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
VERSION: ${{ github.ref }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }} (Prerelease)
body: |
## ⚠️ Prerelease Version - For Testing Only
This is a prerelease version intended for testing purposes.
**Important Notes:**
- This version may contain bugs or experimental features
- Not recommended for production use
- Please report any issues you encounter
### Installation
**Method 1: Using BRAT (Recommended)**
1. Install [BRAT](https://github.com/TfTHacker/obsidian42-brat) plugin if you haven't already
2. Open BRAT settings
3. Click "Add Beta plugin"
4. Enter: `jxpeng98/obsidian-to-NotionNext`
5. Enable "Share to NotionNext" in Community Plugins
**Method 2: Manual Installation**
1. Download the `${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip` file
2. Extract it to your `.obsidian/plugins/` folder
3. Reload Obsidian
### Changelog
See [CHANGELOG.md](${{ env.CHANGELOG_FILENAME }}) for details.
---
**Feedback:** Please report issues in the [GitHub Issues](https://github.com/${{ github.repository }}/issues) section.
draft: false
prerelease: true
- name: Upload zip file
id: upload-zip
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./${{ env.PLUGIN_NAME }}.zip
asset_name: ${{ env.PLUGIN_NAME }}-${{ steps.build.outputs.tag_name }}.zip
asset_content_type: application/zip
- name: Upload main.js
id: upload-main
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./main.js
asset_name: main.js
asset_content_type: text/javascript
- name: Upload manifest.json
id: upload-manifest
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.REPO_ACCESS_TOKEN }}
with:
upload_url: ${{ steps.create_prerelease.outputs.upload_url }}
asset_path: ./manifest.json
asset_name: manifest.json
asset_content_type: application/json

View File

@@ -1,23 +1,35 @@
name: Release Obsidian-to-NotionNext plugin
name: Release
on:
push:
branches:
- main
tags:
- "*"
- "v*.*.*"
- "[0-9]+.[0-9]+.[0-9]+"
env:
PLUGIN_NAME: share-to-notionnext # Change this to match the id of your plugin.
CHANGELOG_FILENAME: CHANGELOG.md
jobs:
build:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: "16.x"
node-version: "18"
# - name: Generate changelog
# id: changelog
# uses: saadmk11/changelog-ci@v1.1.2
# with:
# github_token: ${{ secrets.REPO_ACCESS_TOKEN }}
# release_version: ${{ github.ref }}
# changelog_filename: CHANGELOG.md
- name: Build
id: build
@@ -39,6 +51,7 @@ jobs:
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
body_path: ${{ env.CHANGELOG_FILENAME }}
draft: false
prerelease: false

32
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Test and Build
on:
push:
branches:
- "*"
env:
PLUGIN_NAME: share-to-notionnext # Change this to match the id of your plugin.
jobs:
build:
name: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- name: Build
id: build
run: |
npm install
npm run build
mkdir ${{ env.PLUGIN_NAME }}
cp main.js manifest.json ${{ env.PLUGIN_NAME }}
zip -r ${{ env.PLUGIN_NAME }}.zip ${{ env.PLUGIN_NAME }}
ls
echo "tag_name=$(git tag --sort version:refname | tail -n 1)" >> $GITHUB_OUTPUT

7
.gitignore vendored
View File

@@ -21,3 +21,10 @@ data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
.history
# local data
local-data
# vitepress
docs/.vitepress/dist
docs/.vitepress/cache

26
CHANGELOG.md Normal file
View File

@@ -0,0 +1,26 @@
# Changelog
## v2.8.0-beta.1 (2025-10-31)
### Added
- **Auto Sync Feature**: Automatically sync notes to Notion when content or frontmatter changes
- Configurable delay (default: 5 seconds, minimum: 2 seconds)
- Support for multiple database syncing
- Smart detection to avoid sync loops when only NotionID is updated
- Content hash comparison to detect body text changes
- Works on both desktop and mobile platforms
- Added comprehensive i18n support for all UI elements and notifications
- Added prerelease workflow for beta testing via GitHub Actions and BRAT
### Changed
- Enhanced settings tab with auto-sync configuration options
- Improved debug logging for better troubleshooting
- Updated documentation with auto-sync usage guide and troubleshooting section
### Fixed
- Fixed mobile compatibility issues by using `window.setTimeout` instead of `NodeJS.Timeout`
- Fixed sync loop prevention logic to properly handle frontmatter and content changes
- Fixed cache update timing to ensure accurate change detection

View File

@@ -1,240 +1,20 @@
# Obsidian share to NotionNext
感谢[原作者](https://github.com/EasyChris/obsidian-to-notion)开发出了这么好用的插件能够将obsidian同步到notion。 但是原仓库只能同步Name和Tags信息如果像我一样通过[NotionNext](https://github.com/tangly1024/NotionNext)来搭建自己的网页,就有一些局限性。每次导入之后都需要进行大量的修改。
# Obsidian to NotionNext
所以我在[原作者](https://github.com/EasyChris/obsidian-to-notion)的基础之上,增加了匹配[NotionNext](https://github.com/tangly1024/NotionNext)模板的功能。这样可以直接在Obsidian编辑整理好之后一键发布。
## 更新说明
### 0.3.0 (大更新)
- 这个版本开始,你可以**任意修改第一列表头的名字 (标题列,默认:'title')**。 **注意你必须保证你的Notion数据库中有'tags这一列的存在并且在markdown文件中把`tags:`添加到你的YAML表头中。否则会返回`400 错误`。但是你可以`tags:`设置为空。**
[![Test](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml)
[![Release](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml)
[![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22share-to-notionnext%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json)](https://GitHub.com/jxpeng98/obsidian-to-NotionNext/releases/)
[![GitHub release (with filter)](https://img.shields.io/github/package-json/v/jxpeng98/obsidian-to-NotionNext)](https://github.com/jxpeng98/obsidian-to-NotionNext/releases/)
![](https://minioapi.pjx.ac.cn/img1/2023/11/4a298b9be3990e9d2201bf2f50ca5a0a.png)
例如这样:
![](https://minioapi.pjx.ac.cn/img1/2023/11/4cd8d79cd9dd9dde299e39c666cb3473.gif)
- 增加了一个控制按钮来控制是否开启当前数据库同步命令的功能。如果你关闭了这个按钮,你在上传命令列表中就不会出现当前数据库的选项。
使用 Notion API 将文件从 Obsidian 分享到任何 Notion 数据库。此插件支持通用 Notion 数据库、NotionNext 博客模板和完全自定义的数据库模式。
![](https://minioapi.pjx.ac.cn/img1/2023/11/becb60fc44783842da4b3cf4c322f363.gif)
**详细说明请访问[文档网站](https://obsidian-to-notionnext.pages.dev/)。**
### 0.2.6
- 增加一个按钮用来控制是否在名列列表中显示如下数据库。
## 功能特性
![](https://minioapi.pjx.ac.cn/img1/2023/11/147c6a4eaa34da41a6f102558ed77106.png)
如果你关闭普通数据库的按钮你在上传命令列表中就不会出现普通数据库的选项。如果你关闭NotionNext数据库的按钮你在上传命令列表中就不会出现NotionNext数据库的选项
- **多种数据库类型**支持通用、NotionNext 和自定义数据库。
- **自定义属性**:在自定义数据库中,可将任何 frontmatter 键映射到任何 Notion 属性
- **灵活同步**:即时选择要同步到哪个数据库。
![](https://minioapi.pjx.ac.cn/img1/2023/11/70b8e4fc2148688ccbd6cfc53ce339a2.png)
## 致谢
### 0.2.3
- 修复了一个bug现在可以正常更新了。
### 0.2.2
- 支持NotionNext 和 普通Notion 数据库的同步。
- 你可以有一个NotionNext和一个普通Notion数据库。
- 普通Notion数据库的同步方式和原作者的一样只同步`title``tags`。**如果使用普通数据库功能,你需要保证你的数据库中有`title``tags`这两个表头。必须使用小写。**
![](https://minioapi.pjx.ac.cn/img1/2023/11/712a12081d855aa60f82a7b46913ab7e.gif)
![](https://minioapi.pjx.ac.cn/img1/2023/11/9de76cecceef74c78884ddfc1c221659.gif)
### 0.2.1
- 重构代码。
### 0.2.0
- 从这个版本开始,重构了交互逻辑。现在当你点击左侧的按钮,会弹出可同步的数据库选项。你可以选择你想要同步的数据库,然后点击同步按钮。**但是现在仅支持同步单个数据库如果你的数据库不是NotionNext你可以不用更新。**
### 0.1.10
- 修正了设置中的中文显示。
### 0.1.8
- 重新整理了代码,增加了一个仓库转换按钮为之后的多数据库支持作准备。**但是现在还不支持多数据库如果你的数据库不是NotionNext你可以不用更新。**
### 0.1.7
- [x] 删除了设置中`convert tags`的选项。 你现在可以直接添加tags而不需要考虑是否开启tags选项。如果你不需要tags可以直接删除tags选项或者留白。
## 使用方式
### 注意事项
本插件现在暂时只能用于匹配[NotionNext](https://github.com/tangly1024/NotionNext)。如果你不是使用这个模板,你只会无限返回`error 400`.
所以没有NotionNext需求的请使用原作者的[Obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion)
### 准备安装
在安装插件之前,你必须配置好了以下内容:
1. 你的NotionNext数据库。
2. 根据原作者的readme.md配置好了Notion API并且已经和你的NotionNext仓库关联。
3. NotionNext Database ID
4. 你的NotionNext数据库有如下内容
- type
- title
- slug
- category
- tags
- date
- status
- summary
- password
- icon
在最新的0.0.6版本,我还增加了以下内容:
- titleicon 标题的emoji图标,暂时只能支持emoji
- coverurl 封面图片的url url可以是任何一种图片的url 例如jpgpngsvg等等。
**如果你是直接复制的NotionNext的模板这些内容应该已经有了。我在原作者的基础之上对本插件的内容进行了更改所以你只需要保证你的数据库有如上内容并且所有的字母都是小写**
**⚠️⚠️⚠️:表头全部小写!!!顺序无所谓!**
### 安装插件
#### 社区插件市场下载
打开`Obsidian -> 设置 -> 社区插件 -> 浏览 -> 搜索Share to NotionNext`, 然后点击安装。
#### 手动安装
1. 关闭Obsidian
2. 从Release下载插件文件解压到你的obsidian插件目录下。
3. 重新打开Obsidian进入设置启用插件。
4. 在设置中找到Obsidian to NotionNext填入你的NotionNext Database ID 和 API token。
### 使用插件
在仓库中我上传了一个模板你可以直接复制到你的模板文件夹中。然后使用Obsidian的模板功能一键生成新笔记。
如果你不想使用模板你也可以直接在Obsidian中创建一个新的文件然后复制下边的内容。然后保存。
```markdown
---
# default value has been set.
# for any unwanted value, you can delete it or set it to empty.
# for example, if you donot want to set password, you can delete password: "1234" or set it to password: ""
# 我已经在插件中设置了默认值,如果有不需要的选项,可以直接删除。
# 例如你不需要密码选项你可以将password: "1234"删除,或者将它设置为空。
# !!!!!!!!!!!!
# 现在阶段一定不要修改表头的名字, please do not change the name of the header in YAML front matter
# !!!!!!!!!!!!
titleicon: 📎 # emoji icon, default is 📜, 默认是📜
date: 2023-07-23 # default is today 默认是今天。 Format is YYYY-MM-DD 格式是YYYY-MM-DD
coverurl: https://img.jxpeng.dev/2023/08/843e27a210847f05a0f7cfb121fec100.jpg # default is empty 默认是空
type: Post # Post or Page, default is Post 默认是Post
slug: test # slug for url, default is empty 默认是空
stats: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
category: test # default is 'Obsidian' 默认是'Obsidian'
summary: this is a summary for test post # default is empty 默认是空
icon: fa-solid fa-camera # you can ignore this, default is empty 默认是空,可直接删除
password: "1234" # if you donot want to set password, you can delete this line, default is empty 默认是空,可直接删除
# 现在必须开启tags选项否则会报错
tags:
- test # tags for post
- web # add more tags if you want
---
Contents Below
```
模板使用如下:
![](https://minioapi.pjx.ac.cn/img1/2023/09/354b950e5777b48832c2475e4a31f2cc.gif)
**插件预览如下**
![](https://minioapi.pjx.ac.cn/img1/2023/09/d6199619b68fab218fca8ae0cebece78.gif)
---
**以下为原README.md**
非常感谢原作者的开发,我只是在原作者的基础之上进行了修改,增加了一些功能。如果你觉得这个插件对你有帮助,可以给[原作者](https://github.com/EasyChris/obsidian-to-notion)一个star。
# Obsidian to Notion
[![](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml)
[![Release Obsidian plugin](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml)
[![GitHub license](https://camo.githubusercontent.com/400c4e52df43f6a0ab8a89b74b1a78d1a64da56a7848b9110c9d2991bb7c3105/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d47504c76332d626c75652e737667)](https://raw.githubusercontent.com/EasyChris/obsidian-to-notion/master/LICENSE)
[![Github all releases](https://img.shields.io/github/downloads/Easychris/obsidian-to-notion/total.svg)](https://GitHub.com/Easychris/obsidian-to-notion/releases/)
[![GitLab latest release](https://badgen.net/github/release/Easychris/obsidian-to-notion/)](https://github.com/Easychris/obsidian-to-notion/releases)
Obsidian share to Notion [English](README.md)
将obsidian文件一键分享到Notion,并在obsidian中添加Notion分享链接
如果能对你有所帮助欢迎给一个star支持。
![](./doc/1.gif)
# 使用方式
## 安装插件
### 市场下载
插件市场搜索 noiton 即可下载
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220628214145.png)
### BRAT
插件中中心搜索 BRAT
添加 `EasyChris/obsidian-to-notion` 到 BRAT 插件安装列表中
返回插件中心启用即可
### 手动安装
```
cd YOUR_OBSIDIAN_FOLDER/.obsidian/plugins/
git clone https://github.com/EasyChris/obsidian-to-notion.git
```
## 申请 Notion API
官方参考文档:[https://developers.notion.com/docs](https://developers.notion.com/docs)
### 第 1 步创建integration。
转到 [https://www.notion.com/my-integrations](https://www.notion.com/my-integrations)
创建完成之后,复制`secrets toekn`
![](https://files.readme.io/2ec137d-093ad49-create-integration.gif)
### 第2步与你的集成共享一个数据库
新建一个的page权限为公开
在page中新建一个数据库 -> 需要`full page database`
![](./doc/3.gif)
`integration`添加到你的新建的数据库中
![](./doc/6.gif)
#### 注意
数据库的第一个自定义名称必须是 "Name",否则同步会失败。
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220618102029.png)
### 第三步复制database ID
```
https://www.notion.so/myworkspace/a8aec43384f447ed84390e8e42c2e089?v=...
|--------- Database ID --------|
```
## 打开插件配置
将得到的 `NOTION_API_KEY``DATABASE_ID`填入配置当中
![](./doc/2.png)
## 上传文件内容到notion
点击上传notion的按钮
![](./doc/4.png)
上传成功之后会自动生成一个分享链接
![](./doc/5.png)
## 页面 Banner 链接[可选]
默认可以不填写
横幅URL必须是图像URL例如https//i.imgur.com/xxx.jpg
## Notion ID [可选]
Notion ID是你想分享文件的页面ID。
如果你不写它notion将分享到默认的链接https://www.notion.so/myworkspace/a8aec43384f447ed84390访问这个页面将重定向到你的网站页面。
如果你写了Notion ID它将分享到页面链接如https://your_user_name.notion.site/myworkspace/a8aec43384f447ed84390。不需要重定向网址。
## 同步图片
使用 [Obsidian Image Auto Upload Plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin) 插件,配置你自己的 cos 或者 oss将图片存储到你自己的云存储然后在 obsidian 中使用图片链接即可。该插件会自动帮你上传图片,并替换成链接。
# 请我喝杯咖啡
[顿顿饭](https://dun.mianbaoduo.com/@easy)
# 感谢
[开发流程 | Obsidian 插件开发文档](https://luhaifeng666.github.io/obsidian-plugin-docs-zh/zh/getting-started/development-workflow.html)
[GitHub - devbean/obsidian-wordpress: An obsidian plugin for publishing docs to WordPress.](https://github.com/devbean/obsidian-wordpress)
[GitHub - obsidianmd/obsidian-api](https://github.com/obsidianmd/obsidian-api)
[GitHub - zhaohongxuan/obsidian-weread-plugin: Obsidian Weread Plugin is an plugin to sync Weread(微信读书) hightlights and annotations into your Obsidian Vault.](https://github.com/zhaohongxuan/obsidian-weread-plugin)
此插件是 EasyChris 的原创作品 [obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion) 的一个分支,增加了新功能并支持更灵活的数据库配置。

334
README.md
View File

@@ -1,329 +1,21 @@
# Obsidian to NotionNext
[中文文档](README-zh.md)
Thanks to the [original author](https://github.com/EasyChris/obsidian-to-notion) for developing such a useful plugin that can synchronize Obsidian to Notion. However, the original repository can only sync Name and Tags information. For those like me who use [NotionNext](https://github.com/tangly1024/NotionNext) to set up their website, this presents some limitations. Every time I import, I need to make a lot of modifications.
[![Test](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/test.yml)
[![Release](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml/badge.svg)](https://github.com/jxpeng98/obsidian-to-NotionNext/actions/workflows/release.yml)
[![Obsidian Downloads](https://img.shields.io/badge/dynamic/json?logo=obsidian&color=%23483699&label=downloads&query=%24%5B%22share-to-notionnext%22%5D.downloads&url=https%3A%2F%2Fraw.githubusercontent.com%2Fobsidianmd%2Fobsidian-releases%2Fmaster%2Fcommunity-plugin-stats.json)](https://GitHub.com/jxpeng98/obsidian-to-NotionNext/releases/)
[![GitHub release (with filter)](https://img.shields.io/github/package-json/v/jxpeng98/obsidian-to-NotionNext)](https://github.com/jxpeng98/obsidian-to-NotionNext/releases/)
Thus, based on the [original author's work](https://github.com/EasyChris/obsidian-to-notion), I've added a feature to match the [NotionNext](https://github.com/tangly1024/NotionNext) template. This way, you can edit directly in Obsidian and publish with a single click after organizing.
[中文版](README-zh.md)
Share files from Obsidian to any Notion database using the Notion API. This plugin supports general Notion databases, NotionNext blog templates, and fully custom database schemas.
**Now, support both NotionNext and General databases.**
**For detailed instructions, please visit the [documentation website](https://obsidian-to-notionnext.pages.dev/).**
## Update
### 0.3.0 (Big Update)
- From this version, you can **modify the first column name (title column, default: 'title')** as you want. (**Note: You need to have the 'tags' column in your Notion General database, and add `tags:` in your markdown frontmatter. If not, you will receive `network error 400`. But you can leave the `tags:` blank.**)
## Features
![](https://minioapi.pjx.ac.cn/img1/2023/11/4a298b9be3990e9d2201bf2f50ca5a0a.png)
Like this:
![](https://minioapi.pjx.ac.cn/img1/2023/11/4cd8d79cd9dd9dde299e39c666cb3473.gif)
- Add a switch button to control whether display the setting tabs in the plugin settings for both NotionNext and Notion General databases.
- **Multiple Database Types**: Supports General, NotionNext, and Custom databases.
- **Custom Properties**: Map any frontmatter key to any Notion property in custom databases.
- **Flexible Syncing**: Choose which database to sync to on-the-fly.
![](https://minioapi.pjx.ac.cn/img1/2023/11/becb60fc44783842da4b3cf4c322f363.gif)
## Acknowledgment
### 0.2.6
- Add a switch button to control whether to show the upload command in the command palette.
![](https://minioapi.pjx.ac.cn/img1/2023/11/147c6a4eaa34da41a6f102558ed77106.png)
If you turn off the button for the General database, you won't see the option for the General database in the upload command list.
If you turn off the button for the NotionNext database, you won't see the option for the NotionNext database in the upload command list.
![](https://minioapi.pjx.ac.cn/img1/2023/11/70b8e4fc2148688ccbd6cfc53ce339a2.png)
### 0.2.3
- Fix the bug, now you can update normally.
### 0.2.2
- Support both NotionNext and General Notion database.
- You can have one NotionNext and one General Notion database.
- General Notion database can only have `title` and `tags` columns, and `tags` columns should be the multi-selected property. **the name of the columns is case sensitive. You should use small letter.**
![](https://minioapi.pjx.ac.cn/img1/2023/11/712a12081d855aa60f82a7b46913ab7e.gif)
![](https://minioapi.pjx.ac.cn/img1/2023/11/9de76cecceef74c78884ddfc1c221659.gif)
### 0.2.1
- Restructure the code
### 0.2.0
- From this version, the interactive logic has been rewritten. When you click the ribbon icon, it will display the sync command for all presetting NotionNext databases. You can choose the database you want to sync to. **However, only NotionNext database is supported for now.**
### 0.1.10
- Fix the Chinese support in the settings.
### 0.1.8
- Rebuild the uploadCommand function, and add one button to select the different databases. **However, only NotionNext database is supported for now.**
### 0.1.7
- [x] Removed the `convert tag` option. Now, you can directly add tags in the YAML front matter. If you don't want to add tags, you can delete the tags in the YAML front matter or leave the tags blank.
## How to Use
### Precautions
For now, this plugin is exclusively for [NotionNext](https://github.com/tangly1024/NotionNext). If you're not using this template, you'll keep receiving `error 400`.
For those without a NotionNext requirement, please use the original [Obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion).
### Pre-Installation Steps
Before installing the plugin, you must have set up the following:
1. Your NotionNext database.
2. According to the original author's readme.md, set up the Notion API, and it should already be associated with your NotionNext repository.
3. NotionNext Database ID
4. Your NotionNext database should have the following contents:
- type
- title
- slug
- category
- tags
- date
- status
- summary
- password
- icon
From version 0.0.6, I also add the following contents:
- titleicon: the unique icon for each post, it can only support emoji currently.
- cover url: the cover image for each post, it should be end with a type of image, such as .jpg, .png, .gif, etc.
**If you've directly copied the NotionNext template, these contents should already exist. I've made changes to this plugin based on the original author's work. All you need to ensure is that your database has the above content, and every letter is in lowercase!!!**
**⚠️⚠️⚠️: All headers are in lowercase!!! The order doesn't matter!**
### Plugin Installation
#### Install via Community Plugins
Open `Obsidian settings -> Community Plugins -> Browse -> NotionNext -> Share to NotionNext`
#### Mannually Install
1. Close Obsidian.
2. Download the plugin file from Release and unzip it into your Obsidian plugin directory.
3. Re-open Obsidian, go to settings, and enable the plugin.
4. In the settings, find Obsidian to NotionNext, and enter your NotionNext Database ID and API token.
### How to Use
### Using the Plugin
In the repository, I have uploaded a template which you can directly copy into your template folder. After that, use Obsidian's template feature to create a new note with one click.
If you don't want to use the template, you can also directly create a new file in Obsidian and then copy the content below. Then save it.
```markdown
---
# default value has been set.
# for any unwanted value, you can delete it or set it to empty.
# for example, if you donot want to set password, you can delete password: "1234" or set it to password: ""
# 我已经在插件中设置了默认值,如果有不需要的选项,可以直接删除。
# 例如你不需要密码选项你可以将password: "1234"删除,或者将它设置为空。
# !!!!!!!!!!!!
# 现在阶段一定不要修改表头的名字, please do not change the name of the header in YAML front matter
# !!!!!!!!!!!!
titleicon: 📎 # emoji icon, default is 📜, 默认是📜
date: 2023-07-23 # default is today 默认是今天。 Format is YYYY-MM-DD 格式是YYYY-MM-DD
coverurl: https://img.jxpeng.dev/2023/08/843e27a210847f05a0f7cfb121fec100.jpg # default is empty 默认是空
type: Post # Post or Page, default is Post 默认是Post
slug: test # slug for url, default is empty 默认是空
stats: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
category: test # default is 'Obsidian' 默认是'Obsidian'
summary: this is a summary for test post # default is empty 默认是空
icon: fa-solid fa-camera # you can ignore this, default is empty 默认是空,可直接删除
password: "1234" # if you donot want to set password, you can delete this line, default is empty 默认是空,可直接删除
# 现在必须开启tags选项否则会报错
tags:
- test # tags for post
- web # add more tags if you want
---
Contents Below
```
Usage of the template is as follows:
![](https://minioapi.pjx.ac.cn/img1/2023/09/354b950e5777b48832c2475e4a31f2cc.gif)
**Plugin preview is shown below**
![](https://minioapi.pjx.ac.cn/img1/2023/09/d6199619b68fab218fca8ae0cebece78.gif)
---
**Original README.md**
Many Thanks for the original author's work. I've only made some changes to the original author's work. If you find this plugin useful, please give the [original author](https://github.com/EasyChris/obsidian-to-notion) a star.
# Obsidian to Notion
[![](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/CI.yml)
[![Release Obsidian plugin](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml/badge.svg)](https://github.com/Easychris/obsidian-to-notion/actions/workflows/release.yml)
[![GitHub license](https://img.shields.io/github/license/EasyChris/obsidian-to-notion)](https://raw.githubusercontent.com/EasyChris/obsidian-to-notion/master/LICENSE)
[![Github all releases](https://img.shields.io/github/downloads/Easychris/obsidian-to-notion/total.svg)](https://GitHub.com/Easychris/obsidian-to-notion/releases/)
[![GitLab latest release](https://badgen.net/github/release/Easychris/obsidian-to-notion/)](https://github.com/Easychris/obsidian-to-notion/releases)
Share of obsidian to Notion [中文文档](README-zh.md)
Sharing files from Obsidian to Notion with a single click, and Obsidian will automatically add the Notion share link
You are welcome to offer it a star if it can benefit you.
![](./doc/1.gif)
# TODO
### [TODO Board](https://github.com/users/EasyChris/projects/3/views/1)
- [x] support for custom page banner
- [x] update the exsit page
- [x] support for mult language
- [x] support for auto copy the share link to clipboard
- [x] support for mobile
- [x] support tags thank for [@jannikbuscha](https://github.com/jannikbuscha)
- [ ] transfer the bi-link format like [[]] into the format that Notion supports.
# How to use
## Install the plugin
### Marketplace download
Open obsidian setting -> Add plugin -> Search -> notion
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220628214145.png)
### BRAT
Enter `BRAT` into the plugin market center to find it.
Add `EasyChris/obsidian-to-notion` to the list of BRAT plugins that have been installed.
Return to the plugin center and turn it on.
### Manual installation
```
cd YOUR_OBSIDIAN_FOLDER/.obsidian/plugins/
git clone https://github.com/EasyChris/obsidian-to-notion.git
```
## Apply Notion API
Official reference documentation: [https://developers.notion.com/docs](https://developers.notion.com/docs)
### Step 1: Create integration.
Go to [https://www.notion.com/my-integrations](https://www.notion.com/my-integrations)
Once created, copy `secrets toekn`
![](https://files.readme.io/2ec137d-093ad49-create-integration.gif)
#### Note:
database first custom name must be "Name", otherwise sync to notion will be failed
![](https://afox-1256168983.cos.ap-shanghai.myqcloud.com/20220618102029.png)
### Step 2: Share a database with your integration
Create a new page (with public permissions)
Create a new database in the page -> you need `full page database`
![](./doc/3.gif)
Add `integration` to your new database
![](./doc/6.gif)
### Step 3: Copy the database ID
```
https://www.notion.so/myworkspace/a8aec43384f447ed84390e8e42c2e089?v=...
| --------- Database ID --------|
```
## Open the plugin configuration
Fill the configuration with the `NOTION_API_KEY` and `DATABASE_ID` you got
![](./doc/2.png)
## Upload file content to notion
Click the uploadCommand notion button
![](./doc/4.png)
A share link will be automatically generated after successful uploadCommand
![](./doc/5.png)
## Banner URL [option]
Banner url must be a image url like: https://i.imgur.com/xxx.jpg
If you don't want to use banner, leave it blank
## Convert Tags [option]
Transfer the Obsidian tags to the Notion table.
It requires the column with the name 'Tags'.
![](./doc/7.png)
Add tags to your notion page
![](./doc/10.png)
* open plugin convert tags
![](./doc/8.png)
* add tags in the head
```markdown
---
tags: [tag1,tag2]
---
this is test tags
```
```markdown
---
tags:
- tag4
---
this is test tags
```
![](./doc/9.png)
Thanks for [@jannikbuscha](https://github.com/jannikbuscha) contribution
## Notion ID [option]
Notion ID is the your notion site ID that you want to share the file to.
if you don't write it, notion will share to the default link like:
https://www.notion.so/myworkspace/a8aec43384f447ed84390
that visit this page need to redirect to your site url
if you write the Notion ID, it will share to the page link like:
https://your_user_name.notion.site/myworkspace/a8aec43384f447ed84390.
The visiter don't need to redirect url.
## Sync image to Notion
To sync images to your oss or cos bucket, use the [Obsidian Image Auto Upload Plugin](https://github.com/renmu123/obsidian-image-auto-upload-plugin).
# Development
```
git clone https://github.com/EasyChris/obsidian-to-notion.git
yarn install
yarn dev
```
## Release
```
node update-version.js
./release.sh
```
```
# Thanks
[Development Process | Obsidian Plugin Development Documentation](https://luhaifeng666.github.io/obsidian-plugin-docs-zh/zh/getting-started/development-workflow.html)
[GitHub - devbean/obsidian-wordpress: An obsidian plugin for publishing docs to WordPress.](https://github.com/devbean/obsidian-wordpress)
[GitHub - obsidianmd/obsidian-api](https://github.com/obsidianmd/obsidian-api)
[GitHub - Easychris/obsidian-to-notion: Obsidian Weread Plugin is an plugin to sync Weread(微信读书) hightlights and annotations into your Obsidian Vault.](https://github.dev/zhaohongxuan/obsidian-weread-plugin)
[GitHub - Quorafind/Obsidian-Memos: A quick capture plugin for Obsidian, all data from your notes.](https://github.com/Quorafind/Obsidian-Memos)
[https://github.com/jannikbuscha/obsidian-to-notion](https://github.com/jannikbuscha)
# License
GNU GPLv3
This plugin is a fork of the original [obsidian-to-notion](https://github.com/EasyChris/obsidian-to-notion) by EasyChris, with added features and support for more flexible database configurations.

BIN
doc/1.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 552 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

BIN
doc/2.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

BIN
doc/3.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

BIN
doc/4.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

BIN
doc/5.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

BIN
doc/6.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

BIN
doc/7.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

BIN
doc/8.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

BIN
doc/9.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

69
docs/.vitepress/config.ts Normal file
View File

@@ -0,0 +1,69 @@
import { defineConfig } from 'vitepress'
import { withSidebar } from 'vitepress-sidebar';
// https://vitepress.dev/reference/site-config
const vitePressOptions = {
title: "Obsidian to NotionNext",
description: "A plugin to share files to any Notion database using the Notion API.",
themeConfig: {
socialLinks: [
{ icon: 'github', link: 'https://github.com/jxpeng98/obsidian-to-NotionNext' }
]
},
locales: {
root: {
label: 'English',
lang: 'en',
link: '/en/',
themeConfig: {
nav: [
{ text: 'Home', link: '/en/' },
{ text: 'Guide', link: '/en/01-getting-started' }
],
}
},
zh: {
label: '简体中文',
lang: 'zh-CN',
link: '/zh/',
themeConfig: {
nav: [
{ text: '首页', link: '/zh/' },
{ text: '指南', link: '/zh/01-getting-started' }
],
}
}
}
};
const commonSidebarOptions = {
documentRootPath: '/',
useTitleFromFrontmatter: true,
frontmatterTitleFieldName: 'title',
collapsed: true,
removePrefixAfterOrdering: true,
prefixSeparator: '-',
hyphenToSpace: true,
useFolderTitleFromIndexFile: true,
useFolderLinkFromIndexFile: true,
sortMenusByName: false,
};
const vitePressSidebarOptions = [
{
...commonSidebarOptions,
scanStartPath: '/en',
basePath: '/',
resolvePath: '/en/'
},
{
...commonSidebarOptions,
scanStartPath: '/zh',
basePath: '/',
resolvePath: '/zh/',
}
];
export default defineConfig(withSidebar(vitePressOptions, vitePressSidebarOptions));

View File

@@ -0,0 +1,45 @@
---
title: Getting Started
description: Guide to setting up the Obsidian to NotionNext plugin
---
# Getting Started
## Get Notion API Token
Before using the plugin, you need to obtain an API Token from Notion to allow the plugin to access your Notion account.
1. Go to the [Notion API](https://www.notion.so/profile/integrations) page to create a new integration. You need to be logged into your Notion account.
2. Click on `+ New integration`.
![new-integration](https://r2imga.jxpeng.dev/2025/10/3d12358494c000ab7035820e1e836934.png)
3. Fill in the required information:
![integration-info](https://r2imga.jxpeng.dev/2025/10/645b8182105e5e64e61bd263394534d6.png)
4. Integration successfully created.
![success](https://r2imga.jxpeng.dev/2025/10/57ea92c48efc15b95a69f3663424f5ae.png)
5. Enter the "Configure integration settings" page and **prepare to copy the API Token,** which you will need in the plugin settings.
![configure-integration](https://r2imga.jxpeng.dev/2025/10/4a50e55c35e47f905fb7fe63af5c8402.png)
::: warning
**⚠️ Note:** Keep your API Token secure and do not share it with others, as it grants access to your Notion data.
:::
## Create a Notion Database and Connect Integration
Next, you need to create a Notion database to store the notes synced from Obsidian.
1. In your Notion workspace, click on `Create a new page` to create a new page.
![create-new-page](https://r2imga.jxpeng.dev/2025/10/1f092ef1d8c5a25aeb75694d654810a1.png)
2. create a new page and select the `Database - Full page` option.
![new-database](https://r2imga.jxpeng.dev/2025/10/73b700fc65a53f2ff518b58832bf9757.png)
3. Click the `...` menu in the top-right corner of the database page, go to `Connections`, and connect your newly created integration.
![connect-integration](https://r2imga.jxpeng.dev/2025/10/e8d9be4718f6f5c76fdc3bee7d694d23.png)
4. Click `Share` -> `Publish` to publish the database to the web.
![publish](https://r2imga.jxpeng.dev/2025/10/4b1d3f597d67508ee67d20a62151200f.png)
5. Click and copy the **Database ID**.
![database-id](https://r2imga.jxpeng.dev/2025/10/d8f22c1daf5063305256e5e50210adf9.png)
Next, you can proceed to install and configure the plugin in Obsidian by following the [Installation Guide](./02-installation.md).

View File

@@ -0,0 +1,28 @@
---
title: Installation
description: Guide to installing the Obsidian to NotionNext plugin
---
# Installation
Once you have completed the previous section setup on the Notion side, you can install and configure the plugin in Obsidian.
1. Open Obsidian's `Settings`.
![obsidian](https://r2imga.jxpeng.dev/2025/10/6f80d5126391162dd7cc98de87d3c1b2.png)
2. Navigate to `Community plugins`.
![community-plugins](https://r2imga.jxpeng.dev/2025/10/adf7dd7d292dcc331d7625b8f409f222.png)
::: tip
If you haven't enabled community plugins before, you may need to turn off `Safe mode` first (`Turn on Community plugins`).
:::
3. Go to `Community plugins` -> `Browse`.
![browse](https://r2imga.jxpeng.dev/2025/10/e4f170f966902999fe2137196d8b6f9c.png)
4. Search for "NotionNext" and click `Install`.
![install](https://r2imga.jxpeng.dev/2025/10/1b0fcf15bc80aeb3714d9c97cbc6d5b0.png)
5. After installation, enable the plugin.
![enable](https://r2imga.jxpeng.dev/2025/10/6c7a7ee7d6e5861a3f0867c826e3f2c0.png)
Now, once enabled, you can find the "Share to NotionNext" settings in the plugin settings tab to begin [configuring your databases](./03-configuration.md) in the next step.

127
docs/en/03-configuration.md Normal file
View File

@@ -0,0 +1,127 @@
---
title: Configuration
description: Guide to configuring Notion databases in the Obsidian to NotionNext plugin
---
# Database Configuration
After installing the plugin and obtaining the Notion API token and Database ID, you can proceed to configure the databases you want to sync with.
First, open the plugin settings in Obsidian.
![open-plugin-settings](https://r2imga.jxpeng.dev/2025/10/d2cfc05a86a8f014354fbd4e8456ccdc.png)
Click "Add new database" to start creating a new database configuration.
![add-database](https://r2img.jxpeng.dev/2024/07/115f47b4180d04fb362b931f8092b5fb.png)
In the plugin settings, you can add and configure the Notion databases you want to sync with. The plugin supports three types of database configurations.
- [Database Configuration](#database-configuration)
- [1⃣ General Database](#1⃣-general-database)
- [2⃣ NotionNext Database](#2⃣-notionnext-database)
- [3⃣ Custom Database](#3⃣-custom-database)
- [Finalizing Configuration](#finalizing-configuration)
## Auto Sync Frontmatter Entry
If you enable auto sync, the plugin needs a frontmatter entry that lists which configured databases should receive updates. You can customise the name of this entry in **Settings → Auto Sync Frontmatter Key** (default: `autosync-database`). Use any text you like—letters, numbers, emojis, or other scripts are all supported.
In your note's frontmatter, add the configured key and list the database abbreviations you created in the settings:
```yaml
---
title: My Article
autosync-database: [blog, ideas]
---
```
The entry can be a YAML list or comma-separated string, and manual uploads will automatically add the current database abbreviation if it is missing. If you change the key name in settings, update your frontmatter to match the new value.
## 1⃣ General Database
This is the most basic database type and is suitable for most users.
**Configuration:**
- **Full Name**: A name for this database configuration.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
**Notion Database Requirements:**
- Must contain a `Title` property named `title`.
- Must contain a `Multi-select` property named `tags`.
![notion-general](https://r2imga.jxpeng.dev/2025/10/3abc05f71a1bd81bdc00fd988dd71108.png)
Then, fill in the configuration fields as shown below:
- **Database Full Name**: the name you want to give this database to recognise it in the database list (e.g. "Learning Database").
- **Database Abbreviate Name**: a short abbreviation for this database (e.g. "learning").
- **Notion Tags Sync**: enable this option if you want to sync tags columns from Obsidian to Notion (**if you enable this option, make sure you add tags in your notes**).
- **Customise title property**: the property in your Notion database that you want to use as the primary column (default is `title`).
- **Notion API Token**: the API token you obtained in the first step.
- **Database ID**: the database ID you obtained in the second step.
![general](https://r2imga.jxpeng.dev/2025/10/9697de930e530c55081e07835e224782.png)
## 2⃣ NotionNext Database
This type is specifically designed for users of the [NotionNext](https://github.com/tangly1024/NotionNext) blog system, with properties preset to match the NotionNext template.
Config the database similarly to the General Database type:
- **Database Full Name**: A name for this database configuration.
- **Database Abbreviate Name**: A short abbreviation for this database.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
![notionnext](https://r2imga.jxpeng.dev/2025/10/5b1b3b3fb4ef9a76f4fed26fcc6c426b.png)
## 3⃣ Custom Database
This type offers maximum flexibility for advanced users. It allows you to map any frontmatter metadata from your Obsidian notes to any property in your Notion database.
You should first config the database similarly to the General Database type:
- **Database Full Name**: A name for this database configuration.
- **Database Abbreviate Name**: A short abbreviation for this database.
- **Notion API Token**: The API token you obtained in the first step.
- **Database ID**: The database ID you obtained in the second step.
![custom](https://r2imga.jxpeng.dev/2025/10/667335d7fd2cfa96e307be3df79e157e.png)
Once you have filled in the basic configuration, you can start to add new properties.
You can click the `Add New Property` button to create a new property mapping.
First, you need to add the title property mapping, which is required for the Notion database to function correctly.
![title-property](https://r2imga.jxpeng.dev/2025/10/2ad52037476d3f86f3c4cfbed507f74b.png)
::: tip
Remember to set the "Notion Property" to the property name in your Notion database (case-sensitive) and the "Frontmatter Key" to the key in your Obsidian note's frontmatter.
:::
After adding the title property, you can continue to add more properties as needed.
![property-1](https://r2imga.jxpeng.dev/2025/10/d4c0bcc3abbc741dd34ce22e589d6223.png)
For now, the plugin supports the following Notion property types:
- Text
- Number
- Select
- Multi-select
- Date
- Files & Media
- Checkbox
- URL
- Email
- Phone Number
![types](https://r2imga.jxpeng.dev/2025/10/81d321693dfd046ad3386e4507d60792.png)
::: info
Relation and Rollup types are not supported yet.
:::
## Finalizing Configuration
After configuring your database, make sure to save your settings. You can now start syncing your Obsidian notes to the configured Notion database by using the "Share to NotionNext" command from the command palette or the note context menu.

142
docs/en/04-sync.md Normal file
View File

@@ -0,0 +1,142 @@
---
title: Syncing Notes
description: How to sync your Obsidian notes to Notion using the NotionNext plugin
---
# Syncing Notes
After configuring your Notion database in the plugin settings, you can start syncing your Obsidian notes to Notion.
## Manual Sync
To sync a note, open the note you want to sync and use the "Share to NotionNext" command from the command palette or the note context menu. This will create a new page in your Notion database with the content of your Obsidian note.
## Auto Sync
The plugin supports automatic syncing that monitors your notes for changes and automatically syncs them to Notion.
### Enabling Auto Sync
1. Open the plugin settings
2. Find the "Auto Sync" toggle under General Settings
3. Enable the toggle
4. Configure the "Auto Sync Delay" (default: 5 seconds, minimum: 2 seconds)
### Prepare the Frontmatter
Auto sync reads the database list from the frontmatter key you configured in **Settings → Auto Sync Frontmatter Key** (default: `autosync-database`). To make sure your notes can sync automatically:
- Add the configured key to your note's frontmatter
- List one or more database abbreviations that you defined in the plugin settings
- Keep the list updated if you change the databases a note should sync to
Example with the default key:
```yaml
---
title: My Article
autosync-database: [blog, portfolio]
---
```
If you change the key name in the settings, update your frontmatter to match. The plugin will prompt you when the entry is missing.
### How Auto Sync Works
When auto sync is enabled:
- The plugin monitors markdown files for changes
- After you stop editing for the configured delay period, auto sync is triggered
- Only files that have already been synced to Notion (have a NotionID in frontmatter) will be auto-synced
- If a file is linked to multiple databases, it will sync to all of them automatically
### Auto Sync Scenarios
#### Scenario A: Missing Auto Sync Entry
```yaml
---
title: My New Article
tags: [blog, tech]
---
```
**Behavior:**
- ✅ Detects that the configured auto sync key is missing
- ✅ Shows notice: `⚠️ Auto sync skipped: Add a "{key}" entry in the frontmatter to choose databases`
- ✅ No sync operation performed
- 📝 **Action Required:** Add the configured key (default `autosync-database`) to the frontmatter with the database abbreviations
#### Scenario B: New Document (Not Yet Synced)
```yaml
---
title: My New Article
aytosync-database: [blog]
---
```
**Behavior:**
- ✅ Detects no NotionID present
- ✅ Shows notice: "⚠️ Auto sync skipped: This document has not been synced to Notion, please upload manually first"
- ✅ No sync operation performed
- 📝 **Action Required:** Manually sync the document first using the command palette
#### Scenario C: Synced to One Database
```yaml
---
title: My Article
NotionID-blog: abc123
autosync-database: [blog]
---
```
**Behavior:**
- ✅ Detects 1 NotionID
- ✅ Automatically syncs to the Blog database
- ✅ Shows success/failure notification from the upload command
- 📝 **No Action Required:** Changes are automatically synced
#### Scenario D: Synced to Multiple Databases
```yaml
---
title: My Article
NotionID-blog: abc123
NotionID-portfolio: def456
NotionID-notes: ghi789
---
```
**Behavior:**
- ✅ Detects 3 NotionIDs
- ✅ Shows notice: "🔄 Auto sync: Syncing to 3 database(s)..."
- ✅ Syncs to all 3 databases sequentially
- ✅ Shows individual result notifications for each database
- 📝 **No Action Required:** Changes are automatically synced to all linked databases
#### Scenario E: Custom Frontmatter Key
```yaml
---
title: My Article
NotionID-blog: abc123
NotionID-portfolio: def456
🚀-sync-targets: [blog, portfolio]
---
```
**Behavior:**
- ✅ Uses your custom key (for example `🚀-sync-targets`) configured in settings
- ✅ Syncs to the listed databases when NotionIDs are present
- 📝 **Remember:** Update both the setting and your frontmatter if you rename the key
### Auto Sync Best Practices
1. **First Sync Manually**: Always perform the first sync manually to establish the NotionID link
2. **Configure Delay Appropriately**: Set a longer delay (5-10 seconds) if you make frequent edits
3. **Monitor Sync Status**: Check the notifications to ensure syncs complete successfully
4. **Check Logs**: Open the developer console (Ctrl+Shift+I / Cmd+Option+I) to view detailed sync logs
### Troubleshooting
Having issues with auto sync? Check the [Troubleshooting Guide](05-troubleshooting.md) for detailed solutions to common problems.

View File

@@ -0,0 +1,74 @@
---
title: Troubleshooting
description: Common issues and solutions for the Obsidian to NotionNext plugin
---
# Troubleshooting
## Auto Sync Issues
### Auto sync not working?
**Possible causes and solutions:**
- **Auto sync not enabled**: Ensure auto sync is enabled in plugin settings under General Settings
- **No NotionID in frontmatter**: Verify the document has a NotionID field (e.g., `NotionID-blog: abc123`) in its frontmatter. Auto sync only works for documents that have been manually synced at least once
- **Invalid database configuration**: Check that your database configuration is valid and the API credentials are correct
- **Console errors**: Look for errors in the developer console (`Ctrl+Shift+I` / `Cmd+Option+I`)
### Sync too frequent?
If auto sync is triggering too often while you're editing:
- **Increase the delay**: Go to plugin settings and increase the "Auto Sync Delay" value (default is 5 seconds)
- **Understanding the delay**: The delay timer resets each time you make an edit, so sync only triggers after you stop editing for the configured duration
### Missing notifications?
If you're not seeing sync notifications:
- **Notification duration**: Notifications appear for 3-6 seconds and then automatically disappear
- **Check console logs**: Open the developer console (`Ctrl+Shift+I` / `Cmd+Option+I`) to view detailed sync information
- **Multiple syncs**: When syncing to multiple databases, you'll see a notification for the multi-database sync plus individual result notifications
### Auto sync skipped for new documents
If you see the message "⚠️ Auto sync skipped: This document has not been synced to Notion, please upload manually first":
- **First sync required**: This is expected behavior. Auto sync only works for documents that already have a NotionID
- **Solution**: Use the command palette (`Ctrl/Cmd + P`) and select "Share to NotionNext" to perform the first manual sync
- **After manual sync**: Once the document has a NotionID in its frontmatter, auto sync will work automatically
## General Sync Issues
### Sync failed with error message
If you see error messages during sync:
1. **Check API credentials**: Verify your Notion API token and Database ID are correct
2. **Check permissions**: Ensure the integration has access to the target database
3. **Network issues**: Check your internet connection
4. **Rate limiting**: Notion has API rate limits; wait a moment and try again
5. **Check console**: Open developer tools to see detailed error information
### Multiple database sync issues
When syncing to multiple databases:
- **Partial failures**: If one database fails, others will still continue syncing
- **Individual notifications**: Each database sync shows its own result notification
- **Check frontmatter**: Verify all NotionID fields are present and correct (e.g., `NotionID-blog`, `NotionID-portfolio`)
## Getting Help
If the problem persists, you can [open an issue on GitHub](https://github.com/jxpeng98/obsidian-to-NotionNext/issues) with detailed error information and the steps you took.
You can find the error logs in Obsidian by going to developer tools (`Ctrl+Shift+I` or `Cmd+Option+I`) and checking the console for any error messages related to the NotionNext plugin.
### What to include in bug reports:
1. **Error messages**: Copy the exact error message from notifications or console
2. **Console logs**: Include relevant logs from the developer console (look for `[AutoSync]`, `[Settings]`, or `[Plugin]` prefixes)
3. **Steps to reproduce**: Describe what you were doing when the issue occurred
4. **Configuration**: Mention which database format you're using (NotionNext, General, or Custom)
5. **Settings**: Note if auto sync is enabled and what delay is configured

8
docs/en/06-changelog.md Normal file
View File

@@ -0,0 +1,8 @@
---
title: Changelog
description: Release notes and updates for Obsidian to NotionNext
---
# Changelog
Welcome to the Changelog for Obsidian to NotionNext! Here you'll find a detailed list of all the updates, improvements, and bug fixes made to the plugin over time from the version `2.7.0` onwards.

10
docs/en/07-roadmap.md Normal file
View File

@@ -0,0 +1,10 @@
---
title: Roadmap
description: Planned features and improvements for Obsidian to NotionNext
---
# Roadmap
- [ ] Automatic Syncing: Implement automatic syncing of notes at regular intervals or upon changes.
- [ ] File Attachments: Support for syncing file attachments from Obsidian to Notion.
- [ ] Relation Property: Enable mapping of Obsidian links to Notion relation properties.

27
docs/en/index.md Normal file
View File

@@ -0,0 +1,27 @@
---
title: Introduction
description: Share files to any Notion database using the Notion API
order: 0
---
# Obsidian to NotionNext
In this documentation, you will find guides and instructions on how to set up and use the Obsidian to NotionNext plugin. This plugin allows you to share your Obsidian notes directly to Notion databases using the Notion API.
This guide will walk you through the process of setting up the Obsidian to NotionNext plugin.
[Getting Started](./01-getting-started.md)
[Installation](./02-installation.md)
[Configuration](./03-configuration.md)
[Syncing Notes](./04-sync.md)
[Troubleshooting](./05-troubleshooting.md)
---
[Changelog](./06-changelog.md)
[Roadmap](./07-roadmap.md)

29
docs/index.md Normal file
View File

@@ -0,0 +1,29 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: "Obsidian to NotionNext"
text: "Share files to any Notion database using the Notion API"
tagline: Support All Notion databases, including NotionNext and General Notion databases, and customise the database list.
actions:
- theme: brand
text: Get Started
link: /en/
- theme: brand
text: 现在开始
link: /zh/
- theme: alt
text: View on GitHub
link: https://github.com/jxpeng98/obsidian-to-NotionNext
features:
- title: All Notion Databases
details: Support for both general and NotionNext-specific databases.
- title: Custom Properties
details: Customize database properties to fit your workflow.
- title: Long Note Sync
details: Sync long notes seamlessly.
- title: Callout Support
details: Obsidian callouts are converted to Notion callout blocks.
---

17
docs/package.json Normal file
View File

@@ -0,0 +1,17 @@
{
"name": "obsidian-to-notionnext-docs",
"private": true,
"engines": {
"node": ">=20"
},
"scripts": {
"dev": "vitepress dev",
"build": "vitepress build",
"preview": "vitepress preview"
},
"devDependencies": {
"vitepress": "^2.0.0-alpha.12",
"vitepress-sidebar": "^1.33.0",
"vue": "^3.5.22"
}
}

1756
docs/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
---
title: 开始使用
description: Obsidian to NotionNext 插件设置指南
---
# 开始使用
## 获取 Notion API 令牌
在使用本插件前,你需要从 Notion 获取一个 API 令牌Token以授权插件访问你的 Notion 账户。
1. 前往 [Notion API](https://www.notion.so/profile/integrations) 页面来创建一个新的集成integration。你需要先登录你的 Notion 账户。
2. 点击 `+ New integration`
![new-integration](https://r2imga.jxpeng.dev/2025/10/3d12358494c000ab7035820e1e836934.png)
3. 填写一些基本信息:
![integration-info](https://r2imga.jxpeng.dev/2025/10/645b8182105e5e64e61bd263394534d6.png)
4. 成功创建集成。
![success](https://r2imga.jxpeng.dev/2025/10/57ea92c48efc15b95a69f3663424f5ae.png)
5. 进入“配置集成设置”页面,**准备好复制 API 令牌**,你很快就会在插件设置中用到它。
![configure-integration](https://r2imga.jxpeng.dev/2025/10/4a50e55c35e47f905fb7fe63af5c8402.png)
::: warning
**⚠️ 注意:** 请妥善保管你的 API 令牌,不要与他人分享,因为它授予了访问你 Notion 数据的权限。
:::
## 创建 Notion 数据库并连接集成
接下来,你需要创建一个 Notion 数据库,用于存放从 Obsidian 同步过来的笔记。
1. 在你的 Notion 工作区中,点击 `Create a new page` 来创建一个新页面。
![create-new-page](https://r2imga.jxpeng.dev/2025/10/1f092ef1d8c5a25aeb75694d654810a1.png)
2. 创建一个新页面后,选择 `Database - Full page` 选项。
![new-database](https://r2imga.jxpeng.dev/2025/10/73b700fc65a53f2ff518b58832bf9757.png)
3. 点击数据库页面右上角的 `...` 菜单,进入 `Connections`,然后连接你刚刚创建的集成。
![connect-integration](https://r2imga.jxpeng.dev/2025/10/e8d9be4718f6f5c76fdc3bee7d694d23.png)
4. 点击 `Share` -> `Publish`,将数据库发布到网络。
![publish](https://r2imga.jxpeng.dev/2025/10/4b1d3f597d67508ee67d20a62151200f.png)
5. 点击并复制 **数据库 ID**
![database-id](https://r2imga.jxpeng.dev/2025/10/d8f22c1daf5063305256e5e50210adf9.png)
接下来,你可以根据[安装指南](./02-installation.md)在 Obsidian 中安装和配置插件了。

View File

@@ -0,0 +1,28 @@
---
title: 安装插件
description: 如何安装 Obsidian to NotionNext 插件
---
# 安装插件
当你在 Notion 端完成上一章节的设置后,就可以在 Obsidian 里安装和配置插件了。
1. 打开 Obsidian 的 `设置`
![obsidian](https://r2imga.jxpeng.dev/2025/10/6f80d5126391162dd7cc98de87d3c1b2.png)
2. 找到 `第三方插件` 菜单。
![community-plugins](https://r2imga.jxpeng.dev/2025/10/adf7dd7d292dcc331d7625b8f409f222.png)
::: tip
如果你之前没有启用过第三方插件,可能需要先关闭 `安全模式`(点击 `打开社区插件`)。
:::
3. 进入 `社区插件` -> `浏览`
![browse](https://r2imga.jxpeng.dev/2025/10/e4f170f966902999fe2137196d8b6f9c.png)
4. 搜索 "NotionNext" 并点击 `安装`
![install](https://r2imga.jxpeng.dev/2025/10/1b0fcf15bc80aeb3714d9c97cbc6d5b0.png)
5. 安装完成后,记得 `启用` 插件。
![enable](https://r2imga.jxpeng.dev/2025/10/6c7a7ee7d6e5861a3f0867c826e3f2c0.png)
启用后,你就可以在插件设置列表中找到 "Share to NotionNext",并在下一步开始[配置你的数据库](./03-configuration.md)了。

112
docs/zh/03-configuration.md Normal file
View File

@@ -0,0 +1,112 @@
---
title: 配置数据库
description: 在 Obsidian to NotionNext 插件中配置 Notion 数据库的指南
---
# 配置数据库
在安装好插件并获取了 Notion API 令牌和数据库 ID 之后,你就可以开始配置要同步的数据库了。
首先,在 Obsidian 中打开插件设置。
![open-plugin-settings](https://r2imga.jxpeng.dev/2025/10/d2cfc05a86a8f014354fbd4e8456ccdc.png)
点击 “添加新数据库” 来创建一个新的数据库配置。
![add-database](https://r2img.jxpeng.dev/2024/07/115f47b4180d04fb362b931f8092b5fb.png)
插件支持三种类型的数据库配置,你可以根据自己的需求选择。
- [数据库配置](#数据库配置)
- [1⃣ 通用数据库](#1⃣-通用数据库)
- [2⃣ NotionNext 数据库](#2⃣-notionnext-数据库)
- [3⃣ 自定义数据库](#3⃣-自定义数据库)
- [完成配置](#完成配置)
## 1⃣ 通用数据库
这是最基础的数据库类型,适合大多数用户。
**配置项:**
- **数据库全名**: 给这个数据库配置起一个容易识别的名字。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
**Notion 数据库要求:**
- 必须包含一个名为 `title``Title` 属性。
- 必须包含一个名为 `tags``Multi-select` 属性。
![notion-general](https://r2imga.jxpeng.dev/2025/10/3abc05f71a1bd81bdc00fd988dd71108.png)
然后,像下面这样填写配置字段:
- **数据库全名 (Database Full Name)**: 你希望这个数据库在列表中显示的名字(例如:“学习资料库”)。
- **数据库简称 (Database Abbreviate Name)**: 一个简短的别名例如“learning”
- **同步 Notion 标签 (Notion Tags Sync)**: 如果希望将 Obsidian 的标签同步到 Notion请启用此选项**启用后,请确保你的笔记中包含 `tags`**)。
- **自定义标题属性 (Customise title property)**: 你想用作主列的 Notion 数据库属性(默认为 `title`)。
- **Notion API 令牌 (Notion API Token)**: 你在第一步中获取的 API 令牌。
- **数据库 ID (Database ID)**: 你在第二步中获取的数据库 ID。
![general](https://r2imga.jxpeng.dev/2025/10/9697de930e530c55081e07835e224782.png)
## 2⃣ NotionNext 数据库
这个类型是为 [NotionNext](https://github.com/tangly1024/NotionNext) 博客系统的用户量身定制的,其属性已预设好以匹配 NotionNext 模板。
配置方式与通用数据库类似:
- **数据库全名**: 为这个数据库配置起一个名字。
- **数据库简称**: 一个简短的别名。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
![notionnext](https://r2imga.jxpeng.dev/2025/10/5b1b3b3fb4ef9a76f4fed26fcc6c426b.png)
## 3⃣ 自定义数据库
这个类型为高级用户提供了极大的灵活性,允许你将 Obsidian 笔记中的任何 frontmatter 元数据映射到 Notion 数据库的任意属性。
首先,你需要像配置通用数据库一样填写基本信息:
- **数据库全名**: 为这个数据库配置起一个名字。
- **数据库简称**: 一个简短的别名。
- **Notion API 令牌**: 你在第一步中获取的 API 令牌。
- **数据库 ID**: 你在第二步中获取的数据库 ID。
![custom](https://r2imga.jxpeng.dev/2025/10/667335d7fd2cfa96e307be3df79e157e.png)
填写完基本配置后,你就可以开始添加新的属性映射了。
你可以点击 `Add New Property` 按钮来创建一个新的属性映射。
首先,你需要添加标题属性的映射,这是 Notion 数据库正常工作所必需的。
![title-property](https://r2imga.jxpeng.dev/2025/10/2ad52037476d3f86f3c4cfbed507f74b.png)
::: tip
请记住,"Notion 属性 (Notion Property)" 需要填写你在 Notion 数据库中的属性名称(区分大小写),而 "Frontmatter 键 (Frontmatter Key)" 则是你 Obsidian 笔记 frontmatter 中的键。
:::
添加完标题属性后,你可以根据需要继续添加更多属性。
![property-1](https://r2imga.jxpeng.dev/2025/10/d4c0bcc3abbc741dd34ce22e589d6223.png)
目前,插件支持以下 Notion 属性类型:
- Text
- Number
- Select
- Multi-select
- Date
- Files & Media
- Checkbox
- URL
- Email
- Phone Number
![types](https://r2imga.jxpeng.dev/2025/10/81d321693dfd046ad3386e4507d60792.png)
::: info
关联Relation和汇总Rollup类型暂时还不支持。
:::
## 完成配置
配置完数据库后,请确保保存你的设置。现在,你可以通过命令面板或笔记右键菜单中的 “Share to NotionNext” 命令,开始将你的 Obsidian 笔记同步到配置好的 Notion 数据库了。

96
docs/zh/04-sync.md Normal file
View File

@@ -0,0 +1,96 @@
---
title: 同步笔记
description: 如何使用 NotionNext 插件将你的 Obsidian 笔记同步到 Notion
---
# 同步笔记
在插件设置中配置好你的 Notion 数据库后,你就可以开始将 Obsidian 笔记同步到 Notion 了。
## 手动同步
要同步一篇笔记,只需打开你想要同步的笔记,然后从命令面板(`Ctrl/Cmd + P`)或笔记的右键菜单中选择 "Share to NotionNext" 命令。这会在你的 Notion 数据库中创建一个新页面,内容与你的 Obsidian 笔记完全一致。
## 自动同步
插件支持自动同步功能,可以监控你的笔记变化并自动同步到 Notion。
### 启用自动同步
1. 打开插件设置
2. 在通用设置下找到"自动同步"开关
3. 开启该开关
4. 配置"自动同步延迟时间"默认5秒最小2秒
### 自动同步工作原理
当自动同步启用后:
- 插件会监控 Markdown 文件的变化
- 在你停止编辑达到配置的延迟时间后,自动触发同步
- 只有已经同步过的文件frontmatter 中有 NotionID才会被自动同步
- 如果文件关联了多个数据库,会自动同步到所有数据库
### 自动同步场景示例
#### 场景 A新文档未同步
```yaml
---
title: 我的新文章
tags: [博客, 技术]
---
```
**行为:**
- ✅ 检测到没有 NotionID
- ✅ 显示提示:"⚠️ 自动同步跳过:此文档未同步到 Notion请先手动上传"
- ✅ 不执行同步操作
- 📝 **需要操作:** 先使用命令面板手动同步文档
#### 场景 B已同步到一个数据库
```yaml
---
title: 我的文章
NotionID-blog: abc123
---
```
**行为:**
- ✅ 检测到 1 个 NotionID
- ✅ 自动同步到 Blog 数据库
- ✅ 显示上传命令返回的成功/失败通知
- 📝 **无需操作:** 变更会自动同步
#### 场景 C同步到多个数据库
```yaml
---
title: 我的文章
NotionID-blog: abc123
NotionID-portfolio: def456
NotionID-notes: ghi789
---
```
**行为:**
- ✅ 检测到 3 个 NotionID
- ✅ 显示提示:"🔄 自动同步:正在同步到 3 个数据库..."
- ✅ 依次同步到所有 3 个数据库
- ✅ 为每个数据库显示独立的结果通知
- 📝 **无需操作:** 变更会自动同步到所有关联的数据库
### 自动同步最佳实践
1. **首次手动同步**:始终先手动执行第一次同步以建立 NotionID 链接
2. **合理配置延迟**如果你经常编辑设置较长的延迟时间5-10 秒)
3. **监控同步状态**:注意查看通知以确保同步成功完成
4. **查看日志**打开开发者控制台Ctrl+Shift+I / Cmd+Option+I查看详细的同步日志
### 故障排除
遇到自动同步问题?请查看[问题排查指南](05-troubleshooting.md)获取常见问题的详细解决方案。

View File

@@ -0,0 +1,74 @@
---
title: 问题排查
description: Obsidian to NotionNext 插件的常见问题与解决方案
---
# 问题排查
## 自动同步问题
### 自动同步不工作?
**可能的原因及解决方案:**
- **未启用自动同步**:确保在插件设置的通用设置中启用了自动同步功能
- **frontmatter 中没有 NotionID**:验证文档的 frontmatter 中有 NotionID 字段(如 `NotionID-blog: abc123`)。自动同步仅适用于至少手动同步过一次的文档
- **数据库配置无效**检查数据库配置是否有效API 凭证是否正确
- **控制台错误**:查看开发者控制台(`Ctrl+Shift+I` / `Cmd+Option+I`)中的错误信息
### 同步太频繁?
如果在编辑时自动同步触发太频繁:
- **增加延迟时间**:前往插件设置,增加"自动同步延迟时间"的值(默认为 5 秒)
- **理解延迟机制**:每次编辑都会重置延迟计时器,只有在停止编辑达到配置的时长后才会触发同步
### 看不到通知?
如果没有看到同步通知:
- **通知显示时长**:通知会显示 3-6 秒然后自动消失
- **查看控制台日志**:打开开发者控制台(`Ctrl+Shift+I` / `Cmd+Option+I`)查看详细的同步信息
- **多数据库同步**:同步到多个数据库时,你会看到一个多数据库同步通知以及各个数据库的结果通知
### 新文档跳过自动同步
如果看到消息"⚠️ 自动同步跳过:此文档未同步到 Notion请先手动上传"
- **需要首次同步**:这是预期行为。自动同步仅适用于已有 NotionID 的文档
- **解决方案**:使用命令面板(`Ctrl/Cmd + P`)选择"Share to NotionNext"执行首次手动同步
- **手动同步后**:一旦文档的 frontmatter 中有了 NotionID自动同步就会自动工作
## 常规同步问题
### 同步失败并显示错误消息
如果在同步时看到错误消息:
1. **检查 API 凭证**:验证 Notion API 令牌和数据库 ID 是否正确
2. **检查权限**:确保集成有权限访问目标数据库
3. **网络问题**:检查网络连接
4. **速率限制**Notion 有 API 速率限制,等待片刻后重试
5. **查看控制台**:打开开发者工具查看详细的错误信息
### 多数据库同步问题
同步到多个数据库时:
- **部分失败**:如果一个数据库失败,其他数据库仍会继续同步
- **独立通知**:每个数据库同步都会显示自己的结果通知
- **检查 frontmatter**:验证所有 NotionID 字段都存在且正确(如 `NotionID-blog``NotionID-portfolio`
## 获取帮助
如果问题依然存在,你可以在 GitHub 上[提交一个 Issue](https://github.com/jxpeng98/obsidian-to-NotionNext/issues),并附上详细的错误信息和你的操作步骤,我会尽快帮助你。
你也可以通过 `Ctrl+Shift+I` (Windows/Linux) 或 `Cmd+Option+I` (Mac) 打开 Obsidian 的开发者工具在控制台Console中查看是否有与 NotionNext 插件相关的错误日志,这对于定位问题非常有帮助。
### 提交 Bug 报告时应包含的信息
1. **错误消息**:复制通知或控制台中的确切错误消息
2. **控制台日志**:包含开发者控制台中的相关日志(查找 `[AutoSync]``[Settings]``[Plugin]` 前缀)
3. **重现步骤**:描述问题发生时你正在做什么
4. **配置信息**说明你使用的数据库格式NotionNext、普通或自定义
5. **设置信息**:注明是否启用了自动同步以及配置的延迟时间

6
docs/zh/06-changelog.md Normal file
View File

@@ -0,0 +1,6 @@
---
title: 更新日志
description: Obsidian to NotionNext 的版本更新与变更记录
---
欢迎来到 Obsidian to NotionNext 的更新日志!这里会记录自 `2.7.0` 版本起的所有更新、改进以及问题修复,方便你快速了解插件的演进情况。

8
docs/zh/07-roadmap.md Normal file
View File

@@ -0,0 +1,8 @@
---
title: 路线图
description: Obsidian to NotionNext 的规划功能与未来改进
---
- [ ] 自动同步:支持按时间间隔或内容变更自动同步笔记。
- [ ] 附件支持:允许将 Obsidian 笔记中的附件一同上传到 Notion。
- [ ] 关联属性:实现将 Obsidian 链接映射到 Notion 的 relation 属性。

27
docs/zh/index.md Normal file
View File

@@ -0,0 +1,27 @@
---
title: 介绍
description: 使用 Notion API 将文件分享到任何 Notion 数据库
order: 0
---
# Obsidian to NotionNext
在这份文档中,你将找到关于如何设置和使用 Obsidian to NotionNext 插件的指南和说明。这款插件可以让你使用 Notion API 将你的 Obsidian 笔记直接分享到 Notion 数据库。
本指南将引导你完成设置 Obsidian to NotionNext 插件的全过程。
[开始使用](./01-getting-started.md)
[安装插件](./02-installation.md)
[配置数据库](./03-configuration.md)
[同步笔记](./04-sync.md)
[问题排查](./05-troubleshooting.md)
---
[更新日志](./06-changelog.md)
[路线图](./07-roadmap.md)

View File

@@ -1,58 +1,60 @@
import esbuild from "esbuild";
import process from "process";
import builtins from 'builtin-modules'
import builtins from "builtin-modules";
const banner =
`/*
const banner = `/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = (process.argv[2] === 'production');
const prod = process.argv[2] === "production";
const ctx = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ['src/main.ts'],
entryPoints: ["src/main.ts"],
bundle: true,
external: [
'obsidian',
'electron',
'@codemirror/autocomplete',
'@codemirror/closebrackets',
'@codemirror/collab',
'@codemirror/commands',
'@codemirror/comment',
'@codemirror/fold',
'@codemirror/gutter',
'@codemirror/highlight',
'@codemirror/history',
'@codemirror/language',
'@codemirror/lint',
'@codemirror/matchbrackets',
'@codemirror/panel',
'@codemirror/rangeset',
'@codemirror/rectangular-selection',
'@codemirror/search',
'@codemirror/state',
'@codemirror/stream-parser',
'@codemirror/text',
'@codemirror/tooltip',
'@codemirror/view',
...builtins
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/closebrackets",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/comment",
"@codemirror/fold",
"@codemirror/gutter",
"@codemirror/highlight",
"@codemirror/history",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/matchbrackets",
"@codemirror/panel",
"@codemirror/rangeset",
"@codemirror/rectangular-selection",
"@codemirror/search",
"@codemirror/state",
"@codemirror/stream-parser",
"@codemirror/text",
"@codemirror/tooltip",
"@codemirror/view",
...builtins,
],
format: 'cjs',
target: 'es2016',
format: "cjs",
target: "es2016",
logLevel: "info",
sourcemap: prod ? false : 'inline',
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: 'main.js',
outfile: "main.js",
});
if (!prod) {
await ctx.watch();
} else {
await ctx.rebuild()
ctx.dispose().then(r => console.log('Build completed'), e => console.error(e));
await ctx.rebuild();
ctx.dispose().then(
(r) => console.log("Build completed"),
(e) => console.error(e),
);
}

View File

@@ -1,7 +1,7 @@
{
"id": "share-to-notionnext",
"name": "Share to NotionNext",
"version": "1.0.0",
"version": "2.7.0",
"minAppVersion": "0.0.1",
"description": "Shares obsidian md file to notion with notion api for NotionNext web deploy, originally created by EasyChris/obsidian-to-notion.",
"author": "EasyChris, jxpeng98",

View File

@@ -12,7 +12,7 @@ date: 2023-07-23 # default is today 默认是今天。 Format is YYYY-MM-DD
coverurl: https://img.jxpeng.dev/2023/08/843e27a210847f05a0f7cfb121fec100.jpg # default is empty 默认是空
type: Post # Post or Page, default is Post 默认是Post
slug: test # slug for url, default is empty 默认是空
stats: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
status: Draft # Draft, Invisible, Published, default is Draft 默认是Draft
category: test # default is 'Obsidian' 默认是'Obsidian'
summary: this is a summary for test post # default is empty 默认是空
icon: fa-solid fa-camera # you can ignore this, default is empty 默认是空,可直接删除

View File

@@ -1,8 +1,8 @@
{
"name": "share-to-notionnext",
"version": "1.0.0",
"version": "2.7.0",
"type": "module",
"description": "Shares obsidian md file to notion with notion api for NotionNext web deploy, originally created by EasyChris/obsidian-to-notion.",
"description": "Share files to any Notion database using the Notion API, originally created by EasyChris/obsidian-to-notion.",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
@@ -10,23 +10,22 @@
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "",
"author": "Jiaxin PENG",
"license": "GNU GPLv3",
"devDependencies": {
"@types/node": "^20.5.7",
"@types/yaml-front-matter": "^4.1.3",
"@typescript-eslint/eslint-plugin": "^6.11.0",
"@typescript-eslint/parser": "^6.11.0",
"builtin-modules": "^3.2.0",
"esbuild": "0.19.2",
"obsidian": "latest",
"@typescript-eslint/eslint-plugin": "^6.16.0",
"@typescript-eslint/parser": "^6.16.0",
"builtin-modules": "^3.3.0",
"esbuild": "0.19.5",
"obsidian": "^1.6.6",
"tslib": "2.6.2",
"typescript": "5.2.2"
},
"dependencies": {
"@tryfabric/martian": "^1.2.4",
"@jxpeng98/martian": "^1.3.1",
"https-proxy-agent": "^7.0.2",
"process": "^0.11.10",
"remark-math": "^6.0.0",
"yaml": "^2.3.4",
"yaml-front-matter": "^4.1.1"

2213
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,9 @@
import { i18nConfig } from "src/lang/I18n";
import { Editor, MarkdownView } from "obsidian";
import { Editor, MarkdownView, setTooltip } from "obsidian";
import { FuzzySuggester, DatabaseList } from "./FuzzySuggester";
import { uploadCommandGeneral, uploadCommandNext } from "../upload/uploadCommand";
import { uploadCommandCustom, uploadCommandGeneral, uploadCommandNext } from "../upload/uploadCommand";
import ObsidianSyncNotionPlugin from "src/main";
import { DatabaseDetails } from "../ui/settingTabs";
interface Command {
@@ -21,26 +22,11 @@ export default class RibbonCommands {
constructor(plugin: ObsidianSyncNotionPlugin) {
this.plugin = plugin;
// Check if NextButton is true, then include the corresponding command
if (this.plugin.settings.NextButton) {
this.Ncommand.push({
id: "share-to-notionnext",
name: i18nConfig.CommandName, // Use the translated text from i18nConfig
editorCallback: async (editor: Editor, view: MarkdownView) => {
await uploadCommandNext(this.plugin, this.plugin.settings, this.plugin.app);
}
});
}
// iterate through the database detail
// Check if GeneralButton is true, then include the corresponding command
if (this.plugin.settings.GeneralButton) {
this.Ncommand.push({
id: "share-to-notion",
name: i18nConfig.CommandNameGeneral, // Use the translated text from i18nConfig
editorCallback: async (editor: Editor, view: MarkdownView) => {
await uploadCommandGeneral(this.plugin, this.plugin.settings, this.plugin.app);
}
});
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
this.addCommandForDatabase(dbDetails);
}
// Register all the commands
@@ -77,24 +63,9 @@ export default class RibbonCommands {
this.Ncommand = [];
if (this.plugin.settings.NextButton) {
this.Ncommand.push({
id: "share-to-notionnext",
name: i18nConfig.CommandName, // Use the translated text from i18nConfig
editorCallback: async (editor: Editor, view: MarkdownView) => {
await uploadCommandNext(this.plugin, this.plugin.settings, this.plugin.app);
}
});
}
if (this.plugin.settings.GeneralButton) {
this.Ncommand.push({
id: "share-to-notion",
name: i18nConfig.CommandNameGeneral, // Use the translated text from i18nConfig
editorCallback: async (editor: Editor, view: MarkdownView) => {
await uploadCommandGeneral(this.plugin, this.plugin.settings, this.plugin.app);
}
});
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
this.addCommandForDatabase(dbDetails);
}
this.Ncommand.forEach(command => {
@@ -107,4 +78,30 @@ export default class RibbonCommands {
);
});
}
private addCommandForDatabase(dbDetails: DatabaseDetails) {
// Example logic - adjust based on your specific requirements
let commandId = `share-to-${dbDetails.abName}`;
let commandName = `Share to ${dbDetails.fullName} (${dbDetails.abName})`; // or use a translated name
let editorCallback: (editor: Editor, view: MarkdownView) => Promise<void>;
if (dbDetails.format === 'next') {
editorCallback = async (editor, view) => {
await uploadCommandNext(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
};
} else if (dbDetails.format === 'general') {
editorCallback = async (editor, view) => {
await uploadCommandGeneral(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
};
}
else if (dbDetails.format === 'custom') {
editorCallback = async (editor, view) => {
await uploadCommandCustom(this.plugin, this.plugin.settings, dbDetails, this.plugin.app);
};
}
this.Ncommand.push({ id: commandId, name: commandName, editorCallback });
}
}

View File

@@ -1,109 +1,49 @@
import {en} from "./locale/en";
import {zh} from "./locale/zh";
import {ja} from "./locale/ja";
export const I18n: {[key: string]:any} = {
en: {
ribbonIcon: "Share to NotionNext",
GeneralSetting: "General information Settings",
CommandID: "share-to-notionnext",
CommandName: "Share to NotionNext Database",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "Share to Notion General Database",
NotionNextButton: "NotionNext Sync",
NotionNextButtonDesc: "Open this option, Sync to NotionNext command will be displayed in the command palette (default: ON)",
NotionNextSettingHeader: "NotionNext Database Settings",
NotionAPI: "Notion API Token",
NotionAPIDesc: "Generate from https://www.notion.so/my-integrations",
NotionAPIText: "Enter your Notion API Token",
DatabaseID: "Database ID",
DatabaseIDText: "Enter your Database ID",
BannerUrl: "Banner url (optional)",
BannerUrlDesc:
"Default is empty, if you want to show a banner, please enter the url (like: https://minioapi.pjx.ac.cn/img1/2023/11/b7b40a0724e93b7d7ab494bb3b8a2da8.png)",
BannerUrlText: "Enter your banner url",
NotionUser: "Notion ID (username, optional)",
NotionUserDesc:
"Collect from share link likes:https://username.notion.site. Your notion id is [username]",
NotionUserText: "Enter your notion ID",
NotionGeneralSettingHeader: "General Notion Database Settings",
NotionGeneralButton: "Notion General Sync",
NotionGeneralButtonDesc: "Open this option, Sync to Notion General Database command will be displayed in the command palette (default: ON)",
NotionCustomTitle: "Customise title property",
NotionCustomTitleDesc: "Modify the column name of the Notion database (default: OFF)",
NotionCustomTitleName: "Preferred title name",
NotionCustomTitleNameDesc: "Enter the preferred title name for the first column of the Notion database (default: title)",
NotionCustomTitleText: "Enter the name",
NotYetFinish:
"Not finished. This function will be available in the next version",
PlaceHolder: "Enter database Name",
"notion-logo": "Share to NotionNext",
"sync-success": "Sync to NotionNext success: \n",
"sync-fail": "Sync to NotionNext fail: \n",
"open-notion": "Please open the file that needs to be synchronized",
"config-secrets-notion-api":
"Please set up the notion API in the settings tab.",
"config-secrets-database-id":
"Please set up the database id in the settings tab.",
"set-tags-fail":
"Set tags fail,please check the frontmatter of the file or close the tag switch in the settings tab.",
NNonMissing:
"The 'NNon' property is missing in the settings. Please set it up.",
"set-api-id":
"Please set up the notion API and database ID in the settings tab.",
NotionCustomSettingHeader: "Notion Custom Database Settings",
NotionCustomButton: "Notion Customised command switch",
NotionCustomButtonDesc: "Open this option, Sync to Notion Customised Database command will be displayed in the command palette",
},
zh: {
ribbonIcon: "分享到 NotionNext",
GeneralSetting: "通用设置",
CommandID: "share-to-notionnext",
CommandName: "分享到 NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "分享到 Notion 普通数据库",
NotionNextButton: "NotionNext 同步",
NotionNextButtonDesc: "打开此选项NotionNext 同步将显示在命令面板中(默认:开)",
NotionNextSettingHeader: "NotionNext 数据库参数设置",
NotionAPI: "Notion API 令牌",
NotionAPIDesc: "从 https://www.notion.so/my-integrations 生成",
NotionAPIText: "输入你的 Notion API 令牌",
DatabaseID: "数据库 ID",
DatabaseIDText: "输入你的数据库 ID",
BannerUrl: "封面图片地址(可选)",
BannerUrlDesc:
"默认为空如果你想显示封面图片请输入图片地址例如https://minioapi.pjx.ac.cn/img1/2023/11/b7b40a0724e93b7d7ab494bb3b8a2da8.png",
BannerUrlText: "输入你的封面图片地址",
NotionUser: "Notion ID用户名可选",
NotionUserDesc:
"数据库分享链接类似https://username.notion.site/。你的 Notion ID 是 [username]",
NotionUserText: "输入你的 Notion ID",
NotionGeneralSettingHeader: "普通 Notion 数据库设置",
NotionGeneralButton: "普通数据库同步",
NotionGeneralButtonDesc: "打开此选项,同步到普通数据库命令将显示在命令面板中(默认:开)",
NotionCustomTitle: "修改 Notion 数据库表头开关",
NotionCustomTitleDesc: "自定义Notion 数据库第一列表头名(默认:关)",
NotionCustomTitleName: "想要修改的表头名",
NotionCustomTitleNameDesc: "输入你想要修改的notion数据库的表头名默认title",
NotionCustomTitleText: "输入表头名",
NotYetFinish: "未完成。此功能将在之后版本中提供",
PlaceHolder: "输入数据库名称",
"notion-logo": "分享到NotionNext",
"sync-success": "同步到NotionNext成功:\n",
"sync-fail": "同步到NotionNext失败: \n",
"open-file": "请打开需要同步的文件",
"config-secrets-notion-api": "请在插件设置中添加notion API",
"config-secrets-database-id": "请在插件设置中添加database id",
"set-tags-fail":
"设置标签失败,请检查文件的frontmatter,或者在插件设置中关闭设置tags开关",
NNonMissing: "未设置'NNon'属性请在插件设置中选择NotionNext数据库。",
"set-api-id": "请在插件设置中设置notion API和database ID",
NotionCustomSettingHeader: "Notion 自定义数据库设置",
NotionCustomButton: "Notion 自定义数据库同步命令开关",
NotionCustomButtonDesc: "打开此选项,同步到自定义数据库命令将显示在命令面板中",
},
en,
zh,
ja,
};
export const I18nConfig = (lang: any): any => {
return I18n[lang];
};
class I18nManager {
private currentLanguage: string;
export const i18nConfig = I18nConfig(
window.localStorage.getItem("language") || "en",
); // Export i18nConfig
constructor() {
this.currentLanguage = this.detectLanguage();
}
// return the language to use
private detectLanguage(): string {
const storedLanguage = window.localStorage.getItem("language");
if (storedLanguage && this.isLanguageSupported(storedLanguage)) {
console.log(`Using stored language: ${storedLanguage}`);
return storedLanguage;
}
const browserLanguage = window.navigator.language.split("-")[0];
if (this.isLanguageSupported(browserLanguage)) {
console.log(`Using browser language: ${browserLanguage}`);
return browserLanguage;
}
// Default to English if no match is found
console.log("Using default language: en");
return "en";
}
private isLanguageSupported(lang: string): boolean {
return Object.prototype.hasOwnProperty.call(I18n, lang);
}
// Get the i18n configuration for the current language
public getConfig(): any {
return I18n[this.currentLanguage];
}
}
export const i18nManager = new I18nManager();
export const i18nConfig = i18nManager.getConfig();

114
src/lang/locale/en.ts Normal file
View File

@@ -0,0 +1,114 @@
export const en = {
databaseFormat: "Database Format",
databaseFormatDesc: "Select the database format you want to sync to NotionNext or General",
databaseNext: "NotionNext",
databaseGeneral: "General",
databaseCustom: "Custom",
databaseFullName: "Database Full Name",
databaseFullNameDesc: "Please give a full name for your database",
databaseFullNameText: "Enter your database full name",
databaseAbbreviateName: "Database Abbreviate Name",
databaseAbbreviateNameDesc: "Please give a nick name for your database",
databaseAbbreviateNameText: "Enter your database nick name",
ribbonIcon: "Share to NotionNext",
GeneralSetting: "General information Settings",
CommandID: "share-to-notionnext",
CommandName: "Share to NotionNext Database",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "Share to Notion General Database",
NotionNextButton: "NotionNext Sync",
NotionNextButtonDesc: "Open this option, Sync to NotionNext command will be displayed in the command palette (default: ON)",
NotionNextSettingHeader: "NotionNext Database Settings",
NotionAPI: "Notion API Token",
NotionAPIDesc: "Generate from https://www.notion.so/my-integrations",
NotionAPIText: "Enter your Notion API Token",
DatabaseID: "Database ID",
DatabaseIDDesc: "Collect from the top-right Share --> Publish",
DatabaseIDText: "Enter your Database ID",
BannerUrl: "Banner url (optional)",
BannerUrlDesc:
"Default is empty, if you want to show a banner, please enter the url (like: https://abc.com/b.png)",
BannerUrlText: "Enter your banner url",
NotionUser: "Notion ID (username, optional)",
NotionUserDesc:
"Collect from share link likes:https://username.notion.site. Your notion id is [username]",
NotionUserText: "Enter your notion ID",
NotionLinkDisplay: "Notion Link Display",
NotionLinkDisplayDesc: "Default is ON, if you want to hide the link in the front matter, please turn it off",
AutoSync: "Auto Sync",
AutoSyncDesc: "Automatically sync to Notion when frontmatter or content is modified (requires existing NotionID)",
AutoSyncFrontmatterKey: "Auto Sync Frontmatter Key",
AutoSyncFrontmatterKeyDesc: "Set the frontmatter property name that lists which databases should auto sync (defaults to autosync-database).",
AutoSyncDelay: "Auto Sync Delay (seconds)",
AutoSyncDelayDesc: "How many seconds to wait after document modification before triggering auto sync (default: 5 seconds, minimum: 2 seconds)",
AutoSyncDelayText: "Enter delay in seconds",
NotionGeneralSettingHeader: "General Notion Database Settings",
NotionGeneralButton: "Notion General Sync",
NotionGeneralButtonDesc: "Open this option, Sync to Notion General Database command will be displayed in the command palette (default: ON)",
NotionTagButton: "Notion Tags Sync",
NotionTagButtonDesc: "Sync Tags to Notion General Database (default: ON)",
NotionCustomTitle: "Customise title property",
NotionCustomTitleDesc: "Modify the column name of the Notion database (default: OFF)",
NotionCustomTitleName: "Preferred title name",
NotionCustomTitleNameDesc: "Enter the preferred title name for the first column of the Notion database (default: title)",
NotionCustomTitleText: "Enter the name",
NotionCustomValues: "Customise values property",
NotionCustomValuesDesc: "Modify the column name of the Notion databaseone per line",
NotionCustomValuesText: "Enter all properties that you want to sync",
NotYetFinish: "Not finished. This function will be available in the next version",
PlaceHolder: "Enter database Name",
"notion-logo": "Share to NotionNext",
"sync-preffix": "Sync to ",
"sync-success": "success",
"sync-fail": "failed",
"open-notion": "Please open the file that needs to be synchronized",
"config-secrets-notion-api":
"Please set up the notion API in the settings tab.",
"config-secrets-database-id":
"Please set up the database id in the settings tab.",
"set-tags-fail":
"Set tags fail,please check the frontmatter of the file or close the tag switch in the settings tab.",
NNonMissing:
"The 'NNon' property is missing in the settings. Please set it up.",
"set-api-id":
"Please set up the notion API and database ID in the settings tab.",
NotionCustomSettingHeader: "Notion Custom Database Settings",
NotionCustomButton: "Notion Customised command switch",
NotionCustomButtonDesc: "Open this option, Sync to Notion Customised Database command will be displayed in the command palette",
CustomPropertyName: "Property Name",
CustomPropertyFirstColumn: "Title Column",
CustomPropertyFirstColumnDesc: "The title of the page, must be the first property",
CustomProperty: "Property",
AddCustomProperty: "Add Custom Property",
AddNewProperty: "Add New Property",
AddNewPropertyDesc: "Add new property match with your notion database",
CopyErrorMessage: "Auto copy failed, please copy it manually",
BlockUploaded: "All blocks uploaded",
ExtraBlockUploaded: "Extra blocks uploaded",
CheckConsole: "Check the console for more information \n opt+cmd+i/ctrl+shift+i",
SettingsMigrated: "✨ Plugin settings updated! Auto sync feature added, check plugin settings",
AutoSyncNoNotionID: "⚠️ Auto sync skipped: This document has not been synced to Notion, please upload manually first",
AutoSyncMissingDatabaseList: "⚠️ Auto sync skipped: Add a \"{key}\" entry in the frontmatter to choose databases",
AutoSyncMultipleSync: "🔄 Auto sync: Syncing to {count} database(s)...",
AutoSyncFailed: "Auto sync to {database} failed: {error}",
AutoSyncError: "Auto sync failed for {filename}: {error}",
"reach-mobile-limit": "The number of blocks exceeds the limit of 100, please use the desktop plugin",
StartUpload: "Start upload {filename}",
AddNewDatabase: "Add New Database",
AddNewDatabaseDesc: "Add a new database configuration",
AddNewDatabaseTooltip: "Add New Database",
EditDatabase: "Edit Database",
Preview: "Preview",
DatabaseFormatLabel: "Database Format",
DatabaseFullNameLabel: "Database Full Name",
DatabaseAbbreviateNameLabel: "Database Abbreviate Name",
NotionAPILabel: "Notion API Key",
DatabaseIDLabel: "Database ID",
ToggleAPIKeyVisibility: "Toggle API Key Visibility",
CopyAPIKey: "Copy API Key",
APIKeyCopied: "API Key copied to clipboard",
ToggleDatabaseIDVisibility: "Toggle Database ID Visibility",
CopyDatabaseID: "Copy Database ID",
DatabaseIDCopied: "Database ID copied to clipboard",
AddNewDatabaseModal: "Add new database",
}

106
src/lang/locale/ja.ts Normal file
View File

@@ -0,0 +1,106 @@
export const ja = {
databaseFormat: "データベース形式",
databaseFormatDesc: "同期したいデータベース形式を選択してください",
databaseNext: "NotionNext",
databaseGeneral: "一般的なNotion",
databaseCustom: "カスタム",
databaseFullName: "データベースの全称",
databaseFullNameDesc: "データベースの全称を入力してください",
databaseFullNameText: "データベースの全称を入力",
databaseAbbreviateName: "データベースの略称",
databaseAbbreviateNameDesc: "データベースの略称を入力してください",
databaseAbbreviateNameText: "データベースの略称を入力",
ribbonIcon: "NotionNextで共有",
GeneralSetting: "一般設定",
CommandID: "share-to-notionnext",
CommandName: "NotionNextデータベースに共有",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "一般的なNotionデータベースに共有",
NotionNextButton: "NotionNext同期",
NotionNextButtonDesc: "このオプションを開くと、NotionNext同期コマンドがコマンドパレットに表示されますデフォルトON",
NotionNextSettingHeader: "NotionNextデータベース設定",
NotionAPI: "Notion API トークン",
NotionAPIDesc: "https://www.notion.so/my-integrations から生成してください",
NotionAPIText: "Notion API トークンを入力",
DatabaseID: "データベースID",
DatabaseIDDesc: "右上の共有 --> 公開から取得してください",
DatabaseIDText: "データベースIDを入力",
BannerUrl: "バナーのURL任意",
BannerUrlDesc: "デフォルトは空白です。バナーを表示したい場合は、URLを入力してくださいhttps://abc.com/b.png",
BannerUrlText: "バナーのURLを入力",
NotionUser: "Notion IDユーザー名、任意",
NotionUserDesc: "共有リンクから取得https://username.notion.site。Notion IDは[username]です",
NotionUserText: "Notion IDを入力",
NotionLinkDisplay: "Notionリンク表示",
NotionLinkDisplayDesc: "デフォルトはONです。front matterにリンクを非表示にしたい場合は、オフにしてください",
AutoSync: "自動同期",
AutoSyncDesc: "frontmatter またはコンテンツが変更されたときに自動的に Notion に同期しますNotionID が必要)",
AutoSyncFrontmatterKey: "自動同期 frontmatter キー",
AutoSyncFrontmatterKeyDesc: "自動同期するデータベースを列挙する frontmatter のプロパティ名を設定します(デフォルトは autosync-database。",
AutoSyncDelay: "自動同期遅延時間(秒)",
AutoSyncDelayDesc: "ドキュメントの変更後、自動同期をトリガーするまでの待機時間デフォルト5秒、最小2秒",
AutoSyncDelayText: "遅延秒数を入力",
NotionGeneralSettingHeader: "一般的なNotionデータベース設定",
NotionGeneralButton: "一般的なNotion同期",
NotionGeneralButtonDesc: "このオプションを開くと、一般的なNotionデータベース同期コマンドがコマンドパレットに表示されますデフォルトON",
NotionTagButton: "Notionタグ同期",
NotionTagButtonDesc: "タグを一般的なNotionデータベースに同期デフォルトON",
NotionCustomTitle: "タイトルのカスタマイズ",
NotionCustomTitleDesc: "Notionデータベースの列名を変更デフォルトOFF",
NotionCustomTitleName: "希望のタイトル名",
NotionCustomTitleNameDesc: "Notionデータベースの最初の列のための希望のタイトル名を入力デフォルトtitle",
NotionCustomTitleText: "名前を入力",
NotionCustomValues: "値のカスタマイズ",
NotionCustomValuesDesc: "Notionデータベースの列名を変更、1行に1つ",
NotionCustomValuesText: "同期したいすべてのプロパティを入力",
NotYetFinish: "未完了。この機能は次のバージョンで利用可能になります",
PlaceHolder: "データベース名を入力",
"notion-logo": "NotionNextで共有",
"sync-success": "NotionNextへの同期に成功\n",
"sync-fail": "NotionNextへの同期に失敗\n",
"open-notion": "同期が必要なファイルを開いてください",
"config-secrets-notion-api": "設定タブでNotion APIを設定してください",
"config-secrets-database-id": "設定タブでデータベースIDを設定してください",
"set-tags-fail": "タグの設定に失敗。ファイルのfrontmatterを確認するか、設定タブでタグのスイッチをオフにしてください",
NNonMissing: "設定に 'NNon' プロパティがありません。設定してください",
"set-api-id": "設定タブでNotion APIおよびデータベースIDを設定してください",
NotionCustomSettingHeader: "Notionカスタムデータベース設定",
NotionCustomButton: "Notionカスタマイズコマンドの切り替え",
NotionCustomButtonDesc: "このオプションを開くと、Notionカスタムデータベース同期コマンドがコマンドパレットに表示されます",
CustomPropertyName: "カスタムプロパティ名",
CustomPropertyFirstColumn: "最初の列のカスタムプロパティ名",
CustomPropertyFirstColumnDesc: "最初の列のカスタムプロパティ名を入力してください",
CustomProperty: "カスタムプロパティ",
AddCustomProperty: "カスタムプロパティを追加",
AddNewProperty: "新しいプロパティを追加",
AddNewPropertyDesc: "新しいプロパティを追加してください",
CopyErrorMessage: "自動コピーに失敗しました",
BlockUploaded: "ブロックがアップロードされました",
ExtraBlockUploaded: "追加ブロックがアップロードされました",
CheckConsole: "詳細情報を確認するには、コンソールを開いてください \n opt+cmd+i/ctrl+shift+i",
SettingsMigrated: "✨ プラグイン設定が更新されました!自動同期機能が追加されました。設定を確認してください",
AutoSyncNoNotionID: "⚠️ 自動同期をスキップ:このドキュメントは Notion に同期されていません。まず手動でアップロードしてください",
AutoSyncMissingDatabaseList: "⚠️ 自動同期をスキップfrontmatter に \"{key}\" 項目を追加してください",
AutoSyncMultipleSync: "🔄 自動同期:{count} 個のデータベースに同期中...",
AutoSyncFailed: "{database} への自動同期に失敗しました:{error}",
AutoSyncError: "{filename} の自動同期に失敗しました:{error}",
"reach-mobile-limit": "ブロック数が100の制限を超えています。デスクトップ版プラグインを使用してください",
StartUpload: "アップロード開始 {filename}",
AddNewDatabase: "新しいデータベースを追加",
AddNewDatabaseDesc: "新しいデータベース構成を追加",
AddNewDatabaseTooltip: "新しいデータベースを追加",
EditDatabase: "データベースを編集",
Preview: "プレビュー",
DatabaseFormatLabel: "データベース形式",
DatabaseFullNameLabel: "データベースの全称",
DatabaseAbbreviateNameLabel: "データベースの略称",
NotionAPILabel: "Notion API キー",
DatabaseIDLabel: "データベース ID",
ToggleAPIKeyVisibility: "API キーの表示を切り替え",
CopyAPIKey: "API キーをコピー",
APIKeyCopied: "API キーをクリップボードにコピーしました",
ToggleDatabaseIDVisibility: "データベース ID の表示を切り替え",
CopyDatabaseID: "データベース ID をコピー",
DatabaseIDCopied: "データベース ID をクリップボードにコピーしました",
AddNewDatabaseModal: "新しいデータベースを追加",
};

108
src/lang/locale/zh.ts Normal file
View File

@@ -0,0 +1,108 @@
export const zh = {
databaseFormat: "数据库格式",
databaseFormatDesc: "选择你想要同步的数据库格式Next 或者 普通",
databaseNext: "NotionNext",
databaseGeneral: "普通",
databaseCustom: "自定义",
databaseFullName: "数据库全称",
databaseFullNameDesc: "给你的数据库起一个全称",
databaseFullNameText: "输入你的数据库全称",
databaseAbbreviateName: "数据库简称",
databaseAbbreviateNameDesc: "给你的数据库起一个简称",
databaseAbbreviateNameText: "输入你的数据库简称",
ribbonIcon: "分享到 NotionNext",
GeneralSetting: "通用设置",
CommandID: "share-to-notionnext",
CommandName: "分享到 NotionNext",
CommandIDGeneral: "share-to-notion",
CommandNameGeneral: "分享到 Notion 普通数据库",
NotionNextButton: "NotionNext 同步",
NotionNextButtonDesc: "打开此选项NotionNext 同步将显示在命令面板中(默认:开)",
NotionNextSettingHeader: "NotionNext 数据库参数设置",
NotionAPI: "Notion API 令牌",
NotionAPIDesc: "从 https://www.notion.so/my-integrations 生成",
NotionAPIText: "输入你的 Notion API 令牌",
DatabaseID: "数据库 ID",
DatabaseIDDesc: "从右上角的分享 --> 发布中获取",
DatabaseIDText: "输入你的数据库 ID",
BannerUrl: "封面图片地址(可选)",
BannerUrlDesc:
"默认为空如果你想显示封面图片请输入图片地址例如https://abc.com/b.png",
BannerUrlText: "输入你的封面图片地址",
NotionUser: "Notion ID用户名可选",
NotionUserDesc:
"数据库分享链接类似https://username.notion.site/。你的 Notion ID 是 [username]",
NotionUserText: "输入你的 Notion ID",
NotionLinkDisplay: "Notion 链接显示",
NotionLinkDisplayDesc: "默认开启如果你不想在front matter中显示链接请关闭",
AutoSync: "自动同步",
AutoSyncDesc: "当检测到文档的 frontmatter 或内容发生修改时,自动同步到 Notion需要文档已有 NotionID",
AutoSyncFrontmatterKey: "自动同步 Frontmatter 键名",
AutoSyncFrontmatterKeyDesc: "设置用于列出自动同步数据库的 frontmatter 属性名称(默认 autosync-database。",
AutoSyncDelay: "自动同步延迟时间(秒)",
AutoSyncDelayDesc: "文档修改后等待多少秒才触发自动同步避免频繁同步默认5秒最小2秒",
AutoSyncDelayText: "输入延迟秒数",
NotionGeneralSettingHeader: "普通 Notion 数据库设置",
NotionGeneralButton: "普通数据库同步",
NotionGeneralButtonDesc: "打开此选项,同步到普通数据库命令将显示在命令面板中(默认:开)",
NotionTagButton: "标签同步开关",
NotionTagButtonDesc: "将标签同步到普通数据库(默认:开)",
NotionCustomTitle: "修改 Notion 数据库表头开关",
NotionCustomTitleDesc: "自定义Notion 数据库第一列表头名(默认:关)",
NotionCustomTitleName: "想要修改的表头名",
NotionCustomTitleNameDesc: "输入你想要修改的notion数据库的表头名默认title",
NotionCustomTitleText: "输入表头名",
NotionCustomValues: "自定义Notion 数据库表头",
NotionCustomValuesDesc: "自定义Notion 数据库表头,每行一个",
NotionCustomValuesText: "输入你想要同步的所有属性",
NotYetFinish: "未完成。此功能将在之后版本中提供",
PlaceHolder: "输入数据库名称",
"notion-logo": "分享到NotionNext",
"sync-success": "同步到NotionNext成功:\n",
"sync-fail": "同步到NotionNext失败: \n",
"open-file": "请打开需要同步的文件",
"config-secrets-notion-api": "请在插件设置中添加notion API",
"config-secrets-database-id": "请在插件设置中添加database id",
"set-tags-fail":
"设置标签失败,请检查文件的frontmatter,或者在插件设置中关闭设置tags开关",
NNonMissing: "未设置'NNon'属性请在插件设置中选择NotionNext数据库。",
"set-api-id": "请在插件设置中设置notion API和database ID",
NotionCustomSettingHeader: "Notion 自定义数据库设置",
NotionCustomButton: "Notion 自定义数据库同步命令开关",
NotionCustomButtonDesc: "打开此选项,同步到自定义数据库命令将显示在命令面板中",
CustomPropertyName: "自定义属性名",
CustomPropertyFirstColumn: "第一列属性名",
CustomPropertyFirstColumnDesc: "第一列必须为标题属性名",
CustomProperty: "自定义属性",
AddCustomProperty: "添加自定义属性",
AddNewProperty: "添加新属性",
AddNewPropertyDesc: "添加一个和Notion数据库匹配的新属性",
CopyErrorMessage: "复制链接失败,请手动复制",
BlockUploaded: "所有内容已成功上传",
ExtraBlockUploaded: "额外内容已成功上传",
CheckConsole: "opt+cmd+i/ctrl+shift+i\n打开控制台查看更多信息",
SettingsMigrated: "✨ 插件设置已更新!新增自动同步功能,请在设置中查看",
AutoSyncNoNotionID: "⚠️ 自动同步跳过:此文档未同步到 Notion请先手动上传",
AutoSyncMissingDatabaseList: "⚠️ 自动同步跳过:请在 frontmatter 中添加 \"{key}\" 项来指定数据库",
AutoSyncMultipleSync: "🔄 自动同步:正在同步到 {count} 个数据库...",
AutoSyncFailed: "自动同步到 {database} 失败:{error}",
AutoSyncError: "自动同步 {filename} 失败:{error}",
StartUpload: "开始上传 {filename}",
AddNewDatabase: "添加新数据库",
AddNewDatabaseDesc: "添加新的数据库配置",
AddNewDatabaseTooltip: "添加新数据库",
EditDatabase: "编辑数据库",
Preview: "预览",
DatabaseFormatLabel: "数据库格式",
DatabaseFullNameLabel: "数据库全称",
DatabaseAbbreviateNameLabel: "数据库简称",
NotionAPILabel: "Notion API 密钥",
DatabaseIDLabel: "数据库 ID",
ToggleAPIKeyVisibility: "切换 API 密钥可见性",
CopyAPIKey: "复制 API 密钥",
APIKeyCopied: "API 密钥已复制到剪贴板",
ToggleDatabaseIDVisibility: "切换数据库 ID 可见性",
CopyDatabaseID: "复制数据库 ID",
DatabaseIDCopied: "数据库 ID 已复制到剪贴板",
AddNewDatabaseModal: "添加新数据库",
}

View File

@@ -1,10 +1,10 @@
import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting } from "obsidian";
import { App, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TFile, EventRef } from "obsidian";
import { addIcons } from 'src/ui/icon';
import { Upload2NotionGeneral } from "src/upload/upload_general/Upload2NotionGeneral";
import { Upload2NotionNext } from "src/upload/upload_next/Upload2NotionNext";
import { i18nConfig } from "src/lang/I18n";
import ribbonCommands from "src/commands/NotionCommands";
import { ObsidianSettingTab, PluginSettings, DEFAULT_SETTINGS } from "src/ui/settingTabs";
import { ObsidianSettingTab, PluginSettings, DEFAULT_SETTINGS, DatabaseDetails } from "src/ui/settingTabs";
import { uploadCommandNext, uploadCommandGeneral, uploadCommandCustom } from "src/upload/uploadCommand";
import { DEFAULT_AUTO_SYNC_DATABASE_KEY, parseAutoSyncDatabaseList, resolveAutoSyncKey } from "src/utils/frontmatter";
// Remember to rename these classes and interfaces!
@@ -13,14 +13,31 @@ export default class ObsidianSyncNotionPlugin extends Plugin {
settings: PluginSettings;
commands: ribbonCommands;
app: App;
modifyEventRef: EventRef | null = null;
autoSyncTimeout: number | null = null;
private syncingFiles: Set<string> = new Set();
private lastFrontmatterCache: Map<string, any> = new Map();
private lastContentHashCache: Map<string, string> = new Map();
private missingAutoSyncNoticeShown: Set<string> = new Set();
async onload() {
await this.loadSettings();
// Log loaded settings for debugging
console.log('[Plugin] Loaded settings:', {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
bannerUrl: this.settings.bannerUrl ? 'set' : 'empty',
notionUser: this.settings.notionUser ? 'set' : 'empty',
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
this.commands = new ribbonCommands(this);
addIcons();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon(
this.addRibbonIcon(
"notion-logo",
i18nConfig.ribbonIcon,
async (evt: MouseEvent) => {
@@ -38,25 +55,405 @@ export default class ObsidianSyncNotionPlugin extends Plugin {
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new ObsidianSettingTab(this.app, this));
// Setup auto sync listener
this.setupAutoSync();
}
onunload() {
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
this.lastFrontmatterCache.clear();
this.lastContentHashCache.clear();
this.missingAutoSyncNoticeShown.clear();
}
async loadSettings() {
const loadedData = await this.loadData();
// Merge loaded data with defaults, ensuring all fields exist
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
loadedData || {}
);
// Ensure critical fields have valid values
if (typeof this.settings.autoSync !== 'boolean') {
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== 'number' || this.settings.autoSyncDelay < 2) {
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.NotionLinkDisplay !== 'boolean') {
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (typeof this.settings.autoSyncFrontmatterKey !== 'string') {
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
// Ensure databaseDetails exists
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== 'object') {
this.settings.databaseDetails = {};
}
// Save settings if any migration was needed
const needsSave = !loadedData ||
loadedData.autoSync === undefined ||
loadedData.autoSyncDelay === undefined ||
loadedData.NotionLinkDisplay === undefined ||
loadedData.autoSyncFrontmatterKey === undefined;
if (needsSave) {
const migratedFields = [];
if (!loadedData) {
console.log('[Settings] First-time setup, creating default settings');
} else {
if (loadedData.autoSync === undefined) migratedFields.push('autoSync');
if (loadedData.autoSyncDelay === undefined) migratedFields.push('autoSyncDelay');
if (loadedData.NotionLinkDisplay === undefined) migratedFields.push('NotionLinkDisplay');
console.log('[Settings] Migrating settings, adding fields:', migratedFields.join(', '));
}
await this.saveSettings();
// Notify user about settings migration (only for existing users, not first-time setup)
if (loadedData && Object.keys(loadedData).length > 0 && migratedFields.length > 0) {
new Notice(i18nConfig.SettingsMigrated, 6000);
console.log('[Settings] Migration notice shown to user');
}
}
}
async saveSettings() {
// Validate settings before saving
this.validateSettings();
await this.saveData(this.settings);
console.log('[Settings] Settings saved successfully', {
autoSync: this.settings.autoSync,
autoSyncDelay: this.settings.autoSyncDelay,
NotionLinkDisplay: this.settings.NotionLinkDisplay,
autoSyncFrontmatterKey: this.settings.autoSyncFrontmatterKey,
databaseCount: Object.keys(this.settings.databaseDetails || {}).length
});
}
validateSettings() {
// Ensure all required fields have valid values
if (typeof this.settings.autoSync !== 'boolean') {
console.warn('[Settings] Invalid autoSync value, resetting to default');
this.settings.autoSync = DEFAULT_SETTINGS.autoSync;
}
if (typeof this.settings.autoSyncDelay !== 'number' || this.settings.autoSyncDelay < 2) {
console.warn('[Settings] Invalid autoSyncDelay value, resetting to default');
this.settings.autoSyncDelay = DEFAULT_SETTINGS.autoSyncDelay;
}
if (typeof this.settings.NotionLinkDisplay !== 'boolean') {
console.warn('[Settings] Invalid NotionLinkDisplay value, resetting to default');
this.settings.NotionLinkDisplay = DEFAULT_SETTINGS.NotionLinkDisplay;
}
if (!this.settings.databaseDetails || typeof this.settings.databaseDetails !== 'object') {
console.warn('[Settings] Invalid databaseDetails, resetting to empty object');
this.settings.databaseDetails = {};
}
if (typeof this.settings.autoSyncFrontmatterKey !== 'string' || this.settings.autoSyncFrontmatterKey.trim().length === 0) {
console.warn('[Settings] Invalid autoSyncFrontmatterKey, resetting to default');
this.settings.autoSyncFrontmatterKey = DEFAULT_AUTO_SYNC_DATABASE_KEY;
} else {
this.settings.autoSyncFrontmatterKey = resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
}
resetAutoSyncNoticeCache() {
this.missingAutoSyncNoticeShown.clear();
}
getAutoSyncFrontmatterKey(): string {
return resolveAutoSyncKey(this.settings.autoSyncFrontmatterKey);
}
async addDatabaseDetails(dbDetails: DatabaseDetails) {
this.settings.databaseDetails = {
...this.settings.databaseDetails,
[dbDetails.abName]: dbDetails,
};
await this.saveSettings();
}
async deleteDatabaseDetails(dbDetails: DatabaseDetails) {
delete this.settings.databaseDetails[dbDetails.abName];
await this.saveSettings();
}
async updateDatabaseDetails(dbDetails: DatabaseDetails) {
// delete the old database details
delete this.settings.databaseDetails[dbDetails.abName];
this.settings.databaseDetails = {
...this.settings.databaseDetails,
[dbDetails.abName]: dbDetails,
};
await this.saveSettings();
}
setupAutoSync() {
// Remove existing listener if any
if (this.modifyEventRef) {
this.app.vault.offref(this.modifyEventRef);
}
// Only setup if autoSync is enabled
if (!this.settings.autoSync) {
return;
}
// Listen for file modifications
this.modifyEventRef = this.app.vault.on('modify', async (file: TFile) => {
// Only process markdown files
if (!(file instanceof TFile) || file.extension !== 'md') {
return;
}
// Debounce: clear existing timeout
if (this.autoSyncTimeout) {
clearTimeout(this.autoSyncTimeout);
}
// Set a new timeout to trigger sync after user-configured delay (in seconds)
const delayMs = (this.settings.autoSyncDelay || 2) * 1000;
this.autoSyncTimeout = window.setTimeout(async () => {
await this.autoSyncFile(file);
}, delayMs);
});
}
onlyNotionIDChanged(oldFrontmatter: any, newFrontmatter: any): boolean {
// Get all keys from both frontmatters
const oldKeys = Object.keys(oldFrontmatter || {});
const newKeys = Object.keys(newFrontmatter || {});
// Filter out NotionID-related keys and Obsidian internal keys
const isIgnoredKey = (key: string) => {
return key.startsWith('NotionID-') ||
key === 'NotionID' ||
key === 'position'; // Obsidian's internal metadata
};
const oldNonNotionKeys = oldKeys.filter(k => !isIgnoredKey(k)).sort();
const newNonNotionKeys = newKeys.filter(k => !isIgnoredKey(k)).sort();
// If number of non-NotionID keys changed, something else changed
if (oldNonNotionKeys.length !== newNonNotionKeys.length) {
console.log('[AutoSync] Frontmatter: Key count changed:', oldNonNotionKeys.length, '->', newNonNotionKeys.length);
return false;
}
// Check if any non-NotionID key values changed
for (const key of oldNonNotionKeys) {
if (!newNonNotionKeys.includes(key)) {
console.log('[AutoSync] Frontmatter: Key removed or added:', key);
return false; // Key was removed or added
}
// Deep comparison for the value
const oldValue = JSON.stringify(oldFrontmatter[key]);
const newValue = JSON.stringify(newFrontmatter[key]);
if (oldValue !== newValue) {
console.log('[AutoSync] Frontmatter: Value changed for key "' + key + '"');
console.log(' Old:', oldValue.substring(0, 100));
console.log(' New:', newValue.substring(0, 100));
return false; // Value changed
}
}
// Check if any new non-NotionID keys were added
for (const key of newNonNotionKeys) {
if (!oldNonNotionKeys.includes(key)) {
console.log('[AutoSync] Frontmatter: New key added:', key);
return false; // New key was added
}
}
// Only NotionID fields changed (or nothing in frontmatter changed)
return true;
}
simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash.toString();
}
async autoSyncFile(file: TFile) {
// Check if file is already being synced
if (this.syncingFiles.has(file.path)) {
console.log(`[AutoSync] File ${file.path} is already being synced, skipping`);
return;
}
try {
this.syncingFiles.add(file.path);
// Get file's frontmatter
const frontMatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
if (!frontMatter) {
console.log(`[AutoSync] No frontmatter found in ${file.path}`);
return;
}
// Get file content hash for comparison
const content = await this.app.vault.read(file);
const contentHash = this.simpleHash(content);
const lastContentHash = this.lastContentHashCache.get(file.path);
// Check if only NotionID fields changed (to avoid sync loops)
const lastFrontmatter = this.lastFrontmatterCache.get(file.path);
if (lastFrontmatter && lastContentHash) {
const frontmatterOnlyNotionIDChanged = this.onlyNotionIDChanged(lastFrontmatter, frontMatter);
const contentUnchanged = contentHash === lastContentHash;
console.log(`[AutoSync] Change analysis for ${file.basename}:`, {
frontmatterOnlyNotionIDChanged,
contentUnchanged,
frontmatterHasRealChanges: !frontmatterOnlyNotionIDChanged,
contentChanged: !contentUnchanged,
willSync: !(frontmatterOnlyNotionIDChanged && contentUnchanged)
});
// Only skip sync if BOTH conditions are true:
// 1. Frontmatter only has NotionID changes (no real user changes)
// 2. Content is completely unchanged
if (frontmatterOnlyNotionIDChanged && contentUnchanged) {
console.log(`[AutoSync] Only NotionID updated (from sync), content unchanged - skipping auto sync`);
// Update cache even when skipping, so next comparison uses the current state
this.lastFrontmatterCache.set(file.path, { ...frontMatter });
this.lastContentHashCache.set(file.path, contentHash);
return;
}
if (!contentUnchanged) {
console.log(`[AutoSync] Content changed - will sync`);
} else if (!frontmatterOnlyNotionIDChanged) {
console.log(`[AutoSync] Frontmatter changed - will sync`);
}
}
const autoSyncKey = this.getAutoSyncFrontmatterKey();
const autoSyncTargets = parseAutoSyncDatabaseList(frontMatter[autoSyncKey]);
if (autoSyncTargets.length === 0) {
if (!this.missingAutoSyncNoticeShown.has(file.path)) {
const message = i18nConfig.AutoSyncMissingDatabaseList.replace('{key}', autoSyncKey);
new Notice(message, 10000);
this.missingAutoSyncNoticeShown.add(file.path);
}
console.log(`[AutoSync] No auto sync database list found in ${file.path} using key "${autoSyncKey}"`);
return;
}
this.missingAutoSyncNoticeShown.delete(file.path);
const dbByShortName = new Map<string, DatabaseDetails>();
for (const key in this.settings.databaseDetails) {
const dbDetails = this.settings.databaseDetails[key];
dbByShortName.set(dbDetails.abName.toLowerCase(), dbDetails);
}
const foundDatabases: Array<{ dbDetails: DatabaseDetails, notionId: string }> = [];
const unresolvedTargets: string[] = [];
for (const target of autoSyncTargets) {
const lookupKey = target.toLowerCase();
const dbDetails = dbByShortName.get(lookupKey);
if (!dbDetails) {
unresolvedTargets.push(target);
continue;
}
const notionIDKey = `NotionID-${dbDetails.abName}`;
if (frontMatter[notionIDKey]) {
foundDatabases.push({
dbDetails,
notionId: String(frontMatter[notionIDKey])
});
}
}
if (unresolvedTargets.length > 0) {
console.log(`[AutoSync] Frontmatter auto sync targets not found in settings: ${unresolvedTargets.join(", ")}`);
}
// If no NotionID found, notify user to upload manually first
if (foundDatabases.length === 0) {
console.log(`[AutoSync] No NotionID found in ${file.path}, skipping auto sync`);
new Notice(i18nConfig.AutoSyncNoNotionID, 4000);
return;
}
// Notify user about multiple syncs if applicable
if (foundDatabases.length > 1) {
const message = i18nConfig.AutoSyncMultipleSync.replace('{count}', String(foundDatabases.length));
new Notice(message, 3000);
console.log(`[AutoSync] Found ${foundDatabases.length} NotionIDs in ${file.path}`);
}
// Sync to all found databases
for (const { dbDetails, notionId } of foundDatabases) {
console.log(`[AutoSync] ${new Date().toISOString()} Auto syncing ${file.basename} to ${dbDetails.fullName} (${dbDetails.abName})`);
try {
// Trigger appropriate upload command based on database format
if (dbDetails.format === 'next') {
await uploadCommandNext(this, this.settings, dbDetails, this.app);
} else if (dbDetails.format === 'general') {
await uploadCommandGeneral(this, this.settings, dbDetails, this.app);
} else if (dbDetails.format === 'custom') {
await uploadCommandCustom(this, this.settings, dbDetails, this.app);
}
} catch (error) {
console.error(`[AutoSync] Error syncing to ${dbDetails.fullName}:`, error);
const message = i18nConfig.AutoSyncFailed
.replace('{database}', dbDetails.fullName)
.replace('{error}', error.message);
new Notice(message, 5000);
}
}
// After sync completes, update cache with the latest frontmatter (including updated NotionIDs)
// Wait a bit for metadata cache to update
window.setTimeout(async () => {
const updatedFrontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
const updatedContent = await this.app.vault.read(file);
const updatedHash = this.simpleHash(updatedContent);
if (updatedFrontmatter) {
this.lastFrontmatterCache.set(file.path, { ...updatedFrontmatter });
this.lastContentHashCache.set(file.path, updatedHash);
console.log(`[AutoSync] Cached updated frontmatter and content hash for ${file.path}`);
}
}, 500);
} catch (error) {
console.error(`[AutoSync] Error syncing file ${file.path}:`, error);
const message = i18nConfig.AutoSyncError
.replace('{filename}', file.basename)
.replace('{error}', error.message);
new Notice(message);
} finally {
this.syncingFiles.delete(file.path);
}
}
}

64
src/ui/DeleteModal.ts Normal file
View File

@@ -0,0 +1,64 @@
import { App, ButtonComponent, Modal, Setting } from "obsidian";
import { DatabaseDetails, ObsidianSettingTab } from "./settingTabs";
import ObsidianSyncNotionPlugin from "../main";
export class DeleteModal extends Modal {
data: Record<string, any> = {
deleted: false,
}
plugin: ObsidianSyncNotionPlugin;
settingTab: ObsidianSettingTab;
dbDetails: DatabaseDetails
constructor(app: App, plugin: ObsidianSyncNotionPlugin, settingTab: ObsidianSettingTab, dbDetails: DatabaseDetails) {
super(app);
this.plugin = plugin;
this.settingTab = settingTab;
this.dbDetails = dbDetails;
}
display() {
this.containerEl.addClass("delete-modal");
this.titleEl.setText('Delete Database');
let { contentEl } = this;
contentEl.empty();
const deleteDiv = contentEl.createDiv('delete-div');
deleteDiv.createEl('h4', { text: 'Are you sure you want to delete the following database?' });
deleteDiv.createEl('h2', { text: this.dbDetails.fullName + ' (' + this.dbDetails.abName + ', ' + this.dbDetails.format + ')' });
// add delete button
let footerEl = contentEl.createDiv('save-button');
let deleteButton = new Setting(footerEl)
deleteButton
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip("Delete")
.setIcon("trash")
.onClick(async () => {
this.data.deleted = true;
this.close();
})
});
deleteButton.addExtraButton((button) => {
return button
.setTooltip('Cancel')
.setIcon('cross')
.onClick(() => {
this.data.deleted = false;
this.close();
});
});
}
onOpen() {
this.display();
}
}

349
src/ui/EditModal.ts Normal file
View File

@@ -0,0 +1,349 @@
import { App, ButtonComponent, Setting } from "obsidian";
import { customProperty, SettingModal } from "./settingModal";
import ObsidianSyncNotionPlugin from "../main";
import { DatabaseDetails, ObsidianSettingTab } from "./settingTabs";
import { i18nConfig } from "../lang/I18n";
export class EditModal extends SettingModal {
propertyLines: Setting[] = []; // Store all property line settings
[key: string]: any; // Index signature
dataTemp: Record<string, any> = {
databaseFormatTemp: '',
// databaseFormatTempInd: false,
databaseFullNameTemp: '',
// databaseFullNameTempInd: false,
databaseAbbreviateNameTemp: '',
// databaseAbbreviateNameTempInd: false,
notionAPITemp: '',
// notionAPITempInd: false,
databaseIDTemp: '',
// databaseIDTempInd: false,
tagButtonTemp: false,
// tagButtonTempInd: false,
customTitleButtonTemp: false,
// customTitleButtonTempInd: false,
customTitleNameTemp: '',
customPropertiesTemp: [],
// customTitleNameTempInd: false,
// customValues: '',
savedTemp: false,
savedTempInd: false,
};
dataPrev: Record<string, any> = {
databaseFormatPrev: '',
// databaseFormatPrevInd: false,
databaseFullNamePrev: '',
// databaseFullNamePrevInd: false,
databaseAbbreviateNamePrev: '',
// databaseAbbreviateNamePrevInd: false,
notionAPIPrev: '',
// notionAPIPrevInd: false,
databaseIDPrev: '',
// databaseIDPrevInd: false,
tagButtonPrev: false,
// tagButtonPrevInd: false,
customTitleButtonPrev: false,
// customTitleButtonPrevInd: false,
customTitleNamePrev: '',
customPropertiesPrev: [],
// customTitleNamePrevInd: false,
// customValues: '',
savedPrev: false,
savedPrevInd: false,
};
plugin: ObsidianSyncNotionPlugin;
settingTab: ObsidianSettingTab;
dbDetails: DatabaseDetails;
constructor(app: App, plugin: ObsidianSyncNotionPlugin, settingTab: ObsidianSettingTab, dbDetails: DatabaseDetails) {
super(app, plugin, settingTab);
this.plugin = plugin;
this.settingTab = settingTab;
if (dbDetails) {
// Temp details
this.dataTemp.databaseFormatTemp = dbDetails.format;
this.dataTemp.databaseFullNameTemp = dbDetails.fullName;
this.dataTemp.databaseAbbreviateNameTemp = dbDetails.abName;
this.dataTemp.notionAPITemp = dbDetails.notionAPI;
this.dataTemp.databaseIDTemp = dbDetails.databaseID;
this.dataTemp.tagButtonTemp = dbDetails.tagButton;
this.dataTemp.customTitleButtonTemp = dbDetails.customTitleButton;
this.dataTemp.customTitleNameTemp = dbDetails.customTitleName;
this.dataTemp.customPropertiesTemp = dbDetails.customProperties.map(prop => ({ ...prop })); // Ensure deep copy
// this.dataTemp.customValues = dbDetails.customValues;
this.dataTemp.savedTemp = dbDetails.saved;
// Prev details
this.dataPrev.databaseFormatPrev = dbDetails.format;
this.dataPrev.databaseFullNamePrev = dbDetails.fullName;
this.dataPrev.databaseAbbreviateNamePrev = dbDetails.abName;
this.dataPrev.notionAPIPrev = dbDetails.notionAPI;
this.dataPrev.databaseIDPrev = dbDetails.databaseID;
this.dataPrev.tagButtonPrev = dbDetails.tagButton;
this.dataPrev.customTitleButtonPrev = dbDetails.customTitleButton;
this.dataPrev.customTitleNamePrev = dbDetails.customTitleName;
this.dataPrev.customPropertiesPrev = dbDetails.customProperties.map(prop => ({ ...prop })); // Ensure deep copy
// this.dataTemp.customValues = dbDetails.customValues;
this.dataPrev.savedPrev = dbDetails.saved;
}
}
display(): void {
this.containerEl.addClass("edit-modal");
this.titleEl.setText(i18nConfig.EditDatabase);
let { contentEl } = this;
contentEl.empty();
const editDiv = contentEl.createDiv('edit-div');
const nextTabs = contentEl.createDiv('next-tabs');
new Setting(editDiv)
.setName(i18nConfig.databaseFormat)
.setDesc(i18nConfig.databaseFormatDesc)
.addDropdown((component) => {
component
.addOption('none', '')
.addOption('general', i18nConfig.databaseGeneral)
.addOption('next', i18nConfig.databaseNext)
.addOption('custom', i18nConfig.databaseCustom)
.setValue(this.dataTemp.databaseFormatTemp)
.onChange(async (value) => {
this.dataTemp.databaseFormatTemp = value;
nextTabs.empty();
this.updateContentBasedOnSelection(value, nextTabs);
});
// Initialize content based on the current dropdown value
this.updateContentBasedOnSelection(this.dataTemp.databaseFormatTemp, nextTabs);
});
// add save button
let footerEl = contentEl.createDiv('save-button');
let saveButton = new Setting(footerEl)
saveButton.addButton((button: ButtonComponent) => {
return button
.setTooltip('Save')
.setIcon('checkmark')
.onClick(async () => {
this.dataTemp.savedTempInd = true;
this.dataTemp.savedTemp = true;
// console.log(this.dataTemp);
// console.log(this.dataPrev);
this.close();
});
}
);
saveButton.addExtraButton((button) => {
return button
.setTooltip('Cancel')
.setIcon('cross')
.onClick(() => {
// console.log(this.dataTemp);
// console.log(this.dataPrev);
this.close();
});
}
);
}
onOpen(): void {
this.display()
}
updateContentBasedOnSelection(value: string, nextTabs: HTMLElement): void {
// Clear existing content
nextTabs.empty();
// Generate content based on the selected value
if (value === 'general') {
nextTabs.createEl('h3', { text: i18nConfig.NotionGeneralSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, 'dataTemp', 'databaseFullNameTemp')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, 'dataTemp', 'databaseAbbreviateNameTemp')
// tag button
this.createSettingEl(nextTabs, i18nConfig.NotionTagButton, i18nConfig.NotionTagButtonDesc, 'toggle', i18nConfig.NotionCustomTitleText, this.dataTemp.tagButtonTemp, 'dataTemp', 'tagButtonTemp')
// add custom title button
new Setting(nextTabs)
.setName(i18nConfig.NotionCustomTitle)
.setDesc(i18nConfig.NotionCustomTitleDesc)
.addToggle((toggle) =>
toggle
.setValue(this.dataTemp.customTitleButtonTemp)
.onChange(async (value) => {
this.dataTemp.customTitleButtonTemp = value;
this.updateSettingEl(CustomNameEl, value)
})
);
// add custom title name
const CustomNameEl = this.createStyleDiv('custom-name', (this.dataTemp.customTitleButtonTemp), nextTabs);
this.createSettingEl(CustomNameEl, i18nConfig.NotionCustomTitleName, i18nConfig.NotionCustomTitleNameDesc, 'text', i18nConfig.NotionCustomTitleText, this.dataTemp.customTitleNameTemp, 'dataTemp', 'customTitleNameTemp')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, 'dataTemp', 'notionAPITemp')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, 'dataTemp', 'databaseIDTemp')
} else if (value === 'next') {
nextTabs.createEl('h3', { text: i18nConfig.NotionNextSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, 'dataTemp', 'databaseFullNameTemp')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, 'dataTemp', 'databaseAbbreviateNameTemp')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, 'dataTemp', 'notionAPITemp')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, 'dataTemp', 'databaseIDTemp')
} else if (value === 'custom') {
nextTabs.createEl('h3', { text: i18nConfig.NotionCustomSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.dataTemp.databaseFullNameTemp, 'dataTemp', 'databaseFullNameTemp')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.dataTemp.databaseAbbreviateNameTemp, 'dataTemp', 'databaseAbbreviateNameTemp')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.dataTemp.notionAPITemp, 'dataTemp', 'notionAPITemp')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.dataTemp.databaseIDTemp, 'dataTemp', 'databaseIDTemp')
// add custom properties
this.initializePropertyLines(nextTabs, this.dataTemp.customPropertiesTemp);
}
}
initializePropertyLines(containerEl: HTMLElement, properties: customProperty[]): void {
if (!containerEl) {
console.error('Failed to initialize property lines: containerEl is null');
return;
}
new Setting(containerEl)
.setName(i18nConfig.AddNewProperty)
.setDesc(i18nConfig.AddNewPropertyDesc)
.addButton(button => {
return button
.setButtonText('Add')
.setTooltip('Add one more property')
.onClick(() => {
this.createPropertyLine(containerEl, properties);
});
});
properties.forEach(property => {
this.updatePropertyLine(containerEl, property, properties);
});
}
updatePropertyLine(containerEl: HTMLElement, property: customProperty, properties: customProperty[]) {
let isExistingProperty = property !== null;
const propertyIndex = isExistingProperty ? property.index : properties.length;
const propertyLine = new Setting(containerEl)
.setName(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${propertyIndex}`)
.setDesc(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText(text => {
text.setPlaceholder(i18nConfig.CustomPropertyName)
.setValue(isExistingProperty ? property.customName : "")
.onChange(value => {
const actualIndex = properties.findIndex(p => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customName = value;
} else {
properties.push({ customName: value, customType: '', index: propertyIndex });
isExistingProperty = true;
}
});
});
propertyLine.addDropdown((dropdown) => {
const options: Record<string, string> = {
'rich_text': 'Text',
'number': 'Number',
'select': 'Select',
'multi_select': 'Multi-Select',
'date': 'Date',
'files': 'Files & Media',
'checkbox': 'Checkbox',
'url': 'URL',
'email': 'Email',
'phone_number': 'Phone Number'
};
if (propertyIndex === 0) {
dropdown.addOption('title', 'Title');
} else {
Object.keys(options).forEach(key => {
dropdown.addOption(key, options[key]);
});
}
dropdown.setValue(isExistingProperty ? property.customType : "")
.onChange(value => {
const actualIndex = properties.findIndex(p => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customType = value;
} else if (!isExistingProperty) {
properties.push({ customName: '', customType: value, index: propertyIndex });
isExistingProperty = true; // Update the flag to prevent re-adding
}
});
});
if (propertyIndex > 0) {
propertyLine.addButton(button => {
return button
.setTooltip("Delete")
.setIcon("trash")
.onClick(() => {
console.log('Deleting property', properties[propertyIndex]);
this.deleteProperty(propertyIndex, properties);
});
});
}
this.propertyLines.push(propertyLine);
this.updatePropertyLines();
}
createStyleDiv(className: string, commandValue: boolean = false, parentEl: HTMLElement): HTMLDivElement {
return super.createStyleDiv(className, commandValue, parentEl);
}
updateSettingEl(element: HTMLElement, commandValue: boolean) {
super.updateSettingEl(element, commandValue);
}
createSettingEl(contentEl: HTMLElement, name: string, desc: string, type: string, placeholder: string, holderValue: any, dataRecord: string, settingsKey: string): Setting {
return super.createSettingEl(contentEl, name, desc, type, placeholder, holderValue, dataRecord, settingsKey);
}
}

178
src/ui/PreviewModal.ts Normal file
View File

@@ -0,0 +1,178 @@
import { App, ExtraButtonComponent, Modal, Notice, Setting } from "obsidian";
import ObsidianSyncNotionPlugin from "../main";
import { DatabaseDetails, ObsidianSettingTab } from "./settingTabs";
import { customProperty } from "./settingModal";
import { i18nConfig } from "../lang/I18n";
export class PreviewModal extends Modal {
plugin: ObsidianSyncNotionPlugin;
settingTab: ObsidianSettingTab;
dbDetails: DatabaseDetails;
constructor(app: App, plugin: ObsidianSyncNotionPlugin, settingTab: ObsidianSettingTab, dbDetails: DatabaseDetails) {
super(app);
this.plugin = plugin;
this.settingTab = settingTab;
this.dbDetails = dbDetails;
}
display(): void {
this.containerEl.addClass('preview-modal')
this.titleEl.setText(i18nConfig.Preview)
let { contentEl } = this;
const previewEl = contentEl.createDiv('preview-content')
const dbFormatEl = new Setting(previewEl)
dbFormatEl
.setName(i18nConfig.DatabaseFormatLabel)
.addText(text => text
.setValue(this.dbDetails.format)
.setDisabled(true));
const dbFullEl = new Setting(previewEl)
dbFullEl
.setName(i18nConfig.DatabaseFullNameLabel)
.addText(text => text
.setValue(this.dbDetails.fullName)
.setDisabled(true));
const dbAbbrEl = new Setting(previewEl)
dbAbbrEl
.setName(i18nConfig.DatabaseAbbreviateNameLabel)
.addText(text => text
.setValue(this.dbDetails.abName)
.setDisabled(true));
// .controlEl.createEl('p', { text: this.dbDetails.abName })
// Setting for toggle and copy buttons
new Setting(previewEl)
.setName(i18nConfig.NotionAPILabel)
.addExtraButton((button: ExtraButtonComponent) => {
let isApiKeyVisible = false;
return button
.setTooltip(i18nConfig.ToggleAPIKeyVisibility)
.setIcon('eye')
.onClick(() => {
isApiKeyVisible = !isApiKeyVisible;
button.setIcon(isApiKeyVisible ? 'eye-off' : 'eye');
apiKeySetting.settingEl.style.display = isApiKeyVisible ? '' : 'none'; // Toggle visibility
});
})
// Setting for displaying the API key
const apiKeySetting = new Setting(previewEl)
apiKeySetting.infoEl.createEl('p', { text: this.dbDetails.notionAPI })
apiKeySetting
.addExtraButton((button: ExtraButtonComponent) => {
return button
.setTooltip(i18nConfig.CopyAPIKey)
.setIcon('clipboard')
.onClick(() => {
navigator.clipboard.writeText(this.dbDetails.notionAPI)
new Notice(i18nConfig.APIKeyCopied);
});
});
apiKeySetting.settingEl.style.display = 'none'; // Hide initially
new Setting(previewEl)
.setName(i18nConfig.DatabaseIDLabel)
.addExtraButton((button: ExtraButtonComponent) => {
let isDbIdVisible = false;
return button
.setTooltip(i18nConfig.ToggleDatabaseIDVisibility)
.setIcon('eye')
.onClick(() => {
isDbIdVisible = !isDbIdVisible;
button.setIcon(isDbIdVisible ? 'eye-off' : 'eye');
dbIdSetting.settingEl.style.display = isDbIdVisible ? '' : 'none'; // Toggle visibility
});
})
const dbIdSetting = new Setting(previewEl)
dbIdSetting.infoEl.createEl('p', { text: this.dbDetails.databaseID })
dbIdSetting
.addExtraButton((button: ExtraButtonComponent) => {
return button
.setTooltip(i18nConfig.CopyDatabaseID)
.setIcon('clipboard')
.onClick(() => {
navigator.clipboard.writeText(this.dbDetails.databaseID)
new Notice(i18nConfig.DatabaseIDCopied);
});
});
dbIdSetting.settingEl.style.display = 'none'; // Hide initially
// Preview the custom properties
if (this.dbDetails.format === 'custom') {
const customPrv = previewEl.createDiv("custom-tabs");
this.previewPropertyLine(previewEl, this.dbDetails.customProperties);
}
}
onOpen() {
this.display()
}
previewPropertyLine(containerEl: HTMLElement, properties: customProperty[]): void {
properties.forEach((property, index) => {
const propertyLine = new Setting(containerEl)
.setName(index === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${index}`)
.setDesc(index === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText(text => {
text.setPlaceholder(i18nConfig.CustomPropertyName)
.setValue(property.customName)
.setDisabled(true);
});
propertyLine.addDropdown((dropdown) => {
const options: Record<string, string> = {
'title': 'Title',
'rich_text': 'Text',
'number': 'Number',
'select': 'Select',
'multi_select': 'Multi-Select',
'date': 'Date',
'files': 'Files & Media',
'checkbox': 'Checkbox',
'url': 'URL',
'email': 'Email',
'phone_number': 'Phone Number',
// Additional options can be added here
};
// Populate dropdown with options
Object.keys(options).forEach(key => {
dropdown.addOption(key, options[key]);
});
dropdown.setValue(property.customType)
.setDisabled(true); // Disable dropdown to prevent changes
});
});
}
}

View File

377
src/ui/settingModal.ts Normal file
View File

@@ -0,0 +1,377 @@
import {
Modal,
Setting,
ButtonComponent, App
} from 'obsidian';
import { i18nConfig } from "../lang/I18n";
import ObsidianSyncNotionPlugin from "../main";
import { DatabaseDetails, ObsidianSettingTab } from "./settingTabs";
export interface customProperty {
customName: string;
customType: string;
index: number;
}
export class SettingModal extends Modal {
propertyLines: Setting[] = []; // Store all property line settings
properties: customProperty[] = []; // Array to store property values and types
[key: string]: any; // Index signature
data: Record<string, any> = {
databaseFormat: 'none',
databaseFullName: '',
databaseAbbreviateName: '',
notionAPI: '',
databaseID: '',
tagButton: true,
customTitleButton: false,
customTitleName: '',
customProperties: [],
// customValues: '',
saved: false,
};
plugin: ObsidianSyncNotionPlugin;
settingTab: ObsidianSettingTab;
constructor(app: App, plugin: ObsidianSyncNotionPlugin, settingTab: ObsidianSettingTab, dbDetails?: DatabaseDetails) {
super(app);
this.plugin = plugin;
this.settingTab = settingTab;
this.properties = [];
if (dbDetails) {
this.data.databaseFormat = dbDetails.format;
this.data.databaseFullName = dbDetails.fullName;
this.data.databaseAbbreviateName = dbDetails.abName;
this.data.notionAPI = dbDetails.notionAPI;
this.data.databaseID = dbDetails.databaseID;
this.data.tagButton = dbDetails.tagButton;
this.data.customTitleButton = dbDetails.customTitleButton;
this.data.customTitleName = dbDetails.customTitleName;
this.data.customProperties = dbDetails.customProperties;
// this.data.customValues = dbDetails.customValues;
this.data.saved = dbDetails.saved;
}
}
display(): void {
this.containerEl.addClass("settings-modal");
this.titleEl.setText(i18nConfig.AddNewDatabaseModal);
// create the dropdown button to select the database format
let { contentEl } = this;
contentEl.empty();
const settingDiv = contentEl.createDiv('setting-div');
const nextTabs = contentEl.createDiv('next-tabs');
new Setting(settingDiv)
.setName(i18nConfig.databaseFormat)
.setDesc(i18nConfig.databaseFormatDesc)
.addDropdown((component) => {
component
.addOption('none', '')
.addOption('general', i18nConfig.databaseGeneral)
.addOption('next', i18nConfig.databaseNext)
.addOption('custom', i18nConfig.databaseCustom)
.setValue(this.data.databaseFormat)
.onChange(async (value) => {
this.data.databaseFormat = value;
nextTabs.empty();
this.updateContentBasedOnSelection(value, nextTabs);
});
// Initialize content based on the current dropdown value
(this.data.saved) ? this.updateContentBasedOnSelection(this.data.databaseFormat, nextTabs) : this.updateContentBasedOnSelection(this.plugin.settings.databaseFormat, nextTabs);
});
// add save button
let footerEl = contentEl.createDiv('save-button');
let saveButton = new Setting(footerEl)
saveButton.addButton((button: ButtonComponent) => {
return button
.setTooltip('Save')
.setIcon('checkmark')
.onClick(async () => {
this.data.saved = true;
this.data.customProperties = this.properties;
this.close();
});
}
);
saveButton.addExtraButton((button) => {
return button
.setTooltip('Cancel')
.setIcon('cross')
.onClick(() => {
this.data.saved = false;
// this.data.customProperties = this.properties;
this.close();
});
}
);
}
updateContentBasedOnSelection(value: string, nextTabs: HTMLElement): void {
// Clear existing content
nextTabs.empty();
// Generate content based on the selected value
if (value === 'general') {
nextTabs.createEl('h3', { text: i18nConfig.NotionGeneralSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.data.databaseFullName, 'data', 'databaseFullName')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, 'data', 'databaseAbbreviateName')
// tag button
this.createSettingEl(nextTabs, i18nConfig.NotionTagButton, i18nConfig.NotionTagButtonDesc, 'toggle', i18nConfig.NotionCustomTitleText, this.data.tagButton, 'data', 'tagButton')
// add custom title button
new Setting(nextTabs)
.setName(i18nConfig.NotionCustomTitle)
.setDesc(i18nConfig.NotionCustomTitleDesc)
.addToggle((toggle) =>
toggle
.setValue(this.data.customTitleButton)
.onChange(async (value) => {
this.data.customTitleButton = value;
this.updateSettingEl(CustomNameEl, value)
})
);
// add custom title name
const CustomNameEl = this.createStyleDiv('custom-name', (this.data.customTitleButton), nextTabs);
this.createSettingEl(CustomNameEl, i18nConfig.NotionCustomTitleName, i18nConfig.NotionCustomTitleNameDesc, 'text', i18nConfig.NotionCustomTitleText, this.data.customTitleName, 'data', 'customTitleName')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.data.notionAPI, 'data', 'notionAPI')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.data.databaseID, 'data', 'databaseID')
} else if (value === 'next') {
nextTabs.createEl('h3', { text: i18nConfig.NotionNextSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.data.databaseFullName, 'data', 'databaseFullName')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, 'data', 'databaseAbbreviateName')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.data.notionAPI, 'data', 'notionAPI')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.data.databaseID, 'data', 'databaseID')
} else if (value === 'custom') {
nextTabs.createEl('h3', { text: i18nConfig.NotionCustomSettingHeader });
// add full name
this.createSettingEl(nextTabs, i18nConfig.databaseFullName, i18nConfig.databaseFullNameDesc, 'text', i18nConfig.databaseFullNameText, this.data.databaseFullName, 'data', 'databaseFullName')
// add abbreviate name
this.createSettingEl(nextTabs, i18nConfig.databaseAbbreviateName, i18nConfig.databaseAbbreviateNameDesc, 'text', i18nConfig.databaseAbbreviateNameText, this.data.databaseAbbreviateName, 'data', 'databaseAbbreviateName')
// add api key
this.createSettingEl(nextTabs, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.data.notionAPI, 'data', 'notionAPI')
// add database id
this.createSettingEl(nextTabs, i18nConfig.DatabaseID, i18nConfig.DatabaseIDDesc, 'password', i18nConfig.DatabaseIDText, this.data.databaseID, 'data', 'databaseID')
// add new property button
new Setting(nextTabs)
.setName(i18nConfig.NotionCustomValues)
.setDesc(i18nConfig.NotionCustomValuesDesc)
.addButton((button: ButtonComponent) => {
return button
.setTooltip('Add one more property')
.setButtonText('Add New Property')
.onClick(async () => {
const customTabs = nextTabs.createDiv("custom-tabs");
this.createPropertyLine(customTabs, this.properties);
});
}
);
}
}
onOpen() {
// add console log to check if the modal is opened
this.display()
}
createPropertyLine(containerEl: HTMLElement, properties: customProperty[]): void {
const propertyIndex = properties.length;
properties.push({ customName: "", customType: "", index: propertyIndex });
const propertyLine = new Setting(containerEl)
.setName(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${propertyIndex}`)
.setDesc(propertyIndex === 0 ? i18nConfig.CustomPropertyFirstColumnDesc : "");
propertyLine.addText(text => {
text.setPlaceholder(i18nConfig.CustomPropertyName)
.setValue("")
.onChange(value => {
let actualIndex = properties.findIndex(p => p.index === propertyIndex);
if (actualIndex !== -1) {
properties[actualIndex].customName = value;
}
});
});
propertyLine.addDropdown((dropdown) => {
const options: Record<string, string> = {
'rich_text': 'Text',
'number': 'Number',
'select': 'Select',
'multi_select': 'Multi-Select',
'date': 'Date',
'files': 'Files & Media',
'checkbox': 'Checkbox',
'url': 'URL',
'email': 'Email',
'phone_number': 'Phone Number',
// 'formula': 'Formula',
// 'relation': 'Relation',
// 'rollup': 'Rollup',
// 'created_time': 'Created time',
// 'created_by': 'Created by',
// 'last_edited_time': 'Last Edited Time',
// 'last_edited_by': 'Last Edited By',
};
const currentProperty = properties[propertyIndex];
if (propertyIndex === 0) {
dropdown.addOption("title", "Title");
} else {
Object.keys(options).forEach(key => {
dropdown.addOption(key, options[key]);
});
}
dropdown.setValue("")
.onChange(value => {
if (currentProperty) {
currentProperty.customType = value;
// Retrieve the index of currentProperty from the properties array
const updatedIndex = properties.findIndex(p => p === currentProperty);
console.log(`Updated value at index ${updatedIndex}: ${value}`);
} else {
console.log("Property not found, may have been deleted.");
}
});
});
if (propertyIndex > 0) {
propertyLine.addButton(button => {
return button
.setTooltip("Delete")
.setIcon("trash")
.onClick(() => {
this.deleteProperty(propertyIndex, properties);
});
});
}
this.propertyLines.push(propertyLine);
this.updatePropertyLines(); // Ensure property lines are updated after creation
}
deleteProperty(propertyIndex: number, properties: customProperty[]): void {
let actualIndex = properties.findIndex(p => p.index === propertyIndex);
if (actualIndex !== -1) {
properties.splice(actualIndex, 1);
if (this.propertyLines[actualIndex]) {
this.propertyLines[actualIndex].settingEl.remove();
this.propertyLines.splice(actualIndex, 1);
}
// Update indices in the properties array
properties.forEach((prop, idx) => {
prop.index = idx;
});
this.updatePropertyLines();
}
}
updatePropertyLines() {
this.propertyLines.forEach((line, idx) => {
line.setName(idx === 0 ? i18nConfig.CustomPropertyFirstColumn : `${i18nConfig.CustomProperty} ${idx}`);
});
}
// create a function to create a div with a style for pop over elements
public createStyleDiv(className: string, commandValue: boolean = false, parentEl: HTMLElement) {
return parentEl.createDiv(className, (div) => {
this.updateSettingEl(div, commandValue);
});
}
// update the setting display style in the setting tab
public updateSettingEl(element: HTMLElement, commandValue: boolean) {
element.style.borderTop = commandValue ? "1px solid var(--background-modifier-border)" : "none";
element.style.paddingTop = commandValue ? "0.75em" : "0";
element.style.display = commandValue ? "block" : "none";
element.style.alignItems = "center";
}
// function to add one setting element in the setting tab.
public createSettingEl(contentEl: HTMLElement, name: string, desc: string, type: string, placeholder: string, holderValue: any, dataRecord: string, settingsKey: string) {
if (type === 'password') {
return new Setting(contentEl)
.setName(name)
.setDesc(desc)
.addText((text) => {
text.inputEl.type = type;
return text
.setPlaceholder(placeholder)
.setValue(holderValue)
.onChange(async (value) => {
this[dataRecord][settingsKey] = value; // Update the settings dictionary await this.plugin.saveSettings();
})
});
} else if (type === 'toggle') {
return new Setting(contentEl)
.setName(name)
.setDesc(desc)
.addToggle((toggle) =>
toggle
.setValue(holderValue)
.onChange(async (value) => {
this[dataRecord][settingsKey] = value; // Update the settings dictionary await this.plugin.saveSettings();
})
);
} else if (type === 'text') {
return new Setting(contentEl)
.setName(name)
.setDesc(desc)
.addText((text) =>
text
.setPlaceholder(placeholder)
.setValue(holderValue)
.onChange(async (value) => {
this[dataRecord][settingsKey] = value; // Update the settings dictionary await this.plugin.saveSettings();
})
);
}
}
}

View File

@@ -1,6 +1,11 @@
import { App, PluginSettingTab, Setting } from "obsidian";
import { App, ButtonComponent, PluginSettingTab, Setting } from "obsidian";
import { i18nConfig } from "../lang/I18n";
import ObsidianSyncNotionPlugin from "../main";
import { SettingModal } from "./settingModal";
import { PreviewModal } from "./PreviewModal";
import { EditModal } from "./EditModal";
import { DeleteModal } from "./DeleteModal";
import { DEFAULT_AUTO_SYNC_DATABASE_KEY } from "src/utils/frontmatter";
export interface PluginSettings {
NextButton: boolean;
@@ -8,16 +13,37 @@ export interface PluginSettings {
databaseIDNext: string;
bannerUrl: string;
notionUser: string;
NotionLinkDisplay: boolean;
autoSync: boolean;
autoSyncDelay: number;
autoSyncFrontmatterKey: string;
proxy: string;
GeneralButton: boolean;
CustomTitleButton: boolean;
CustomTitleName: string;
tagButton: boolean;
customTitleButton: boolean;
customTitleName: string;
notionAPIGeneral: string;
databaseIDGeneral: string;
CustomButton: boolean;
CustomValues: string;
notionAPICustom: string;
databaseIDCustom: string;
[key: string]: any;
databaseDetails: Record<string, DatabaseDetails>
}
export interface DatabaseDetails {
format: string;
fullName: string;
abName: string;
notionAPI: string;
databaseID: string;
tagButton: boolean;
customTitleButton: boolean;
customTitleName: string;
customProperties: { customName: string, customType: string, index: number }[];
// customValues: string;
saved: boolean;
}
export const DEFAULT_SETTINGS: PluginSettings = {
@@ -26,20 +52,29 @@ export const DEFAULT_SETTINGS: PluginSettings = {
databaseIDNext: "",
bannerUrl: "",
notionUser: "",
NotionLinkDisplay: true,
autoSync: false,
autoSyncDelay: 5,
autoSyncFrontmatterKey: DEFAULT_AUTO_SYNC_DATABASE_KEY,
proxy: "",
GeneralButton: true,
CustomTitleButton: false,
CustomTitleName: "",
tagButton: true,
customTitleButton: false,
customTitleName: "",
notionAPIGeneral: "",
databaseIDGeneral: "",
CustomButton: false,
CustomValues: "",
notionAPICustom: "",
databaseIDCustom: "",
databaseDetails: {},
};
export class ObsidianSettingTab extends PluginSettingTab {
plugin: ObsidianSyncNotionPlugin;
databaseEl: HTMLDivElement;
autoSyncDelayContainer: HTMLElement | null = null;
constructor(app: App, plugin: ObsidianSyncNotionPlugin) {
super(app, plugin);
@@ -58,132 +93,123 @@ export class ObsidianSettingTab extends PluginSettingTab {
this.createSettingEl(containerEl, i18nConfig.NotionUser, i18nConfig.NotionUserDesc, 'text', i18nConfig.NotionUserText, this.plugin.settings.notionUser, 'notionUser')
containerEl.createEl('h2', { text: i18nConfig.NotionNextSettingHeader })
this.createSettingEl(containerEl, i18nConfig.NotionLinkDisplay, i18nConfig.NotionLinkDisplayDesc, 'toggle', i18nConfig.NotionLinkDisplay, this.plugin.settings.NotionLinkDisplay, 'NotionLinkDisplay')
this.createSettingEl(containerEl, i18nConfig.AutoSync, i18nConfig.AutoSyncDesc, 'toggle', i18nConfig.AutoSync, this.plugin.settings.autoSync, 'autoSync')
new Setting(containerEl)
.setName(i18nConfig.NotionNextButton)
.setDesc(i18nConfig.NotionNextButtonDesc)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.NextButton)
.setName(i18nConfig.AutoSyncFrontmatterKey)
.setDesc(i18nConfig.AutoSyncFrontmatterKeyDesc)
.addText((text) =>
text
.setPlaceholder(DEFAULT_AUTO_SYNC_DATABASE_KEY)
.setValue(this.plugin.settings.autoSyncFrontmatterKey ?? "")
.onChange(async (value) => {
this.plugin.settings.NextButton = value;
this.updateSettingEl(notionAPINextEl, value)
this.updateSettingEl(databaseIDNextEl, value)
this.plugin.settings.autoSyncFrontmatterKey = value;
await this.plugin.saveSettings();
await this.plugin.commands.updateCommand();
this.plugin.resetAutoSyncNoticeCache();
})
);
// Auto Sync Delay setting - only visible when autoSync is enabled
this.autoSyncDelayContainer = containerEl.createDiv();
const delaySetting = new Setting(this.autoSyncDelayContainer)
.setName(i18nConfig.AutoSyncDelay)
.setDesc(i18nConfig.AutoSyncDelayDesc)
.addText((text) =>
text
.setPlaceholder(i18nConfig.AutoSyncDelayText)
.setValue(String(this.plugin.settings.autoSyncDelay))
.onChange(async (value) => {
const delay = parseFloat(value);
if (!isNaN(delay) && delay >= 2) {
this.plugin.settings.autoSyncDelay = delay;
await this.plugin.saveSettings();
} else if (!isNaN(delay) && delay < 2) {
// If user enters less than 2 seconds, set it to 2
this.plugin.settings.autoSyncDelay = 2;
await this.plugin.saveSettings();
text.setValue('2');
}
})
);
const notionAPINextEl = this.createStyleDiv('api-next', this.plugin.settings.NextButton)
this.createSettingEl(notionAPINextEl, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.plugin.settings.notionAPINext, 'notionAPINext')
const databaseIDNextEl = this.createStyleDiv('databaseID-next', this.plugin.settings.NextButton)
this.createSettingEl(databaseIDNextEl, i18nConfig.DatabaseID, i18nConfig.NotionAPIDesc, 'password', i18nConfig.DatabaseIDText, this.plugin.settings.databaseIDNext, 'databaseIDNext')
// Set initial visibility
this.updateAutoSyncDelayVisibility();
// General Database Settings
containerEl.createEl('h2', { text: i18nConfig.NotionGeneralSettingHeader });
// new Setting(containerEl)
// .setName(i18nConfig.NotYetFinish)
// add new button
new Setting(containerEl)
.setName(i18nConfig.NotionGeneralButton)
.setDesc(i18nConfig.NotionGeneralButtonDesc)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.GeneralButton)
.onChange(async (value) => {
this.plugin.settings.GeneralButton = value;
.setName(i18nConfig.AddNewDatabase)
.setDesc(i18nConfig.AddNewDatabaseDesc)
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip(i18nConfig.AddNewDatabaseTooltip)
.setIcon("plus")
.onClick(async () => {
let modal = new SettingModal(this.app, this.plugin, this);
this.updateSettingEl(CustomTitleEl, value)
this.updateSettingEl(notionAPIGeneralEl, value)
this.updateSettingEl(databaseIDGeneralEl, value)
modal.onClose = () => {
if (modal.data.saved) {
const dbDetails = {
format: modal.data.databaseFormat,
fullName: modal.data.databaseFullName,
abName: modal.data.databaseAbbreviateName,
notionAPI: modal.data.notionAPI,
databaseID: modal.data.databaseID,
tagButton: modal.data.tagButton,
customTitleButton: modal.data.customTitleButton,
customTitleName: modal.data.customTitleName,
customProperties: modal.data.customProperties,
// customValues: modal.data.customValues,
saved: modal.data.saved,
}
this.plugin.addDatabaseDetails(dbDetails);
await this.plugin.saveSettings();
await this.plugin.commands.updateCommand();
this.plugin.commands.updateCommand();
})
);
this.display()
}
}
const CustomTitleEl = this.createStyleDiv('custom-title', this.plugin.settings.GeneralButton);
new Setting(CustomTitleEl)
.setName(i18nConfig.NotionCustomTitle)
.setDesc(i18nConfig.NotionCustomTitleDesc)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.CustomTitleButton)
.onChange(async (value) => {
this.plugin.settings.CustomTitleButton = value;
modal.open();
});
});
this.updateSettingEl(CustomNameEl, value)
// new section to display all created database
containerEl.createEl('h2', { text: "Database List" });
await this.plugin.saveSettings();
await this.plugin.commands.updateCommand();
})
);
this.databaseEl = containerEl.createDiv('database-list');
// list all created database
this.showDatabase();
const CustomNameEl = this.createStyleDiv('custom-name', this.plugin.settings.CustomTitleButton);
this.createSettingEl(CustomNameEl, i18nConfig.NotionCustomTitleName, i18nConfig.NotionCustomTitleNameDesc, 'text', i18nConfig.NotionCustomTitleText, this.plugin.settings.CustomTitleName, 'CustomTitleName')
// new Setting(containerEl)
// .setName("Convert tags(optional)")
// .setDesc("Transfer the Obsidian tags to the Notion table. It requires the column with the name 'Tags'")
// .addToggle((toggle) =>
// toggle
// .setValue(this.plugin.settings.allowTags)
// .onChange(async (value) => {
// this.plugin.settings.allowTags = value;
// await this.plugin.saveSettings();
// })
// );
const notionAPIGeneralEl = this.createStyleDiv('api-general', this.plugin.settings.GeneralButton);
this.createSettingEl(notionAPIGeneralEl, i18nConfig.NotionAPI, i18nConfig.NotionAPIDesc, 'password', i18nConfig.NotionAPIText, this.plugin.settings.notionAPIGeneral, 'notionAPIGeneral')
const databaseIDGeneralEl = this.createStyleDiv('databaseID-general', this.plugin.settings.GeneralButton);
this.createSettingEl(databaseIDGeneralEl, i18nConfig.DatabaseID, i18nConfig.NotionAPIDesc, 'password', i18nConfig.DatabaseIDText, this.plugin.settings.databaseIDGeneral, 'databaseIDGeneral')
// Custom Database Settings
// containerEl.createEl('h2', {text: i18nConfig.NotionCustomSettingHeader});
//
// new Setting(containerEl)
// .setName(i18nConfig.NotionCustomButton)
// .setDesc(i18nConfig.NotionCustomButtonDesc)
// .addToggle((toggle) =>
// toggle
// .setValue(this.plugin.settings.CustomButton)
// .onChange(async (value) => {
// this.plugin.settings.CustomButton = value;
// await this.plugin.saveSettings();
// })
// );
}
// create a function to create a div with a style for pop over elements
private createStyleDiv(className: string, commandValue: boolean = false) {
return this.containerEl.createDiv(className, (div) => {
this.updateSettingEl(div, commandValue);
});
}
// public createStyleDiv(className: string, commandValue: boolean = false) {
// return this.containerEl.createDiv(className, (div) => {
// this.updateSettingEl(div, commandValue);
// });
// }
// update the setting display style in the setting tab
private updateSettingEl(element: HTMLElement, commandValue: boolean) {
public updateSettingEl(element: HTMLElement, commandValue: boolean) {
element.style.borderTop = commandValue ? "1px solid var(--background-modifier-border)" : "none";
element.style.paddingTop = commandValue ? "0.75em" : "0";
element.style.display = commandValue ? "block" : "none";
element.style.alignItems = "center";
}
// Update visibility of autoSyncDelay setting based on autoSync toggle
public updateAutoSyncDelayVisibility() {
if (this.autoSyncDelayContainer) {
this.autoSyncDelayContainer.style.display = this.plugin.settings.autoSync ? "block" : "none";
}
}
// function to add one setting element in the setting tab.
private createSettingEl(containerEl: HTMLElement, name: string, desc: string, type: string, placeholder: string, holderValue: any, settingsKey: string) {
public createSettingEl(containerEl: HTMLElement, name: string, desc: string, type: string, placeholder: string, holderValue: any, settingsKey: string) {
if (type === 'password') {
return new Setting(containerEl)
.setName(name)
@@ -209,6 +235,12 @@ export class ObsidianSettingTab extends PluginSettingTab {
this.plugin.settings[settingsKey] = value; // Update the plugin settings directly
await this.plugin.saveSettings();
await this.plugin.commands.updateCommand();
// If autoSync setting changed, update the listener and visibility
if (settingsKey === 'autoSync') {
this.plugin.setupAutoSync();
this.updateAutoSyncDelayVisibility();
}
})
);
} else if (type === 'text') {
@@ -228,4 +260,110 @@ export class ObsidianSettingTab extends PluginSettingTab {
}
}
// function to show all the database details
showDatabase() {
this.databaseEl.empty();
for (let key in this.plugin.settings.databaseDetails) {
let dbDetails = this.plugin.settings.databaseDetails[key];
const databaseDiv = this.databaseEl.createDiv('database-div');
let settingEl = new Setting(databaseDiv)
.setName(`${dbDetails.fullName} (${dbDetails.abName})`)
.setDesc(dbDetails.format)
// add a button for preview data
settingEl
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip("Preview Database")
.setIcon("eye")
.onClick(async () => {
let modal = new PreviewModal(this.app, this.plugin, this, dbDetails);
modal.open();
});
});
// add a button for edit data
settingEl
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip("Edit Database")
.setIcon("pencil")
.onClick(async () => {
let modal = new EditModal(this.app, this.plugin, this, dbDetails);
modal.onClose = () => {
if (modal.dataTemp.savedTempInd) {
const dbDetailsNew: DatabaseDetails = {
format: modal.dataTemp.databaseFormatTemp,
fullName: modal.dataTemp.databaseFullNameTemp,
abName: modal.dataTemp.databaseAbbreviateNameTemp,
notionAPI: modal.dataTemp.notionAPITemp,
databaseID: modal.dataTemp.databaseIDTemp,
tagButton: modal.dataTemp.tagButtonTemp,
customTitleButton: modal.dataTemp.customTitleButtonTemp,
customTitleName: modal.dataTemp.customTitleNameTemp,
customProperties: modal.dataTemp.customPropertiesTemp,
// customValues: modal.data.customValues,
saved: modal.dataTemp.savedTemp,
}
const dbDetailsPrev: DatabaseDetails = {
format: modal.dataPrev.databaseFormatPrev,
fullName: modal.dataPrev.databaseFullNamePrev,
abName: modal.dataPrev.databaseAbbreviateNamePrev,
notionAPI: modal.dataPrev.notionAPIPrev,
databaseID: modal.dataPrev.databaseIDPrev,
tagButton: modal.dataPrev.tagButtonPrev,
customTitleButton: modal.dataPrev.customTitleButtonPrev,
customTitleName: modal.dataPrev.customTitleNamePrev,
customProperties: modal.dataPrev.customPropertiesPrev,
// customValues: modal.data.customValues,
saved: modal.dataPrev.savedPrev,
}
this.plugin.deleteDatabaseDetails(dbDetailsPrev);
this.plugin.updateDatabaseDetails(dbDetailsNew);
this.plugin.commands.updateCommand();
this.display()
}
}
modal.open();
});
});
settingEl
.addButton((button: ButtonComponent): ButtonComponent => {
return button
.setTooltip("Delete Database")
.setIcon("trash")
.onClick(async () => {
let modal = new DeleteModal(this.app, this.plugin, this, dbDetails);
modal.onClose = () => {
if (modal.data.deleted) {
this.plugin.deleteDatabaseDetails(dbDetails);
console.log(dbDetails.fullName + " deleted");
this.plugin.commands.updateCommand();
this.display()
}
}
modal.open();
});
});
}
}
}

628
src/upload/Upload2Notion.ts Normal file
View File

@@ -0,0 +1,628 @@
import { App, TFile } from "obsidian";
import { markdownToBlocks } from "@jxpeng98/martian";
import * as yamlFrontMatter from "yaml-front-matter";
import { LIMITS, paragraph } from "@jxpeng98/martian";
import MyPlugin from "src/main";
import { DatabaseDetails } from "../ui/settingTabs";
import { updateYamlInfo } from "./updateYaml";
import { UploadBase, NotionPageResponse } from "./common/UploadBase";
export type DatasetType = "general" | "next" | "custom";
interface BaseSyncRequest {
dataset: DatasetType;
markdown: string;
nowFile: TFile;
app: App;
}
interface GeneralSyncRequest extends BaseSyncRequest {
dataset: "general";
title: string;
cover: string;
tags: string[];
}
interface NextSyncRequest extends BaseSyncRequest {
dataset: "next";
title: string;
emoji: string;
cover: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
}
interface CustomSyncRequest extends BaseSyncRequest {
dataset: "custom";
cover: string;
customValues: Record<string, string>;
}
export type SyncRequest =
| GeneralSyncRequest
| NextSyncRequest
| CustomSyncRequest;
interface GeneralParams {
title: string;
cover?: string;
tags: string[];
childArr: any[];
notionId?: string;
}
interface NextParams {
title: string;
emoji: string;
cover?: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
childArr: any[];
notionId?: string;
}
interface CustomParams {
cover?: string;
customValues: Record<string, string>;
childArr: any[];
notionId?: string;
}
export class Upload2Notion extends UploadBase {
constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
super(plugin, dbDetails);
}
async sync(request: SyncRequest): Promise<NotionPageResponse> {
const startedAt = Date.now();
let response: NotionPageResponse;
switch (request.dataset) {
case "general":
response = await this.handleGeneral(request);
break;
case "next":
response = await this.handleNext(request);
break;
case "custom":
response = await this.handleCustom(request);
break;
default:
throw new Error(`Unsupported dataset type: ${(request as any).dataset}`);
}
if (response.response && response.response.status === 200) {
await updateYamlInfo(
request.markdown,
request.nowFile,
response.data,
request.app,
this.plugin,
this.dbDetails,
);
} else {
console.log(`[Upload2Notion] Sync failed`, response.data);
}
return response;
}
private async handleGeneral(request: GeneralSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling general dataset`, {
cover: request.cover,
tags: request.tags,
});
const blocks = this.buildBlocks(request.markdown, {
notionLimits: {truncate: false},
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "General dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
tagCount: request.tags?.length ?? 0,
});
return this.upsertGeneral({
title: request.title,
cover: request.cover,
tags: request.tags || [],
childArr: blocks,
notionId,
});
}
private async handleNext(request: NextSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling next dataset`, {
type: request.type,
slug: request.slug,
category: request.category,
});
const blocks = this.buildBlocks(request.markdown, {
notionLimits: {truncate: false},
});
this.splitRichTextParagraphs(blocks);
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Next dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
hasEmoji: !!request.emoji,
tags: request.tags || [],
});
return this.upsertNext({
title: request.title,
emoji: request.emoji,
cover: request.cover,
tags: request.tags || [],
type: request.type,
slug: request.slug,
stats: request.stats,
category: request.category,
summary: request.summary,
password: request.password,
favicon: request.favicon,
datetime: request.datetime,
childArr: blocks,
notionId,
});
}
private async handleCustom(request: CustomSyncRequest): Promise<NotionPageResponse> {
console.log(`[Upload2Notion] Handling custom dataset`, {
customKeys: Object.keys(request.customValues || {}),
});
const blocks = this.buildBlocks(request.markdown, {
strictImageUrls: true,
notionLimits: {truncate: false},
});
const notionId = this.getNotionId(request.app, request.nowFile);
this.debugLog("Upload2Notion", "Custom dataset payload prepared", {
blockCount: blocks.length,
notionId: notionId ?? null,
customValueKeys: Object.keys(request.customValues || {}),
});
return this.upsertCustom({
cover: request.cover,
customValues: request.customValues,
childArr: blocks,
notionId,
});
}
private buildBlocks(markdown: string, options: Record<string, unknown>): any[] {
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const content = yamlContent.__content;
const blocks = markdownToBlocks(content, options);
this.debugLog("Upload2Notion", "Converted markdown to blocks", {
blockCount: blocks.length,
firstBlockTypes: blocks.slice(0, 5).map((block: any) => block?.type),
options,
});
return blocks;
}
private getNotionId(app: App, nowFile: TFile): string | undefined {
const frontMatter = app.metadataCache.getFileCache(nowFile)?.frontmatter;
if (!frontMatter) {
this.debugLog("Upload2Notion", "No frontmatter found when resolving Notion ID", {
filePath: nowFile.path,
});
return undefined;
}
const {abName} = this.dbDetails;
const notionIDKey = `NotionID-${abName}`;
const notionId = frontMatter[notionIDKey];
return notionId ? String(notionId) : undefined;
}
private splitRichTextParagraphs(blocks: any[]): void {
blocks.forEach((block, index) => {
if (
block.type === "paragraph" &&
block.paragraph.rich_text.length > LIMITS.RICH_TEXT_ARRAYS
) {
console.log(`[Upload2Notion] Splitting rich text paragraph`, {
index,
length: block.paragraph.rich_text.length,
});
const paragraphChunks = this.chunkArray<any>(block.paragraph.rich_text, 100);
const newParagraphBlocks = paragraphChunks.map((chunk) => paragraph(chunk));
blocks.splice(index, 1, ...newParagraphBlocks);
}
});
}
private chunkArray<T>(items: T[], size: number): T[][] {
const result: T[][] = [];
for (let i = 0; i < items.length; i += size) {
result.push(items.slice(i, i + size));
}
return result;
}
private async upsertGeneral(params: GeneralParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting general page", {
title: params.title,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
notionIdExisting: params.notionId ?? null,
tagList: params.tags,
});
if (params.notionId) {
console.log(`[Upload2Notion] Deleting existing Notion page`, {
notionId: params.notionId,
});
await this.deletePage(params.notionId);
}
const body = this.buildGeneralBody({
title: params.title,
tags: params.tags,
firstChunk,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private async upsertNext(params: NextParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting NotionNext page", {
title: params.title,
type: params.type,
slug: params.slug,
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
hasEmoji: !!params.emoji,
notionIdExisting: params.notionId ?? null,
});
if (params.notionId) {
await this.deletePage(params.notionId);
}
const body = this.buildNextBody({
firstChunk,
title: params.title,
emoji: params.emoji,
tags: params.tags,
type: params.type,
slug: params.slug,
stats: params.stats,
category: params.category,
summary: params.summary,
password: params.password,
favicon: params.favicon,
datetime: params.datetime,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private async upsertCustom(params: CustomParams): Promise<NotionPageResponse> {
const {firstChunk, extraChunks} = this.prepareBlocks(params.childArr);
const cover = params.notionId
? await this.resolveCoverForUpdate(params.cover)
: params.cover;
this.debugLog("Upload2Notion", "Upserting custom page", {
blockCount: params.childArr.length,
firstChunkSize: firstChunk.length,
extraChunkCount: extraChunks.length,
cover: cover ?? null,
notionIdExisting: params.notionId ?? null,
customValueKeys: Object.keys(params.customValues || {}),
});
if (params.notionId) {
await this.deletePage(params.notionId);
}
const body = this.buildCustomBody({
customValues: params.customValues,
firstChunk,
});
this.applyCover(body, cover);
console.log(body);
return this.submitPage(body, extraChunks);
}
private buildGeneralBody(params: {title: string; tags: string[]; firstChunk: any[]}): any {
const {
databaseID,
customTitleButton,
customTitleName,
tagButton,
} = this.dbDetails;
return {
parent: {
database_id: databaseID,
},
properties: {
[customTitleButton ? customTitleName : "title"]: {
title: [
{
text: {
content: params.title,
},
},
],
},
...(tagButton
? {
tags: {
multi_select:
params.tags && params.tags.length > 0
? params.tags.map((tag) => ({name: tag}))
: [],
},
}
: {}),
},
children: params.firstChunk,
};
}
private buildNextBody(params: {
firstChunk: any[];
title: string;
emoji: string;
tags: string[];
type: string;
slug: string;
stats: string;
category: string;
summary: string;
password: string;
favicon: string;
datetime: string;
}): any {
const {databaseID} = this.dbDetails;
const pageProperties: any = {
parent: {
database_id: databaseID,
},
properties: {
title: {
title: [
{
text: {
content: params.title,
},
},
],
},
type: {
select: {
name: params.type || "Post",
},
},
status: {
select: {
name: params.stats || "Draft",
},
},
category: {
select: {
name: params.category || "Obsidian",
},
},
password: {
rich_text: [
{
text: {
content: params.password || "",
},
},
],
},
icon: {
rich_text: [
{
text: {
content: params.favicon || "",
},
},
],
},
date: {
date: {
start: params.datetime || new Date().toISOString(),
},
},
},
};
if (params.tags && params.tags.length > 0) {
pageProperties.properties.tags = {
multi_select: params.tags.map((tag) => ({name: tag})),
};
}
if (params.emoji) {
pageProperties.icon = {
emoji: params.emoji,
};
}
if (params.slug) {
pageProperties.properties.slug = {
rich_text: [
{
text: {
content: params.slug,
},
},
],
};
}
if (params.summary) {
pageProperties.properties.summary = {
rich_text: [
{
text: {
content: params.summary,
},
},
],
};
}
return {
...pageProperties,
children: params.firstChunk,
};
}
private buildCustomBody(params: {
customValues: Record<string, string>;
firstChunk: any[];
}): any {
const {customProperties, databaseID} = this.dbDetails;
const properties: { [key: string]: any } = {};
if (customProperties) {
customProperties.forEach(({customName, customType}) => {
if (params.customValues[customName] !== undefined) {
const propertyValue = this.buildCustomProperty(customName, customType, params.customValues);
if (propertyValue !== undefined) {
properties[customName] = propertyValue;
}
}
});
}
return {
parent: {
database_id: databaseID,
},
properties,
children: params.firstChunk,
};
}
private buildCustomProperty(customName: string, customType: string, customValues: Record<string, any>) {
const value = customValues[customName] || "";
switch (customType) {
case "title":
return {
title: [
{
text: {
content: value,
},
},
],
};
case "rich_text":
return {
rich_text: [
{
text: {
content: value || "",
},
},
],
};
case "date":
return {
date: {
start: value || new Date().toISOString(),
},
};
case "number":
return {
number: Number(value),
};
case "phone_number":
return {
phone_number: value,
};
case "email":
return {
email: value,
};
case "url":
return {
url: value,
};
case "files":
return {
files: Array.isArray(value)
? value.map((url: string) => ({
name: url,
type: "external",
external: {
url,
},
}))
: [
{
name: value,
type: "external",
external: {
url: value,
},
},
],
};
case "checkbox":
return {
checkbox: Boolean(value) || false,
};
case "select":
return {
select: {
name: value,
},
};
case "multi_select":
return {
multi_select: Array.isArray(value)
? value.map((item: string) => ({name: item}))
: [{name: value}],
};
case "relation":
return {
relation: Array.isArray(value)
? value.map((item: string) => ({id: item}))
: [{id: value}],
};
default:
return undefined;
}
}
}

View File

@@ -0,0 +1,248 @@
import { Notice, requestUrl } from "obsidian";
import MyPlugin from "src/main";
import { DatabaseDetails } from "../../ui/settingTabs";
import { i18nConfig } from "../../lang/I18n";
export interface NotionPageResponse {
response: any;
data: any;
}
interface PreparedBlocks {
firstChunk: any[];
extraChunks: any[][];
}
export abstract class UploadBase {
protected plugin: MyPlugin;
protected dbDetails: DatabaseDetails;
protected constructor(plugin: MyPlugin, dbDetails: DatabaseDetails) {
this.plugin = plugin;
this.dbDetails = dbDetails;
}
async deletePage(notionID: string) {
const {notionAPI} = this.dbDetails;
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: "",
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Deleting Notion page ${notionID}`),
);
}
protected prepareBlocks(childArr: any[]): PreparedBlocks {
this.stripCodeAnnotations(childArr);
const childArrLength = childArr.length;
if (childArrLength <= 100) {
this.debugLog("UploadBase", "Blocks fit into a single request", {
totalBlocks: childArrLength,
});
return {
firstChunk: childArr,
extraChunks: [],
};
}
const extraChunks: any[][] = [];
for (let i = 100; i < childArr.length; i += 100) {
extraChunks.push(childArr.slice(i, i + 100));
}
this.debugLog("UploadBase", "Blocks split into multiple chunks", {
totalBlocks: childArrLength,
firstChunkSize: 100,
extraChunkCount: extraChunks.length,
lastChunkSize: extraChunks[extraChunks.length - 1].length,
});
return {
firstChunk: childArr.slice(0, 100),
extraChunks,
};
}
protected applyCover(body: any, cover?: string) {
if (cover) {
body.cover = {
type: "external",
external: {
url: cover,
},
};
} else if (!body.cover && this.plugin.settings.bannerUrl) {
body.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl,
},
};
}
this.debugLog("UploadBase", "Cover applied to payload", {
chosenCover: body.cover?.external?.url ?? null,
defaultBannerUsed: !cover && !!this.plugin.settings.bannerUrl,
});
}
protected async resolveCoverForUpdate(cover?: string): Promise<string | undefined> {
if (cover) {
this.debugLog("UploadBase", "Existing cover retained for update", {
cover,
});
return cover;
}
const databaseCover = await this.fetchDatabaseCover();
return databaseCover ?? undefined;
}
protected async submitPage(body: any, extraChunks: any[][]): Promise<NotionPageResponse> {
const {notionAPI} = this.dbDetails;
const startedAt = Date.now();
const response = await requestUrl({
url: `https://api.notion.com/v1/pages`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(body),
throw: false,
}).catch((error) =>
this.handleRequestError(error, "Creating Notion page"),
);
const data = await response.json;
this.debugLog("UploadBase", "Page creation response received", {
status: response.status,
durationMs: Date.now() - startedAt,
notionUrl: data?.url ?? null,
pageId: data?.id ?? null,
});
if (response.status !== 200) {
new Notice(`Error ${data.status}: ${data.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${data.message}`);
} else {
if (extraChunks.length > 0) {
await this.appendExtraBlocks(data.id, extraChunks);
}
}
return {response, data};
}
private stripCodeAnnotations(childArr: any[]) {
childArr.forEach((block: any) => {
if (block.type === "code") {
block.code.rich_text.forEach((item: any) => {
if (item.type === "text" && item.annotations) {
delete item.annotations;
}
});
}
});
}
private async appendExtraBlocks(pageId: string, extraChunks: any[][]) {
const {notionAPI} = this.dbDetails;
for (let i = 0; i < extraChunks.length; i++) {
const chunk = extraChunks[i];
const extraBlocks = {
children: chunk,
};
const extraResponse = await requestUrl({
url: `https://api.notion.com/v1/blocks/${pageId}/children`,
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
body: JSON.stringify(extraBlocks),
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Appending blocks to page ${pageId}`),
);
const extraData: any = await extraResponse.json;
if (extraResponse.status !== 200) {
new Notice(`Error ${extraData.status}: ${extraData.code} \n ${i18nConfig["CheckConsole"]}`, 5000);
console.log(`Error message: \n ${extraData.message}`);
} else {
console.log(`${i18nConfig["ExtraBlockUploaded"]} to page: ${pageId}`);
if (i === extraChunks.length - 1) {
console.log(`${i18nConfig["BlockUploaded"]} to page: ${pageId}`);
new Notice(`${i18nConfig["BlockUploaded"]} page: ${pageId}`, 5000);
}
}
}
}
private async fetchDatabaseCover(): Promise<string | null> {
const {notionAPI, databaseID} = this.dbDetails;
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: "GET",
headers: {
Authorization: "Bearer " + notionAPI,
"Notion-Version": "2022-06-28",
},
throw: false,
}).catch((error) =>
this.handleRequestError(error, `Fetching database ${databaseID}`),
);
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
}
return null;
}
protected debugLog(context: string, message: string, payload?: Record<string, unknown>): void {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
protected maskValue(value?: string, visibleChars = 4): string | undefined {
if (!value) {
return value;
}
if (value.length <= visibleChars * 2) {
return `${value.slice(0, visibleChars)}***`;
}
return `${value.slice(0, visibleChars)}***${value.slice(-visibleChars)}`;
}
private handleRequestError(error: unknown, context: string): never {
const message = error instanceof Error && error.message
? error.message
: String(error);
console.error(`[UploadBase] ${context} failed`, {
message,
error,
});
throw new Error(
`${context} failed: ${message}. Please check your network connection or proxy settings.`,
);
}
}

View File

@@ -0,0 +1,62 @@
import {App, Notice} from "obsidian";
import {i18nConfig} from "../../lang/I18n";
import {DatabaseDetails} from "../../ui/settingTabs";
export async function getNowFileMarkdownContentCustom(
app: App,
dbDetails: DatabaseDetails,
) {
const nowFile = app.workspace.getActiveFile();
if (!nowFile) {
new Notice(i18nConfig["open-file"]);
return;
}
let cover = '';
let customValues: Record<string, any> = {};
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
cover = FileCache.frontmatter.coverurl;
// Get custom property names from dbDetails excluding the title type property
const customPropertyNames = dbDetails.customProperties
.filter(property => property.customType !== 'title') // Exclude 'title' type property
.map(property => property.customName);
// Extract custom values from the front matter based on the names
// Only collect data 'Relation' should be handled separately in the function buildBodyString
customPropertyNames.forEach(propertyName => {
if (FileCache.frontmatter && FileCache.frontmatter[propertyName] !== undefined) {
customValues[propertyName] = FileCache.frontmatter[propertyName];
}
});
// Check if any of the customProperties has a customType of 'title'
const titleProperty = dbDetails.customProperties
.find(property => property.customType === 'title');
// If a 'title' type property exists, use the file's basename as its value
if (titleProperty) {
customValues[titleProperty.customName] =
(FileCache.frontmatter && FileCache.frontmatter[titleProperty.customName]) ?
FileCache.frontmatter[titleProperty.customName] : // use the front matter value if it exists
nowFile.basename; // Use 'basename' for the file name without extension
}
} catch (error) {
new Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = await nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
cover,
customValues,
};
} else {
new Notice(i18nConfig["open-file"]);
return;
}
}

View File

@@ -0,0 +1,33 @@
import { App, Notice } from "obsidian";
import { i18nConfig } from "../../lang/I18n";
import { PluginSettings } from "../../ui/settingTabs";
export async function getNowFileMarkdownContentGeneral(
app: App,
settings: PluginSettings,
) {
const nowFile = app.workspace.getActiveFile();
let cover = '';
let tags = [];
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
cover = FileCache.frontmatter.coverurl;
tags = FileCache.frontmatter.tags;
} catch (error) {
new Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = await nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
cover,
tags,
};
} else {
new Notice(i18nConfig["open-file"]);
return;
}
}

View File

@@ -13,6 +13,7 @@ export async function getNowFileMarkdownContentNext(
let type = '';
let slug = '';
let stats = '';
let status = '';
let category = '';
let summary = '';
let paword = '';
@@ -26,7 +27,7 @@ export async function getNowFileMarkdownContentNext(
tags = FileCache.frontmatter.tags;
type = FileCache.frontmatter.type;
slug = FileCache.frontmatter.slug;
stats = FileCache.frontmatter.stats;
stats = FileCache.frontmatter.stats || FileCache.frontmatter.status;
category = FileCache.frontmatter.category;
summary = FileCache.frontmatter.summary;
paword = FileCache.frontmatter.password;

View File

@@ -1,6 +1,8 @@
import { App, Notice, TFile } from "obsidian";
import ObsidianSyncNotionPlugin from "../main";
import { PluginSettings } from "../ui/settingTabs";
import { DatabaseDetails } from "../ui/settingTabs";
import { i18nConfig } from "src/lang/I18n";
import { ensureAutoSyncDatabaseEntry } from "src/utils/frontmatter";
export async function updateYamlInfo(
yamlContent: string,
@@ -8,10 +10,15 @@ export async function updateYamlInfo(
res: any,
app: App,
plugin: ObsidianSyncNotionPlugin,
dbDetails: DatabaseDetails,
) {
let { url, id } = res.json
let { url, id } = res;
// replace www to notionID
const { notionUser } = plugin.settings;
const { notionUser, NotionLinkDisplay } = plugin.settings;
const { abName } = dbDetails
const notionIDKey = `NotionID-${abName}`;
const linkKey = `link-${abName}`;
const autoSyncKey = plugin.getAutoSyncFrontmatterKey();
if (notionUser !== "") {
// replace url str "www" to notionID
@@ -19,33 +26,27 @@ export async function updateYamlInfo(
}
await app.fileManager.processFrontMatter(nowFile, yamlContent => {
if (yamlContent['notionID']) {
delete yamlContent['notionID']
if (yamlContent[notionIDKey]) {
delete yamlContent[notionIDKey]
}
if (yamlContent['link']) {
delete yamlContent['link']
if (yamlContent[linkKey]) {
delete yamlContent[linkKey]
}
// add new notionID and link
yamlContent.notionID = id;
yamlContent.link = url;
yamlContent[notionIDKey] = id;
(NotionLinkDisplay) ? yamlContent[linkKey] = url : null;
// ensure auto sync database list contains current short name
yamlContent[autoSyncKey] = ensureAutoSyncDatabaseEntry(
yamlContent[autoSyncKey],
abName
);
});
try {
await navigator.clipboard.writeText(url)
} catch (error) {
new Notice(`复制链接失败,请手动复制${error}`)
console.log(error)
new Notice(`${i18nConfig.CopyErrorMessage}`);
}
// const __content = yamlContent.__content;
// delete yamlContent.__content
// const yamlhead = yaml.stringify(yamlContent)
// // if yamlhead hava last \n remove it
// const yamlhead_remove_n = yamlhead.replace(/\n$/, '')
// // if __content have start \n remove it
// const __content_remove_n = __content.replace(/^\n/, '')
// const content = '---\n' +yamlhead_remove_n +'\n---\n' + __content_remove_n;
// try {
// await nowFile.vault.modify(nowFile, content)
// } catch (error) {
// new Notice(`write file error ${error}`)
// }
}

View File

@@ -1,62 +1,158 @@
import {i18nConfig} from "../lang/I18n";
import {App, Notice} from "obsidian";
import { Upload2NotionNext } from "./upload_next/Upload2NotionNext";
import { Upload2NotionGeneral } from "./upload_general/Upload2NotionGeneral";
import { PluginSettings } from "../ui/settingTabs";
import {Upload2Notion} from "./Upload2Notion";
import type {NotionPageResponse} from "./common/UploadBase";
import {DatabaseDetails, PluginSettings} from "../ui/settingTabs";
import ObsidianSyncNotionPlugin from "../main";
import { getNowFileMarkdownContentNext } from "./upload_next/getMarkdownNext";
import { getNowFileMarkdownContentGeneral } from "./upload_general/getMarkdownGeneral";
import {getNowFileMarkdownContentNext} from "./common/getMarkdownNext";
import {getNowFileMarkdownContentGeneral} from "./common/getMarkdownGeneral";
import {getNowFileMarkdownContentCustom} from "./common/getMarkdownCustom";
const SYNC_ERROR_NOTICE_DURATION = 8000;
function extractErrorMessage(error: unknown): string {
if (error instanceof Error && error.message) {
return error.message;
}
return String(error);
}
function notifySyncError(prefix: string, basename: string, error: unknown): void {
const errorMessage = extractErrorMessage(error);
console.error(`${prefix} Sync failed`, error);
new Notice(
`${i18nConfig["sync-fail"]} ${basename}. ${errorMessage}\n${i18nConfig["CheckConsole"]}`,
SYNC_ERROR_NOTICE_DURATION,
);
}
function logCommandDebug(context: string, message: string, payload?: Record<string, unknown>): void {
if (payload) {
console.log(`[${context}] ${message}`, payload);
} else {
console.log(`[${context}] ${message}`);
}
}
export async function uploadCommandNext(
plugin: ObsidianSyncNotionPlugin,
settings: PluginSettings,
dbDetails: DatabaseDetails,
app: App,
) {
const { notionAPINext, databaseIDNext } = settings;
// Check if NNon exists
// if (NNon === undefined) {
// const NNonmessage = i18nConfig.NNonMissing;
// new Notice(NNonmessage);
// return;
// }
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandNext] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPINext === "" || databaseIDNext === "") {
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new Notice(setAPIMessage);
return;
}
const { markDownData, nowFile, emoji, cover, tags, type, slug, stats, category, summary, paword, favicon, datetime } = await getNowFileMarkdownContentNext(app, settings)
const {
markDownData,
nowFile,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime
} = await getNowFileMarkdownContentNext(app, settings);
logCommandDebug("uploadCommandNext", "Metadata extracted from markdown", {
hasMarkdown: !!markDownData,
markdownLength: markDownData?.length ?? 0,
tagCount: tags?.length ?? 0,
coverIncluded: !!cover,
hasEmoji: !!emoji,
type,
slug,
hasPassword: !!paword,
datetime,
});
if (markDownData) {
const {basename} = nowFile;
const upload = new Upload2NotionNext(plugin);
const res = await upload.syncMarkdownToNotionNext(basename, emoji, cover, tags, type, slug, stats, category, summary, paword, favicon, datetime, markDownData, nowFile, this.app);
logCommandDebug("uploadCommandNext", "Preparing to upload", {
filename: basename,
filePath: nowFile.path,
});
if (res.status === 200) {
new Notice(`${i18nConfig["sync-success"]}${basename}`);
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "next",
title: basename,
emoji: emoji || "",
cover: cover || "",
tags: tags || [],
type: type || "",
slug: slug || "",
stats: stats || "",
category: category || "",
summary: summary || "",
password: paword || "",
favicon: favicon || "",
datetime: datetime || "",
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandNext]", basename, error);
logCommandDebug("uploadCommandNext", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandNext", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandNext", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}
}
export async function uploadCommandGeneral(
plugin: ObsidianSyncNotionPlugin,
settings: PluginSettings,
dbDetails: DatabaseDetails,
app: App,
) {
const { notionAPIGeneral, databaseIDGeneral } = settings;
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandGeneral] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPIGeneral === "" || databaseIDGeneral === "") {
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new Notice(setAPIMessage);
return;
@@ -64,16 +160,135 @@ export async function uploadCommandGeneral(
const {markDownData, nowFile, cover, tags} = await getNowFileMarkdownContentGeneral(app, settings)
new Notice(i18nConfig.StartUpload.replace('{filename}', nowFile.basename));
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const {basename} = nowFile;
logCommandDebug("uploadCommandGeneral", "Preparing to upload", {
filename: basename,
markdownLength: markDownData.length,
tagCount: tags?.length ?? 0,
hasCover: !!cover,
});
const upload = new Upload2NotionGeneral(plugin);
const res = await upload.syncMarkdownToNotionGeneral(basename, cover, tags, markDownData, nowFile, this.app);
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "general",
title: basename,
cover: cover || "",
tags: tags || [],
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandGeneral]", basename, error);
logCommandDebug("uploadCommandGeneral", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
if (res.status === 200) {
new Notice(`${i18nConfig["sync-success"]}${basename}`);
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandGeneral", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandGeneral", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}
}
export async function uploadCommandCustom(
plugin: ObsidianSyncNotionPlugin,
settings: PluginSettings,
dbDetails: DatabaseDetails,
app: App,
) {
const {notionAPI, databaseID} = dbDetails;
console.log(`[uploadCommandCustom] ${new Date().toISOString()} Triggered for file`, app.workspace.getActiveFile()?.path);
// Check if the user has set up the Notion API and database ID
if (notionAPI === "" || databaseID === "") {
const setAPIMessage = i18nConfig["set-api-id"];
new Notice(setAPIMessage);
return;
}
const {markDownData, nowFile, cover, customValues} = await getNowFileMarkdownContentCustom(app, dbDetails)
new Notice(i18nConfig.StartUpload.replace('{filename}', nowFile.basename));
console.log(`Start upload ${nowFile.basename}`);
if (markDownData) {
const {basename} = nowFile;
logCommandDebug("uploadCommandCustom", "Preparing to upload", {
filename: basename,
markdownLength: markDownData.length,
hasCover: !!cover,
customValueKeys: Object.keys(customValues || {}),
});
const upload = new Upload2Notion(plugin, dbDetails);
let res: NotionPageResponse;
try {
res = await upload.sync({
dataset: "custom",
cover: cover || "",
customValues,
markdown: markDownData,
nowFile,
app,
});
} catch (error: unknown) {
notifySyncError("[uploadCommandCustom]", basename, error);
logCommandDebug("uploadCommandCustom", "Sync threw error", {
filename: basename,
error: extractErrorMessage(error),
});
return;
}
const {response} = res;
if (response.status === 200) {
new Notice(`${i18nConfig["sync-preffix"]} ${basename} ${i18nConfig["sync-success"]}`).noticeEl.style.color = "green";
logCommandDebug("uploadCommandCustom", "Sync succeeded", {
filename: basename,
status: response.status,
pageId: res.data?.id ?? null,
pageUrl: res.data?.url ?? null,
});
} else {
new Notice(`${i18nConfig["sync-fail"]} ${basename}`, 5000);
console.log(`${i18nConfig["sync-fail"]} ${basename}`);
logCommandDebug("uploadCommandCustom", "Sync failed with status", {
filename: basename,
status: response.status,
errorCode: res.data?.code ?? null,
errorStatus: res.data?.status ?? null,
});
}
}

View File

@@ -1,90 +0,0 @@
import {App, Notice, requestUrl, TFile} from "obsidian";
import {Client} from '@notionhq/client';
import {markdownToBlocks,} from "@tryfabric/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
export class UploadBaseGeneral {
plugin: MyPlugin;
notion: Client;
agent: any;
constructor(plugin: MyPlugin) {
this.plugin = plugin;
}
async deletePage(notionID: string) {
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.plugin.settings.notionAPINext,
'Notion-Version': '2022-06-28',
},
body: ''
});
}
async getDataBase(databaseID: string) {
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.plugin.settings.notionAPINext,
'Notion-Version': '2022-06-28',
}
}
)
// Check if cover is present in the JSON response and then get the URL
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
} else {
return null; // or some other default value, if you prefer
}
}
// async updateYamlInfo(yamlContent: string, nowFile: TFile, res: any, app: App, settings: any) {
// let {url, id} = res.json
// // replace www to notionID
// const {notionUser} = this.plugin.settings;
//
// if (notionUser !== "") {
// // replace url str "www" to notionID
// url = url.replace("www.notion.so", `${notionUser}.notion.site`)
// }
//
// await app.fileManager.processFrontMatter(nowFile, yamlContent => {
// if (yamlContent['notionID']) {
// delete yamlContent['notionID']
// }
// if (yamlContent['link']) {
// delete yamlContent['link']
// }
// // add new notionID and link
// yamlContent.notionID = id;
// yamlContent.link = url;
// });
//
// try {
// await navigator.clipboard.writeText(url)
// } catch (error) {
// new Notice(`复制链接失败,请手动复制${error}`)
// }
// // const __content = yamlContent.__content;
// // delete yamlContent.__content
// // const yamlhead = yaml.stringify(yamlContent)
// // // if yamlhead hava last \n remove it
// // const yamlhead_remove_n = yamlhead.replace(/\n$/, '')
// // // if __content have start \n remove it
// // const __content_remove_n = __content.replace(/^\n/, '')
// // const content = '---\n' +yamlhead_remove_n +'\n---\n' + __content_remove_n;
// // try {
// // await nowFile.vault.modify(nowFile, content)
// // } catch (error) {
// // new Notice(`write file error ${error}`)
// // }
// }
}

View File

@@ -1,144 +0,0 @@
import { App, Notice, requestUrl, TFile } from "obsidian";
import { Client } from '@notionhq/client';
import { markdownToBlocks, } from "@tryfabric/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import { PluginSettings } from "../../ui/settingTabs";
import { UploadBaseGeneral } from "./BaseUpload2NotionGeneral";
import { updateYamlInfo } from "../updateYaml";
export class Upload2NotionGeneral extends UploadBaseGeneral {
settings: PluginSettings;
constructor(plugin: MyPlugin) {
super(plugin);
}
// 因为需要解析notion的block进行对比非常的麻烦
// 暂时就直接删除新建一个page
async updatePage(
notionID: string,
title: string,
cover: string,
tags: string[],
childArr: any,
) {
await this.deletePage(notionID)
const databasecover = await this.getDataBase(this.plugin.settings.databaseIDGeneral)
if (cover == null) {
cover = databasecover
}
return await this.createPage(
title,
cover,
tags,
childArr)
}
async createPage(
title: string,
cover: string,
tags: string[],
childArr: any,
) {
const bodyString: any = {
parent: {
database_id: this.plugin.settings.databaseIDGeneral,
},
properties: {
[this.plugin.settings.CustomTitleButton ? this.plugin.settings.CustomTitleName : 'title']: {
title: [
{
text: {
content: title
},
},
],
},
tags: {
multi_select: tags && true ? tags.map(tag => {
return { "name": tag }
}) : [],
},
},
children: childArr,
}
if (cover) {
bodyString.cover = {
type: "external",
external: {
url: cover
}
}
}
if (!bodyString.cover && this.plugin.settings.bannerUrl) {
bodyString.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl
}
}
}
try {
return await requestUrl({
url: `https://api.notion.com/v1/pages`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'User-Agent': 'obsidian.md',
'Authorization': 'Bearer ' + this.plugin.settings.notionAPIGeneral,
'Notion-Version': '2022-06-28',
},
body: JSON.stringify(bodyString),
})
} catch (error) {
new Notice(`network error ${error}`)
}
}
async syncMarkdownToNotionGeneral(
title: string,
cover: string,
tags: string[],
markdown: string,
nowFile: TFile,
app: App,
): Promise<any> {
let res: any
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const __content = yamlContent.__content
const file2Block = markdownToBlocks(__content);
const frontmasster = app.metadataCache.getFileCache(nowFile)?.frontmatter
const notionID = frontmasster ? frontmasster.notionID : null
if (notionID) {
res = await this.updatePage(
notionID,
title,
cover,
tags,
file2Block
);
} else {
res = await this.createPage(
title,
cover,
tags,
file2Block
);
}
if (res.status === 200) {
await updateYamlInfo(markdown, nowFile, res, app, this.plugin)
} else {
new Notice(`${res.text}`)
}
return res
}
}

View File

@@ -1,33 +0,0 @@
import {App, Notice} from "obsidian";
import {i18nConfig} from "../../lang/I18n";
import {PluginSettings} from "../../ui/settingTabs";
export async function getNowFileMarkdownContentGeneral(
app: App,
settings: PluginSettings,
) {
const nowFile = app.workspace.getActiveFile();
let cover = '';
let tags = [];
const FileCache = app.metadataCache.getFileCache(nowFile);
try {
cover = FileCache.frontmatter.coverurl;
tags = FileCache.frontmatter.tags;
} catch (error) {
new Notice(i18nConfig["set-tags-fail"]);
}
if (nowFile) {
const markDownData = await nowFile.vault.read(nowFile);
return {
markDownData,
nowFile,
cover,
tags,
};
} else {
new Notice(i18nConfig["open-file"]);
return;
}
}

View File

@@ -1,90 +0,0 @@
import {App, Notice, requestUrl, TFile} from "obsidian";
import {Client} from '@notionhq/client';
import {markdownToBlocks,} from "@tryfabric/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
export class UploadBaseNext {
plugin: MyPlugin;
notion: Client;
agent: any;
constructor(plugin: MyPlugin) {
this.plugin = plugin;
}
async deletePage(notionID: string) {
return requestUrl({
url: `https://api.notion.com/v1/blocks/${notionID}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.plugin.settings.notionAPINext,
'Notion-Version': '2022-06-28',
},
body: ''
});
}
async getDataBase(databaseID: string) {
const response = await requestUrl({
url: `https://api.notion.com/v1/databases/${databaseID}`,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.plugin.settings.notionAPINext,
'Notion-Version': '2022-06-28',
}
}
)
// Check if cover is present in the JSON response and then get the URL
if (response.json.cover && response.json.cover.external) {
return response.json.cover.external.url;
} else {
return null; // or some other default value, if you prefer
}
}
// async updateYamlInfo(yamlContent: string, nowFile: TFile, res: any, app: App, settings: any) {
// let {url, id} = res.json
// // replace www to notionID
// const { notionUser} = this.plugin.settings;
//
// if (notionUser !== "") {
// // replace url str "www" to notionID
// url = url.replace("www.notion.so", `${notionUser}.notion.site`)
// }
//
// await app.fileManager.processFrontMatter(nowFile, yamlContent => {
// if (yamlContent['notionID']) {
// delete yamlContent['notionID']
// }
// if (yamlContent['link']) {
// delete yamlContent['link']
// }
// // add new notionID and link
// yamlContent.notionID = id;
// yamlContent.link = url;
// });
//
// try {
// await navigator.clipboard.writeText(url)
// } catch (error) {
// new Notice(`复制链接失败,请手动复制${error}`)
// }
// // const __content = yamlContent.__content;
// // delete yamlContent.__content
// // const yamlhead = yaml.stringify(yamlContent)
// // // if yamlhead hava last \n remove it
// // const yamlhead_remove_n = yamlhead.replace(/\n$/, '')
// // // if __content have start \n remove it
// // const __content_remove_n = __content.replace(/^\n/, '')
// // const content = '---\n' +yamlhead_remove_n +'\n---\n' + __content_remove_n;
// // try {
// // await nowFile.vault.modify(nowFile, content)
// // } catch (error) {
// // new Notice(`write file error ${error}`)
// // }
// }
}

View File

@@ -1,257 +0,0 @@
import { UploadBaseNext } from "./BaseUpload2NotionNext";
import { App, Notice, requestUrl, TFile } from "obsidian";
import { Client } from '@notionhq/client';
import { markdownToBlocks, } from "@tryfabric/martian";
import * as yamlFrontMatter from "yaml-front-matter";
// import * as yaml from "yaml"
import MyPlugin from "src/main";
import {PluginSettings} from "../../ui/settingTabs";
import {updateYamlInfo} from "../updateYaml";
export class Upload2NotionNext extends UploadBaseNext {
settings: PluginSettings;
constructor(plugin: MyPlugin) {
super(plugin);
}
// 因为需要解析notion的block进行对比非常的麻烦
// 暂时就直接删除新建一个page
async updatePage(
notionID: string,
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
paword: string,
favicon: string,
datetime: string,
childArr: any
) {
await this.deletePage(notionID)
const databasecover = await this.getDataBase(this.plugin.settings.databaseIDNext)
if (cover == null) {
cover = databasecover
}
return await this.createPage(
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
childArr)
}
async createPage(
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
pawrod: string,
favicon: string,
datetime: string,
childArr: any
) {
const bodyString: any = {
parent: {
database_id: this.plugin.settings.databaseIDNext
},
icon: {
emoji: emoji || '📜'
},
properties: {
title: {
title: [
{
text: {
content: title
},
},
],
},
tags: {
multi_select: tags && true ? tags.map(tag => {
return { "name": tag }
}) : [],
},
type: {
select: {
name: type || 'Post'
}
},
slug: {
rich_text: [
{
text: {
content: slug || ''
}
}
]
},
status: {
select: {
name: stats || 'Draft'
}
},
category: {
select: {
name: category || 'Obsidian'
}
},
summary: {
rich_text: [
{
text: {
content: summary || ''
}
}
]
},
password: {
rich_text: [
{
text: {
content: pawrod || ''
}
}
]
},
icon: {
rich_text: [
{
text: {
content: favicon || ''
}
}
]
},
date: {
date: {
start: datetime || new Date().toISOString()
}
}
},
children: childArr,
}
if (cover) {
bodyString.cover = {
type: "external",
external: {
url: cover
}
}
}
if (!bodyString.cover && this.plugin.settings.bannerUrl) {
bodyString.cover = {
type: "external",
external: {
url: this.plugin.settings.bannerUrl
}
}
}
try {
return await requestUrl({
url: `https://api.notion.com/v1/pages`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'User-Agent': 'obsidian.md',
'Authorization': 'Bearer ' + this.plugin.settings.notionAPINext,
'Notion-Version': '2022-06-28',
},
body: JSON.stringify(bodyString),
})
} catch (error) {
new Notice(`network error ${error}`)
}
}
async syncMarkdownToNotionNext(
title: string,
emoji: string,
cover: string,
tags: string[],
type: string,
slug: string,
stats: string,
category: string,
summary: string,
paword: string,
favicon: string,
datetime: string,
markdown: string,
nowFile: TFile,
app: App,
): Promise<any> {
let res: any
const yamlContent: any = yamlFrontMatter.loadFront(markdown);
const __content = yamlContent.__content
const file2Block = markdownToBlocks(__content);
const frontmasster = app.metadataCache.getFileCache(nowFile)?.frontmatter
const notionID = frontmasster ? frontmasster.notionID : null
if (notionID) {
res = await this.updatePage(
notionID,
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
file2Block
);
} else {
res = await this.createPage(
title,
emoji,
cover,
tags,
type,
slug,
stats,
category,
summary,
paword,
favicon,
datetime,
file2Block
);
}
if (res.status === 200) {
await updateYamlInfo(markdown, nowFile, res, app, this.plugin)
} else {
new Notice(`${res.text}`)
}
return res
}
}

63
src/utils/frontmatter.ts Normal file
View File

@@ -0,0 +1,63 @@
export const DEFAULT_AUTO_SYNC_DATABASE_KEY = "autosync-database";
export function resolveAutoSyncKey(rawKey: unknown): string {
if (typeof rawKey === "string") {
const trimmed = rawKey.trim();
if (trimmed.length > 0) {
return trimmed;
}
}
return DEFAULT_AUTO_SYNC_DATABASE_KEY;
}
function toCandidateList(value: unknown): string[] {
if (Array.isArray(value)) {
return value.map(item => String(item ?? "").trim());
}
if (typeof value === "string") {
if (value.includes(",")) {
return value.split(",").map(item => item.trim());
}
return [value.trim()];
}
return [];
}
export function parseAutoSyncDatabaseList(value: unknown): string[] {
const candidates = toCandidateList(value)
.map(name => name.replace(/^\[|\]$/g, "").trim()) // strip stray brackets
.filter(Boolean);
const seen = new Map<string, string>();
for (const name of candidates) {
const key = name.toLowerCase();
if (!seen.has(key)) {
seen.set(key, name);
}
}
return Array.from(seen.values());
}
export function ensureAutoSyncDatabaseEntry(value: unknown, abName: string): string[] {
const current = parseAutoSyncDatabaseList(value);
const lower = abName.toLowerCase();
let contains = false;
const updated = current.map(name => {
if (name.toLowerCase() === lower) {
contains = true;
return abName;
}
return name;
});
if (!contains) {
updated.push(abName);
}
return updated;
}

View File

@@ -3,6 +3,8 @@
"baseUrl": ".",
"inlineSourceMap": true,
"inlineSources": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"module": "ESNext",
"target": "ES6",
"allowJs": true,
@@ -17,8 +19,8 @@
]
},
"include": [
"**/*.ts"
,
"src/Upload2Notion.ts"
"**/*.ts",
"src/Upload2Notion.ts",
"src/*.ts"
]
}

View File

@@ -1,11 +1,10 @@
// update package.json version
import fs from 'fs';
import fs from "fs";
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
const packageJson = JSON.parse(fs.readFileSync("./package.json", "utf8"));
console.log(packageJson.version);
// get node args
const args = process.argv.slice(2);
@@ -13,14 +12,13 @@ packageJson.version = args[0];
console.log(packageJson.version);
// write package.json
fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2));
fs.writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
// read manifest.json
const manifestJson = JSON.parse(fs.readFileSync('./manifest.json', 'utf8'));
const manifestJson = JSON.parse(fs.readFileSync("./manifest.json", "utf8"));
manifestJson.version = args[0];
// write manifest.json
fs.writeFileSync('./manifest.json', JSON.stringify(manifestJson, null, 2));
fs.writeFileSync("./manifest.json", JSON.stringify(manifestJson, null, 2));

1478
yarn.lock

File diff suppressed because it is too large Load Diff