diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..6c3d019
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,51 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_call:
+
+jobs:
+ test:
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Go
+ uses: actions/setup-go@v5
+ with:
+ go-version-file: go.mod
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Install frontend dependencies
+ working-directory: frontend
+ run: npm ci
+
+ - name: Build frontend assets
+ working-directory: frontend
+ run: npm run build
+
+ - name: Install Linux dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev
+
+ - name: Go vet
+ run: go vet ./internal/... .
+
+ - name: Go tests
+ run: go test ./internal/... .
+
+ - name: TypeScript check
+ working-directory: frontend
+ run: npx tsc --noEmit
+
+ - name: Frontend tests
+ working-directory: frontend
+ env:
+ TZ: Asia/Shanghai
+ run: npm test
diff --git a/.github/workflows/release-v2.yml b/.github/workflows/release-v2.yml
index d980107..e077a2b 100644
--- a/.github/workflows/release-v2.yml
+++ b/.github/workflows/release-v2.yml
@@ -14,7 +14,11 @@ on:
required: true
jobs:
+ test:
+ uses: ./.github/workflows/ci.yml
+
build:
+ needs: test
strategy:
matrix:
include:
@@ -39,7 +43,7 @@ jobs:
- name: Setup Go
uses: actions/setup-go@v5
with:
- go-version: "1.22"
+ go-version-file: go.mod
- name: Setup Node
uses: actions/setup-node@v4
@@ -54,7 +58,7 @@ jobs:
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev
- name: Install Wails
- run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
+ run: go install github.com/wailsapp/wails/v2/cmd/wails@v2.12.0
- name: Install frontend deps
shell: bash
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
deleted file mode 100644
index 8b0ff47..0000000
--- a/.github/workflows/release.yml
+++ /dev/null
@@ -1,173 +0,0 @@
-name: Build & Release
-
-permissions:
- contents: write
-
-on:
- push:
- tags:
- - "v*"
- workflow_dispatch:
- inputs:
- version:
- description: "Release version (e.g. 1.0.2 or v1.0.2)"
- required: true
-
-jobs:
- build:
- strategy:
- matrix:
- include:
- - os: macos-15
- platform: darwin
- arch: arm64
- - os: macos-15-intel
- platform: darwin
- arch: x86_64
- - os: windows-2022
- platform: windows
- arch: amd64
- - os: ubuntu-22.04
- platform: linux
- arch: amd64
-
- runs-on: ${{ matrix.os }}
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup Go
- uses: actions/setup-go@v5
- with:
- go-version: "1.22"
-
- - uses: actions/setup-node@v4
- with:
- node-version: "20"
-
- - name: Install Linux deps
- if: runner.os == 'Linux'
- run: |
- sudo apt-get update
- sudo apt-get install -y zip
- sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev
-
- - name: Install Wails
- run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
-
- - name: Install frontend deps
- shell: bash
- working-directory: frontend
- run: |
- if [ -f package-lock.json ]; then
- npm ci
- else
- npm install --no-audit --no-fund
- fi
-
- - name: Build
- shell: bash
- run: |
- if [ "$RUNNER_OS" = "Windows" ]; then
- wails build -clean -platform windows/amd64
- else
- wails build -clean
- fi
-
- - name: Package (Windows)
- if: runner.os == 'Windows'
- run: |
- mkdir dist
- @'
- Windows 下载/运行说明(重要)
-
- 你从 GitHub Release 下载的 .zip/.exe 可能会被 Windows 标记为“来自互联网”(MOTW),导致:
- - 弹出“Windows 已保护你的电脑”(SmartScreen)
- - 第一次启动较慢/卡住(安全扫描 + WebView2 初始化)
-
- 解决办法(任选其一):
-
- 1) 推荐:先对 zip 解除锁定,再解压
- - 右键 zip -> 属性 -> 勾选/点击“解除锁定(Unblock)” -> 应用
-
- 2) 或者:解压后对 exe 解除锁定
- - 右键 exe -> 属性 -> “解除锁定(Unblock)” -> 应用
-
- 3) PowerShell(可选):
- Unblock-File .\LockNote.exe
- 或对整个文件夹:
- Get-ChildItem -Recurse | Unblock-File
- '@ | Out-File -Encoding utf8 dist/README-WINDOWS.txt
-
- Compress-Archive -Path build/bin/*,dist/README-WINDOWS.txt -DestinationPath dist/locknote-${{ matrix.platform }}-${{ matrix.arch }}.zip
-
- - name: Package (macOS)
- if: runner.os == 'macOS'
- run: |
- mkdir -p dist
- cd build/bin
- zip -r ../../dist/locknote-${{ matrix.platform }}-${{ matrix.arch }}.zip .
-
- - name: Package (Linux)
- if: runner.os == 'Linux'
- run: |
- mkdir -p dist
- cd build/bin
- zip -r ../../dist/locknote-${{ matrix.platform }}-${{ matrix.arch }}.zip .
-
- - uses: actions/upload-artifact@v4
- with:
- name: locknote-${{ matrix.platform }}-${{ matrix.arch }}
- path: dist/*.zip
-
- release:
- needs: build
- if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v4
- with:
- fetch-depth: 0
-
- - name: Determine release tag
- id: reltag
- shell: bash
- run: |
- if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
- v="${{ inputs.version }}"
- if [[ "$v" == v* ]]; then
- echo "tag=$v" >> "$GITHUB_OUTPUT"
- else
- echo "tag=v$v" >> "$GITHUB_OUTPUT"
- fi
- else
- echo "tag=${{ github.ref_name }}" >> "$GITHUB_OUTPUT"
- fi
-
- - name: Create and push tag (workflow_dispatch)
- if: github.event_name == 'workflow_dispatch'
- shell: bash
- run: |
- TAG="${{ steps.reltag.outputs.tag }}"
- git config user.name "github-actions[bot]"
- git config user.email "github-actions[bot]@users.noreply.github.com"
-
- if git rev-parse "$TAG" >/dev/null 2>&1; then
- echo "Tag $TAG already exists locally."
- else
- git tag -a "$TAG" -m "Release $TAG"
- fi
-
- if git ls-remote --exit-code --tags origin "refs/tags/$TAG" >/dev/null 2>&1; then
- echo "Tag $TAG already exists on origin."
- else
- git push origin "refs/tags/$TAG"
- fi
-
- - uses: actions/download-artifact@v4
-
- - uses: softprops/action-gh-release@v2
- with:
- tag_name: ${{ steps.reltag.outputs.tag }}
- files: "**/*.zip"
diff --git a/.gitignore b/.gitignore
index 501871a..ac548de 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,7 @@
/frontend/node_modules_ubuntu/
/frontend/node_modules_mac/
/build/
+/.idea/
/.vscode/
/tests/*
!/tests/source/
diff --git a/.idea/.gitignore b/.idea/.gitignore
deleted file mode 100644
index 35410ca..0000000
--- a/.idea/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# 默认忽略的文件
-/shelf/
-/workspace.xml
-# 基于编辑器的 HTTP 客户端请求
-/httpRequests/
-# Datasource local storage ignored files
-/dataSources/
-/dataSources.local.xml
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
deleted file mode 100644
index c73d219..0000000
--- a/.idea/inspectionProfiles/Project_Default.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/jsLinters/jshint.xml b/.idea/jsLinters/jshint.xml
deleted file mode 100644
index 01dd1a2..0000000
--- a/.idea/jsLinters/jshint.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/locknote-client.iml b/.idea/locknote-client.iml
deleted file mode 100644
index 5e764c4..0000000
--- a/.idea/locknote-client.iml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
deleted file mode 100644
index 9450de9..0000000
--- a/.idea/modules.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index 94a25f7..0000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/README.en.md b/README.en.md
index 2b47928..e8c9191 100644
--- a/README.en.md
+++ b/README.en.md
@@ -190,13 +190,16 @@ locknote/
The Wails entry point, same-package APIs, and tests of unexported functions remain at the root.
Source contract tests live in tests/source/: run go test ./tests/source, or go test ./... for all Go tests.
-## Security Notes
+## Security Model
-- Master key only resides in memory after unlocking
+LockNote encrypts note bodies, titles and previews, note history, attachments and thumbnails, and todo titles. Tag names, notebook names, original attachment filenames, smart-view filters, password hints, timestamps, and file counts and sizes are not encrypted.
+
+Backups contain only notes, history, and attachments; they do not contain tags, notebooks, todos, settings, or the database. **Restore Backup works only with a backup from the same vault.** To move data to another device or use a different key, use recovery-key import. If both the password and recovery key are lost, the data is unrecoverable by design.
+
+- The master key remains in memory only after unlocking
- Each note uses an independent random nonce
-- Ciphertext files use atomic write
-- Password reset supported via recovery key
-- If you lose both your login password and the recovery key, your data cannot be recovered
+- Ciphertext files are written atomically
+- Password reset is supported through the recovery key
## Version
diff --git a/README.md b/README.md
index 9daca1a..28332c4 100644
--- a/README.md
+++ b/README.md
@@ -190,13 +190,16 @@ locknote/
根目录保留 Wails 入口及同包 API;依赖未导出函数的单元测试随实现保留在根目录。
源码契约测试统一位于 tests/source/,可运行 go test ./tests/source;完整 Go 测试运行 go test ./...。
-## 安全说明
+## 安全模型
+
+LockNote 使用加密密钥保护笔记正文、标题和预览、历史版本、附件及缩略图,以及待办事项标题。标签名称、笔记本名称、附件原始文件名、智能视图筛选条件、密码提示、时间戳及文件数量和大小不加密。
+
+备份仅包含笔记、历史版本和附件,不包含标签、笔记本、待办事项、设置或数据库。**“恢复备份”仅适用于同一密码库的备份**;要迁移到其他设备或使用不同密钥,请选择“用恢复密钥导入”。如果密码和恢复密钥都丢失,数据将按设计无法恢复。
- 主密钥仅在解锁后驻留内存
- 每篇笔记使用独立随机 nonce
- 密文文件采用原子写入
- 支持恢复密钥重置密码
-- 如果你同时遗失登录密码和恢复密钥,数据将无法恢复
## 版本
diff --git a/api.go b/api.go
index 539919f..5bb3c7b 100644
--- a/api.go
+++ b/api.go
@@ -8,6 +8,7 @@ import (
"errors"
"locknote/internal/attachments"
"locknote/internal/database"
+ "locknote/internal/fsutil"
"locknote/internal/markdown"
"locknote/internal/notebooks"
"locknote/internal/notes"
@@ -21,108 +22,209 @@ import (
"strconv"
"strings"
"time"
+ "unicode"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) CreateNote(title, content string) (*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Create(title, content)
+ return c.Notes().Create(title, content)
}
func (a *App) GetNote(id string) (*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Get(id)
+ return c.Notes().Get(id)
}
func (a *App) UpdateNote(id, title, content string) (*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Update(id, title, content)
+ return c.Notes().Update(id, title, content)
}
func (a *App) SetNotePinned(id string, pinned bool) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().SetPinned(id, pinned)
+ return c.Notes().SetPinned(id, pinned)
}
func (a *App) SoftDeleteNote(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().SoftDelete(id)
+ return c.Notes().SoftDelete(id)
}
func (a *App) RestoreNote(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Restore(id)
+ return c.Notes().Restore(id)
}
func (a *App) DeleteNote(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Delete(id)
+ return c.Notes().Delete(id)
}
func (a *App) ListNotes() ([]*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().List()
+ return c.Notes().List()
}
func (a *App) ListNotesPaginated(limit, offset int) (*notes.ListResult, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().ListPaginated(limit, offset)
+ return c.Notes().ListPaginated(limit, offset)
}
func (a *App) SearchNotes(query string) ([]*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().Search(query)
+ return c.Notes().Search(query)
}
func (a *App) MigrateOldNotes() (int, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return 0, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().MigrateOldNotes()
+ return c.Notes().MigrateOldNotes()
}
func (a *App) ListDeletedNotes() ([]*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().ListDeleted()
+ return c.Notes().ListDeleted()
}
func (a *App) GetNoteHistory(noteID string) ([]*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().GetHistory(noteID)
+ return c.Notes().GetHistory(noteID)
}
func (a *App) RestoreNoteFromHistory(noteID, historyID string) (*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().RestoreFromHistory(noteID, historyID)
+ return c.Notes().RestoreFromHistory(noteID, historyID)
}
func (a *App) CreateTag(name, color string) (*tags.Tag, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().Create(name, color)
+ return c.Tags().Create(name, color)
}
func (a *App) UpdateTag(id, name, color string) (*tags.Tag, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().Update(id, name, color)
+ return c.Tags().Update(id, name, color)
}
func (a *App) DeleteTag(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().Delete(id)
+ return c.Tags().Delete(id)
}
func (a *App) ListTags() ([]*tags.Tag, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().List()
+ return c.Tags().List()
}
func (a *App) AddTagToNote(noteID, tagID string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().AddToNote(noteID, tagID)
+ return c.Tags().AddToNote(noteID, tagID)
}
func (a *App) RemoveTagFromNote(noteID, tagID string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Tags().RemoveFromNote(noteID, tagID)
+ return c.Tags().RemoveFromNote(noteID, tagID)
}
func parseOptionalDate(value string) (*time.Time, error) {
@@ -140,16 +242,31 @@ func parseOptionalDate(value string) (*time.Time, error) {
}
func (a *App) ListTodos() ([]*todos.Todo, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().List()
+ return c.Todos().List()
}
func (a *App) GetTodo(id string) (*todos.Todo, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().Get(id)
+ return c.Todos().Get(id)
}
func (a *App) CreateTodo(title, priority, dueAt string) (*todos.Todo, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
parsedDueAt, err := parseOptionalDate(dueAt)
@@ -162,10 +279,15 @@ func (a *App) CreateTodo(title, priority, dueAt string) (*todos.Todo, error) {
Priority: priority,
DueAt: parsedDueAt,
}
- return a.core.Todos().Create(input)
+ return c.Todos().Create(input)
}
func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
parsedDueAt, err := parseOptionalDate(dueAt)
@@ -173,7 +295,7 @@ func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error)
return nil, err
}
- return a.core.Todos().Update(todos.UpdateTodoInput{
+ return c.Todos().Update(todos.UpdateTodoInput{
ID: id,
Title: title,
Priority: priority,
@@ -182,49 +304,94 @@ func (a *App) UpdateTodo(id, title, priority, dueAt string) (*todos.Todo, error)
}
func (a *App) SetTodoCompleted(id string, completed bool) (*todos.Todo, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().SetCompleted(id, completed)
+ return c.Todos().SetCompleted(id, completed)
}
func (a *App) DeleteTodo(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().Delete(id)
+ return c.Todos().Delete(id)
}
func (a *App) CreateTodoSubtask(todoID, title string) (*todos.Subtask, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().CreateSubtask(todoID, title)
+ return c.Todos().CreateSubtask(todoID, title)
}
func (a *App) UpdateTodoSubtask(id, title string) (*todos.Subtask, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().UpdateSubtask(id, title)
+ return c.Todos().UpdateSubtask(id, title)
}
func (a *App) SetTodoSubtaskCompleted(id string, completed bool) (*todos.Subtask, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().SetSubtaskCompleted(id, completed)
+ return c.Todos().SetSubtaskCompleted(id, completed)
}
func (a *App) DeleteTodoSubtask(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Todos().DeleteSubtask(id)
+ return c.Todos().DeleteSubtask(id)
}
func (a *App) GetSettings() (*database.Settings, error) {
- return a.core.GetSettings()
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
+ return c.GetSettings()
}
func (a *App) UpdateSettings(autoLockMinutes int, lockOnMinimize, lockOnSleep bool) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
settings := &database.Settings{
AutoLockMinutes: autoLockMinutes,
LockOnMinimize: lockOnMinimize,
LockOnSleep: lockOnSleep,
}
- return a.core.UpdateSettings(settings)
+ return c.UpdateSettings(settings)
}
func (a *App) CreateBackup() (string, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return "", coreErr
+ }
+
a.UpdateActivity()
savePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
@@ -241,7 +408,7 @@ func (a *App) CreateBackup() (string, error) {
return "", nil
}
- err = a.core.Backup().CreateBackup(savePath)
+ err = c.Backup().CreateBackup(savePath)
if err != nil {
return "", err
}
@@ -250,6 +417,11 @@ func (a *App) CreateBackup() (string, error) {
}
func (a *App) RestoreBackup() error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
@@ -265,10 +437,15 @@ func (a *App) RestoreBackup() error {
return nil
}
- return a.core.Backup().RestoreBackup(openPath)
+ return c.RestoreBackup(openPath)
}
func (a *App) ImportBackupWithKey(dataKey string) (int, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return 0, coreErr
+ }
+
a.UpdateActivity()
openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
@@ -284,20 +461,25 @@ func (a *App) ImportBackupWithKey(dataKey string) (int, error) {
return 0, nil
}
- return a.core.Notes().ImportFromBackup(openPath, dataKey)
+ return c.Notes().ImportFromBackup(openPath, dataKey)
}
func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return "", coreErr
+ }
+
a.UpdateActivity()
- note, err := a.core.Notes().Get(noteID)
+ note, err := c.Notes().Get(noteID)
if err != nil {
return "", err
}
savePath, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
Title: "导出笔记",
- DefaultFilename: note.Title + ".md",
+ DefaultFilename: sanitizeFileName(note.Title) + ".md",
Filters: []runtime.FileFilter{
{DisplayName: "Markdown 文件", Pattern: "*.md"},
},
@@ -314,7 +496,7 @@ func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) {
if err != nil {
return "", err
}
- err = writeFileAtomic(savePath, []byte(exportedContent))
+ err = fsutil.WriteFileAtomic(savePath, []byte(exportedContent), 0600)
if err != nil {
return "", err
}
@@ -322,6 +504,26 @@ func (a *App) ExportNoteAsMarkdown(noteID string) (string, error) {
return savePath, nil
}
+func sanitizeFileName(name string) string {
+ var sanitized strings.Builder
+ for _, char := range name {
+ if unicode.IsControl(char) || strings.ContainsRune(`/\:*?"<>|`, char) {
+ sanitized.WriteRune('_')
+ } else {
+ sanitized.WriteRune(char)
+ }
+ }
+ name = strings.Trim(sanitized.String(), " .")
+ runes := []rune(name)
+ if len(runes) > 100 {
+ name = strings.Trim(string(runes[:100]), " .")
+ }
+ if name == "" {
+ return "note"
+ }
+ return name
+}
+
var attachmentURLPattern = regexp.MustCompile(`locknote-attachment://([A-Za-z0-9_-]+)`)
func formatAssetsDirName(t time.Time) string {
@@ -452,6 +654,11 @@ func createUniqueAssetsDir(baseDir string, now time.Time) (string, string, error
}
func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time) (string, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return "", coreErr
+ }
+
attachmentIDs := collectAttachmentIDs(content)
if len(attachmentIDs) == 0 {
return content, nil
@@ -465,13 +672,13 @@ func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time
fileNames := make(map[string]string, len(attachmentIDs))
usedNames := map[string]int{}
for _, id := range attachmentIDs {
- attachment, data, err := a.core.Attachments().GetData(id)
+ attachment, data, err := c.Attachments().GetData(id)
if err != nil {
return "", err
}
fileName := uniqueExportImageName(attachment.OriginalName, attachment.MIMEType, attachment.ID, usedNames)
fileNames[id] = fileName
- if err := writeFileAtomic(filepath.Join(assetsDirPath, fileName), data); err != nil {
+ if err := fsutil.WriteFileAtomic(filepath.Join(assetsDirPath, fileName), data, 0600); err != nil {
return "", err
}
}
@@ -480,6 +687,11 @@ func (a *App) exportMarkdownAttachments(content, exportDir string, now time.Time
}
func (a *App) ImportMarkdown() (*notes.Note, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
@@ -501,7 +713,7 @@ func (a *App) ImportMarkdown() (*notes.Note, error) {
}
title := markdown.ExtractTitle(openPath, string(content))
- return a.core.Notes().Create(title, string(content))
+ return c.Notes().Create(title, string(content))
}
func parseImageDataURL(dataURL string) (string, []byte, error) {
@@ -528,6 +740,11 @@ func imageMIMEFromFile(path string, data []byte) string {
}
func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
openPath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
@@ -551,7 +768,7 @@ func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) {
if mimeType == "" {
return nil, errors.New("不支持的图片格式")
}
- return a.core.Attachments().CreateImage(attachments.CreateImageInput{
+ return c.Attachments().CreateImage(attachments.CreateImageInput{
OriginalName: filepath.Base(openPath),
MIMEType: mimeType,
Data: data,
@@ -560,124 +777,216 @@ func (a *App) ImportImage(noteID string) (*attachments.Attachment, error) {
}
func (a *App) CreateImageFromDataURL(noteID, originalName, dataURL string) (*attachments.Attachment, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().CreateImageFromDataURL(noteID, originalName, dataURL)
+ return c.Attachments().CreateImageFromDataURL(noteID, originalName, dataURL)
}
func (a *App) GetAttachmentDataURL(id string) (string, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return "", coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().GetDataURL(id)
+ return c.Attachments().GetDataURL(id)
}
func (a *App) GetAttachmentThumbnailDataURL(id string) (string, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return "", coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().GetThumbnailDataURL(id)
+ return c.Attachments().GetThumbnailDataURL(id)
}
func (a *App) ListAttachments() ([]*attachments.Attachment, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().ListImages()
+ return c.Attachments().ListImages()
}
func (a *App) ListDeletedAttachments() ([]*attachments.Attachment, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().ListDeletedImages()
+ return c.Attachments().ListDeletedImages()
}
func (a *App) SoftDeleteAttachment(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().SoftDelete(id)
+ return c.Attachments().SoftDelete(id)
}
func (a *App) RestoreAttachment(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().Restore(id)
+ return c.Attachments().Restore(id)
}
func (a *App) DeleteAttachment(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().Delete(id)
+ return c.Attachments().Delete(id)
}
func (a *App) SetAttachmentFavorite(id string, favorite bool) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Attachments().SetFavorite(id, favorite)
+ return c.Attachments().SetFavorite(id, favorite)
}
func (a *App) AttachAttachmentToNote(noteID, attachmentID string) error {
- a.UpdateActivity()
- return a.core.Attachments().AttachToNote(noteID, attachmentID)
-}
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
-func (a *App) DetachAttachmentFromNote(noteID, attachmentID string) error {
a.UpdateActivity()
- return a.core.Attachments().DetachFromNote(noteID, attachmentID)
+ return c.Attachments().AttachToNote(noteID, attachmentID)
}
-func writeFileAtomic(path string, data []byte) error {
- tempPath := path + ".tmp"
- if err := os.WriteFile(tempPath, data, 0600); err != nil {
- os.Remove(tempPath)
- return err
- }
- if err := os.Rename(tempPath, path); err != nil {
- os.Remove(tempPath)
- return err
+func (a *App) DetachAttachmentFromNote(noteID, attachmentID string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
}
- return nil
+
+ a.UpdateActivity()
+ return c.Attachments().DetachFromNote(noteID, attachmentID)
}
// Notebook APIs
func (a *App) CreateNotebook(name, icon string) (*notebooks.Notebook, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().Create(name, icon)
+ return c.Notebooks().Create(name, icon)
}
func (a *App) UpdateNotebook(id, name, icon string) (*notebooks.Notebook, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().Update(id, name, icon)
+ return c.Notebooks().Update(id, name, icon)
}
func (a *App) DeleteNotebook(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().Delete(id)
+ return c.Notebooks().Delete(id)
}
func (a *App) ListNotebooks() ([]*notebooks.Notebook, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().List()
+ return c.Notebooks().List()
}
func (a *App) ReorderNotebooks(ids []string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().ReorderNotebooks(ids)
+ return c.Notebooks().ReorderNotebooks(ids)
}
func (a *App) SetNotebookPinned(id string, pinned bool) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notebooks().SetPinned(id, pinned)
+ return c.Notebooks().SetPinned(id, pinned)
}
func (a *App) SetNoteNotebook(noteID string, notebookID *string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().SetNotebook(noteID, notebookID)
+ return c.Notes().SetNotebook(noteID, notebookID)
}
func (a *App) SetNotesNotebook(noteIDs []string, notebookID *string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().SetNotesNotebook(noteIDs, notebookID)
+ return c.Notes().SetNotesNotebook(noteIDs, notebookID)
}
func (a *App) BatchDeleteNotes(noteIDs []string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().BatchSoftDelete(noteIDs)
+ return c.Notes().BatchSoftDelete(noteIDs)
}
func (a *App) BatchAddTagToNotes(noteIDs []string, tagID string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
for _, noteID := range noteIDs {
- if err := a.core.Tags().AddToNote(noteID, tagID); err != nil {
+ if err := c.Tags().AddToNote(noteID, tagID); err != nil {
return err
}
}
@@ -685,33 +994,63 @@ func (a *App) BatchAddTagToNotes(noteIDs []string, tagID string) error {
}
func (a *App) ReorderNotes(ids []string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.Notes().ReorderNotes(ids)
+ return c.Notes().ReorderNotes(ids)
}
// SmartView APIs
func (a *App) CreateSmartView(name, icon string, filter smartviews.Filter) (*smartviews.SmartView, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.SmartViews().Create(name, icon, filter)
+ return c.SmartViews().Create(name, icon, filter)
}
func (a *App) UpdateSmartView(id, name, icon string, filter smartviews.Filter) (*smartviews.SmartView, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.SmartViews().Update(id, name, icon, filter)
+ return c.SmartViews().Update(id, name, icon, filter)
}
func (a *App) DeleteSmartView(id string) error {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return coreErr
+ }
+
a.UpdateActivity()
- return a.core.SmartViews().Delete(id)
+ return c.SmartViews().Delete(id)
}
func (a *App) ListSmartViews() ([]*smartviews.SmartView, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.SmartViews().List()
+ return c.SmartViews().List()
}
func (a *App) GetSmartView(id string) (*smartviews.SmartView, error) {
+ c, coreErr := a.coreOrErr()
+ if coreErr != nil {
+ return nil, coreErr
+ }
+
a.UpdateActivity()
- return a.core.SmartViews().Get(id)
+ return c.SmartViews().Get(id)
}
diff --git a/api_diagram.go b/api_diagram.go
index 657fbd3..98899c1 100644
--- a/api_diagram.go
+++ b/api_diagram.go
@@ -3,6 +3,7 @@ package main
import (
"encoding/xml"
"errors"
+ "locknote/internal/fsutil"
"strings"
"github.com/wailsapp/wails/v2/pkg/runtime"
@@ -35,7 +36,7 @@ func saveDiagramSVG(svg string, choosePath func() (string, error)) (string, erro
if !strings.HasSuffix(strings.ToLower(path), ".svg") {
path += ".svg"
}
- if err := writeFileAtomic(path, []byte(svg)); err != nil {
+ if err := fsutil.WriteFileAtomic(path, []byte(svg), 0600); err != nil {
return "", err
}
return path, nil
diff --git a/api_test.go b/api_test.go
new file mode 100644
index 0000000..ff971f9
--- /dev/null
+++ b/api_test.go
@@ -0,0 +1,26 @@
+package main
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSanitizeFileName(t *testing.T) {
+ tests := []struct {
+ name string
+ want string
+ }{
+ {"bad/name\\file:?.md", "bad_name_file__.md"},
+ {" .hidden. ", "hidden"},
+ {"\x00\x1f", "__"},
+ {"...", "note"},
+ }
+ for _, test := range tests {
+ if got := sanitizeFileName(test.name); got != test.want {
+ t.Errorf("sanitizeFileName(%q) = %q, want %q", test.name, got, test.want)
+ }
+ }
+ if got := len([]rune(sanitizeFileName(strings.Repeat("x", 101)))); got != 100 {
+ t.Fatalf("sanitized filename length = %d, want 100", got)
+ }
+}
diff --git a/app.go b/app.go
index db6a69e..c26eff5 100644
--- a/app.go
+++ b/app.go
@@ -6,12 +6,14 @@ package main
import (
"context"
+ "errors"
"fmt"
"locknote/internal/core"
"log"
"os"
"path/filepath"
"sync"
+ "sync/atomic"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
@@ -29,6 +31,8 @@ type App struct {
windowWatcherOnce sync.Once
watcherStop chan struct{}
lastMinimized bool
+ allowClose atomic.Bool
+ closeRequestStart atomic.Bool
}
func NewApp() *App {
@@ -137,6 +141,14 @@ func (a *App) getCoreIfReady() *core.Core {
}
}
+func (a *App) coreOrErr() (*core.Core, error) {
+ c := a.getCoreIfReady()
+ if c == nil {
+ return nil, errors.New("应用尚未就绪,请稍候重试")
+ }
+ return c, nil
+}
+
func (a *App) startWindowWatcherOnce() {
a.windowWatcherOnce.Do(func() {
a.startWindowWatcher()
@@ -150,6 +162,26 @@ func (a *App) shutdown(ctx context.Context) {
}
}
+func (a *App) beforeClose(ctx context.Context) bool {
+ if a.allowClose.Load() {
+ return false
+ }
+ if a.closeRequestStart.CompareAndSwap(false, true) {
+ runtime.EventsEmit(ctx, "app:before-close")
+ time.AfterFunc(3*time.Second, func() {
+ if !a.allowClose.Swap(true) {
+ runtime.Quit(ctx)
+ }
+ })
+ }
+ return true
+}
+
+func (a *App) ConfirmClose() {
+ a.allowClose.Store(true)
+ runtime.Quit(a.ctx)
+}
+
func (a *App) startWindowWatcher() {
a.windowWatcher = time.NewTicker(500 * time.Millisecond)
go func() {
@@ -196,52 +228,94 @@ func (a *App) checkWindowState() {
// ============ 委托给 core 的安全相关方法 ============
-func (a *App) IsFirstRun() bool {
- return a.core.IsFirstRun()
+func (a *App) IsFirstRun() (bool, error) {
+ c, err := a.coreOrErr()
+ if err != nil {
+ return false, err
+ }
+ return c.IsFirstRun()
}
func (a *App) SetupPassword(password, hint, displayKey string) (*core.SetupResult, error) {
- return a.core.SetupPassword(password, hint, displayKey)
+ c, err := a.coreOrErr()
+ if err != nil {
+ return nil, err
+ }
+ return c.SetupPassword(password, hint, displayKey)
}
func (a *App) VerifyDataKey(displayKey string) (bool, error) {
- return a.core.VerifyDataKey(displayKey)
+ c, err := a.coreOrErr()
+ if err != nil {
+ return false, err
+ }
+ return c.VerifyDataKey(displayKey)
}
func (a *App) Unlock(password string) (bool, error) {
- return a.core.Unlock(password)
+ c, err := a.coreOrErr()
+ if err != nil {
+ return false, err
+ }
+ return c.Unlock(password)
}
func (a *App) Lock() {
- a.core.Lock()
+ if c := a.getCoreIfReady(); c != nil {
+ c.Lock()
+ }
}
func (a *App) IsUnlocked() bool {
- return a.core.IsUnlocked()
+ if c := a.getCoreIfReady(); c != nil {
+ return c.IsUnlocked()
+ }
+ return false
}
func (a *App) GetPasswordHint() (string, error) {
- return a.core.GetPasswordHint()
+ c, err := a.coreOrErr()
+ if err != nil {
+ return "", err
+ }
+ return c.GetPasswordHint()
}
func (a *App) ChangePassword(oldPassword, newPassword, newHint string) error {
- return a.core.ChangePassword(oldPassword, newPassword, newHint)
+ c, err := a.coreOrErr()
+ if err != nil {
+ return err
+ }
+ return c.ChangePassword(oldPassword, newPassword, newHint)
}
func (a *App) ResetPasswordWithDataKey(displayKey, newPassword, newHint string) error {
- return a.core.ResetPasswordWithDataKey(displayKey, newPassword, newHint)
+ c, err := a.coreOrErr()
+ if err != nil {
+ return err
+ }
+ return c.ResetPasswordWithDataKey(displayKey, newPassword, newHint)
}
func (a *App) UpdateActivity() {
- a.core.UpdateActivity()
+ if c := a.getCoreIfReady(); c != nil {
+ c.UpdateActivity()
+ }
}
func (a *App) GenerateDataKey() (string, error) {
- return a.core.GenerateDataKey()
+ c, err := a.coreOrErr()
+ if err != nil {
+ return "", err
+ }
+ return c.GenerateDataKey()
}
func (a *App) GetDataDir() string {
- return a.core.GetDataDir()
+ if c := a.getCoreIfReady(); c != nil {
+ return c.GetDataDir()
+ }
+ return ""
}
func (a *App) GetVersion() string {
diff --git a/build/bin/locknote.app/Contents/Info.plist b/build/bin/locknote.app/Contents/Info.plist
deleted file mode 100644
index 516534c..0000000
--- a/build/bin/locknote.app/Contents/Info.plist
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
- CFBundlePackageType
- APPL
- CFBundleName
- LockNote.app
- CFBundleExecutable
- LockNote
- CFBundleIdentifier
- com.wails.locknote
- CFBundleVersion
- 1.0.9
- CFBundleGetInfoString
- Built using Wails (https://wails.io)
- CFBundleShortVersionString
- 1.0.9
- CFBundleIconFile
- iconfile
- LSMinimumSystemVersion
- 10.13.0
- NSHighResolutionCapable
- true
- NSHumanReadableCopyright
- Copyright (c) 2026 LockNote.app
-
-
- NSAppTransportSecurity
-
- NSAllowsLocalNetworking
-
-
-
-
diff --git a/build/bin/locknote.app/Contents/Resources/iconfile.icns b/build/bin/locknote.app/Contents/Resources/iconfile.icns
deleted file mode 100644
index 3b5754a..0000000
Binary files a/build/bin/locknote.app/Contents/Resources/iconfile.icns and /dev/null differ
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index aa0c09d..f4af056 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "locknote-frontend",
- "version": "1.0.7",
+ "version": "1.0.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "locknote-frontend",
- "version": "1.0.7",
+ "version": "1.0.9",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
diff --git a/frontend/package.json b/frontend/package.json
index 5658880..7ad8f2c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,12 +1,13 @@
{
"name": "locknote-frontend",
"private": true,
- "version": "1.0.7",
+ "version": "1.0.9",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "tsc -p tsconfig.test.json && node --test .test-dist/*.test.js"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d1e7114..5678373 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -10,6 +10,8 @@ import { SetupScreen } from './components/SetupScreen';
import { StartupProgressScreen } from './components/StartupProgressScreen';
import * as App from '../wailsjs/go/main/App';
import { EventsEmit, EventsOn } from '../wailsjs/runtime/runtime';
+import { flushEditor } from './editorFlush';
+import { formatMessage, useI18n } from './i18n';
// Extend Window interface for Wails runtime
declare global {
@@ -47,39 +49,29 @@ function isWailsRuntimeReady(): boolean {
);
}
-// Wait for Wails runtime to be ready. Windows cold starts can take longer on
-// first launch while WebView2 and the Wails bridge warm up.
async function waitForWailsRuntime(): Promise {
- const checkInterval = 100; // Check every 100ms
-
- for (;;) {
- if (isWailsRuntimeReady()) {
- return;
- }
- await new Promise(resolve => setTimeout(resolve, checkInterval));
+ while (!isWailsRuntimeReady()) {
+ await new Promise(resolve => setTimeout(resolve, 100));
}
}
const wailsRuntimeReady = waitForWailsRuntime();
const FIRST_RUN_STARTUP_MINIMUM_MS = 1400;
-async function waitForCoreReady(onStatus?: (message: string) => void): Promise {
- const retryDelay = 300;
-
- for (;;) {
+async function waitForCoreReady(
+ onStatus: ((message: string) => void) | undefined,
+ messages: { preparingData: string; failed: string },
+): Promise {
+ while (true) {
const ready = await App.IsCoreReady();
- if (ready) {
- return;
- }
-
+ if (ready) return;
const startupError = await App.GetStartupError();
if (startupError) {
- onStatus?.(`启动失败:${startupError}`);
- } else {
- onStatus?.('正在准备本地数据...');
+ onStatus?.(formatMessage(messages.failed, { error: startupError }));
+ throw new Error(startupError);
}
-
- await new Promise(resolve => setTimeout(resolve, retryDelay));
+ onStatus?.(messages.preparingData);
+ await new Promise(resolve => setTimeout(resolve, 300));
}
}
@@ -109,9 +101,10 @@ function throttle void>(func: T, limit: number
}
function AppRoot() {
+ const { t } = useI18n();
const { isUnlocked, isFirstRun, setUnlocked, setFirstRun, setVersion, setDataDir } = useStore();
const [loading, setLoading] = useState(true);
- const [startupMessage, setStartupMessage] = useState('正在启动应用核心...');
+ const [startupMessage, setStartupMessage] = useState(t.startup.starting);
const [startupProgress, setStartupProgress] = useState(8);
const [showOnboarding, setShowOnboarding] = useState(false);
@@ -125,12 +118,9 @@ function AppRoot() {
}, []);
useEffect(() => {
- // Only emit frontend:ready after runtime is ready
- const emitReady = async () => {
- await wailsRuntimeReady;
- EventsEmit('frontend:ready');
- };
- emitReady();
+ void wailsRuntimeReady
+ .then(() => EventsEmit('frontend:ready'))
+ .catch((error) => console.error('Failed to emit frontend readiness:', error));
}, []);
useEffect(() => {
@@ -143,9 +133,9 @@ function AppRoot() {
setStartupProgress(18);
await wailsRuntimeReady;
setStartupProgress(34);
- await waitForCoreReady(setStartupMessage);
+ await waitForCoreReady(setStartupMessage, t.startup);
- setStartupMessage('正在读取本地数据...');
+ setStartupMessage(t.startup.readingData);
setStartupProgress(68);
const firstRun = await App.IsFirstRun();
setFirstRun(firstRun);
@@ -162,7 +152,7 @@ function AppRoot() {
setDataDir(dataDir);
if (firstRun) {
- setStartupMessage('正在初始化...');
+ setStartupMessage(t.startup.initializing);
}
setStartupProgress(92);
await waitForMinimumStartupDisplay(startupStartedAt, firstRun);
@@ -170,8 +160,13 @@ function AppRoot() {
setLoading(false);
} catch (error) {
console.error('Init error:', error);
+ if (retryCount >= 120) {
+ setStartupMessage(formatMessage(t.startup.failed, { error: String(error) }));
+ setStartupProgress(100);
+ return;
+ }
// Retry on failure - WebView2 may still be initializing on Windows first run.
- setStartupMessage(`正在启动应用核心... (${retryCount + 1})`);
+ setStartupMessage(formatMessage(t.startup.retrying, { count: retryCount + 1 }));
setStartupProgress(12);
await new Promise(resolve => setTimeout(resolve, retryDelay));
return init(retryCount + 1);
@@ -179,7 +174,7 @@ function AppRoot() {
};
init();
- }, [setFirstRun, setUnlocked, setVersion, setDataDir]);
+ }, [setFirstRun, setUnlocked, setVersion, setDataDir, t.startup]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -203,13 +198,15 @@ function AppRoot() {
if (key === 'l') {
e.preventDefault();
- App.Lock()
- .then(() => {
+ void (async () => {
+ try {
+ await flushEditor();
+ await App.Lock();
useStore.getState().setUnlocked(false);
- })
- .catch((error) => {
+ } catch (error) {
console.error('Failed to lock:', error);
- });
+ }
+ })();
return;
}
@@ -244,6 +241,35 @@ function AppRoot() {
};
}, []);
+ useEffect(() => {
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === 'hidden') {
+ void flushEditor();
+ }
+ };
+ const handleBlur = () => {
+ void flushEditor();
+ };
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+ window.addEventListener('blur', handleBlur);
+ return () => {
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ window.removeEventListener('blur', handleBlur);
+ };
+ }, []);
+
+ useEffect(() => {
+ const offBeforeClose = EventsOn('app:before-close', async () => {
+ await flushEditor();
+ App.ConfirmClose().catch((error) => {
+ console.error('Failed to confirm window close:', error);
+ });
+ });
+ return () => {
+ offBeforeClose();
+ };
+ }, []);
+
// Track user activity to reset the idle lock timer
useEffect(() => {
if (!isUnlocked) {
diff --git a/frontend/src/appStartup.test.ts b/frontend/src/appStartup.test.ts
index 27faca1..b74236c 100644
--- a/frontend/src/appStartup.test.ts
+++ b/frontend/src/appStartup.test.ts
@@ -7,25 +7,31 @@ const onboardingSource = readFileSync('src/components/OnboardingScreen.tsx', 'ut
const startupProgressSource = readFileSync('src/components/StartupProgressScreen.tsx', 'utf8');
test('App waits for Wails runtime without falling through to the first-run screen on Windows cold start', () => {
+ assert.equal(/async function waitForWailsRuntime/.test(source), true);
+ assert.equal(/while \(!isWailsRuntimeReady\(\)\) \{\s*await new Promise\(resolve => setTimeout\(resolve, 100\)\);/.test(source), true);
assert.equal(/const wailsRuntimeReady = waitForWailsRuntime\(\);/.test(source), true);
- assert.equal(/waitForWailsRuntime\(maxWaitTime = 10000\)/.test(source), false);
- assert.equal(/Date\.now\(\) - startTime < maxWaitTime/.test(source), false);
- assert.equal(/Wails runtime not ready after timeout[\s\S]*setLoading\(false\)/.test(source), false);
+ assert.equal(/wailsRuntimeReady\s*\.then\(\(\) => EventsEmit\('frontend:ready'\)\)/.test(source), true);
assert.equal(/await wailsRuntimeReady;/.test(source), true);
});
test('App waits for background core initialization before calling first-run APIs', () => {
+ const coreReadySource = source.match(/async function waitForCoreReady[\s\S]*?\n}\n/)?.[0] ?? '';
assert.equal(/waitForCoreReady/.test(source), true);
- assert.equal(/await waitForCoreReady\(setStartupMessage\);/.test(source), true);
+ assert.equal(/await waitForCoreReady\(setStartupMessage, t\.startup\);/.test(source), true);
assert.equal(/App\.IsCoreReady/.test(source), true);
assert.equal(/App\.GetStartupError/.test(source), true);
- assert.equal(source.indexOf('await waitForCoreReady(setStartupMessage);') < source.indexOf('const firstRun = await App.IsFirstRun();'), true);
+ assert.equal(source.indexOf('await waitForCoreReady(setStartupMessage, t.startup);') < source.indexOf('const firstRun = await App.IsFirstRun();'), true);
+ assert.equal(/while \(true\)/.test(coreReadySource), true);
+ assert.equal(/await new Promise\(resolve => setTimeout\(resolve, 300\)\)/.test(coreReadySource), true);
+ assert.equal(/if \(startupError\) \{[\s\S]*onStatus\?\.\(formatMessage\(messages\.failed, \{ error: startupError \}\)\);[\s\S]*throw new Error\(startupError\);/.test(coreReadySource), true);
+ assert.equal((coreReadySource.match(/throw new Error/g) || []).length, 1);
});
test('App shows a cold-start message while the Windows runtime is still warming up', () => {
assert.equal(/const \[startupMessage, setStartupMessage\]/.test(source), true);
- assert.equal(/useState\('正在启动应用核心\.\.\.'\)/.test(source), true);
- assert.equal(/setStartupMessage\(`正在启动应用核心\.\.\. \(\$\{retryCount \+ 1\}\)`\)/.test(source), true);
+ assert.equal(/retryCount >= 120/.test(source), true);
+ assert.equal(/setStartupMessage\(formatMessage\(t\.startup\.failed/.test(source), true);
+ assert.equal(/setStartupProgress\(100\)/.test(source), true);
assert.equal(/
{t.backup.title}
{t.backup.subtitle}
+ {t.backup.securityHint}
)}
diff --git a/frontend/src/components/MainLayout.tsx b/frontend/src/components/MainLayout.tsx
index ce6d9aa..61cd469 100644
--- a/frontend/src/components/MainLayout.tsx
+++ b/frontend/src/components/MainLayout.tsx
@@ -1,4 +1,5 @@
import { useEffect } from 'react';
+import { useI18n } from '../i18n';
import { useStore } from '../store';
import { Sidebar } from './Sidebar';
import { NoteList } from './NoteList';
@@ -12,6 +13,7 @@ import { CalendarView } from './CalendarView';
import * as App from '../../wailsjs/go/main/App';
export function MainLayout() {
+ const { t } = useI18n();
const {
currentView,
setNotes,
@@ -59,21 +61,25 @@ export function MainLayout() {
}, [setCommandPaletteOpen]);
useEffect(() => {
+ let cancelled = false;
const loadSelectedNote = async () => {
if (selectedNoteId) {
try {
const note = await App.GetNote(selectedNoteId);
- setSelectedNote(note);
+ if (!cancelled) setSelectedNote(note);
} catch (error) {
console.error('Failed to load note:', error);
- setSelectedNote(null);
+ if (!cancelled) setSelectedNote(null);
}
- } else {
+ } else if (!cancelled) {
setSelectedNote(null);
}
};
loadSelectedNote();
+ return () => {
+ cancelled = true;
+ };
}, [selectedNoteId, setSelectedNote]);
const renderContent = () => {
@@ -88,7 +94,7 @@ export function MainLayout() {