Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 272227e4e3 | |||
| ec8f8c1e2d | |||
| 1c14092068 | |||
| 00bdafc621 | |||
| 78422899e4 | |||
| c47f7de5b8 | |||
| 37aae9e03c | |||
| fa134d31d6 | |||
| d035dcd531 | |||
| c50bf452ca | |||
| dace5ce2b0 | |||
| ef145169aa | |||
| 7b746155f7 | |||
|
|
b289f4054d | ||
|
|
bdee1fdf84 | ||
| 541e4e96cf | |||
| 401eb3ab39 | |||
| d3eba96a29 | |||
| 81c02db00d | |||
|
|
9cb2ccbb4e | ||
| 8a10b8fe0f | |||
| 8fce8bdca4 | |||
| 1ab934cee9 | |||
| 6659ac6fad | |||
| 3a5ab1c614 | |||
| 1e07e1f833 | |||
| e1e91a3683 | |||
| c30d95a3e0 | |||
| 97f6fa843c | |||
| f43fc47539 | |||
|
|
c330de52fa | ||
| 67d35626cb | |||
| cc4c2189dc | |||
| d16905c0a3 | |||
| 4e611db349 | |||
| 7e9fc0ac3f | |||
| ff072d1a93 |
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
38
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
3
.github/workflows/build-release.yml
vendored
3
.github/workflows/build-release.yml
vendored
@@ -28,6 +28,7 @@ env:
|
||||
jobs:
|
||||
# 准备构建配置
|
||||
prepare:
|
||||
permissions: {}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
@@ -84,6 +85,8 @@ jobs:
|
||||
fi
|
||||
|
||||
build:
|
||||
permissions:
|
||||
contents: read
|
||||
needs: prepare
|
||||
if: ${{ fromJson(needs.prepare.outputs.matrix).include[0] != null }}
|
||||
strategy:
|
||||
|
||||
109
.github/workflows/codeql.yml
vendored
Normal file
109
.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL Advanced"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
schedule:
|
||||
- cron: '29 8 * * 3'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
# Runner size impacts CodeQL analysis time. To learn more, please see:
|
||||
# - https://gh.io/recommended-hardware-resources-for-running-codeql
|
||||
# - https://gh.io/supported-runners-and-hardware-resources
|
||||
# - https://gh.io/using-larger-runners (GitHub.com only)
|
||||
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
|
||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
# required for all workflows
|
||||
security-events: write
|
||||
|
||||
# required to fetch internal or private CodeQL packs
|
||||
packages: read
|
||||
|
||||
# only required for workflows in private repositories
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: actions
|
||||
build-mode: none
|
||||
- language: c-cpp
|
||||
build-mode: none
|
||||
- language: go
|
||||
build-mode: autobuild
|
||||
- language: javascript-typescript
|
||||
build-mode: none
|
||||
- language: python
|
||||
build-mode: none
|
||||
- language: rust
|
||||
build-mode: none
|
||||
# CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
|
||||
# Use `c-cpp` to analyze code written in C, C++ or both
|
||||
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
|
||||
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
|
||||
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
|
||||
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
|
||||
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
|
||||
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Add any setup steps before running the `github/codeql-action/init` action.
|
||||
# This includes steps like installing compilers or runtimes (`actions/setup-node`
|
||||
# or others). This is typically only required for manual builds.
|
||||
# - name: Setup runtime (example)
|
||||
# uses: actions/setup-example@v1
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
|
||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
|
||||
# If the analyze step fails for one of the languages you are analyzing with
|
||||
# "We were unable to automatically build your code", modify the matrix above
|
||||
# to set the build mode to "manual" for that language. Then modify this step
|
||||
# to build your code.
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
- name: Run manual build steps
|
||||
if: matrix.build-mode == 'manual'
|
||||
shell: bash
|
||||
run: |
|
||||
echo 'If you are using a "manual" build mode for one or more of the' \
|
||||
'languages you are analyzing, replace this with the commands to build' \
|
||||
'your code, for example:'
|
||||
echo ' make bootstrap'
|
||||
echo ' make release'
|
||||
exit 1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
@@ -61,5 +61,3 @@ export class ServiceOptions {
|
||||
return new ServiceOptions($$parsedSource as Partial<ServiceOptions>);
|
||||
}
|
||||
}
|
||||
|
||||
export type Window = any;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export * from "./models.js";
|
||||
17
frontend/bindings/voidraft/internal/common/helper/models.ts
Normal file
17
frontend/bindings/voidraft/internal/common/helper/models.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import {Create as $Create} from "@wailsio/runtime";
|
||||
|
||||
/**
|
||||
* CancelFunc 取消订阅函数
|
||||
* 调用此函数可以取消对配置的监听
|
||||
*/
|
||||
export type CancelFunc = any;
|
||||
|
||||
/**
|
||||
* ObserverCallback 观察者回调函数
|
||||
*/
|
||||
export type ObserverCallback = any;
|
||||
4
frontend/bindings/voidraft/internal/models/ent/index.ts
Normal file
4
frontend/bindings/voidraft/internal/models/ent/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export * from "./models.js";
|
||||
370
frontend/bindings/voidraft/internal/models/ent/models.ts
Normal file
370
frontend/bindings/voidraft/internal/models/ent/models.ts
Normal file
@@ -0,0 +1,370 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import {Create as $Create} from "@wailsio/runtime";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as theme$0 from "./theme/models.js";
|
||||
|
||||
/**
|
||||
* Document is the model entity for the Document schema.
|
||||
*/
|
||||
export class Document {
|
||||
/**
|
||||
* ID of the ent.
|
||||
*/
|
||||
"id"?: number;
|
||||
|
||||
/**
|
||||
* UUID for cross-device sync (UUIDv7)
|
||||
*/
|
||||
"uuid": string;
|
||||
|
||||
/**
|
||||
* creation time
|
||||
*/
|
||||
"created_at": string;
|
||||
|
||||
/**
|
||||
* update time
|
||||
*/
|
||||
"updated_at": string;
|
||||
|
||||
/**
|
||||
* deleted at
|
||||
*/
|
||||
"deleted_at"?: string | null;
|
||||
|
||||
/**
|
||||
* document title
|
||||
*/
|
||||
"title": string;
|
||||
|
||||
/**
|
||||
* document content
|
||||
*/
|
||||
"content": string;
|
||||
|
||||
/**
|
||||
* document locked status
|
||||
*/
|
||||
"locked": boolean;
|
||||
|
||||
/** Creates a new Document instance. */
|
||||
constructor($$source: Partial<Document> = {}) {
|
||||
if (!("uuid" in $$source)) {
|
||||
this["uuid"] = "";
|
||||
}
|
||||
if (!("created_at" in $$source)) {
|
||||
this["created_at"] = "";
|
||||
}
|
||||
if (!("updated_at" in $$source)) {
|
||||
this["updated_at"] = "";
|
||||
}
|
||||
if (!("title" in $$source)) {
|
||||
this["title"] = "";
|
||||
}
|
||||
if (!("content" in $$source)) {
|
||||
this["content"] = "";
|
||||
}
|
||||
if (!("locked" in $$source)) {
|
||||
this["locked"] = false;
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Document instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Document {
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
return new Document($$parsedSource as Partial<Document>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension is the model entity for the Extension schema.
|
||||
*/
|
||||
export class Extension {
|
||||
/**
|
||||
* ID of the ent.
|
||||
*/
|
||||
"id"?: number;
|
||||
|
||||
/**
|
||||
* UUID for cross-device sync (UUIDv7)
|
||||
*/
|
||||
"uuid": string;
|
||||
|
||||
/**
|
||||
* creation time
|
||||
*/
|
||||
"created_at": string;
|
||||
|
||||
/**
|
||||
* update time
|
||||
*/
|
||||
"updated_at": string;
|
||||
|
||||
/**
|
||||
* deleted at
|
||||
*/
|
||||
"deleted_at"?: string | null;
|
||||
|
||||
/**
|
||||
* extension name
|
||||
*/
|
||||
"name": string;
|
||||
|
||||
/**
|
||||
* extension enabled or not
|
||||
*/
|
||||
"enabled": boolean;
|
||||
|
||||
/**
|
||||
* extension config
|
||||
*/
|
||||
"config": { [_: string]: any };
|
||||
|
||||
/** Creates a new Extension instance. */
|
||||
constructor($$source: Partial<Extension> = {}) {
|
||||
if (!("uuid" in $$source)) {
|
||||
this["uuid"] = "";
|
||||
}
|
||||
if (!("created_at" in $$source)) {
|
||||
this["created_at"] = "";
|
||||
}
|
||||
if (!("updated_at" in $$source)) {
|
||||
this["updated_at"] = "";
|
||||
}
|
||||
if (!("name" in $$source)) {
|
||||
this["name"] = "";
|
||||
}
|
||||
if (!("enabled" in $$source)) {
|
||||
this["enabled"] = false;
|
||||
}
|
||||
if (!("config" in $$source)) {
|
||||
this["config"] = {};
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Extension instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Extension {
|
||||
const $$createField7_0 = $$createType0;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("config" in $$parsedSource) {
|
||||
$$parsedSource["config"] = $$createField7_0($$parsedSource["config"]);
|
||||
}
|
||||
return new Extension($$parsedSource as Partial<Extension>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* KeyBinding is the model entity for the KeyBinding schema.
|
||||
*/
|
||||
export class KeyBinding {
|
||||
/**
|
||||
* ID of the ent.
|
||||
*/
|
||||
"id"?: number;
|
||||
|
||||
/**
|
||||
* UUID for cross-device sync (UUIDv7)
|
||||
*/
|
||||
"uuid": string;
|
||||
|
||||
/**
|
||||
* creation time
|
||||
*/
|
||||
"created_at": string;
|
||||
|
||||
/**
|
||||
* update time
|
||||
*/
|
||||
"updated_at": string;
|
||||
|
||||
/**
|
||||
* deleted at
|
||||
*/
|
||||
"deleted_at"?: string | null;
|
||||
|
||||
/**
|
||||
* command identifier
|
||||
*/
|
||||
"name": string;
|
||||
|
||||
/**
|
||||
* keybinding type: standard or emacs
|
||||
*/
|
||||
"type": string;
|
||||
|
||||
/**
|
||||
* universal keybinding (cross-platform)
|
||||
*/
|
||||
"key"?: string;
|
||||
|
||||
/**
|
||||
* macOS specific keybinding
|
||||
*/
|
||||
"macos"?: string;
|
||||
|
||||
/**
|
||||
* Windows specific keybinding
|
||||
*/
|
||||
"windows"?: string;
|
||||
|
||||
/**
|
||||
* Linux specific keybinding
|
||||
*/
|
||||
"linux"?: string;
|
||||
|
||||
/**
|
||||
* extension name (functional category)
|
||||
*/
|
||||
"extension": string;
|
||||
|
||||
/**
|
||||
* whether this keybinding is enabled
|
||||
*/
|
||||
"enabled": boolean;
|
||||
|
||||
/**
|
||||
* prevent browser default behavior
|
||||
*/
|
||||
"preventDefault": boolean;
|
||||
|
||||
/**
|
||||
* keybinding scope (default: editor)
|
||||
*/
|
||||
"scope"?: string;
|
||||
|
||||
/** Creates a new KeyBinding instance. */
|
||||
constructor($$source: Partial<KeyBinding> = {}) {
|
||||
if (!("uuid" in $$source)) {
|
||||
this["uuid"] = "";
|
||||
}
|
||||
if (!("created_at" in $$source)) {
|
||||
this["created_at"] = "";
|
||||
}
|
||||
if (!("updated_at" in $$source)) {
|
||||
this["updated_at"] = "";
|
||||
}
|
||||
if (!("name" in $$source)) {
|
||||
this["name"] = "";
|
||||
}
|
||||
if (!("type" in $$source)) {
|
||||
this["type"] = "";
|
||||
}
|
||||
if (!("extension" in $$source)) {
|
||||
this["extension"] = "";
|
||||
}
|
||||
if (!("enabled" in $$source)) {
|
||||
this["enabled"] = false;
|
||||
}
|
||||
if (!("preventDefault" in $$source)) {
|
||||
this["preventDefault"] = false;
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new KeyBinding instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): KeyBinding {
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
return new KeyBinding($$parsedSource as Partial<KeyBinding>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Theme is the model entity for the Theme schema.
|
||||
*/
|
||||
export class Theme {
|
||||
/**
|
||||
* ID of the ent.
|
||||
*/
|
||||
"id"?: number;
|
||||
|
||||
/**
|
||||
* UUID for cross-device sync (UUIDv7)
|
||||
*/
|
||||
"uuid": string;
|
||||
|
||||
/**
|
||||
* creation time
|
||||
*/
|
||||
"created_at": string;
|
||||
|
||||
/**
|
||||
* update time
|
||||
*/
|
||||
"updated_at": string;
|
||||
|
||||
/**
|
||||
* deleted at
|
||||
*/
|
||||
"deleted_at"?: string | null;
|
||||
|
||||
/**
|
||||
* theme name
|
||||
*/
|
||||
"name": string;
|
||||
|
||||
/**
|
||||
* theme type
|
||||
*/
|
||||
"type": theme$0.Type;
|
||||
|
||||
/**
|
||||
* theme colors
|
||||
*/
|
||||
"colors": { [_: string]: any };
|
||||
|
||||
/** Creates a new Theme instance. */
|
||||
constructor($$source: Partial<Theme> = {}) {
|
||||
if (!("uuid" in $$source)) {
|
||||
this["uuid"] = "";
|
||||
}
|
||||
if (!("created_at" in $$source)) {
|
||||
this["created_at"] = "";
|
||||
}
|
||||
if (!("updated_at" in $$source)) {
|
||||
this["updated_at"] = "";
|
||||
}
|
||||
if (!("name" in $$source)) {
|
||||
this["name"] = "";
|
||||
}
|
||||
if (!("type" in $$source)) {
|
||||
this["type"] = ("" as theme$0.Type);
|
||||
}
|
||||
if (!("colors" in $$source)) {
|
||||
this["colors"] = {};
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Theme instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Theme {
|
||||
const $$createField7_0 = $$createType0;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("colors" in $$parsedSource) {
|
||||
$$parsedSource["colors"] = $$createField7_0($$parsedSource["colors"]);
|
||||
}
|
||||
return new Theme($$parsedSource as Partial<Theme>);
|
||||
}
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = $Create.Map($Create.Any, $Create.Any);
|
||||
@@ -0,0 +1,4 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export * from "./models.js";
|
||||
@@ -0,0 +1,22 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import {Create as $Create} from "@wailsio/runtime";
|
||||
|
||||
/**
|
||||
* Type defines the type for the "type" enum field.
|
||||
*/
|
||||
export enum Type {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
/**
|
||||
* Type values.
|
||||
*/
|
||||
TypeDark = "dark",
|
||||
TypeLight = "light",
|
||||
};
|
||||
@@ -193,58 +193,6 @@ export class ConfigMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Document represents a document in the system
|
||||
*/
|
||||
export class Document {
|
||||
"id": number;
|
||||
"title": string;
|
||||
"content": string;
|
||||
"createdAt": string;
|
||||
"updatedAt": string;
|
||||
"is_deleted": boolean;
|
||||
|
||||
/**
|
||||
* 锁定标志,锁定的文档无法被删除
|
||||
*/
|
||||
"is_locked": boolean;
|
||||
|
||||
/** Creates a new Document instance. */
|
||||
constructor($$source: Partial<Document> = {}) {
|
||||
if (!("id" in $$source)) {
|
||||
this["id"] = 0;
|
||||
}
|
||||
if (!("title" in $$source)) {
|
||||
this["title"] = "";
|
||||
}
|
||||
if (!("content" in $$source)) {
|
||||
this["content"] = "";
|
||||
}
|
||||
if (!("createdAt" in $$source)) {
|
||||
this["createdAt"] = "";
|
||||
}
|
||||
if (!("updatedAt" in $$source)) {
|
||||
this["updatedAt"] = "";
|
||||
}
|
||||
if (!("is_deleted" in $$source)) {
|
||||
this["is_deleted"] = false;
|
||||
}
|
||||
if (!("is_locked" in $$source)) {
|
||||
this["is_locked"] = false;
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Document instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Document {
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
return new Document($$parsedSource as Partial<Document>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* EditingConfig 编辑设置配置
|
||||
*/
|
||||
@@ -286,6 +234,12 @@ export class EditingConfig {
|
||||
*/
|
||||
"tabType": TabType;
|
||||
|
||||
/**
|
||||
* 快捷键模式
|
||||
* 快捷键模式(standard 或 emacs)
|
||||
*/
|
||||
"keymapMode": KeyBindingType;
|
||||
|
||||
/**
|
||||
* 保存选项
|
||||
* 自动保存延迟(毫秒)
|
||||
@@ -315,6 +269,9 @@ export class EditingConfig {
|
||||
if (!("tabType" in $$source)) {
|
||||
this["tabType"] = ("" as TabType);
|
||||
}
|
||||
if (!("keymapMode" in $$source)) {
|
||||
this["keymapMode"] = ("" as KeyBindingType);
|
||||
}
|
||||
if (!("autoSaveDelay" in $$source)) {
|
||||
this["autoSaveDelay"] = 0;
|
||||
}
|
||||
@@ -332,40 +289,21 @@ export class EditingConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension 单个扩展配置
|
||||
* Extension 扩展配置
|
||||
*/
|
||||
export class Extension {
|
||||
/**
|
||||
* 扩展唯一标识
|
||||
*/
|
||||
"id": ExtensionID;
|
||||
|
||||
/**
|
||||
* 是否启用
|
||||
*/
|
||||
"key": ExtensionName;
|
||||
"enabled": boolean;
|
||||
|
||||
/**
|
||||
* 是否为默认扩展
|
||||
*/
|
||||
"isDefault": boolean;
|
||||
|
||||
/**
|
||||
* 扩展配置项
|
||||
*/
|
||||
"config": ExtensionConfig;
|
||||
|
||||
/** Creates a new Extension instance. */
|
||||
constructor($$source: Partial<Extension> = {}) {
|
||||
if (!("id" in $$source)) {
|
||||
this["id"] = ("" as ExtensionID);
|
||||
if (!("key" in $$source)) {
|
||||
this["key"] = ("" as ExtensionName);
|
||||
}
|
||||
if (!("enabled" in $$source)) {
|
||||
this["enabled"] = false;
|
||||
}
|
||||
if (!("isDefault" in $$source)) {
|
||||
this["isDefault"] = false;
|
||||
}
|
||||
if (!("config" in $$source)) {
|
||||
this["config"] = ({} as ExtensionConfig);
|
||||
}
|
||||
@@ -377,10 +315,10 @@ export class Extension {
|
||||
* Creates a new Extension instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Extension {
|
||||
const $$createField3_0 = $$createType6;
|
||||
const $$createField2_0 = $$createType6;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("config" in $$parsedSource) {
|
||||
$$parsedSource["config"] = $$createField3_0($$parsedSource["config"]);
|
||||
$$parsedSource["config"] = $$createField2_0($$parsedSource["config"]);
|
||||
}
|
||||
return new Extension($$parsedSource as Partial<Extension>);
|
||||
}
|
||||
@@ -392,82 +330,83 @@ export class Extension {
|
||||
export type ExtensionConfig = { [_: string]: any };
|
||||
|
||||
/**
|
||||
* ExtensionID 扩展标识符
|
||||
* ExtensionName 扩展标识符
|
||||
*/
|
||||
export enum ExtensionID {
|
||||
export enum ExtensionName {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
/**
|
||||
* 编辑增强扩展
|
||||
* 彩虹括号
|
||||
*/
|
||||
ExtensionRainbowBrackets = "rainbowBrackets",
|
||||
RainbowBrackets = "rainbowBrackets",
|
||||
|
||||
/**
|
||||
* 超链接
|
||||
*/
|
||||
ExtensionHyperlink = "hyperlink",
|
||||
Hyperlink = "hyperlink",
|
||||
|
||||
/**
|
||||
* 颜色选择器
|
||||
*/
|
||||
ExtensionColorSelector = "colorSelector",
|
||||
ColorSelector = "colorSelector",
|
||||
|
||||
/**
|
||||
* 代码折叠
|
||||
*/
|
||||
ExtensionFold = "fold",
|
||||
Fold = "fold",
|
||||
|
||||
/**
|
||||
* 划词翻译
|
||||
*/
|
||||
ExtensionTranslator = "translator",
|
||||
Translator = "translator",
|
||||
|
||||
/**
|
||||
* Markdown渲染
|
||||
*/
|
||||
ExtensionMarkdown = "markdown",
|
||||
Markdown = "markdown",
|
||||
|
||||
/**
|
||||
* 显示空白字符
|
||||
*/
|
||||
ExtensionHighlightWhitespace = "highlightWhitespace",
|
||||
HighlightWhitespace = "highlightWhitespace",
|
||||
|
||||
/**
|
||||
* 高亮行尾空白
|
||||
*/
|
||||
ExtensionHighlightTrailingWhitespace = "highlightTrailingWhitespace",
|
||||
HighlightTrailingWhitespace = "highlightTrailingWhitespace",
|
||||
|
||||
/**
|
||||
* UI增强扩展
|
||||
* 小地图
|
||||
*/
|
||||
ExtensionMinimap = "minimap",
|
||||
Minimap = "minimap",
|
||||
|
||||
/**
|
||||
* 行号显示
|
||||
*/
|
||||
ExtensionLineNumbers = "lineNumbers",
|
||||
LineNumbers = "lineNumbers",
|
||||
|
||||
/**
|
||||
* 上下文菜单
|
||||
*/
|
||||
ExtensionContextMenu = "contextMenu",
|
||||
ContextMenu = "contextMenu",
|
||||
|
||||
/**
|
||||
* 工具扩展
|
||||
* 搜索功能
|
||||
*/
|
||||
ExtensionSearch = "search",
|
||||
Search = "search",
|
||||
|
||||
/**
|
||||
* 核心扩展
|
||||
* 编辑器核心功能
|
||||
* HTTP 客户端
|
||||
*/
|
||||
ExtensionEditor = "editor",
|
||||
HttpClient = "httpClient",
|
||||
|
||||
/**
|
||||
* 代码块导出图片
|
||||
*/
|
||||
BlockImage = "blockImage",
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -759,19 +698,39 @@ export class HotkeyCombo {
|
||||
*/
|
||||
export class KeyBinding {
|
||||
/**
|
||||
* 快捷键动作
|
||||
* 命令唯一标识符
|
||||
*/
|
||||
"command": KeyBindingCommand;
|
||||
"name": KeyBindingName;
|
||||
|
||||
/**
|
||||
* 快捷键类型(standard 或 "emacs")
|
||||
*/
|
||||
"type": KeyBindingType;
|
||||
|
||||
/**
|
||||
* 通用快捷键(跨平台)
|
||||
*/
|
||||
"key"?: string;
|
||||
|
||||
/**
|
||||
* macOS 专用快捷键
|
||||
*/
|
||||
"macos"?: string;
|
||||
|
||||
/**
|
||||
* windows 专用快捷键
|
||||
*/
|
||||
"win"?: string;
|
||||
|
||||
/**
|
||||
* Linux 专用快捷键
|
||||
*/
|
||||
"linux"?: string;
|
||||
|
||||
/**
|
||||
* 所属扩展
|
||||
*/
|
||||
"extension": ExtensionID;
|
||||
|
||||
/**
|
||||
* 快捷键组合(如 "Mod-f", "Ctrl-Shift-p")
|
||||
*/
|
||||
"key": string;
|
||||
"extension": ExtensionName;
|
||||
|
||||
/**
|
||||
* 是否启用
|
||||
@@ -779,26 +738,31 @@ export class KeyBinding {
|
||||
"enabled": boolean;
|
||||
|
||||
/**
|
||||
* 是否为默认快捷键
|
||||
* 阻止浏览器默认行为
|
||||
*/
|
||||
"isDefault": boolean;
|
||||
"preventDefault": boolean;
|
||||
|
||||
/**
|
||||
* 作用域(默认 "editor")
|
||||
*/
|
||||
"scope"?: string;
|
||||
|
||||
/** Creates a new KeyBinding instance. */
|
||||
constructor($$source: Partial<KeyBinding> = {}) {
|
||||
if (!("command" in $$source)) {
|
||||
this["command"] = ("" as KeyBindingCommand);
|
||||
if (!("name" in $$source)) {
|
||||
this["name"] = ("" as KeyBindingName);
|
||||
}
|
||||
if (!("type" in $$source)) {
|
||||
this["type"] = ("" as KeyBindingType);
|
||||
}
|
||||
if (!("extension" in $$source)) {
|
||||
this["extension"] = ("" as ExtensionID);
|
||||
}
|
||||
if (!("key" in $$source)) {
|
||||
this["key"] = "";
|
||||
this["extension"] = ("" as ExtensionName);
|
||||
}
|
||||
if (!("enabled" in $$source)) {
|
||||
this["enabled"] = false;
|
||||
}
|
||||
if (!("isDefault" in $$source)) {
|
||||
this["isDefault"] = false;
|
||||
if (!("preventDefault" in $$source)) {
|
||||
this["preventDefault"] = false;
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
@@ -814,263 +778,425 @@ export class KeyBinding {
|
||||
}
|
||||
|
||||
/**
|
||||
* KeyBindingCommand 快捷键命令
|
||||
* KeyBindingName 快捷键命令标识符
|
||||
*/
|
||||
export enum KeyBindingCommand {
|
||||
export enum KeyBindingName {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
/**
|
||||
* 搜索扩展相关
|
||||
* 显示搜索
|
||||
*/
|
||||
ShowSearchCommand = "showSearch",
|
||||
ShowSearch = "showSearch",
|
||||
|
||||
/**
|
||||
* 隐藏搜索
|
||||
*/
|
||||
HideSearchCommand = "hideSearch",
|
||||
HideSearch = "hideSearch",
|
||||
|
||||
/**
|
||||
* 代码块扩展相关
|
||||
* 块内选择全部
|
||||
*/
|
||||
BlockSelectAllCommand = "blockSelectAll",
|
||||
BlockSelectAll = "blockSelectAll",
|
||||
|
||||
/**
|
||||
* 在当前块后添加新块
|
||||
*/
|
||||
BlockAddAfterCurrentCommand = "blockAddAfterCurrent",
|
||||
BlockAddAfterCurrent = "blockAddAfterCurrent",
|
||||
|
||||
/**
|
||||
* 在最后添加新块
|
||||
*/
|
||||
BlockAddAfterLastCommand = "blockAddAfterLast",
|
||||
BlockAddAfterLast = "blockAddAfterLast",
|
||||
|
||||
/**
|
||||
* 在当前块前添加新块
|
||||
*/
|
||||
BlockAddBeforeCurrentCommand = "blockAddBeforeCurrent",
|
||||
BlockAddBeforeCurrent = "blockAddBeforeCurrent",
|
||||
|
||||
/**
|
||||
* 跳转到上一个块
|
||||
*/
|
||||
BlockGotoPreviousCommand = "blockGotoPrevious",
|
||||
BlockGotoPrevious = "blockGotoPrevious",
|
||||
|
||||
/**
|
||||
* 跳转到下一个块
|
||||
*/
|
||||
BlockGotoNextCommand = "blockGotoNext",
|
||||
BlockGotoNext = "blockGotoNext",
|
||||
|
||||
/**
|
||||
* 选择上一个块
|
||||
*/
|
||||
BlockSelectPreviousCommand = "blockSelectPrevious",
|
||||
BlockSelectPrevious = "blockSelectPrevious",
|
||||
|
||||
/**
|
||||
* 选择下一个块
|
||||
*/
|
||||
BlockSelectNextCommand = "blockSelectNext",
|
||||
BlockSelectNext = "blockSelectNext",
|
||||
|
||||
/**
|
||||
* 删除当前块
|
||||
*/
|
||||
BlockDeleteCommand = "blockDelete",
|
||||
BlockDelete = "blockDelete",
|
||||
|
||||
/**
|
||||
* 向上移动当前块
|
||||
*/
|
||||
BlockMoveUpCommand = "blockMoveUp",
|
||||
BlockMoveUp = "blockMoveUp",
|
||||
|
||||
/**
|
||||
* 向下移动当前块
|
||||
*/
|
||||
BlockMoveDownCommand = "blockMoveDown",
|
||||
BlockMoveDown = "blockMoveDown",
|
||||
|
||||
/**
|
||||
* 删除行
|
||||
*/
|
||||
BlockDeleteLineCommand = "blockDeleteLine",
|
||||
BlockDeleteLine = "blockDeleteLine",
|
||||
|
||||
/**
|
||||
* 向上移动行
|
||||
*/
|
||||
BlockMoveLineUpCommand = "blockMoveLineUp",
|
||||
BlockMoveLineUp = "blockMoveLineUp",
|
||||
|
||||
/**
|
||||
* 向下移动行
|
||||
*/
|
||||
BlockMoveLineDownCommand = "blockMoveLineDown",
|
||||
BlockMoveLineDown = "blockMoveLineDown",
|
||||
|
||||
/**
|
||||
* 字符转置
|
||||
*/
|
||||
BlockTransposeCharsCommand = "blockTransposeChars",
|
||||
BlockTransposeChars = "blockTransposeChars",
|
||||
|
||||
/**
|
||||
* 格式化代码块
|
||||
*/
|
||||
BlockFormatCommand = "blockFormat",
|
||||
BlockFormat = "blockFormat",
|
||||
|
||||
/**
|
||||
* 复制
|
||||
*/
|
||||
BlockCopyCommand = "blockCopy",
|
||||
BlockCopy = "blockCopy",
|
||||
|
||||
/**
|
||||
* 剪切
|
||||
*/
|
||||
BlockCutCommand = "blockCut",
|
||||
BlockCut = "blockCut",
|
||||
|
||||
/**
|
||||
* 粘贴
|
||||
*/
|
||||
BlockPasteCommand = "blockPaste",
|
||||
BlockPaste = "blockPaste",
|
||||
|
||||
/**
|
||||
* 代码折叠扩展相关
|
||||
* 折叠代码
|
||||
*/
|
||||
FoldCodeCommand = "foldCode",
|
||||
FoldCode = "foldCode",
|
||||
|
||||
/**
|
||||
* 展开代码
|
||||
*/
|
||||
UnfoldCodeCommand = "unfoldCode",
|
||||
UnfoldCode = "unfoldCode",
|
||||
|
||||
/**
|
||||
* 折叠全部
|
||||
*/
|
||||
FoldAllCommand = "foldAll",
|
||||
FoldAll = "foldAll",
|
||||
|
||||
/**
|
||||
* 展开全部
|
||||
*/
|
||||
UnfoldAllCommand = "unfoldAll",
|
||||
UnfoldAll = "unfoldAll",
|
||||
|
||||
/**
|
||||
* 通用编辑扩展相关
|
||||
* 光标按语法左移
|
||||
*/
|
||||
CursorSyntaxLeftCommand = "cursorSyntaxLeft",
|
||||
CursorSyntaxLeft = "cursorSyntaxLeft",
|
||||
|
||||
/**
|
||||
* 光标按语法右移
|
||||
*/
|
||||
CursorSyntaxRightCommand = "cursorSyntaxRight",
|
||||
CursorSyntaxRight = "cursorSyntaxRight",
|
||||
|
||||
/**
|
||||
* 按语法选择左侧
|
||||
*/
|
||||
SelectSyntaxLeftCommand = "selectSyntaxLeft",
|
||||
SelectSyntaxLeft = "selectSyntaxLeft",
|
||||
|
||||
/**
|
||||
* 按语法选择右侧
|
||||
*/
|
||||
SelectSyntaxRightCommand = "selectSyntaxRight",
|
||||
SelectSyntaxRight = "selectSyntaxRight",
|
||||
|
||||
/**
|
||||
* 向上复制行
|
||||
*/
|
||||
CopyLineUpCommand = "copyLineUp",
|
||||
CopyLineUp = "copyLineUp",
|
||||
|
||||
/**
|
||||
* 向下复制行
|
||||
*/
|
||||
CopyLineDownCommand = "copyLineDown",
|
||||
CopyLineDown = "copyLineDown",
|
||||
|
||||
/**
|
||||
* 插入空行
|
||||
*/
|
||||
InsertBlankLineCommand = "insertBlankLine",
|
||||
InsertBlankLine = "insertBlankLine",
|
||||
|
||||
/**
|
||||
* 选择行
|
||||
*/
|
||||
SelectLineCommand = "selectLine",
|
||||
SelectLine = "selectLine",
|
||||
|
||||
/**
|
||||
* 选择父级语法
|
||||
*/
|
||||
SelectParentSyntaxCommand = "selectParentSyntax",
|
||||
SelectParentSyntax = "selectParentSyntax",
|
||||
|
||||
/**
|
||||
* 简化选择
|
||||
*/
|
||||
SimplifySelection = "simplifySelection",
|
||||
|
||||
/**
|
||||
* 在上方添加光标
|
||||
*/
|
||||
AddCursorAbove = "addCursorAbove",
|
||||
|
||||
/**
|
||||
* 在下方添加光标
|
||||
*/
|
||||
AddCursorBelow = "addCursorBelow",
|
||||
|
||||
/**
|
||||
* 光标按单词左移
|
||||
*/
|
||||
CursorGroupLeft = "cursorGroupLeft",
|
||||
|
||||
/**
|
||||
* 光标按单词右移
|
||||
*/
|
||||
CursorGroupRight = "cursorGroupRight",
|
||||
|
||||
/**
|
||||
* 按单词选择左侧
|
||||
*/
|
||||
SelectGroupLeft = "selectGroupLeft",
|
||||
|
||||
/**
|
||||
* 按单词选择右侧
|
||||
*/
|
||||
SelectGroupRight = "selectGroupRight",
|
||||
|
||||
/**
|
||||
* 删除到行尾
|
||||
*/
|
||||
DeleteToLineEnd = "deleteToLineEnd",
|
||||
|
||||
/**
|
||||
* 删除到行首
|
||||
*/
|
||||
DeleteToLineStart = "deleteToLineStart",
|
||||
|
||||
/**
|
||||
* 移动到行首
|
||||
*/
|
||||
CursorLineStart = "cursorLineStart",
|
||||
|
||||
/**
|
||||
* 移动到行尾
|
||||
*/
|
||||
CursorLineEnd = "cursorLineEnd",
|
||||
|
||||
/**
|
||||
* 选择到行首
|
||||
*/
|
||||
SelectLineStart = "selectLineStart",
|
||||
|
||||
/**
|
||||
* 选择到行尾
|
||||
*/
|
||||
SelectLineEnd = "selectLineEnd",
|
||||
|
||||
/**
|
||||
* 跳转到文档开头
|
||||
*/
|
||||
CursorDocStart = "cursorDocStart",
|
||||
|
||||
/**
|
||||
* 跳转到文档结尾
|
||||
*/
|
||||
CursorDocEnd = "cursorDocEnd",
|
||||
|
||||
/**
|
||||
* 选择到文档开头
|
||||
*/
|
||||
SelectDocStart = "selectDocStart",
|
||||
|
||||
/**
|
||||
* 选择到文档结尾
|
||||
*/
|
||||
SelectDocEnd = "selectDocEnd",
|
||||
|
||||
/**
|
||||
* 选择到匹配括号
|
||||
*/
|
||||
SelectMatchingBracket = "selectMatchingBracket",
|
||||
|
||||
/**
|
||||
* 分割行
|
||||
*/
|
||||
SplitLine = "splitLine",
|
||||
|
||||
/**
|
||||
* 光标左移一个字符
|
||||
*/
|
||||
CursorCharLeft = "cursorCharLeft",
|
||||
|
||||
/**
|
||||
* 光标右移一个字符
|
||||
*/
|
||||
CursorCharRight = "cursorCharRight",
|
||||
|
||||
/**
|
||||
* 光标上移一行
|
||||
*/
|
||||
CursorLineUp = "cursorLineUp",
|
||||
|
||||
/**
|
||||
* 光标下移一行
|
||||
*/
|
||||
CursorLineDown = "cursorLineDown",
|
||||
|
||||
/**
|
||||
* 向上翻页
|
||||
*/
|
||||
CursorPageUp = "cursorPageUp",
|
||||
|
||||
/**
|
||||
* 向下翻页
|
||||
*/
|
||||
CursorPageDown = "cursorPageDown",
|
||||
|
||||
/**
|
||||
* 选择左移一个字符
|
||||
*/
|
||||
SelectCharLeft = "selectCharLeft",
|
||||
|
||||
/**
|
||||
* 选择右移一个字符
|
||||
*/
|
||||
SelectCharRight = "selectCharRight",
|
||||
|
||||
/**
|
||||
* 选择上移一行
|
||||
*/
|
||||
SelectLineUp = "selectLineUp",
|
||||
|
||||
/**
|
||||
* 选择下移一行
|
||||
*/
|
||||
SelectLineDown = "selectLineDown",
|
||||
|
||||
/**
|
||||
* 减少缩进
|
||||
*/
|
||||
IndentLessCommand = "indentLess",
|
||||
IndentLess = "indentLess",
|
||||
|
||||
/**
|
||||
* 增加缩进
|
||||
*/
|
||||
IndentMoreCommand = "indentMore",
|
||||
IndentMore = "indentMore",
|
||||
|
||||
/**
|
||||
* 缩进选择
|
||||
*/
|
||||
IndentSelectionCommand = "indentSelection",
|
||||
IndentSelection = "indentSelection",
|
||||
|
||||
/**
|
||||
* 光标到匹配括号
|
||||
*/
|
||||
CursorMatchingBracketCommand = "cursorMatchingBracket",
|
||||
CursorMatchingBracket = "cursorMatchingBracket",
|
||||
|
||||
/**
|
||||
* 切换注释
|
||||
*/
|
||||
ToggleCommentCommand = "toggleComment",
|
||||
ToggleComment = "toggleComment",
|
||||
|
||||
/**
|
||||
* 切换块注释
|
||||
*/
|
||||
ToggleBlockCommentCommand = "toggleBlockComment",
|
||||
ToggleBlockComment = "toggleBlockComment",
|
||||
|
||||
/**
|
||||
* 插入新行并缩进
|
||||
*/
|
||||
InsertNewlineAndIndentCommand = "insertNewlineAndIndent",
|
||||
InsertNewlineAndIndent = "insertNewlineAndIndent",
|
||||
|
||||
/**
|
||||
* 向后删除字符
|
||||
*/
|
||||
DeleteCharBackwardCommand = "deleteCharBackward",
|
||||
DeleteCharBackward = "deleteCharBackward",
|
||||
|
||||
/**
|
||||
* 向前删除字符
|
||||
*/
|
||||
DeleteCharForwardCommand = "deleteCharForward",
|
||||
DeleteCharForward = "deleteCharForward",
|
||||
|
||||
/**
|
||||
* 向后删除组
|
||||
*/
|
||||
DeleteGroupBackwardCommand = "deleteGroupBackward",
|
||||
DeleteGroupBackward = "deleteGroupBackward",
|
||||
|
||||
/**
|
||||
* 向前删除组
|
||||
*/
|
||||
DeleteGroupForwardCommand = "deleteGroupForward",
|
||||
DeleteGroupForward = "deleteGroupForward",
|
||||
|
||||
/**
|
||||
* 历史记录扩展相关
|
||||
* 撤销
|
||||
*/
|
||||
HistoryUndoCommand = "historyUndo",
|
||||
HistoryUndo = "historyUndo",
|
||||
|
||||
/**
|
||||
* 重做
|
||||
*/
|
||||
HistoryRedoCommand = "historyRedo",
|
||||
HistoryRedo = "historyRedo",
|
||||
|
||||
/**
|
||||
* 撤销选择
|
||||
*/
|
||||
HistoryUndoSelectionCommand = "historyUndoSelection",
|
||||
HistoryUndoSelection = "historyUndoSelection",
|
||||
|
||||
/**
|
||||
* 重做选择
|
||||
*/
|
||||
HistoryRedoSelectionCommand = "historyRedoSelection",
|
||||
HistoryRedoSelection = "historyRedoSelection",
|
||||
|
||||
/**
|
||||
* 复制块为图片
|
||||
*/
|
||||
CopyBlockImage = "copyBlockImage",
|
||||
};
|
||||
|
||||
export enum KeyBindingType {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
/**
|
||||
* standard 标准快捷键
|
||||
*/
|
||||
Standard = "standard",
|
||||
|
||||
/**
|
||||
* emacs 快捷键
|
||||
*/
|
||||
Emacs = "emacs",
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1138,76 +1264,6 @@ export enum TabType {
|
||||
TabTypeTab = "tab",
|
||||
};
|
||||
|
||||
/**
|
||||
* Theme 主题数据库模型
|
||||
*/
|
||||
export class Theme {
|
||||
"id": number;
|
||||
"name": string;
|
||||
"type": ThemeType;
|
||||
"colors": ThemeColorConfig;
|
||||
"isDefault": boolean;
|
||||
"createdAt": string;
|
||||
"updatedAt": string;
|
||||
|
||||
/** Creates a new Theme instance. */
|
||||
constructor($$source: Partial<Theme> = {}) {
|
||||
if (!("id" in $$source)) {
|
||||
this["id"] = 0;
|
||||
}
|
||||
if (!("name" in $$source)) {
|
||||
this["name"] = "";
|
||||
}
|
||||
if (!("type" in $$source)) {
|
||||
this["type"] = ("" as ThemeType);
|
||||
}
|
||||
if (!("colors" in $$source)) {
|
||||
this["colors"] = ({} as ThemeColorConfig);
|
||||
}
|
||||
if (!("isDefault" in $$source)) {
|
||||
this["isDefault"] = false;
|
||||
}
|
||||
if (!("createdAt" in $$source)) {
|
||||
this["createdAt"] = "";
|
||||
}
|
||||
if (!("updatedAt" in $$source)) {
|
||||
this["updatedAt"] = "";
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new Theme instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): Theme {
|
||||
const $$createField3_0 = $$createType9;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("colors" in $$parsedSource) {
|
||||
$$parsedSource["colors"] = $$createField3_0($$parsedSource["colors"]);
|
||||
}
|
||||
return new Theme($$parsedSource as Partial<Theme>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ThemeColorConfig 使用与前端 ThemeColors 相同的结构,存储任意主题键值
|
||||
*/
|
||||
export type ThemeColorConfig = { [_: string]: any };
|
||||
|
||||
/**
|
||||
* ThemeType 主题类型枚举
|
||||
*/
|
||||
export enum ThemeType {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
ThemeTypeDark = "dark",
|
||||
ThemeTypeLight = "light",
|
||||
};
|
||||
|
||||
/**
|
||||
* UpdateSourceType 更新源类型
|
||||
*/
|
||||
@@ -1306,8 +1362,8 @@ export class UpdatesConfig {
|
||||
* Creates a new UpdatesConfig instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): UpdatesConfig {
|
||||
const $$createField6_0 = $$createType10;
|
||||
const $$createField7_0 = $$createType11;
|
||||
const $$createField6_0 = $$createType9;
|
||||
const $$createField7_0 = $$createType10;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("github" in $$parsedSource) {
|
||||
$$parsedSource["github"] = $$createField6_0($$parsedSource["github"]);
|
||||
@@ -1334,11 +1390,5 @@ var $$createType6 = (function $$initCreateType6(...args): any {
|
||||
});
|
||||
const $$createType7 = $Create.Map($Create.Any, $Create.Any);
|
||||
const $$createType8 = HotkeyCombo.createFrom;
|
||||
var $$createType9 = (function $$initCreateType9(...args): any {
|
||||
if ($$createType9 === $$initCreateType9) {
|
||||
$$createType9 = $$createType7;
|
||||
}
|
||||
return $$createType9(...args);
|
||||
});
|
||||
const $$createType10 = GithubConfig.createFrom;
|
||||
const $$createType11 = GiteaConfig.createFrom;
|
||||
const $$createType9 = GithubConfig.createFrom;
|
||||
const $$createType10 = GiteaConfig.createFrom;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* BackupService 提供基于Git的备份功能
|
||||
* BackupService 提供基于Git的备份同步功能
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -18,7 +18,7 @@ import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/applic
|
||||
import * as models$0 from "../models/models.js";
|
||||
|
||||
/**
|
||||
* HandleConfigChange 处理备份配置变更
|
||||
* HandleConfigChange 处理配置变更
|
||||
*/
|
||||
export function HandleConfigChange(config: models$0.GitBackupConfig | null): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(395287784, config) as any;
|
||||
@@ -34,15 +34,7 @@ export function Initialize(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* PushToRemote 推送本地更改到远程仓库
|
||||
*/
|
||||
export function PushToRemote(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(262644139) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reinitialize 重新初始化备份服务,用于响应配置变更
|
||||
* Reinitialize 重新初始化
|
||||
*/
|
||||
export function Reinitialize(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(301562543) as any;
|
||||
@@ -50,7 +42,7 @@ export function Reinitialize(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown 服务关闭时的清理工作
|
||||
* ServiceShutdown 服务关闭
|
||||
*/
|
||||
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(422131801) as any;
|
||||
@@ -63,7 +55,7 @@ export function ServiceStartup(options: application$0.ServiceOptions): Promise<v
|
||||
}
|
||||
|
||||
/**
|
||||
* StartAutoBackup 启动自动备份定时器
|
||||
* StartAutoBackup 启动自动备份
|
||||
*/
|
||||
export function StartAutoBackup(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3035755449) as any;
|
||||
@@ -77,3 +69,11 @@ export function StopAutoBackup(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2641894021) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync 执行完整的同步流程:导出 -> commit -> pull -> 解决冲突 -> push -> 导入
|
||||
*/
|
||||
export function Sync(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3420383211) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
@@ -15,11 +15,10 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as models$0 from "../models/models.js";
|
||||
|
||||
import * as helper$0 from "../common/helper/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as $models from "./models.js";
|
||||
import * as models$0 from "../models/models.js";
|
||||
|
||||
/**
|
||||
* Get 获取配置项
|
||||
@@ -50,7 +49,7 @@ export function MigrateConfig(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetConfig 强制重置所有配置为默认值
|
||||
* ResetConfig 重置所有配置为默认值
|
||||
*/
|
||||
export function ResetConfig(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3593047389) as any;
|
||||
@@ -66,7 +65,7 @@ export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup initializes the service when the application starts
|
||||
* ServiceStartup 服务启动时初始化
|
||||
*/
|
||||
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3311949428, options) as any;
|
||||
@@ -84,7 +83,7 @@ export function Set(key: string, value: any): Promise<void> & { cancel(): void }
|
||||
/**
|
||||
* Watch 注册配置变更监听器
|
||||
*/
|
||||
export function Watch(path: string, callback: $models.ObserverCallback): Promise<$models.CancelFunc> & { cancel(): void } {
|
||||
export function Watch(path: string, callback: helper$0.ObserverCallback): Promise<helper$0.CancelFunc> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1143583035, path, callback) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
@@ -92,7 +91,7 @@ export function Watch(path: string, callback: $models.ObserverCallback): Promise
|
||||
/**
|
||||
* WatchWithContext 使用 Context 注册监听器
|
||||
*/
|
||||
export function WatchWithContext(path: string, callback: $models.ObserverCallback): Promise<void> & { cancel(): void } {
|
||||
export function WatchWithContext(path: string, callback: helper$0.ObserverCallback): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1454973098, path, callback) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* DatabaseService provides shared database functionality
|
||||
* DatabaseService 数据库服务
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -15,15 +15,7 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
|
||||
|
||||
/**
|
||||
* RegisterModel 注册模型与表的映射关系
|
||||
*/
|
||||
export function RegisterModel(tableName: string, model: any): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(175397515, tableName, model) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown shuts down the service when the application closes
|
||||
* ServiceShutdown 服务关闭
|
||||
*/
|
||||
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3907893632) as any;
|
||||
@@ -31,7 +23,7 @@ export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup initializes the service when the application starts
|
||||
* ServiceStartup 服务启动
|
||||
*/
|
||||
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2067840771, options) as any;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* DocumentService provides document management functionality
|
||||
* DocumentService 文档服务
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -15,12 +15,12 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as models$0 from "../models/models.js";
|
||||
import * as ent$0 from "../models/ent/models.js";
|
||||
|
||||
/**
|
||||
* CreateDocument creates a new document and returns the created document with ID
|
||||
* CreateDocument 创建文档
|
||||
*/
|
||||
export function CreateDocument(title: string): Promise<models$0.Document | null> & { cancel(): void } {
|
||||
export function CreateDocument(title: string): Promise<ent$0.Document | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3360680842, title) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
@@ -30,7 +30,7 @@ export function CreateDocument(title: string): Promise<models$0.Document | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* DeleteDocument marks a document as deleted (default document with ID=1 cannot be deleted)
|
||||
* DeleteDocument 删除文档
|
||||
*/
|
||||
export function DeleteDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(412287269, id) as any;
|
||||
@@ -38,9 +38,9 @@ export function DeleteDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* GetDocumentByID gets a document by ID
|
||||
* GetDocumentByID 根据ID获取文档
|
||||
*/
|
||||
export function GetDocumentByID(id: number): Promise<models$0.Document | null> & { cancel(): void } {
|
||||
export function GetDocumentByID(id: number): Promise<ent$0.Document | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3468193232, id) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
@@ -50,9 +50,9 @@ export function GetDocumentByID(id: number): Promise<models$0.Document | null> &
|
||||
}
|
||||
|
||||
/**
|
||||
* ListAllDocumentsMeta lists all active (non-deleted) document metadata
|
||||
* ListAllDocumentsMeta 列出所有文档
|
||||
*/
|
||||
export function ListAllDocumentsMeta(): Promise<(models$0.Document | null)[]> & { cancel(): void } {
|
||||
export function ListAllDocumentsMeta(): Promise<(ent$0.Document | null)[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3073950297) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType2($result);
|
||||
@@ -62,19 +62,7 @@ export function ListAllDocumentsMeta(): Promise<(models$0.Document | null)[]> &
|
||||
}
|
||||
|
||||
/**
|
||||
* ListDeletedDocumentsMeta lists all deleted document metadata
|
||||
*/
|
||||
export function ListDeletedDocumentsMeta(): Promise<(models$0.Document | null)[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(490143787) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType2($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* LockDocument 锁定文档,防止删除
|
||||
* LockDocument 锁定文档
|
||||
*/
|
||||
export function LockDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1889494473, id) as any;
|
||||
@@ -82,15 +70,7 @@ export function LockDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* RestoreDocument restores a deleted document
|
||||
*/
|
||||
export function RestoreDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(784200778, id) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup initializes the service when the application starts
|
||||
* ServiceStartup 服务启动
|
||||
*/
|
||||
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1474135487, options) as any;
|
||||
@@ -106,7 +86,7 @@ export function UnlockDocument(id: number): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateDocumentContent updates the content of a document
|
||||
* UpdateDocumentContent 更新文档内容
|
||||
*/
|
||||
export function UpdateDocumentContent(id: number, content: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3251897116, id, content) as any;
|
||||
@@ -114,7 +94,7 @@ export function UpdateDocumentContent(id: number, content: string): Promise<void
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateDocumentTitle updates the title of a document
|
||||
* UpdateDocumentTitle 更新文档标题
|
||||
*/
|
||||
export function UpdateDocumentTitle(id: number, title: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2045530459, id, title) as any;
|
||||
@@ -122,6 +102,6 @@ export function UpdateDocumentTitle(id: number, title: string): Promise<void> &
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = models$0.Document.createFrom;
|
||||
const $$createType0 = ent$0.Document.createFrom;
|
||||
const $$createType1 = $Create.Nullable($$createType0);
|
||||
const $$createType2 = $Create.Array($$createType1);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* ExtensionService 扩展管理服务
|
||||
* ExtensionService 扩展服务
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -16,12 +16,15 @@ import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/applic
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as models$0 from "../models/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as ent$0 from "../models/ent/models.js";
|
||||
|
||||
/**
|
||||
* GetAllExtensions 获取所有扩展配置
|
||||
* GetDefaultExtensions 获取默认扩展配置(用于前端绑定生成)
|
||||
*/
|
||||
export function GetAllExtensions(): Promise<models$0.Extension[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3094292124) as any;
|
||||
export function GetDefaultExtensions(): Promise<models$0.Extension[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(4036328166) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
}) as any;
|
||||
@@ -30,23 +33,51 @@ export function GetAllExtensions(): Promise<models$0.Extension[]> & { cancel():
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetAllExtensionsToDefault 重置所有扩展到默认状态
|
||||
* GetExtensionByID 根据ID获取扩展
|
||||
*/
|
||||
export function ResetAllExtensionsToDefault(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(270611949) as any;
|
||||
export function GetExtensionByID(id: number): Promise<ent$0.Extension | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1521424252, id) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType3($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetExtensionConfig 获取扩展配置
|
||||
*/
|
||||
export function GetExtensionConfig(id: number): Promise<{ [_: string]: any }> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1629559882, id) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType4($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetExtensions 获取所有扩展
|
||||
*/
|
||||
export function GetExtensions(): Promise<(ent$0.Extension | null)[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3179289021) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType5($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetExtensionConfig 重置单个扩展到默认状态
|
||||
*/
|
||||
export function ResetExtensionConfig(id: number): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3990780299, id) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetExtensionToDefault 重置扩展到默认状态
|
||||
*/
|
||||
export function ResetExtensionToDefault(id: models$0.ExtensionID): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(868308101, id) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup 启动时调用
|
||||
* ServiceStartup 服务启动
|
||||
*/
|
||||
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(40324057, options) as any;
|
||||
@@ -54,21 +85,33 @@ export function ServiceStartup(options: application$0.ServiceOptions): Promise<v
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateExtensionEnabled 更新扩展启用状态
|
||||
* SyncExtensions 同步扩展配置
|
||||
*/
|
||||
export function UpdateExtensionEnabled(id: models$0.ExtensionID, enabled: boolean): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1067300094, id, enabled) as any;
|
||||
export function SyncExtensions(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(167560004) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateExtensionState 更新扩展状态
|
||||
* UpdateExtensionConfig 更新扩展配置
|
||||
*/
|
||||
export function UpdateExtensionState(id: models$0.ExtensionID, enabled: boolean, config: models$0.ExtensionConfig): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2917946454, id, enabled, config) as any;
|
||||
export function UpdateExtensionConfig(id: number, config: { [_: string]: any }): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3184142503, id, config) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateExtensionEnabled 更新扩展启用状态
|
||||
*/
|
||||
export function UpdateExtensionEnabled(id: number, enabled: boolean): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1067300094, id, enabled) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = models$0.Extension.createFrom;
|
||||
const $$createType1 = $Create.Array($$createType0);
|
||||
const $$createType2 = ent$0.Extension.createFrom;
|
||||
const $$createType3 = $Create.Nullable($$createType2);
|
||||
const $$createType4 = $Create.Map($Create.Any, $Create.Any);
|
||||
const $$createType5 = $Create.Array($$createType3);
|
||||
|
||||
@@ -18,12 +18,12 @@ import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/applic
|
||||
import * as models$0 from "../models/models.js";
|
||||
|
||||
/**
|
||||
* GetCurrentHotkey 获取当前热键
|
||||
* GetSupportedKeys 返回系统支持的快捷键列表
|
||||
*/
|
||||
export function GetCurrentHotkey(): Promise<models$0.HotkeyCombo | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2572811187) as any;
|
||||
export function GetSupportedKeys(): Promise<string[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1511528650) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
return $$createType0($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
@@ -86,5 +86,4 @@ export function UpdateHotkey(enable: boolean, combo: models$0.HotkeyCombo | null
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = models$0.HotkeyCombo.createFrom;
|
||||
const $$createType1 = $Create.Nullable($$createType0);
|
||||
const $$createType0 = $Create.Array($Create.Any);
|
||||
|
||||
@@ -17,7 +17,6 @@ import * as SystemService from "./systemservice.js";
|
||||
import * as TestService from "./testservice.js";
|
||||
import * as ThemeService from "./themeservice.js";
|
||||
import * as TranslationService from "./translationservice.js";
|
||||
import * as TrayService from "./trayservice.js";
|
||||
import * as WindowService from "./windowservice.js";
|
||||
export {
|
||||
BackupService,
|
||||
@@ -36,7 +35,6 @@ export {
|
||||
TestService,
|
||||
ThemeService,
|
||||
TranslationService,
|
||||
TrayService,
|
||||
WindowService
|
||||
};
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* KeyBindingService 快捷键管理服务
|
||||
* KeyBindingService 快捷键服务
|
||||
* @module
|
||||
*/
|
||||
|
||||
@@ -16,12 +16,15 @@ import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/applic
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as models$0 from "../models/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as ent$0 from "../models/ent/models.js";
|
||||
|
||||
/**
|
||||
* GetAllKeyBindings 获取所有快捷键配置
|
||||
* GetDefaultKeyBindings 获取默认快捷键配置
|
||||
*/
|
||||
export function GetAllKeyBindings(): Promise<models$0.KeyBinding[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1633502882) as any;
|
||||
export function GetDefaultKeyBindings(): Promise<models$0.KeyBinding[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3843471588) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
}) as any;
|
||||
@@ -30,13 +33,72 @@ export function GetAllKeyBindings(): Promise<models$0.KeyBinding[]> & { cancel()
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup 启动时调用
|
||||
* GetKeyBindingByID 根据ID获取快捷键
|
||||
*/
|
||||
export function GetKeyBindingByID(id: number): Promise<ent$0.KeyBinding | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1578192526, id) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType3($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetKeyBindings 根据类型获取快捷键
|
||||
*/
|
||||
export function GetKeyBindings(kbType: models$0.KeyBindingType): Promise<(ent$0.KeyBinding | null)[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(4253885163, kbType) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType4($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetKeyBindings 重置所有快捷键到默认值
|
||||
*/
|
||||
export function ResetKeyBindings(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(4251626010) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceStartup 服务启动
|
||||
*/
|
||||
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2057121990, options) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SyncKeyBindings 同步快捷键配置
|
||||
*/
|
||||
export function SyncKeyBindings(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1522202638) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateKeyBindingEnabled 更新快捷键启用状态
|
||||
*/
|
||||
export function UpdateKeyBindingEnabled(id: number, enabled: boolean): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(843626124, id, enabled) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateKeyBindingKeys 更新快捷键绑定(根据操作系统自动判断更新哪个字段)
|
||||
*/
|
||||
export function UpdateKeyBindingKeys(id: number, key: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3432755175, id, key) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = models$0.KeyBinding.createFrom;
|
||||
const $$createType1 = $Create.Array($$createType0);
|
||||
const $$createType2 = ent$0.KeyBinding.createFrom;
|
||||
const $$createType3 = $Create.Nullable($$createType2);
|
||||
const $$createType4 = $Create.Array($$createType3);
|
||||
|
||||
@@ -12,12 +12,6 @@ import * as http$0 from "../../../net/http/models.js";
|
||||
// @ts-ignore: Unused imports
|
||||
import * as time$0 from "../../../time/models.js";
|
||||
|
||||
/**
|
||||
* CancelFunc 取消订阅函数
|
||||
* 调用此函数可以取消对配置的监听
|
||||
*/
|
||||
export type CancelFunc = any;
|
||||
|
||||
/**
|
||||
* HttpRequest HTTP请求结构
|
||||
*/
|
||||
@@ -191,15 +185,14 @@ export class MemoryStats {
|
||||
* MigrationProgress 迁移进度信息
|
||||
*/
|
||||
export class MigrationProgress {
|
||||
"status": MigrationStatus;
|
||||
/**
|
||||
* 0-100
|
||||
*/
|
||||
"progress": number;
|
||||
"error"?: string;
|
||||
|
||||
/** Creates a new MigrationProgress instance. */
|
||||
constructor($$source: Partial<MigrationProgress> = {}) {
|
||||
if (!("status" in $$source)) {
|
||||
this["status"] = ("" as MigrationStatus);
|
||||
}
|
||||
if (!("progress" in $$source)) {
|
||||
this["progress"] = 0;
|
||||
}
|
||||
@@ -216,20 +209,6 @@ export class MigrationProgress {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MigrationStatus 迁移状态
|
||||
*/
|
||||
export enum MigrationStatus {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
MigrationStatusMigrating = "migrating",
|
||||
MigrationStatusCompleted = "completed",
|
||||
MigrationStatusFailed = "failed",
|
||||
};
|
||||
|
||||
/**
|
||||
* OSInfo 操作系统信息
|
||||
*/
|
||||
@@ -266,11 +245,6 @@ export class OSInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ObserverCallback 观察者回调函数
|
||||
*/
|
||||
export type ObserverCallback = any;
|
||||
|
||||
/**
|
||||
* SelfUpdateResult 自我更新结果
|
||||
*/
|
||||
|
||||
@@ -15,12 +15,12 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import * as models$0 from "../models/models.js";
|
||||
import * as ent$0 from "../models/ent/models.js";
|
||||
|
||||
/**
|
||||
* GetThemeByName 通过名称获取主题覆盖,若不存在则返回 nil
|
||||
* GetThemeByName 根据Key获取主题
|
||||
*/
|
||||
export function GetThemeByName(name: string): Promise<models$0.Theme | null> & { cancel(): void } {
|
||||
export function GetThemeByName(name: string): Promise<ent$0.Theme | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1938954770, name) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType1($result);
|
||||
@@ -30,18 +30,10 @@ export function GetThemeByName(name: string): Promise<models$0.Theme | null> & {
|
||||
}
|
||||
|
||||
/**
|
||||
* ResetTheme 删除指定主题的覆盖配置
|
||||
* ResetTheme 删除主题
|
||||
*/
|
||||
export function ResetTheme(name: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1806334457, name) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown 服务关闭
|
||||
*/
|
||||
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1676749034) as any;
|
||||
export function ResetTheme(key: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1806334457, key) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
@@ -54,13 +46,13 @@ export function ServiceStartup(options: application$0.ServiceOptions): Promise<v
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateTheme 保存或更新主题覆盖
|
||||
* UpdateTheme 保存或更新主题
|
||||
*/
|
||||
export function UpdateTheme(name: string, colors: models$0.ThemeColorConfig): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(70189749, name, colors) as any;
|
||||
export function UpdateTheme(key: string, colors: { [_: string]: any }): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(70189749, key, colors) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = models$0.Theme.createFrom;
|
||||
const $$createType0 = ent$0.Theme.createFrom;
|
||||
const $$createType1 = $Create.Nullable($$createType0);
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* TrayService 系统托盘服务
|
||||
* @module
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore: Unused imports
|
||||
import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
|
||||
/**
|
||||
* AutoShowHide 自动显示/隐藏主窗口
|
||||
*/
|
||||
export function AutoShowHide(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(4044219428) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* HandleWindowClose 处理窗口关闭事件
|
||||
*/
|
||||
export function HandleWindowClose(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1824247204) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* HandleWindowMinimize 处理窗口最小化事件
|
||||
*/
|
||||
export function HandleWindowMinimize(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(178686624) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* MinimizeButtonClicked 处理标题栏最小化按钮点击
|
||||
*/
|
||||
export function MinimizeButtonClicked(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2477618539) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ShouldMinimizeToTray 检查是否应该最小化到托盘
|
||||
*/
|
||||
export function ShouldMinimizeToTray(): Promise<boolean> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3403884012) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ShowWindow 显示主窗口
|
||||
*/
|
||||
export function ShowWindow(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1315913255) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
@@ -14,18 +14,6 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
// @ts-ignore: Unused imports
|
||||
import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
|
||||
|
||||
/**
|
||||
* GetOpenWindows 获取所有打开的文档窗口
|
||||
*/
|
||||
export function GetOpenWindows(): Promise<application$0.Window[]> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1464997251) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType0($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* IsDocumentWindowOpen 检查指定文档的窗口是否已打开
|
||||
*/
|
||||
@@ -57,6 +45,3 @@ export function ServiceStartup(options: application$0.ServiceOptions): Promise<v
|
||||
let $resultPromise = $Call.ByID(2432987694, options) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = $Create.Array($Create.Any);
|
||||
|
||||
1043
frontend/package-lock.json
generated
1043
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -23,7 +23,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.0",
|
||||
"@codemirror/commands": "^6.10.0",
|
||||
"@codemirror/commands": "^6.10.1",
|
||||
"@codemirror/lang-angular": "^0.1.4",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
@@ -34,7 +34,7 @@
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-lezer": "^6.0.2",
|
||||
"@codemirror/lang-liquid": "^6.3.0",
|
||||
"@codemirror/lang-liquid": "^6.3.1",
|
||||
"@codemirror/lang-markdown": "^6.5.0",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
@@ -44,62 +44,63 @@
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-wast": "^6.0.2",
|
||||
"@codemirror/lang-yaml": "^6.1.2",
|
||||
"@codemirror/language": "^6.11.3",
|
||||
"@codemirror/language": "^6.12.1",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.2",
|
||||
"@codemirror/lint": "^6.9.2",
|
||||
"@codemirror/search": "^6.5.11",
|
||||
"@codemirror/state": "^6.5.2",
|
||||
"@codemirror/view": "^6.38.8",
|
||||
"@codemirror/state": "^6.5.3",
|
||||
"@codemirror/view": "^6.39.6",
|
||||
"@cospaia/prettier-plugin-clojure": "^0.0.2",
|
||||
"@lezer/highlight": "^1.2.3",
|
||||
"@lezer/lr": "^1.4.4",
|
||||
"@lezer/lr": "^1.4.5",
|
||||
"@prettier/plugin-xml": "^3.4.2",
|
||||
"@replit/codemirror-lang-svelte": "^6.0.0",
|
||||
"@toml-tools/lexer": "^1.0.0",
|
||||
"@toml-tools/parser": "^1.0.0",
|
||||
"@toml-tools/lexer": "^1.0.1",
|
||||
"@toml-tools/parser": "^1.0.1",
|
||||
"@types/katex": "^0.16.7",
|
||||
"@zumer/snapdom": "^2.0.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"codemirror-lang-elixir": "^4.0.0",
|
||||
"colors-named": "^1.0.2",
|
||||
"colors-named-hex": "^1.0.2",
|
||||
"colors-named": "^1.0.4",
|
||||
"colors-named-hex": "^1.0.3",
|
||||
"groovy-beautify": "^0.0.17",
|
||||
"hsl-matcher": "^1.2.4",
|
||||
"java-parser": "^3.0.1",
|
||||
"katex": "^0.16.25",
|
||||
"linguist-languages": "^9.1.0",
|
||||
"katex": "^0.16.27",
|
||||
"linguist-languages": "^9.1.11",
|
||||
"marked": "^17.0.1",
|
||||
"mermaid": "^11.12.1",
|
||||
"mermaid": "^11.12.2",
|
||||
"php-parser": "^3.2.5",
|
||||
"pinia": "^3.0.4",
|
||||
"pinia-plugin-persistedstate": "^4.7.1",
|
||||
"prettier": "^3.7.2",
|
||||
"sass": "^1.94.2",
|
||||
"vue": "^3.5.25",
|
||||
"vue-i18n": "^11.2.2",
|
||||
"prettier": "^3.7.4",
|
||||
"sass": "^1.97.1",
|
||||
"vue": "^3.5.26",
|
||||
"vue-i18n": "^11.2.7",
|
||||
"vue-pick-colors": "^1.8.0",
|
||||
"vue-router": "^4.6.3"
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@lezer/generator": "^1.8.0",
|
||||
"@types/node": "^24.10.1",
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@wailsio/runtime": "latest",
|
||||
"@types/node": "^25.0.3",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@wailsio/runtime": "^3.0.0-alpha.77",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-vue": "^10.6.2",
|
||||
"globals": "^16.5.0",
|
||||
"happy-dom": "^20.0.11",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"typescript-eslint": "^8.50.1",
|
||||
"unplugin-vue-components": "^30.0.0",
|
||||
"vite": "npm:rolldown-vite@latest",
|
||||
"vite-plugin-node-polyfills": "^0.24.0",
|
||||
"vitepress": "^2.0.0-alpha.12",
|
||||
"vitest": "^4.0.14",
|
||||
"vitest": "^4.0.16",
|
||||
"vue-eslint-parser": "^10.2.0",
|
||||
"vue-tsc": "^3.1.5"
|
||||
"vue-tsc": "^3.2.1"
|
||||
},
|
||||
"overrides": {
|
||||
"vite": "npm:rolldown-vite@latest"
|
||||
|
||||
@@ -19,13 +19,13 @@ onBeforeMount(async () => {
|
||||
// 并行初始化配置、系统信息和快捷键配置
|
||||
await Promise.all([
|
||||
configStore.initConfig(),
|
||||
systemStore.initializeSystemInfo(),
|
||||
systemStore.initSystemInfo(),
|
||||
keybindingStore.loadKeyBindings(),
|
||||
]);
|
||||
|
||||
// 初始化语言和主题
|
||||
await configStore.initializeLanguage();
|
||||
await themeStore.initializeTheme();
|
||||
await configStore.initLanguage();
|
||||
await themeStore.initTheme();
|
||||
await translationStore.loadTranslators();
|
||||
|
||||
// 启动时检查更新
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
AppConfig,
|
||||
AuthMethod,
|
||||
KeyBindingType,
|
||||
LanguageType,
|
||||
SystemThemeType,
|
||||
TabType,
|
||||
@@ -31,6 +32,7 @@ export const CONFIG_KEY_MAP = {
|
||||
enableTabIndent: 'editing.enableTabIndent',
|
||||
tabSize: 'editing.tabSize',
|
||||
tabType: 'editing.tabType',
|
||||
keymapMode: 'editing.keymapMode',
|
||||
autoSaveDelay: 'editing.autoSaveDelay',
|
||||
// appearance
|
||||
language: 'appearance.language',
|
||||
@@ -95,11 +97,12 @@ export const DEFAULT_CONFIG: AppConfig = {
|
||||
enableTabIndent: true,
|
||||
tabSize: CONFIG_LIMITS.tabSize.default,
|
||||
tabType: CONFIG_LIMITS.tabType.default,
|
||||
keymapMode: KeyBindingType.Standard,
|
||||
autoSaveDelay: 5000
|
||||
},
|
||||
appearance: {
|
||||
language: LanguageType.LangZhCN,
|
||||
systemTheme: SystemThemeType.SystemThemeAuto,
|
||||
systemTheme: SystemThemeType.SystemThemeDark,
|
||||
currentTheme: 'default-dark'
|
||||
},
|
||||
updates: {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* 翻译图标SVG
|
||||
*/
|
||||
export const TRANSLATION_ICON_SVG = `
|
||||
<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
|
||||
<path d="M599.68 485.056h-8l30.592 164.672c20.352-7.04 38.72-17.344 54.912-31.104a271.36 271.36 0 0 1-40.704-64.64l32.256-4.032c8.896 17.664 19.072 33.28 30.592 46.72 23.872-27.968 42.24-65.152 55.04-111.744l-154.688 0.128z m121.92 133.76c18.368 15.36 39.36 26.56 62.848 33.472l14.784 4.416-8.64 30.336-14.72-4.352a205.696 205.696 0 0 1-76.48-41.728c-20.672 17.92-44.928 31.552-71.232 40.064l20.736 110.912H519.424l-9.984 72.512h385.152c18.112 0 32.704-14.144 32.704-31.616V295.424a32.128 32.128 0 0 0-32.704-31.552H550.528l35.2 189.696h79.424v-31.552h61.44v31.552h102.4v31.616h-42.688c-14.272 55.488-35.712 100.096-64.64 133.568zM479.36 791.68H193.472c-36.224 0-65.472-28.288-65.472-63.168V191.168C128 156.16 157.312 128 193.472 128h327.68l20.544 104.32h352.832c36.224 0 65.472 28.224 65.472 63.104v537.408c0 34.944-29.312 63.168-65.472 63.168H468.608l10.688-104.32zM337.472 548.352v-33.28H272.768v-48.896h60.16V433.28h-60.16v-41.728h64.704v-32.896h-102.4v189.632h102.4z m158.272 0V453.76c0-17.216-4.032-30.272-12.16-39.488-8.192-9.152-20.288-13.696-36.032-13.696a55.04 55.04 0 0 0-24.768 5.376 39.04 39.04 0 0 0-17.088 15.936h-1.984l-5.056-18.56h-28.352V548.48h37.12V480c0-17.088 2.304-29.376 6.912-36.736 4.608-7.424 12.16-11.072 22.528-11.072 7.616 0 13.248 2.56 16.64 7.872 3.52 5.248 5.312 13.056 5.312 23.488v84.736h36.928z" fill="currentColor"></path>
|
||||
</svg>`;
|
||||
65
frontend/src/common/utils/formatter.ts
Normal file
65
frontend/src/common/utils/formatter.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Formatter utility functions
|
||||
*/
|
||||
|
||||
export interface DateTimeFormatOptions {
|
||||
locale?: string;
|
||||
includeTime?: boolean;
|
||||
hour12?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format date time string to localized format
|
||||
* @param dateString - ISO date string or null
|
||||
* @param options - Formatting options
|
||||
* @returns Formatted date string or error message
|
||||
*/
|
||||
export const formatDateTime = (
|
||||
dateString: string | null,
|
||||
options: DateTimeFormatOptions = {}
|
||||
): string => {
|
||||
const {
|
||||
locale = 'en-US',
|
||||
includeTime = true,
|
||||
hour12 = false
|
||||
} = options;
|
||||
|
||||
if (!dateString) {
|
||||
return 'Unknown time';
|
||||
}
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
|
||||
if (isNaN(date.getTime())) {
|
||||
return 'Invalid date';
|
||||
}
|
||||
|
||||
const formatOptions: Intl.DateTimeFormatOptions = {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
};
|
||||
|
||||
if (includeTime) {
|
||||
formatOptions.hour = '2-digit';
|
||||
formatOptions.minute = '2-digit';
|
||||
formatOptions.hour12 = hour12;
|
||||
}
|
||||
|
||||
return date.toLocaleString(locale, formatOptions);
|
||||
} catch {
|
||||
return 'Time error';
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Truncate string with ellipsis
|
||||
* @param str - String to truncate
|
||||
* @param maxLength - Maximum length before truncation
|
||||
* @returns Truncated string with ellipsis if needed
|
||||
*/
|
||||
export const truncateString = (str: string, maxLength: number): string => {
|
||||
if (!str) return '';
|
||||
return str.length > maxLength ? str.substring(0, maxLength) + '...' : str;
|
||||
};
|
||||
42
frontend/src/common/utils/validation.ts
Normal file
42
frontend/src/common/utils/validation.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Validation utility functions
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validate document title
|
||||
* @param title - The title to validate
|
||||
* @param maxLength - Maximum allowed length (default: 50)
|
||||
* @returns Error message if invalid, null if valid
|
||||
*/
|
||||
export const validateDocumentTitle = (title: string, maxLength: number = 50): string | null => {
|
||||
const trimmed = title.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
return 'Document name cannot be empty';
|
||||
}
|
||||
|
||||
if (trimmed.length > maxLength) {
|
||||
return `Document name cannot exceed ${maxLength} characters`;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a string is empty or whitespace only
|
||||
* @param value - The string to check
|
||||
* @returns true if empty or whitespace only
|
||||
*/
|
||||
export const isEmpty = (value: string | null | undefined): boolean => {
|
||||
return !value || value.trim().length === 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a string exceeds max length
|
||||
* @param value - The string to check
|
||||
* @param maxLength - Maximum allowed length
|
||||
* @returns true if exceeds max length
|
||||
*/
|
||||
export const exceedsMaxLength = (value: string, maxLength: number): boolean => {
|
||||
return value.trim().length > maxLength;
|
||||
};
|
||||
@@ -142,7 +142,7 @@ onBeforeUnmount(() => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: var(--voidraft-font-mono),serif;
|
||||
font-family: Menlo, monospace,serif;
|
||||
}
|
||||
|
||||
.loading-word {
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
<template>
|
||||
<div
|
||||
v-if="visible && canClose"
|
||||
class="tab-context-menu"
|
||||
:style="{
|
||||
left: position.x + 'px',
|
||||
top: position.y + 'px'
|
||||
}"
|
||||
@click.stop
|
||||
v-if="visible && canClose"
|
||||
v-click-outside="handleClose"
|
||||
class="tab-context-menu"
|
||||
:style="{
|
||||
left: position.x + 'px',
|
||||
top: position.y + 'px'
|
||||
}"
|
||||
@click.stop
|
||||
>
|
||||
<div v-if="canClose" class="menu-item" @click="handleMenuClick('close')">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M18 6L6 18M6 6l12 12"/>
|
||||
</svg>
|
||||
<span class="menu-text">{{ t('tabs.contextMenu.closeTab') }}</span>
|
||||
</div>
|
||||
<div v-if="hasOtherTabs" class="menu-item" @click="handleMenuClick('closeOthers')">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
|
||||
<path d="M9 9l6 6M15 9l-6 6"/>
|
||||
</svg>
|
||||
<span class="menu-text">{{ t('tabs.contextMenu.closeOthers') }}</span>
|
||||
</div>
|
||||
<div v-if="hasTabsToLeft" class="menu-item" @click="handleMenuClick('closeLeft')">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M15 18l-6-6 6-6"/>
|
||||
<path d="M9 18l-6-6 6-6"/>
|
||||
</svg>
|
||||
<span class="menu-text">{{ t('tabs.contextMenu.closeLeft') }}</span>
|
||||
</div>
|
||||
<div v-if="hasTabsToRight" class="menu-item" @click="handleMenuClick('closeRight')">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg class="menu-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M9 18l6-6-6-6"/>
|
||||
<path d="M15 18l6-6-6-6"/>
|
||||
</svg>
|
||||
@@ -39,9 +44,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useTabStore } from '@/stores/tabStore';
|
||||
import {computed, onMounted, onUnmounted} from 'vue';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
@@ -54,7 +59,7 @@ const emit = defineEmits<{
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const {t} = useI18n();
|
||||
const tabStore = useTabStore();
|
||||
|
||||
// 计算属性
|
||||
@@ -79,6 +84,9 @@ const hasTabsToLeft = computed(() => {
|
||||
return index > 0;
|
||||
});
|
||||
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
// 处理菜单项点击
|
||||
const handleMenuClick = (action: string) => {
|
||||
if (!props.targetDocumentId) return;
|
||||
@@ -98,33 +106,8 @@ const handleMenuClick = (action: string) => {
|
||||
break;
|
||||
}
|
||||
|
||||
emit('close');
|
||||
handleClose();
|
||||
};
|
||||
|
||||
// 处理外部点击
|
||||
const handleClickOutside = (_event: MouseEvent) => {
|
||||
if (props.visible) {
|
||||
emit('close');
|
||||
}
|
||||
};
|
||||
|
||||
// 处理ESC键
|
||||
const handleEscapeKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && props.visible) {
|
||||
emit('close');
|
||||
}
|
||||
};
|
||||
|
||||
// 生命周期
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
document.addEventListener('keydown', handleEscapeKey);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
document.removeEventListener('keydown', handleEscapeKey);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
<template>
|
||||
<div class="linux-titlebar" style="--wails-draggable:drag" @contextmenu.prevent>
|
||||
<div class="titlebar-content" @dblclick="toggleMaximize" @contextmenu.prevent>
|
||||
<div class="titlebar-content" @dblclick="handleToggleMaximize" @contextmenu.prevent>
|
||||
<div class="titlebar-icon">
|
||||
<img src="/appicon.png" alt="voidraft"/>
|
||||
</div>
|
||||
<div v-if="!tabStore.isTabsEnabled && !isInSettings" class="titlebar-title" :title="fullTitleText">{{ titleText }}</div>
|
||||
<div v-if="!tabStore.isTabsEnabled && !isInSettings" class="titlebar-title" :title="fullTitleText">
|
||||
{{ titleText }}
|
||||
</div>
|
||||
<!-- 标签页容器区域 -->
|
||||
<div class="titlebar-tabs" v-if="tabStore.isTabsEnabled && !isInSettings" style="--wails-draggable:drag">
|
||||
<TabContainer />
|
||||
<TabContainer/>
|
||||
</div>
|
||||
<!-- 设置页面标题 -->
|
||||
<div v-if="isInSettings" class="titlebar-title" :title="fullTitleText">{{ titleText }}</div>
|
||||
@@ -26,7 +28,7 @@
|
||||
|
||||
<button
|
||||
class="titlebar-button maximize-button"
|
||||
@click="toggleMaximize"
|
||||
@click="handleToggleMaximize"
|
||||
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" v-if="!isMaximized">
|
||||
@@ -55,81 +57,43 @@
|
||||
import {computed, onMounted, ref} from 'vue';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useRoute} from 'vue-router';
|
||||
import * as runtime from '@wailsio/runtime';
|
||||
import {useDocumentStore} from '@/stores/documentStore';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
import TabContainer from '@/components/tabs/TabContainer.vue';
|
||||
import {useTabStore} from "@/stores/tabStore";
|
||||
import {
|
||||
minimizeWindow,
|
||||
toggleMaximize,
|
||||
closeWindow,
|
||||
getMaximizedState,
|
||||
generateTitleText,
|
||||
generateFullTitleText
|
||||
} from './index';
|
||||
|
||||
const tabStore = useTabStore();
|
||||
const {t} = useI18n();
|
||||
const route = useRoute();
|
||||
const isMaximized = ref(false);
|
||||
const tabStore = useTabStore();
|
||||
const documentStore = useDocumentStore();
|
||||
|
||||
// 判断是否在设置页面
|
||||
const isMaximized = ref(false);
|
||||
const isInSettings = computed(() => route.path.startsWith('/settings'));
|
||||
|
||||
// 计算标题文本
|
||||
const titleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
if (currentDoc) {
|
||||
// 限制文档标题长度,避免标题栏换行
|
||||
const maxTitleLength = 30;
|
||||
const truncatedTitle = currentDoc.title.length > maxTitleLength
|
||||
? currentDoc.title.substring(0, maxTitleLength) + '...'
|
||||
: currentDoc.title;
|
||||
return `voidraft - ${truncatedTitle}`;
|
||||
}
|
||||
return 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
// 计算完整标题文本(用于tooltip)
|
||||
const fullTitleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
return currentDoc ? `voidraft - ${currentDoc.title}` : 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateFullTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
const minimizeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Minimise();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMaximize = async () => {
|
||||
try {
|
||||
await runtime.Window.ToggleMaximise();
|
||||
await checkMaximizedState();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const closeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Close();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const checkMaximizedState = async () => {
|
||||
try {
|
||||
isMaximized.value = await runtime.Window.IsMaximised();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
const handleToggleMaximize = async () => {
|
||||
await toggleMaximize();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await checkMaximizedState();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -160,7 +124,7 @@ onMounted(async () => {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: default;
|
||||
min-width: 0; /* 允许内容收缩 */
|
||||
min-width: 0;
|
||||
|
||||
-webkit-context-menu: none;
|
||||
-moz-context-menu: none;
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
<div class="macos-titlebar" style="--wails-draggable:drag" @contextmenu.prevent>
|
||||
<div class="titlebar-controls" style="--wails-draggable:no-drag" @contextmenu.prevent>
|
||||
<button
|
||||
class="titlebar-button close-button"
|
||||
@click="closeWindow"
|
||||
:title="t('titlebar.close')"
|
||||
class="titlebar-button close-button"
|
||||
@click="closeWindow"
|
||||
:title="t('titlebar.close')"
|
||||
>
|
||||
<div class="button-icon">
|
||||
<svg width="6" height="6" viewBox="0 0 6 6" v-show="showControlIcons">
|
||||
@@ -14,9 +14,9 @@
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="titlebar-button minimize-button"
|
||||
@click="minimizeWindow"
|
||||
:title="t('titlebar.minimize')"
|
||||
class="titlebar-button minimize-button"
|
||||
@click="minimizeWindow"
|
||||
:title="t('titlebar.minimize')"
|
||||
>
|
||||
<div class="button-icon">
|
||||
<svg width="8" height="1" viewBox="0 0 8 1" v-show="showControlIcons">
|
||||
@@ -26,9 +26,9 @@
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="titlebar-button maximize-button"
|
||||
@click="toggleMaximize"
|
||||
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
|
||||
class="titlebar-button maximize-button"
|
||||
@click="handleToggleMaximize"
|
||||
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
|
||||
>
|
||||
<div class="button-icon">
|
||||
<svg width="6" height="6" viewBox="0 0 6 6" v-show="showControlIcons && !isMaximized">
|
||||
@@ -45,95 +45,58 @@
|
||||
|
||||
<!-- 标签页容器区域 -->
|
||||
<div class="titlebar-tabs" v-if="tabStore.isTabsEnabled && !isInSettings" style="--wails-draggable:drag">
|
||||
<TabContainer />
|
||||
<TabContainer/>
|
||||
</div>
|
||||
|
||||
<div class="titlebar-content" @dblclick="toggleMaximize" @contextmenu.prevent v-if="!tabStore.isTabsEnabled || isInSettings">
|
||||
<div class="titlebar-content" @dblclick="handleToggleMaximize" @contextmenu.prevent
|
||||
v-if="!tabStore.isTabsEnabled || isInSettings">
|
||||
<div class="titlebar-title" :title="fullTitleText">{{ titleText }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute } from 'vue-router';
|
||||
import * as runtime from '@wailsio/runtime';
|
||||
import { useDocumentStore } from '@/stores/documentStore';
|
||||
import {computed, onMounted, ref} from 'vue';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useRoute} from 'vue-router';
|
||||
import {useDocumentStore} from '@/stores/documentStore';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
import TabContainer from '@/components/tabs/TabContainer.vue';
|
||||
import { useTabStore } from "@/stores/tabStore";
|
||||
import {
|
||||
minimizeWindow,
|
||||
toggleMaximize,
|
||||
closeWindow,
|
||||
getMaximizedState,
|
||||
generateTitleText,
|
||||
generateFullTitleText
|
||||
} from './index';
|
||||
|
||||
const tabStore = useTabStore();
|
||||
const { t } = useI18n();
|
||||
const {t} = useI18n();
|
||||
const route = useRoute();
|
||||
const isMaximized = ref(false);
|
||||
const showControlIcons = ref(false);
|
||||
const tabStore = useTabStore();
|
||||
const documentStore = useDocumentStore();
|
||||
|
||||
// 判断是否在设置页面
|
||||
const isMaximized = ref(false);
|
||||
const showControlIcons = ref(false);
|
||||
const isInSettings = computed(() => route.path.startsWith('/settings'));
|
||||
|
||||
const minimizeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Minimise();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMaximize = async () => {
|
||||
try {
|
||||
await runtime.Window.ToggleMaximise();
|
||||
await checkMaximizedState();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const closeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Close();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const checkMaximizedState = async () => {
|
||||
try {
|
||||
isMaximized.value = await runtime.Window.IsMaximised();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
// 计算标题文本
|
||||
const titleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
if (currentDoc) {
|
||||
// 限制文档标题长度,避免标题栏换行
|
||||
const maxTitleLength = 30;
|
||||
const truncatedTitle = currentDoc.title.length > maxTitleLength
|
||||
? currentDoc.title.substring(0, maxTitleLength) + '...'
|
||||
: currentDoc.title;
|
||||
return `voidraft - ${truncatedTitle}`;
|
||||
}
|
||||
return 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
// 计算完整标题文本(用于tooltip)
|
||||
const fullTitleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
return currentDoc ? `voidraft - ${currentDoc.title}` : 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateFullTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
const handleToggleMaximize = async () => {
|
||||
await toggleMaximize();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await checkMaximizedState();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -261,9 +224,8 @@ onMounted(async () => {
|
||||
margin-left: 8px;
|
||||
margin-right: 8px;
|
||||
min-width: 0;
|
||||
overflow: visible; /* 允许TabContainer内部处理滚动 */
|
||||
overflow: visible;
|
||||
|
||||
/* 确保TabContainer能够正确处理滚动 */
|
||||
:deep(.tab-container) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -285,7 +247,6 @@ onMounted(async () => {
|
||||
}
|
||||
}
|
||||
|
||||
/* 确保底部线条能够正确显示 */
|
||||
:deep(.tab-item) {
|
||||
position: relative;
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
<template>
|
||||
<div class="windows-titlebar" style="--wails-draggable:drag">
|
||||
<div class="titlebar-content" @dblclick="toggleMaximize" @contextmenu.prevent>
|
||||
<div class="titlebar-content" @dblclick="handleToggleMaximize" @contextmenu.prevent>
|
||||
<div class="titlebar-icon">
|
||||
<img src="/appicon.png" alt="voidraft"/>
|
||||
</div>
|
||||
<div v-if="!tabStore.isTabsEnabled && !isInSettings" class="titlebar-title" :title="fullTitleText">{{ titleText }}</div>
|
||||
<div v-if="!tabStore.isTabsEnabled && !isInSettings" class="titlebar-title" :title="fullTitleText">
|
||||
{{ titleText }}
|
||||
</div>
|
||||
<!-- 标签页容器区域 -->
|
||||
<div class="titlebar-tabs" v-if="tabStore.isTabsEnabled && !isInSettings" style="--wails-draggable:drag">
|
||||
<TabContainer />
|
||||
<TabContainer/>
|
||||
</div>
|
||||
<!-- 设置页面标题 -->
|
||||
<div v-if="isInSettings" class="titlebar-title" :title="fullTitleText">{{ titleText }}</div>
|
||||
@@ -24,7 +26,7 @@
|
||||
|
||||
<button
|
||||
class="titlebar-button maximize-button"
|
||||
@click="toggleMaximize"
|
||||
@click="handleToggleMaximize"
|
||||
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
|
||||
>
|
||||
<span class="titlebar-icon" v-html="maximizeIcon"></span>
|
||||
@@ -45,84 +47,44 @@
|
||||
import {computed, onMounted, ref} from 'vue';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useRoute} from 'vue-router';
|
||||
import * as runtime from '@wailsio/runtime';
|
||||
import {useDocumentStore} from '@/stores/documentStore';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
import TabContainer from '@/components/tabs/TabContainer.vue';
|
||||
import {useTabStore} from "@/stores/tabStore";
|
||||
import {
|
||||
minimizeWindow,
|
||||
toggleMaximize,
|
||||
closeWindow,
|
||||
getMaximizedState,
|
||||
generateTitleText,
|
||||
generateFullTitleText
|
||||
} from './index';
|
||||
|
||||
const tabStore = useTabStore();
|
||||
const {t} = useI18n();
|
||||
const route = useRoute();
|
||||
const isMaximized = ref(false);
|
||||
const tabStore = useTabStore();
|
||||
const documentStore = useDocumentStore();
|
||||
|
||||
// 计算属性用于图标,减少重复渲染
|
||||
const isMaximized = ref(false);
|
||||
const maximizeIcon = computed(() => isMaximized.value ? '' : '');
|
||||
|
||||
// 判断是否在设置页面
|
||||
const isInSettings = computed(() => route.path.startsWith('/settings'));
|
||||
|
||||
// 计算标题文本
|
||||
const titleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
if (currentDoc) {
|
||||
// 限制文档标题长度,避免标题栏换行
|
||||
const maxTitleLength = 30;
|
||||
const truncatedTitle = currentDoc.title.length > maxTitleLength
|
||||
? currentDoc.title.substring(0, maxTitleLength) + '...'
|
||||
: currentDoc.title;
|
||||
return `voidraft - ${truncatedTitle}`;
|
||||
}
|
||||
return 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
// 计算完整标题文本(用于tooltip)
|
||||
const fullTitleText = computed(() => {
|
||||
if (isInSettings.value) {
|
||||
return `voidraft - ` + t('settings.title');
|
||||
}
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
return currentDoc ? `voidraft - ${currentDoc.title}` : 'voidraft';
|
||||
if (isInSettings.value) return `voidraft - ${t('settings.title')}`;
|
||||
return generateFullTitleText(documentStore.currentDocument?.title);
|
||||
});
|
||||
|
||||
const minimizeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Minimise();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMaximize = async () => {
|
||||
try {
|
||||
await runtime.Window.ToggleMaximise();
|
||||
await checkMaximizedState();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const closeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Close();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const checkMaximizedState = async () => {
|
||||
try {
|
||||
isMaximized.value = await runtime.Window.IsMaximised();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
const handleToggleMaximize = async () => {
|
||||
await toggleMaximize();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await checkMaximizedState();
|
||||
isMaximized.value = await getMaximizedState();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -152,7 +114,7 @@ onMounted(async () => {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
cursor: default;
|
||||
min-width: 0; /* 允许内容收缩 */
|
||||
min-width: 0;
|
||||
|
||||
-webkit-context-menu: none;
|
||||
-moz-context-menu: none;
|
||||
@@ -178,7 +140,6 @@ onMounted(async () => {
|
||||
overflow: hidden;
|
||||
margin-left: 8px;
|
||||
min-width: 0;
|
||||
//margin-right: 8px;
|
||||
}
|
||||
|
||||
.titlebar-controls {
|
||||
|
||||
60
frontend/src/components/titlebar/index.ts
Normal file
60
frontend/src/components/titlebar/index.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import * as runtime from '@wailsio/runtime';
|
||||
|
||||
/**
|
||||
* Titlebar utility functions
|
||||
*/
|
||||
|
||||
// Window control functions
|
||||
export const minimizeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Minimise();
|
||||
} catch (error) {
|
||||
console.error('Failed to minimize window:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export const toggleMaximize = async () => {
|
||||
try {
|
||||
await runtime.Window.ToggleMaximise();
|
||||
} catch (error) {
|
||||
console.error('Failed to toggle maximize:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export const closeWindow = async () => {
|
||||
try {
|
||||
await runtime.Window.Close();
|
||||
} catch (error) {
|
||||
console.error('Failed to close window:', error);
|
||||
}
|
||||
};
|
||||
|
||||
export const getMaximizedState = async (): Promise<boolean> => {
|
||||
try {
|
||||
return await runtime.Window.IsMaximised();
|
||||
} catch (error) {
|
||||
console.error('Failed to check maximized state:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate title text with optional truncation
|
||||
*/
|
||||
export const generateTitleText = (
|
||||
title: string | undefined,
|
||||
maxLength: number = 30
|
||||
): string => {
|
||||
if (!title) return 'voidraft';
|
||||
const truncated = title.length > maxLength
|
||||
? title.substring(0, maxLength) + '...'
|
||||
: title;
|
||||
return `voidraft - ${truncated}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate full title text (no truncation)
|
||||
*/
|
||||
export const generateFullTitleText = (title: string | undefined): string => {
|
||||
return title ? `voidraft - ${title}` : 'voidraft';
|
||||
};
|
||||
@@ -1,49 +1,63 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { useDocumentStore } from '@/stores/documentStore';
|
||||
import { useTabStore } from '@/stores/tabStore';
|
||||
import { useWindowStore } from '@/stores/windowStore';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { Document } from '@/../bindings/voidraft/internal/models/models';
|
||||
import {computed, nextTick, reactive, ref, watch} from 'vue';
|
||||
import {useDocumentStore} from '@/stores/documentStore';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
import {useWindowStore} from '@/stores/windowStore';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useConfirm} from '@/composables';
|
||||
import {validateDocumentTitle} from '@/common/utils/validation';
|
||||
import {formatDateTime, truncateString} from '@/common/utils/formatter';
|
||||
import type {Document} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
|
||||
// 类型定义
|
||||
interface DocumentItem extends Document {
|
||||
isCreateOption?: boolean;
|
||||
}
|
||||
|
||||
const documentStore = useDocumentStore();
|
||||
const tabStore = useTabStore();
|
||||
const windowStore = useWindowStore();
|
||||
const { t } = useI18n();
|
||||
const {t} = useI18n();
|
||||
|
||||
// DOM 引用
|
||||
const inputRef = ref<HTMLInputElement>();
|
||||
const editInputRef = ref<HTMLInputElement>();
|
||||
|
||||
// 组件状态
|
||||
const inputValue = ref('');
|
||||
const inputRef = ref<HTMLInputElement>();
|
||||
const editingId = ref<number | null>(null);
|
||||
const editingTitle = ref('');
|
||||
const editInputRef = ref<HTMLInputElement>();
|
||||
const deleteConfirmId = ref<number | null>(null);
|
||||
const state = reactive({
|
||||
isLoaded: false,
|
||||
searchQuery: '',
|
||||
editing: {
|
||||
id: null as number | null,
|
||||
title: ''
|
||||
}
|
||||
});
|
||||
|
||||
// 常量
|
||||
const MAX_TITLE_LENGTH = 50;
|
||||
const DELETE_CONFIRM_TIMEOUT = 3000;
|
||||
|
||||
// 计算属性
|
||||
const currentDocName = computed(() => {
|
||||
if (!documentStore.currentDocument) return t('toolbar.selectDocument');
|
||||
const title = documentStore.currentDocument.title;
|
||||
return title.length > 12 ? title.substring(0, 12) + '...' : title;
|
||||
return truncateString(documentStore.currentDocument.title || '', 12);
|
||||
});
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
const filteredItems = computed<DocumentItem[]>(() => {
|
||||
const docs = documentStore.documentList;
|
||||
const query = inputValue.value.trim();
|
||||
const query = state.searchQuery.trim();
|
||||
|
||||
if (!query) return docs;
|
||||
|
||||
const filtered = docs.filter(doc =>
|
||||
doc.title.toLowerCase().includes(query.toLowerCase())
|
||||
(doc.title || '').toLowerCase().includes(query.toLowerCase())
|
||||
);
|
||||
|
||||
// 如果输入的不是已存在文档的完整标题,添加创建选项
|
||||
const exactMatch = docs.some(doc => doc.title.toLowerCase() === query.toLowerCase());
|
||||
const exactMatch = docs.some(doc => (doc.title || '').toLowerCase() === query.toLowerCase());
|
||||
if (!exactMatch && query.length > 0) {
|
||||
return [
|
||||
{ id: -1, title: t('toolbar.createDocument') + ` "${query}"`, isCreateOption: true } as any,
|
||||
{id: -1, title: t('toolbar.createDocument') + ` "${query}"`, isCreateOption: true} as DocumentItem,
|
||||
...filtered
|
||||
];
|
||||
}
|
||||
@@ -51,53 +65,32 @@ const filteredItems = computed(() => {
|
||||
return filtered;
|
||||
});
|
||||
|
||||
// 工具函数
|
||||
const validateTitle = (title: string): string | null => {
|
||||
if (!title.trim()) return t('toolbar.documentNameRequired');
|
||||
if (title.trim().length > MAX_TITLE_LENGTH) {
|
||||
return t('toolbar.documentNameTooLong', { max: MAX_TITLE_LENGTH });
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const formatTime = (dateString: string | null) => {
|
||||
if (!dateString) return t('toolbar.unknownTime');
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
if (isNaN(date.getTime())) return t('toolbar.invalidDate');
|
||||
|
||||
const locale = t('locale') === 'zh-CN' ? 'zh-CN' : 'en-US';
|
||||
return date.toLocaleString(locale, {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
});
|
||||
} catch {
|
||||
return t('toolbar.timeError');
|
||||
}
|
||||
};
|
||||
|
||||
// 核心操作
|
||||
const openMenu = async () => {
|
||||
documentStore.openDocumentSelector();
|
||||
await documentStore.getDocumentMetaList();
|
||||
documentStore.openDocumentSelector();
|
||||
state.isLoaded = true;
|
||||
await nextTick();
|
||||
inputRef.value?.focus();
|
||||
};
|
||||
|
||||
// 删除确认
|
||||
const {isConfirming: isDeleting, startConfirm: startDeleteConfirm, reset: resetDeleteConfirm} = useConfirm({
|
||||
timeout: DELETE_CONFIRM_TIMEOUT
|
||||
});
|
||||
|
||||
const closeMenu = () => {
|
||||
state.isLoaded = false;
|
||||
documentStore.closeDocumentSelector();
|
||||
inputValue.value = '';
|
||||
editingId.value = null;
|
||||
editingTitle.value = '';
|
||||
deleteConfirmId.value = null;
|
||||
state.searchQuery = '';
|
||||
state.editing.id = null;
|
||||
state.editing.title = '';
|
||||
resetDeleteConfirm();
|
||||
};
|
||||
|
||||
const selectDoc = async (doc: Document) => {
|
||||
if (doc.id === undefined) return;
|
||||
|
||||
// 如果选择的就是当前文档,直接关闭菜单
|
||||
if (documentStore.currentDocument?.id === doc.id) {
|
||||
closeMenu();
|
||||
@@ -121,7 +114,7 @@ const selectDoc = async (doc: Document) => {
|
||||
|
||||
const createDoc = async (title: string) => {
|
||||
const trimmedTitle = title.trim();
|
||||
const error = validateTitle(trimmedTitle);
|
||||
const error = validateDocumentTitle(trimmedTitle, MAX_TITLE_LENGTH);
|
||||
if (error) return;
|
||||
|
||||
try {
|
||||
@@ -132,20 +125,28 @@ const createDoc = async (title: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const selectItem = async (item: any) => {
|
||||
const selectDocItem = async (item: any) => {
|
||||
if (item.isCreateOption) {
|
||||
await createDoc(inputValue.value.trim());
|
||||
await createDoc(state.searchQuery.trim());
|
||||
} else {
|
||||
await selectDoc(item);
|
||||
}
|
||||
};
|
||||
|
||||
// 搜索框回车处理
|
||||
const handleSearchEnter = () => {
|
||||
const query = state.searchQuery.trim();
|
||||
if (query && filteredItems.value.length > 0) {
|
||||
selectDocItem(filteredItems.value[0]);
|
||||
}
|
||||
};
|
||||
|
||||
// 编辑操作
|
||||
const startRename = (doc: Document, event: Event) => {
|
||||
const renameDoc = (doc: Document, event: Event) => {
|
||||
event.stopPropagation();
|
||||
editingId.value = doc.id;
|
||||
editingTitle.value = doc.title;
|
||||
deleteConfirmId.value = null;
|
||||
state.editing.id = doc.id ?? null;
|
||||
state.editing.title = doc.title || '';
|
||||
resetDeleteConfirm();
|
||||
nextTick(() => {
|
||||
editInputRef.value?.focus();
|
||||
editInputRef.value?.select();
|
||||
@@ -153,35 +154,41 @@ const startRename = (doc: Document, event: Event) => {
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editingId.value || !editingTitle.value.trim()) {
|
||||
editingId.value = null;
|
||||
editingTitle.value = '';
|
||||
if (!state.editing.id || !state.editing.title.trim()) {
|
||||
state.editing.id = null;
|
||||
state.editing.title = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmedTitle = editingTitle.value.trim();
|
||||
const error = validateTitle(trimmedTitle);
|
||||
const trimmedTitle = state.editing.title.trim();
|
||||
const error = validateDocumentTitle(trimmedTitle, MAX_TITLE_LENGTH);
|
||||
if (error) return;
|
||||
|
||||
try {
|
||||
await documentStore.updateDocumentMetadata(editingId.value, trimmedTitle);
|
||||
await documentStore.updateDocumentMetadata(state.editing.id, trimmedTitle);
|
||||
await documentStore.getDocumentMetaList();
|
||||
|
||||
// 如果tabs功能开启且该文档有标签页,更新标签页标题
|
||||
if (tabStore.isTabsEnabled && tabStore.hasTab(editingId.value)) {
|
||||
tabStore.updateTabTitle(editingId.value, trimmedTitle);
|
||||
if (tabStore.isTabsEnabled && tabStore.hasTab(state.editing.id)) {
|
||||
tabStore.updateTabTitle(state.editing.id, trimmedTitle);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to update document:', error);
|
||||
} finally {
|
||||
editingId.value = null;
|
||||
editingTitle.value = '';
|
||||
state.editing.id = null;
|
||||
state.editing.title = '';
|
||||
}
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
state.editing.id = null;
|
||||
state.editing.title = '';
|
||||
};
|
||||
|
||||
// 其他操作
|
||||
const openInNewWindow = async (doc: Document, event: Event) => {
|
||||
event.stopPropagation();
|
||||
if (doc.id === undefined) return;
|
||||
try {
|
||||
await documentStore.openDocumentInNewWindow(doc.id);
|
||||
} catch (error) {
|
||||
@@ -191,13 +198,14 @@ const openInNewWindow = async (doc: Document, event: Event) => {
|
||||
|
||||
const handleDelete = async (doc: Document, event: Event) => {
|
||||
event.stopPropagation();
|
||||
if (doc.id === undefined) return;
|
||||
|
||||
if (deleteConfirmId.value === doc.id) {
|
||||
if (isDeleting(doc.id)) {
|
||||
// 确认删除前检查文档是否在其他窗口打开
|
||||
const hasOpen = await windowStore.isDocumentWindowOpen(doc.id);
|
||||
if (hasOpen) {
|
||||
documentStore.setError(doc.id, t('toolbar.alreadyOpenInNewWindow'));
|
||||
deleteConfirmId.value = null;
|
||||
resetDeleteConfirm();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -210,228 +218,181 @@ const handleDelete = async (doc: Document, event: Event) => {
|
||||
if (firstDoc) await selectDoc(firstDoc);
|
||||
}
|
||||
}
|
||||
deleteConfirmId.value = null;
|
||||
resetDeleteConfirm();
|
||||
} else {
|
||||
// 进入确认状态
|
||||
deleteConfirmId.value = doc.id;
|
||||
editingId.value = null;
|
||||
|
||||
// 3秒后自动取消确认状态
|
||||
setTimeout(() => {
|
||||
if (deleteConfirmId.value === doc.id) {
|
||||
deleteConfirmId.value = null;
|
||||
}
|
||||
}, 3000);
|
||||
startDeleteConfirm(doc.id);
|
||||
state.editing.id = null;
|
||||
}
|
||||
};
|
||||
|
||||
// 键盘事件处理
|
||||
const createKeyHandler = (handlers: Record<string, () => void>) => (event: KeyboardEvent) => {
|
||||
const handler = handlers[event.key];
|
||||
if (handler) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handler();
|
||||
}
|
||||
};
|
||||
|
||||
const handleGlobalKeydown = createKeyHandler({
|
||||
Escape: () => {
|
||||
if (editingId.value) {
|
||||
editingId.value = null;
|
||||
editingTitle.value = '';
|
||||
} else if (deleteConfirmId.value) {
|
||||
deleteConfirmId.value = null;
|
||||
} else {
|
||||
closeMenu();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handleInputKeydown = createKeyHandler({
|
||||
Enter: () => {
|
||||
const query = inputValue.value.trim();
|
||||
if (query && filteredItems.value.length > 0) {
|
||||
selectItem(filteredItems.value[0]);
|
||||
}
|
||||
},
|
||||
Escape: closeMenu
|
||||
});
|
||||
|
||||
const handleEditKeydown = createKeyHandler({
|
||||
Enter: saveEdit,
|
||||
Escape: () => {
|
||||
editingId.value = null;
|
||||
editingTitle.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
// 点击外部关闭
|
||||
const handleClickOutside = (event: Event) => {
|
||||
const target = event.target as HTMLElement;
|
||||
if (!target.closest('.document-selector')) {
|
||||
// 切换菜单
|
||||
const toggleMenu = () => {
|
||||
if (documentStore.showDocumentSelector) {
|
||||
closeMenu();
|
||||
} else {
|
||||
openMenu();
|
||||
}
|
||||
};
|
||||
|
||||
// 生命周期
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
document.addEventListener('keydown', handleGlobalKeydown);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
document.removeEventListener('keydown', handleGlobalKeydown);
|
||||
});
|
||||
|
||||
// 监听菜单状态变化
|
||||
watch(() => documentStore.showDocumentSelector, (isOpen) => {
|
||||
if (isOpen) {
|
||||
if (isOpen && !state.isLoaded) {
|
||||
openMenu();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="document-selector">
|
||||
<div class="document-selector" v-click-outside="closeMenu">
|
||||
<!-- 选择器按钮 -->
|
||||
<button class="doc-btn" @click="documentStore.toggleDocumentSelector">
|
||||
<button class="doc-btn" @click="toggleMenu">
|
||||
<span class="doc-icon">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>
|
||||
<polyline points="14,2 14,8 20,8"></polyline>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="doc-name">{{ currentDocName }}</span>
|
||||
<span class="arrow" :class="{ open: documentStore.showDocumentSelector }">▲</span>
|
||||
<span class="arrow" :class="{ open: state.isLoaded }">▲</span>
|
||||
</button>
|
||||
|
||||
<!-- 菜单 -->
|
||||
<div v-if="documentStore.showDocumentSelector" class="doc-menu">
|
||||
<!-- 输入框 -->
|
||||
<div class="input-box">
|
||||
<input
|
||||
ref="inputRef"
|
||||
v-model="inputValue"
|
||||
type="text"
|
||||
class="main-input"
|
||||
:placeholder="t('toolbar.searchOrCreateDocument')"
|
||||
:maxlength="MAX_TITLE_LENGTH"
|
||||
@keydown="handleInputKeydown"
|
||||
/>
|
||||
<svg class="input-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8"></circle>
|
||||
<path d="m21 21-4.35-4.35"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<Transition name="slide-up">
|
||||
<div v-if="state.isLoaded" class="doc-menu">
|
||||
<!-- 输入框 -->
|
||||
<div class="input-box">
|
||||
<input
|
||||
ref="inputRef"
|
||||
v-model="state.searchQuery"
|
||||
type="text"
|
||||
class="main-input"
|
||||
:placeholder="t('toolbar.searchOrCreateDocument')"
|
||||
:maxlength="MAX_TITLE_LENGTH"
|
||||
@keydown.enter="handleSearchEnter"
|
||||
@keydown.esc="closeMenu"
|
||||
/>
|
||||
<svg class="input-icon" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8"></circle>
|
||||
<path d="m21 21-4.35-4.35"></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- 项目列表 -->
|
||||
<div class="item-list">
|
||||
<div
|
||||
v-for="item in filteredItems"
|
||||
:key="item.id"
|
||||
class="list-item"
|
||||
:class="{
|
||||
'active': !item.isCreateOption && documentStore.currentDocument?.id === item.id,
|
||||
'create-item': item.isCreateOption
|
||||
}"
|
||||
@click="selectItem(item)"
|
||||
>
|
||||
<!-- 创建选项 -->
|
||||
<div v-if="item.isCreateOption" class="create-option">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M5 12h14"></path>
|
||||
<path d="M12 5v14"></path>
|
||||
</svg>
|
||||
<span>{{ item.title }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 文档项 -->
|
||||
<div v-else class="doc-item-content">
|
||||
<!-- 普通显示 -->
|
||||
<div v-if="editingId !== item.id" class="doc-info">
|
||||
<div class="doc-title">{{ item.title }}</div>
|
||||
<!-- 根据状态显示错误信息或时间 -->
|
||||
<div v-if="documentStore.selectorError?.docId === item.id" class="doc-error">
|
||||
{{ documentStore.selectorError?.message }}
|
||||
</div>
|
||||
<div v-else class="doc-date">{{ formatTime(item.updatedAt) }}</div>
|
||||
<!-- 项目列表 -->
|
||||
<div class="item-list">
|
||||
<div
|
||||
v-for="item in filteredItems"
|
||||
:key="item.id"
|
||||
class="list-item"
|
||||
:class="{
|
||||
'active': !item.isCreateOption && documentStore.currentDocument?.id === item.id,
|
||||
'create-item': item.isCreateOption
|
||||
}"
|
||||
@click="selectDocItem(item)"
|
||||
>
|
||||
<!-- 创建选项 -->
|
||||
<div v-if="item.isCreateOption" class="create-option">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M5 12h14"></path>
|
||||
<path d="M12 5v14"></path>
|
||||
</svg>
|
||||
<span>{{ item.title }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 编辑状态 -->
|
||||
<div v-else class="doc-edit">
|
||||
<input
|
||||
:ref="el => editInputRef = el as HTMLInputElement"
|
||||
v-model="editingTitle"
|
||||
type="text"
|
||||
class="edit-input"
|
||||
:maxlength="MAX_TITLE_LENGTH"
|
||||
@keydown="handleEditKeydown"
|
||||
@blur="saveEdit"
|
||||
@click.stop
|
||||
/>
|
||||
</div>
|
||||
<!-- 文档项 -->
|
||||
<div v-else class="doc-item-content">
|
||||
<!-- 普通显示 -->
|
||||
<div v-if="state.editing.id !== item.id" class="doc-info">
|
||||
<div class="doc-title">{{ item.title }}</div>
|
||||
<!-- 根据状态显示错误信息或时间 -->
|
||||
<div v-if="documentStore.selectorError?.docId === item.id" class="doc-error">
|
||||
{{ documentStore.selectorError?.message }}
|
||||
</div>
|
||||
<div v-else class="doc-date">{{ formatDateTime(item.updated_at) }}</div>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div v-if="editingId !== item.id" class="doc-actions">
|
||||
<!-- 只有非当前文档才显示在新窗口打开按钮 -->
|
||||
<button
|
||||
v-if="documentStore.currentDocument?.id !== item.id"
|
||||
class="action-btn"
|
||||
@click="openInNewWindow(item, $event)"
|
||||
:title="t('toolbar.openInNewWindow')"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
|
||||
fill="currentColor">
|
||||
<path
|
||||
d="M172.8 1017.6c-89.6 0-166.4-70.4-166.4-166.4V441.6c0-89.6 70.4-166.4 166.4-166.4h416c89.6 0 166.4 70.4 166.4 166.4v416c0 89.6-70.4 166.4-166.4 166.4l-416-6.4z m0-659.2c-51.2 0-89.6 38.4-89.6 89.6v416c0 51.2 38.4 89.6 89.6 89.6h416c51.2 0 89.6-38.4 89.6-89.6V441.6c0-51.2-38.4-89.6-89.6-89.6H172.8z"></path>
|
||||
<path
|
||||
d="M851.2 19.2H435.2C339.2 19.2 268.8 96 268.8 185.6v25.6h70.4v-25.6c0-51.2 38.4-89.6 89.6-89.6h409.6c51.2 0 89.6 38.4 89.6 89.6v409.6c0 51.2-38.4 89.6-89.6 89.6h-38.4V768h51.2c96 0 166.4-76.8 166.4-166.4V185.6c0-96-76.8-166.4-166.4-166.4z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="action-btn" @click="startRename(item, $event)" :title="t('toolbar.rename')">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
v-if="documentStore.documentList.length > 1 && item.id !== 1"
|
||||
class="action-btn delete-btn"
|
||||
:class="{ 'delete-confirm': deleteConfirmId === item.id }"
|
||||
@click="handleDelete(item, $event)"
|
||||
:title="deleteConfirmId === item.id ? t('toolbar.confirmDelete') : t('toolbar.delete')"
|
||||
>
|
||||
<svg v-if="deleteConfirmId !== item.id" xmlns="http://www.w3.org/2000/svg" width="12" height="12"
|
||||
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
|
||||
stroke-linejoin="round">
|
||||
<polyline points="3,6 5,6 21,6"></polyline>
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
||||
</svg>
|
||||
<span v-else class="confirm-text">{{ t('toolbar.confirm') }}</span>
|
||||
</button>
|
||||
<!-- 编辑状态 -->
|
||||
<div v-else class="doc-edit">
|
||||
<input
|
||||
:ref="el => editInputRef = el as HTMLInputElement"
|
||||
v-model="state.editing.title"
|
||||
type="text"
|
||||
class="edit-input"
|
||||
:maxlength="MAX_TITLE_LENGTH"
|
||||
@keydown.enter="saveEdit"
|
||||
@keydown.esc="cancelEdit"
|
||||
@blur="saveEdit"
|
||||
@click.stop
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div v-if="state.editing.id !== item.id" class="doc-actions">
|
||||
<!-- 只有非当前文档才显示在新窗口打开按钮 -->
|
||||
<button
|
||||
v-if="documentStore.currentDocument?.id !== item.id"
|
||||
class="action-btn"
|
||||
@click="openInNewWindow(item, $event)"
|
||||
:title="t('toolbar.openInNewWindow')"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
|
||||
fill="currentColor">
|
||||
<path
|
||||
d="M172.8 1017.6c-89.6 0-166.4-70.4-166.4-166.4V441.6c0-89.6 70.4-166.4 166.4-166.4h416c89.6 0 166.4 70.4 166.4 166.4v416c0 89.6-70.4 166.4-166.4 166.4l-416-6.4z m0-659.2c-51.2 0-89.6 38.4-89.6 89.6v416c0 51.2 38.4 89.6 89.6 89.6h416c51.2 0 89.6-38.4 89.6-89.6V441.6c0-51.2-38.4-89.6-89.6-89.6H172.8z"></path>
|
||||
<path
|
||||
d="M851.2 19.2H435.2C339.2 19.2 268.8 96 268.8 185.6v25.6h70.4v-25.6c0-51.2 38.4-89.6 89.6-89.6h409.6c51.2 0 89.6 38.4 89.6 89.6v409.6c0 51.2-38.4 89.6-89.6 89.6h-38.4V768h51.2c96 0 166.4-76.8 166.4-166.4V185.6c0-96-76.8-166.4-166.4-166.4z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="action-btn" @click="renameDoc(item, $event)" :title="t('toolbar.rename')">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
v-if="documentStore.documentList.length > 1 && item.id !== 1"
|
||||
class="action-btn delete-btn"
|
||||
:class="{ 'delete-confirm': isDeleting(item.id!) }"
|
||||
@click="handleDelete(item, $event)"
|
||||
:title="isDeleting(item.id!) ? t('toolbar.confirmDelete') : t('toolbar.delete')"
|
||||
>
|
||||
<svg v-if="!isDeleting(item.id!)" xmlns="http://www.w3.org/2000/svg" width="12" height="12"
|
||||
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
|
||||
stroke-linejoin="round">
|
||||
<polyline points="3,6 5,6 21,6"></polyline>
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
||||
</svg>
|
||||
<span v-else class="confirm-text">{{ t('toolbar.confirm') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-if="filteredItems.length === 0" class="empty">
|
||||
{{ t('toolbar.noDocumentFound') }}
|
||||
</div>
|
||||
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="documentStore.isLoading" class="loading">
|
||||
{{ t('toolbar.loading') }}
|
||||
<!-- 空状态 -->
|
||||
<div v-if="filteredItems.length === 0" class="empty">
|
||||
{{ t('toolbar.noDocumentFound') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.slide-up-enter-active,
|
||||
.slide-up-leave-active {
|
||||
transition: opacity 0.15s ease, transform 0.15s ease;
|
||||
}
|
||||
|
||||
.slide-up-enter-from,
|
||||
.slide-up-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
.document-selector {
|
||||
position: relative;
|
||||
|
||||
@@ -483,8 +444,8 @@ watch(() => documentStore.showDocumentSelector, (isOpen) => {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 3px;
|
||||
margin-bottom: 4px;
|
||||
width: 260px;
|
||||
max-height: calc(100vh - 40px); // 限制最大高度,留出titlebar空间(32px)和一些边距
|
||||
width: 300px;
|
||||
max-height: calc(100vh - 40px);
|
||||
z-index: 1000;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
|
||||
overflow: hidden;
|
||||
@@ -527,7 +488,7 @@ watch(() => documentStore.showDocumentSelector, (isOpen) => {
|
||||
}
|
||||
|
||||
.item-list {
|
||||
max-height: calc(100vh - 100px); // 为输入框和边距预留空间
|
||||
max-height: calc(100vh - 100px);
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
|
||||
@@ -669,7 +630,7 @@ watch(() => documentStore.showDocumentSelector, (isOpen) => {
|
||||
}
|
||||
}
|
||||
|
||||
.empty, .loading {
|
||||
.empty {
|
||||
padding: 16px 8px;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
@@ -680,9 +641,17 @@ watch(() => documentStore.showDocumentSelector, (isOpen) => {
|
||||
}
|
||||
|
||||
@keyframes fadeInOut {
|
||||
0% { opacity: 0; }
|
||||
10% { opacity: 1; }
|
||||
90% { opacity: 1; }
|
||||
100% { opacity: 0; }
|
||||
0% {
|
||||
opacity: 0;
|
||||
}
|
||||
10% {
|
||||
opacity: 1;
|
||||
}
|
||||
90% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
5
frontend/src/composables/index.ts
Normal file
5
frontend/src/composables/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { useConfirm } from './useConfirm';
|
||||
export type { UseConfirmOptions } from './useConfirm';
|
||||
|
||||
export { usePolling } from './usePolling';
|
||||
export type { UsePollingOptions, UsePollingReturn } from './usePolling';
|
||||
174
frontend/src/composables/useConfirm.ts
Normal file
174
frontend/src/composables/useConfirm.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { ref, readonly, onUnmounted, type Ref, type DeepReadonly } from 'vue';
|
||||
|
||||
export interface UseConfirmOptions<T extends string | number = string | number> {
|
||||
/** Auto cancel timeout in ms (default: 3000, set 0 to disable) */
|
||||
timeout?: number;
|
||||
/** Callback when confirmed */
|
||||
onConfirm?: (id: T) => void | Promise<void>;
|
||||
/** Callback when cancelled (timeout or manual) */
|
||||
onCancel?: (id: T) => void;
|
||||
}
|
||||
|
||||
export interface UseConfirmReturn<T extends string | number = string | number> {
|
||||
/** Current confirming id (readonly) */
|
||||
confirmId: DeepReadonly<Ref<T | null>>;
|
||||
/** Whether confirm action is executing */
|
||||
isPending: DeepReadonly<Ref<boolean>>;
|
||||
/** Check if a specific id is in confirming state */
|
||||
isConfirming: (id: T) => boolean;
|
||||
/** Start confirming state (with auto timeout) */
|
||||
startConfirm: (id: T) => void;
|
||||
/** Request confirmation (toggle between request and execute) */
|
||||
requestConfirm: (id: T) => Promise<boolean>;
|
||||
/** Manually confirm current id */
|
||||
confirm: () => Promise<void>;
|
||||
/** Cancel confirmation */
|
||||
cancel: () => void;
|
||||
/** Reset without triggering callbacks */
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable for handling confirm actions (e.g., delete confirmation)
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Basic usage
|
||||
* const { isConfirming, requestConfirm } = useConfirm({
|
||||
* timeout: 3000,
|
||||
* onConfirm: async (id) => { await deleteItem(id) }
|
||||
* })
|
||||
*
|
||||
* // In template
|
||||
* <button @click="requestConfirm('delete')">
|
||||
* {{ isConfirming('delete') ? 'Confirm?' : 'Delete' }}
|
||||
* </button>
|
||||
*
|
||||
* // With loading state
|
||||
* const { isPending, requestConfirm } = useConfirm({ ... })
|
||||
* <button :disabled="isPending" @click="requestConfirm('id')">
|
||||
* {{ isPending ? 'Processing...' : 'Delete' }}
|
||||
* </button>
|
||||
* ```
|
||||
*/
|
||||
export function useConfirm<T extends string | number = string | number>(
|
||||
options: UseConfirmOptions<T> = {}
|
||||
): UseConfirmReturn<T> {
|
||||
const { timeout = 3000, onConfirm, onCancel } = options;
|
||||
|
||||
const confirmId = ref<T | null>(null) as Ref<T | null>;
|
||||
const isPending = ref(false);
|
||||
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const clearTimer = (): void => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if a specific id is in confirming state
|
||||
*/
|
||||
const isConfirming = (id: T): boolean => {
|
||||
return confirmId.value === id;
|
||||
};
|
||||
|
||||
/**
|
||||
* Start confirming state for an id (with auto timeout)
|
||||
*/
|
||||
const startConfirm = (id: T): void => {
|
||||
clearTimer();
|
||||
confirmId.value = id;
|
||||
|
||||
// Auto cancel after timeout (0 = disabled)
|
||||
if (timeout > 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
if (confirmId.value === id) {
|
||||
confirmId.value = null;
|
||||
onCancel?.(id);
|
||||
}
|
||||
}, timeout);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Request confirmation for an id
|
||||
* - First click: enter confirming state
|
||||
* - Second click: execute confirm action
|
||||
* @returns true if confirmed, false if entered confirming state
|
||||
*/
|
||||
const requestConfirm = async (id: T): Promise<boolean> => {
|
||||
// Prevent action while pending
|
||||
if (isPending.value) return false;
|
||||
|
||||
if (confirmId.value === id) {
|
||||
// Already confirming, execute action
|
||||
clearTimer();
|
||||
isPending.value = true;
|
||||
try {
|
||||
await onConfirm?.(id);
|
||||
return true;
|
||||
} finally {
|
||||
confirmId.value = null;
|
||||
isPending.value = false;
|
||||
}
|
||||
} else {
|
||||
// Enter confirming state
|
||||
startConfirm(id);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Manually confirm the current id
|
||||
*/
|
||||
const confirm = async (): Promise<void> => {
|
||||
if (confirmId.value === null || isPending.value) return;
|
||||
|
||||
clearTimer();
|
||||
const id = confirmId.value;
|
||||
isPending.value = true;
|
||||
try {
|
||||
await onConfirm?.(id);
|
||||
} finally {
|
||||
confirmId.value = null;
|
||||
isPending.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cancel the confirming state
|
||||
*/
|
||||
const cancel = (): void => {
|
||||
if (confirmId.value === null) return;
|
||||
|
||||
const id = confirmId.value;
|
||||
clearTimer();
|
||||
confirmId.value = null;
|
||||
onCancel?.(id);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset state without triggering callbacks
|
||||
*/
|
||||
const reset = (): void => {
|
||||
clearTimer();
|
||||
confirmId.value = null;
|
||||
isPending.value = false;
|
||||
};
|
||||
|
||||
// Cleanup on unmount
|
||||
onUnmounted(clearTimer);
|
||||
|
||||
return {
|
||||
confirmId: readonly(confirmId),
|
||||
isPending: readonly(isPending),
|
||||
isConfirming,
|
||||
startConfirm,
|
||||
requestConfirm,
|
||||
confirm,
|
||||
cancel,
|
||||
reset
|
||||
};
|
||||
}
|
||||
147
frontend/src/composables/usePolling.ts
Normal file
147
frontend/src/composables/usePolling.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { ref, readonly, onUnmounted, type Ref, type DeepReadonly } from 'vue';
|
||||
|
||||
export interface UsePollingOptions<T> {
|
||||
/** Polling interval in ms (default: 500) */
|
||||
interval?: number;
|
||||
/** Execute immediately when started (default: true) */
|
||||
immediate?: boolean;
|
||||
/** Auto-stop condition, return true to stop polling */
|
||||
shouldStop?: (data: T) => boolean;
|
||||
/** Callback on each successful poll */
|
||||
onSuccess?: (data: T) => void;
|
||||
/** Callback when error occurs */
|
||||
onError?: (error: unknown) => void;
|
||||
/** Callback when polling stops (either manual or auto) */
|
||||
onStop?: () => void;
|
||||
}
|
||||
|
||||
export interface UsePollingReturn<T> {
|
||||
/** Latest fetched data (readonly) */
|
||||
data: DeepReadonly<Ref<T | null>>;
|
||||
/** Error message if any (readonly) */
|
||||
error: DeepReadonly<Ref<string>>;
|
||||
/** Whether polling is active (readonly) */
|
||||
isActive: DeepReadonly<Ref<boolean>>;
|
||||
/** Start polling */
|
||||
start: () => void;
|
||||
/** Stop polling */
|
||||
stop: () => void;
|
||||
/** Reset all state (also stops polling) */
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable for polling async operations with auto-stop support
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Basic usage
|
||||
* const { data, isActive, start, stop } = usePolling(
|
||||
* () => api.getProgress(),
|
||||
* {
|
||||
* interval: 200,
|
||||
* shouldStop: (d) => d.progress >= 100 || !!d.error,
|
||||
* onSuccess: (d) => console.log('Progress:', d.progress)
|
||||
* }
|
||||
* )
|
||||
*
|
||||
* // Start polling
|
||||
* start()
|
||||
*
|
||||
* // With reactive data binding
|
||||
* <div>{{ isActive ? `${data?.progress}%` : 'Idle' }}</div>
|
||||
* ```
|
||||
*/
|
||||
export function usePolling<T>(
|
||||
fetcher: () => Promise<T>,
|
||||
options: UsePollingOptions<T> = {}
|
||||
): UsePollingReturn<T> {
|
||||
const {
|
||||
interval = 500,
|
||||
immediate = true,
|
||||
shouldStop,
|
||||
onSuccess,
|
||||
onError,
|
||||
onStop
|
||||
} = options;
|
||||
|
||||
const data = ref<T | null>(null) as Ref<T | null>;
|
||||
const error = ref('');
|
||||
const isActive = ref(false);
|
||||
let timerId = 0;
|
||||
|
||||
const clearTimer = (): void => {
|
||||
if (timerId) {
|
||||
clearInterval(timerId);
|
||||
timerId = 0;
|
||||
}
|
||||
};
|
||||
|
||||
const poll = async (): Promise<void> => {
|
||||
try {
|
||||
const result = await fetcher();
|
||||
data.value = result;
|
||||
error.value = '';
|
||||
onSuccess?.(result);
|
||||
|
||||
// Check auto-stop condition
|
||||
if (shouldStop?.(result)) {
|
||||
stop();
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
onError?.(e);
|
||||
stop();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Start polling
|
||||
*/
|
||||
const start = (): void => {
|
||||
if (isActive.value) return;
|
||||
|
||||
isActive.value = true;
|
||||
error.value = '';
|
||||
|
||||
// Execute immediately if configured
|
||||
if (immediate) {
|
||||
poll();
|
||||
}
|
||||
|
||||
timerId = window.setInterval(poll, interval);
|
||||
};
|
||||
|
||||
/**
|
||||
* Stop polling
|
||||
*/
|
||||
const stop = (): void => {
|
||||
if (!isActive.value) return;
|
||||
|
||||
clearTimer();
|
||||
isActive.value = false;
|
||||
onStop?.();
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset all state to initial values
|
||||
*/
|
||||
const reset = (): void => {
|
||||
clearTimer();
|
||||
data.value = null;
|
||||
error.value = '';
|
||||
isActive.value = false;
|
||||
};
|
||||
|
||||
// Cleanup on unmount
|
||||
onUnmounted(clearTimer);
|
||||
|
||||
return {
|
||||
data: readonly(data),
|
||||
error: readonly(error),
|
||||
isActive: readonly(isActive),
|
||||
start,
|
||||
stop,
|
||||
reset
|
||||
};
|
||||
}
|
||||
37
frontend/src/directives/clickOutside.ts
Normal file
37
frontend/src/directives/clickOutside.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Directive, DirectiveBinding } from 'vue';
|
||||
|
||||
type ClickOutsideHandler = (event: MouseEvent) => void;
|
||||
|
||||
interface ClickOutsideElement extends HTMLElement {
|
||||
_clickOutsideHandler?: (event: MouseEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* v-click-outside directive
|
||||
* Triggers a callback when clicking outside the element
|
||||
*
|
||||
* Usage:
|
||||
* <div v-click-outside="handleClickOutside">...</div>
|
||||
*/
|
||||
export const clickOutside: Directive<ClickOutsideElement, ClickOutsideHandler> = {
|
||||
mounted(el: ClickOutsideElement, binding: DirectiveBinding<ClickOutsideHandler>) {
|
||||
const handler = (event: MouseEvent) => {
|
||||
const target = event.target as Node;
|
||||
if (el && !el.contains(target)) {
|
||||
binding.value(event);
|
||||
}
|
||||
};
|
||||
|
||||
el._clickOutsideHandler = handler;
|
||||
document.addEventListener('click', handler);
|
||||
},
|
||||
|
||||
unmounted(el: ClickOutsideElement) {
|
||||
if (el._clickOutsideHandler) {
|
||||
document.removeEventListener('click', el._clickOutsideHandler);
|
||||
delete el._clickOutsideHandler;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default clickOutside;
|
||||
13
frontend/src/directives/index.ts
Normal file
13
frontend/src/directives/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { App } from 'vue';
|
||||
import { clickOutside } from './clickOutside';
|
||||
|
||||
export { clickOutside };
|
||||
|
||||
/**
|
||||
* Register all custom directives
|
||||
*/
|
||||
export function registerDirectives(app: App) {
|
||||
app.directive('click-outside', clickOutside);
|
||||
}
|
||||
|
||||
export default registerDirectives;
|
||||
@@ -33,13 +33,6 @@ export default {
|
||||
confirmDelete: 'Click again to confirm delete',
|
||||
openInNewWindow: 'Open in New Window',
|
||||
alreadyOpenInNewWindow: 'Already open in another window',
|
||||
documentNameTooLong: 'Document name cannot exceed {max} characters',
|
||||
documentNameRequired: 'Document name cannot be empty',
|
||||
cannotDeleteLastDocument: 'Cannot delete the last document',
|
||||
cannotDeleteDefaultDocument: 'Cannot delete the default document',
|
||||
unknownTime: 'Unknown time',
|
||||
invalidDate: 'Invalid date',
|
||||
timeError: 'Time error',
|
||||
},
|
||||
languages: {
|
||||
'zh-CN': 'Chinese',
|
||||
@@ -51,11 +44,18 @@ export default {
|
||||
auto: 'Follow System'
|
||||
},
|
||||
keybindings: {
|
||||
keymapMode: 'Keymap Mode',
|
||||
modes: {
|
||||
standard: 'Standard Mode',
|
||||
emacs: 'Emacs Mode'
|
||||
},
|
||||
headers: {
|
||||
shortcut: 'Shortcut',
|
||||
category: 'Category',
|
||||
extension: 'Extension',
|
||||
description: 'Description'
|
||||
},
|
||||
resetToDefault: 'Reset to Default',
|
||||
confirmReset: 'Confirm Reset?',
|
||||
commands: {
|
||||
showSearch: 'Show search panel',
|
||||
hideSearch: 'Hide search panel',
|
||||
@@ -83,6 +83,7 @@ export default {
|
||||
blockCopy: 'Copy',
|
||||
blockCut: 'Cut',
|
||||
blockPaste: 'Paste',
|
||||
copyBlockImage: 'Copy block image',
|
||||
historyUndo: 'Undo',
|
||||
historyRedo: 'Redo',
|
||||
historyUndoSelection: 'Undo selection',
|
||||
@@ -100,6 +101,25 @@ export default {
|
||||
insertBlankLine: 'Insert blank line',
|
||||
selectLine: 'Select line',
|
||||
selectParentSyntax: 'Select parent syntax',
|
||||
simplifySelection: 'Simplify selection',
|
||||
addCursorAbove: 'Add cursor above',
|
||||
addCursorBelow: 'Add cursor below',
|
||||
cursorGroupLeft: 'Cursor word left',
|
||||
cursorGroupRight: 'Cursor word right',
|
||||
selectGroupLeft: 'Select word left',
|
||||
selectGroupRight: 'Select word right',
|
||||
deleteToLineEnd: 'Delete to line end',
|
||||
deleteToLineStart: 'Delete to line start',
|
||||
cursorLineStart: 'Cursor to line start',
|
||||
cursorLineEnd: 'Cursor to line end',
|
||||
selectLineStart: 'Select to line start',
|
||||
selectLineEnd: 'Select to line end',
|
||||
cursorDocStart: 'Cursor to document start',
|
||||
cursorDocEnd: 'Cursor to document end',
|
||||
selectDocStart: 'Select to document start',
|
||||
selectDocEnd: 'Select to document end',
|
||||
selectMatchingBracket: 'Select to matching bracket',
|
||||
splitLine: 'Split line',
|
||||
indentLess: 'Indent less',
|
||||
indentMore: 'Indent more',
|
||||
indentSelection: 'Indent selection',
|
||||
@@ -111,6 +131,18 @@ export default {
|
||||
deleteCharForward: 'Delete character forward',
|
||||
deleteGroupBackward: 'Delete group backward',
|
||||
deleteGroupForward: 'Delete group forward',
|
||||
|
||||
// Emacs mode additional basic navigation commands
|
||||
cursorCharLeft: 'Cursor left one character',
|
||||
cursorCharRight: 'Cursor right one character',
|
||||
cursorLineUp: 'Cursor up one line',
|
||||
cursorLineDown: 'Cursor down one line',
|
||||
cursorPageUp: 'Page up',
|
||||
cursorPageDown: 'Page down',
|
||||
selectCharLeft: 'Select left one character',
|
||||
selectCharRight: 'Select right one character',
|
||||
selectLineUp: 'Select up one line',
|
||||
selectLineDown: 'Select down one line',
|
||||
}
|
||||
},
|
||||
tabs: {
|
||||
@@ -234,14 +266,10 @@ export default {
|
||||
sshKeyPassphrase: 'SSH Key Passphrase',
|
||||
sshKeyPassphrasePlaceholder: 'Enter SSH key passphrase',
|
||||
backupOperations: 'Backup Operations',
|
||||
pushToRemote: 'Push to Remote',
|
||||
pushing: 'Pushing...',
|
||||
syncToRemote: 'Sync to Remote',
|
||||
syncing: 'Syncing...',
|
||||
actions: {
|
||||
push: 'Push',
|
||||
},
|
||||
status: {
|
||||
success: 'Success',
|
||||
failed: 'Failed'
|
||||
sync: 'Sync',
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -297,6 +325,15 @@ export default {
|
||||
highlightTrailingWhitespace: {
|
||||
name: 'Highlight Trailing Whitespace',
|
||||
description: 'Highlight trailing whitespace at the end of lines'
|
||||
},
|
||||
httpClient: {
|
||||
name: 'HTTP Client',
|
||||
description: 'Send HTTP requests directly in the editor and view responses'
|
||||
},
|
||||
blockImage: {
|
||||
name: 'Block Image Export',
|
||||
description: 'Render the current code block to an image and copy it to the clipboard',
|
||||
copyMenu: 'Copy block as image'
|
||||
}
|
||||
},
|
||||
monitor: {
|
||||
|
||||
@@ -33,13 +33,6 @@ export default {
|
||||
confirmDelete: '再次点击确认删除',
|
||||
openInNewWindow: '在新窗口中打开',
|
||||
alreadyOpenInNewWindow: '已在新窗口中打开',
|
||||
documentNameTooLong: '文档名称不能超过{max}个字符',
|
||||
documentNameRequired: '文档名称不能为空',
|
||||
cannotDeleteLastDocument: '无法删除最后一个文档',
|
||||
cannotDeleteDefaultDocument: '无法删除默认文档',
|
||||
unknownTime: '未知时间',
|
||||
invalidDate: '无效日期',
|
||||
timeError: '时间错误',
|
||||
},
|
||||
languages: {
|
||||
'zh-CN': '简体中文',
|
||||
@@ -51,11 +44,18 @@ export default {
|
||||
auto: '跟随系统'
|
||||
},
|
||||
keybindings: {
|
||||
keymapMode: '快捷键模式',
|
||||
modes: {
|
||||
standard: '标准模式',
|
||||
emacs: 'Emacs 模式'
|
||||
},
|
||||
headers: {
|
||||
shortcut: '快捷键',
|
||||
category: '分类',
|
||||
extension: '扩展',
|
||||
description: '描述'
|
||||
},
|
||||
resetToDefault: '重置为默认',
|
||||
confirmReset: '确认重置?',
|
||||
commands: {
|
||||
showSearch: '显示搜索面板',
|
||||
hideSearch: '隐藏搜索面板',
|
||||
@@ -83,6 +83,7 @@ export default {
|
||||
blockCopy: '复制',
|
||||
blockCut: '剪切',
|
||||
blockPaste: '粘贴',
|
||||
copyBlockImage: '复制块图片',
|
||||
historyUndo: '撤销',
|
||||
historyRedo: '重做',
|
||||
historyUndoSelection: '撤销选择',
|
||||
@@ -100,6 +101,25 @@ export default {
|
||||
insertBlankLine: '插入空行',
|
||||
selectLine: '选择行',
|
||||
selectParentSyntax: '选择父级语法',
|
||||
simplifySelection: '简化选择',
|
||||
addCursorAbove: '在上方添加光标',
|
||||
addCursorBelow: '在下方添加光标',
|
||||
cursorGroupLeft: '光标按单词左移',
|
||||
cursorGroupRight: '光标按单词右移',
|
||||
selectGroupLeft: '按单词选择左侧',
|
||||
selectGroupRight: '按单词选择右侧',
|
||||
deleteToLineEnd: '删除到行尾',
|
||||
deleteToLineStart: '删除到行首',
|
||||
cursorLineStart: '移动到行首',
|
||||
cursorLineEnd: '移动到行尾',
|
||||
selectLineStart: '选择到行首',
|
||||
selectLineEnd: '选择到行尾',
|
||||
cursorDocStart: '跳转到文档开头',
|
||||
cursorDocEnd: '跳转到文档结尾',
|
||||
selectDocStart: '选择到文档开头',
|
||||
selectDocEnd: '选择到文档结尾',
|
||||
selectMatchingBracket: '选择到匹配括号',
|
||||
splitLine: '分割行',
|
||||
indentLess: '减少缩进',
|
||||
indentMore: '增加缩进',
|
||||
indentSelection: '缩进选择',
|
||||
@@ -111,6 +131,18 @@ export default {
|
||||
deleteCharForward: '向前删除字符',
|
||||
deleteGroupBackward: '向后删除组',
|
||||
deleteGroupForward: '向前删除组',
|
||||
|
||||
// Emacs 模式额外的基础导航命令
|
||||
cursorCharLeft: '光标左移一个字符',
|
||||
cursorCharRight: '光标右移一个字符',
|
||||
cursorLineUp: '光标上移一行',
|
||||
cursorLineDown: '光标下移一行',
|
||||
cursorPageUp: '向上翻页',
|
||||
cursorPageDown: '向下翻页',
|
||||
selectCharLeft: '选择左移一个字符',
|
||||
selectCharRight: '选择右移一个字符',
|
||||
selectLineUp: '选择上移一行',
|
||||
selectLineDown: '选择下移一行',
|
||||
}
|
||||
},
|
||||
tabs: {
|
||||
@@ -236,14 +268,10 @@ export default {
|
||||
sshKeyPassphrase: 'SSH密钥密码',
|
||||
sshKeyPassphrasePlaceholder: '请输入SSH密钥密码',
|
||||
backupOperations: '备份操作',
|
||||
pushToRemote: '推送到远程',
|
||||
pushing: '推送中...',
|
||||
syncToRemote: '同步到远程',
|
||||
syncing: '同步中...',
|
||||
actions: {
|
||||
push: '推送',
|
||||
},
|
||||
status: {
|
||||
success: '成功',
|
||||
failed: '失败'
|
||||
sync: '同步',
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -299,6 +327,15 @@ export default {
|
||||
highlightTrailingWhitespace: {
|
||||
name: '高亮行尾空白',
|
||||
description: '高亮显示行尾的多余空白字符'
|
||||
},
|
||||
httpClient: {
|
||||
name: 'HTTP 客户端',
|
||||
description: '在编辑器中直接发送 HTTP 请求并查看响应'
|
||||
},
|
||||
blockImage: {
|
||||
name: '代码块导出图片',
|
||||
description: '将当前代码块渲染为图片并复制到剪贴板',
|
||||
copyMenu: '复制块为图片'
|
||||
}
|
||||
},
|
||||
monitor: {
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import {createApp} from 'vue';
|
||||
import { createApp } from 'vue';
|
||||
import App from './App.vue';
|
||||
import '@/assets/styles/index.css';
|
||||
import {createPinia} from 'pinia';
|
||||
import { createPinia } from 'pinia';
|
||||
import i18n from './i18n';
|
||||
import router from './router';
|
||||
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
|
||||
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
|
||||
import { registerDirectives } from './directives';
|
||||
import {EditorView} from "@codemirror/view";
|
||||
|
||||
(EditorView as any).EDIT_CONTEXT = false;
|
||||
|
||||
const pinia = createPinia();
|
||||
pinia.use(piniaPluginPersistedstate);
|
||||
|
||||
const pinia = createPinia()
|
||||
pinia.use(piniaPluginPersistedstate)
|
||||
const app = createApp(App);
|
||||
app.use(pinia)
|
||||
app.use(pinia);
|
||||
app.use(i18n);
|
||||
app.use(router);
|
||||
registerDirectives(app);
|
||||
app.mount('#app');
|
||||
@@ -1,49 +1,31 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref, onScopeDispose } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
import { BackupService } from '@/../bindings/voidraft/internal/services';
|
||||
import { useConfigStore } from '@/stores/configStore';
|
||||
import { createTimerManager } from '@/common/utils/timerUtils';
|
||||
|
||||
export const useBackupStore = defineStore('backup', () => {
|
||||
const isPushing = ref(false);
|
||||
const message = ref<string | null>(null);
|
||||
const isError = ref(false);
|
||||
const isSyncing = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
const timer = createTimerManager();
|
||||
const configStore = useConfigStore();
|
||||
|
||||
onScopeDispose(() => timer.clear());
|
||||
|
||||
const pushToRemote = async () => {
|
||||
const isConfigured = Boolean(configStore.config.backup.repo_url?.trim());
|
||||
|
||||
if (isPushing.value || !isConfigured) {
|
||||
const sync = async (): Promise<void> => {
|
||||
if (isSyncing.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
isSyncing.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
isPushing.value = true;
|
||||
message.value = null;
|
||||
timer.clear();
|
||||
|
||||
await BackupService.PushToRemote();
|
||||
|
||||
isError.value = false;
|
||||
message.value = 'push successful';
|
||||
timer.set(() => { message.value = null; }, 3000);
|
||||
} catch (error) {
|
||||
isError.value = true;
|
||||
message.value = error instanceof Error ? error.message : 'backup operation failed';
|
||||
timer.set(() => { message.value = null; }, 5000);
|
||||
await BackupService.Sync();
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
isPushing.value = false;
|
||||
isSyncing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isPushing,
|
||||
message,
|
||||
isError,
|
||||
pushToRemote
|
||||
isSyncing,
|
||||
error,
|
||||
sync
|
||||
};
|
||||
});
|
||||
@@ -161,7 +161,7 @@ export const useConfigStore = defineStore('config', () => {
|
||||
|
||||
|
||||
// 初始化语言设置
|
||||
const initializeLanguage = async (): Promise<void> => {
|
||||
const initLanguage = async (): Promise<void> => {
|
||||
try {
|
||||
// 如果配置未加载,先加载配置
|
||||
if (!state.configLoaded) {
|
||||
@@ -210,7 +210,7 @@ export const useConfigStore = defineStore('config', () => {
|
||||
|
||||
// 语言相关方法
|
||||
setLanguage,
|
||||
initializeLanguage,
|
||||
initLanguage,
|
||||
|
||||
// 主题相关方法
|
||||
setSystemTheme,
|
||||
@@ -248,7 +248,7 @@ export const useConfigStore = defineStore('config', () => {
|
||||
setFontWeight: (value: string) => updateConfig('fontWeight', value),
|
||||
|
||||
// 路径操作
|
||||
setDataPath: (value: string) => updateConfig('dataPath', value),
|
||||
setDataPath: (value: string) => updateConfigLocal('dataPath', value),
|
||||
|
||||
// 保存配置相关方法
|
||||
setAutoSaveDelay: (value: number) => updateConfig('autoSaveDelay', value),
|
||||
@@ -275,6 +275,9 @@ export const useConfigStore = defineStore('config', () => {
|
||||
// 标签页配置相关方法
|
||||
setEnableTabs: (value: boolean) => updateConfig('enableTabs', value),
|
||||
|
||||
// 快捷键模式配置相关方法
|
||||
setKeymapMode: (value: any) => updateConfig('keymapMode', value),
|
||||
|
||||
// 更新配置相关方法
|
||||
setAutoUpdate: (value: boolean) => updateConfig('autoUpdate', value),
|
||||
|
||||
|
||||
@@ -2,12 +2,11 @@ import {defineStore} from 'pinia';
|
||||
import {computed, ref} from 'vue';
|
||||
import {DocumentService} from '@/../bindings/voidraft/internal/services';
|
||||
import {OpenDocumentWindow} from '@/../bindings/voidraft/internal/services/windowservice';
|
||||
import {Document} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {Document} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
import {useTabStore} from "@/stores/tabStore";
|
||||
import type {EditorViewState} from '@/stores/editorStore';
|
||||
|
||||
export const useDocumentStore = defineStore('document', () => {
|
||||
const DEFAULT_DOCUMENT_ID = ref<number>(1); // 默认草稿文档ID
|
||||
|
||||
// === 核心状态 ===
|
||||
const documents = ref<Record<number, Document>>({});
|
||||
@@ -15,7 +14,6 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
const currentDocument = ref<Document | null>(null);
|
||||
|
||||
// === 编辑器状态持久化 ===
|
||||
// 修复:使用统一的 EditorViewState 类型定义
|
||||
const documentStates = ref<Record<number, EditorViewState>>({});
|
||||
|
||||
// === UI状态 ===
|
||||
@@ -26,15 +24,18 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
// === 计算属性 ===
|
||||
const documentList = computed(() =>
|
||||
Object.values(documents.value).sort((a, b) => {
|
||||
return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
|
||||
const timeA = a.updated_at ? new Date(a.updated_at).getTime() : 0;
|
||||
const timeB = b.updated_at ? new Date(b.updated_at).getTime() : 0;
|
||||
return timeB - timeA;
|
||||
})
|
||||
);
|
||||
|
||||
// === 私有方法 ===
|
||||
const setDocuments = (docs: Document[]) => {
|
||||
documents.value = {};
|
||||
docs.forEach(doc => {
|
||||
documents.value[doc.id] = doc;
|
||||
if (doc.id !== undefined) {
|
||||
documents.value[doc.id] = doc;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -64,25 +65,16 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
clearError();
|
||||
};
|
||||
|
||||
const toggleDocumentSelector = () => {
|
||||
if (showDocumentSelector.value) {
|
||||
closeDocumentSelector();
|
||||
} else {
|
||||
openDocumentSelector();
|
||||
}
|
||||
};
|
||||
|
||||
// === 文档操作方法 ===
|
||||
|
||||
// 在新窗口中打开文档
|
||||
const openDocumentInNewWindow = async (docId: number): Promise<boolean> => {
|
||||
try {
|
||||
await OpenDocumentWindow(docId);
|
||||
const tabStore = useTabStore();
|
||||
if (tabStore.isTabsEnabled && tabStore.hasTab(docId)) {
|
||||
tabStore.closeTab(docId);
|
||||
}
|
||||
|
||||
await OpenDocumentWindow(docId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to open document in new window:', error);
|
||||
@@ -94,7 +86,7 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
const createNewDocument = async (title: string): Promise<Document | null> => {
|
||||
try {
|
||||
const doc = await DocumentService.CreateDocument(title);
|
||||
if (doc) {
|
||||
if (doc && doc.id !== undefined) {
|
||||
documents.value[doc.id] = doc;
|
||||
return doc;
|
||||
}
|
||||
@@ -123,8 +115,6 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
// 打开文档
|
||||
const openDocument = async (docId: number): Promise<boolean> => {
|
||||
try {
|
||||
closeDocumentSelector();
|
||||
|
||||
// 获取完整文档数据
|
||||
const doc = await DocumentService.GetDocumentByID(docId);
|
||||
if (!doc) {
|
||||
@@ -150,14 +140,18 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
const doc = documents.value[docId];
|
||||
if (doc) {
|
||||
doc.title = title;
|
||||
doc.updatedAt = new Date().toISOString();
|
||||
doc.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
if (currentDocument.value?.id === docId) {
|
||||
currentDocument.value.title = title;
|
||||
currentDocument.value.updatedAt = new Date().toISOString();
|
||||
currentDocument.value.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
// 同步更新标签页标题
|
||||
const tabStore = useTabStore();
|
||||
tabStore.updateTabTitle(docId, title);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to update document metadata:', error);
|
||||
@@ -168,20 +162,21 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
// 删除文档
|
||||
const deleteDocument = async (docId: number): Promise<boolean> => {
|
||||
try {
|
||||
// 检查是否是默认文档(使用ID判断)
|
||||
if (docId === DEFAULT_DOCUMENT_ID.value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await DocumentService.DeleteDocument(docId);
|
||||
|
||||
// 更新本地状态
|
||||
delete documents.value[docId];
|
||||
|
||||
// 同步清理标签页
|
||||
const tabStore = useTabStore();
|
||||
if (tabStore.hasTab(docId)) {
|
||||
tabStore.closeTab(docId);
|
||||
}
|
||||
|
||||
// 如果删除的是当前文档,切换到第一个可用文档
|
||||
if (currentDocumentId.value === docId) {
|
||||
const availableDocs = Object.values(documents.value);
|
||||
if (availableDocs.length > 0) {
|
||||
if (availableDocs.length > 0 && availableDocs[0].id !== undefined) {
|
||||
await openDocument(availableDocs[0].id);
|
||||
} else {
|
||||
currentDocumentId.value = null;
|
||||
@@ -208,8 +203,10 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
// 如果URL中没有指定文档ID,则使用持久化的文档ID
|
||||
await openDocument(currentDocumentId.value);
|
||||
} else {
|
||||
// 否则打开默认文档
|
||||
await openDocument(DEFAULT_DOCUMENT_ID.value);
|
||||
// 否则打开第一个文档
|
||||
if (documentList.value[0].id) {
|
||||
await openDocument(documentList.value[0].id);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize document store:', error);
|
||||
@@ -217,7 +214,6 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
};
|
||||
|
||||
return {
|
||||
DEFAULT_DOCUMENT_ID,
|
||||
// 状态
|
||||
documents,
|
||||
documentList,
|
||||
@@ -237,7 +233,6 @@ export const useDocumentStore = defineStore('document', () => {
|
||||
deleteDocument,
|
||||
openDocumentSelector,
|
||||
closeDocumentSelector,
|
||||
toggleDocumentSelector,
|
||||
setError,
|
||||
clearError,
|
||||
initialize,
|
||||
|
||||
@@ -4,7 +4,6 @@ import {EditorView} from '@codemirror/view';
|
||||
import {EditorState, Extension} from '@codemirror/state';
|
||||
import {useConfigStore} from './configStore';
|
||||
import {useDocumentStore} from './documentStore';
|
||||
import {ExtensionID} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {DocumentService, ExtensionService} from '@/../bindings/voidraft/internal/services';
|
||||
import {ensureSyntaxTree} from "@codemirror/language";
|
||||
import {createBasicSetup} from '@/views/editor/basic/basicSetup';
|
||||
@@ -14,6 +13,7 @@ import {createFontExtensionFromBackend, updateFontConfig} from '@/views/editor/b
|
||||
import {createStatsUpdateExtension} from '@/views/editor/basic/statsExtension';
|
||||
import {createContentChangePlugin} from '@/views/editor/basic/contentChangeExtension';
|
||||
import {createWheelZoomExtension} from '@/views/editor/basic/wheelZoomExtension';
|
||||
import {createCursorPositionExtension, scrollToCursor} from '@/views/editor/basic/cursorPositionExtension';
|
||||
import {createDynamicKeymapExtension, updateKeymapExtension} from '@/views/editor/keymap';
|
||||
import {
|
||||
createDynamicExtensions,
|
||||
@@ -22,14 +22,14 @@ import {
|
||||
setExtensionManagerView
|
||||
} from '@/views/editor/manager';
|
||||
import {useExtensionStore} from './extensionStore';
|
||||
import createCodeBlockExtension, {blockState} from "@/views/editor/extensions/codeblock";
|
||||
import createCodeBlockExtension from "@/views/editor/extensions/codeblock";
|
||||
import {LruCache} from '@/common/utils/lruCache';
|
||||
import {AsyncManager} from '@/common/utils/asyncManager';
|
||||
import {generateContentHash} from "@/common/utils/hashUtils";
|
||||
import {createTimerManager, type TimerManager} from '@/common/utils/timerUtils';
|
||||
import {EDITOR_CONFIG} from '@/common/constant/editor';
|
||||
import {createHttpClientExtension} from "@/views/editor/extensions/httpclient";
|
||||
import {createDebounce} from '@/common/utils/debounce';
|
||||
import {useKeybindingStore} from "@/stores/keybindingStore";
|
||||
|
||||
export interface DocumentStats {
|
||||
lines: number;
|
||||
@@ -37,7 +37,7 @@ export interface DocumentStats {
|
||||
selectedCharacters: number;
|
||||
}
|
||||
|
||||
// 修复:只保存光标位置,恢复时自动滚动到光标处(更简单可靠)
|
||||
// 修复:只保存光标位置,恢复时自动滚动到光标处
|
||||
export interface EditorViewState {
|
||||
cursorPos: number;
|
||||
}
|
||||
@@ -93,84 +93,6 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
}
|
||||
}, { delay: 500 }); // 500ms 内的多次输入只清理一次
|
||||
|
||||
// === 私有方法 ===
|
||||
|
||||
/**
|
||||
* 检查位置是否在代码块分隔符区域内
|
||||
*/
|
||||
const isPositionInDelimiter = (view: EditorView, pos: number): boolean => {
|
||||
try {
|
||||
const blocks = view.state.field(blockState, false);
|
||||
if (!blocks) return false;
|
||||
|
||||
for (const block of blocks) {
|
||||
if (pos >= block.delimiter.from && pos < block.delimiter.to) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 调整光标位置到有效的内容区域
|
||||
* 如果位置在分隔符内,移动到该块的内容开始位置
|
||||
*/
|
||||
const adjustCursorPosition = (view: EditorView, pos: number): number => {
|
||||
try {
|
||||
const blocks = view.state.field(blockState, false);
|
||||
if (!blocks || blocks.length === 0) return pos;
|
||||
|
||||
// 如果位置在分隔符内,移动到该块的内容开始位置
|
||||
for (const block of blocks) {
|
||||
if (pos >= block.delimiter.from && pos < block.delimiter.to) {
|
||||
return block.content.from;
|
||||
}
|
||||
}
|
||||
|
||||
return pos;
|
||||
} catch {
|
||||
return pos;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 恢复编辑器的光标位置(自动滚动到光标处)
|
||||
*/
|
||||
const restoreEditorState = (instance: EditorInstance, documentId: number): void => {
|
||||
const savedState = instance.editorState;
|
||||
|
||||
if (savedState) {
|
||||
// 有保存的状态,恢复光标位置
|
||||
let pos = Math.min(savedState.cursorPos, instance.view.state.doc.length);
|
||||
|
||||
// 确保位置不在分隔符上
|
||||
if (isPositionInDelimiter(instance.view, pos)) {
|
||||
pos = adjustCursorPosition(instance.view, pos);
|
||||
}
|
||||
|
||||
// 修复:设置光标位置并居中滚动(更好的用户体验)
|
||||
instance.view.dispatch({
|
||||
selection: {anchor: pos, head: pos},
|
||||
effects: EditorView.scrollIntoView(pos, {
|
||||
y: "center", // 垂直居中显示
|
||||
yMargin: 100 // 上下留一些边距
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// 首次打开或没有记录,光标在文档末尾
|
||||
const docLength = instance.view.state.doc.length;
|
||||
instance.view.dispatch({
|
||||
selection: {anchor: docLength, head: docLength},
|
||||
effects: EditorView.scrollIntoView(docLength, {
|
||||
y: "center",
|
||||
yMargin: 100
|
||||
})
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 缓存化的语法树确保方法
|
||||
const ensureSyntaxTreeCached = (view: EditorView, documentId: number): void => {
|
||||
@@ -245,7 +167,7 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
increaseFontSize: () => configStore.increaseFontSizeLocal(),
|
||||
decreaseFontSize: () => configStore.decreaseFontSizeLocal(),
|
||||
onSave: () => configStore.saveFontSize(),
|
||||
saveDelay: 500
|
||||
saveDelay: 1000
|
||||
});
|
||||
|
||||
// 统计扩展
|
||||
@@ -260,8 +182,8 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
enableAutoDetection: true
|
||||
});
|
||||
|
||||
const httpExtension = createHttpClientExtension();
|
||||
|
||||
// 光标位置持久化扩展
|
||||
const cursorPositionExtension = createCursorPositionExtension(documentId);
|
||||
|
||||
// 再次检查操作有效性
|
||||
if (!operationManager.isOperationValid(operationId, documentId)) {
|
||||
@@ -277,7 +199,7 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
}
|
||||
|
||||
// 动态扩展,传递文档ID以便扩展管理器可以预初始化
|
||||
const dynamicExtensions = await createDynamicExtensions(documentId);
|
||||
const dynamicExtensions = await createDynamicExtensions();
|
||||
|
||||
// 最终检查操作有效性
|
||||
if (!operationManager.isOperationValid(operationId, documentId)) {
|
||||
@@ -295,14 +217,23 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
statsExtension,
|
||||
contentChangeExtension,
|
||||
codeBlockExtension,
|
||||
cursorPositionExtension,
|
||||
...dynamicExtensions,
|
||||
...httpExtension,
|
||||
];
|
||||
|
||||
// 创建编辑器状态
|
||||
// 获取保存的光标位置
|
||||
const savedState = documentStore.documentStates[documentId];
|
||||
const docLength = content.length;
|
||||
const initialCursorPos = savedState?.cursorPos !== undefined
|
||||
? Math.min(savedState.cursorPos, docLength)
|
||||
: docLength;
|
||||
|
||||
|
||||
// 创建编辑器状态,设置初始光标位置
|
||||
const state = EditorState.create({
|
||||
doc: content,
|
||||
extensions
|
||||
extensions,
|
||||
selection: { anchor: initialCursorPos, head: initialCursorPos }
|
||||
});
|
||||
|
||||
return new EditorView({
|
||||
@@ -320,7 +251,6 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
lastModified: new Date(),
|
||||
autoSaveTimer: createTimerManager(),
|
||||
syntaxTreeCache: null,
|
||||
// 修复:创建实例时从 documentStore 读取持久化的编辑器状态
|
||||
editorState: documentStore.documentStates[documentId]
|
||||
};
|
||||
|
||||
@@ -401,8 +331,8 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
//使用 nextTick + requestAnimationFrame 确保 DOM 完全渲染
|
||||
nextTick(() => {
|
||||
requestAnimationFrame(() => {
|
||||
// 恢复编辑器状态(光标位置和滚动位置)
|
||||
restoreEditorState(instance, documentId);
|
||||
// 滚动到当前光标位置
|
||||
scrollToCursor(instance.view);
|
||||
|
||||
// 聚焦编辑器
|
||||
instance.view.focus();
|
||||
@@ -433,7 +363,6 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
instance.isDirty = false;
|
||||
instance.lastModified = new Date();
|
||||
}
|
||||
// 如果内容在保存期间被修改了,保持 isDirty 状态
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -462,15 +391,14 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
}, getAutoSaveDelay());
|
||||
};
|
||||
|
||||
// === 公共API ===
|
||||
|
||||
// 设置编辑器容器
|
||||
const setEditorContainer = (container: HTMLElement | null) => {
|
||||
containerElement.value = container;
|
||||
|
||||
// 如果设置容器时已有当前文档,立即加载编辑器
|
||||
if (container && documentStore.currentDocument) {
|
||||
loadEditor(documentStore.currentDocument.id, documentStore.currentDocument.content);
|
||||
if (container && documentStore.currentDocument && documentStore.currentDocument.id !== undefined) {
|
||||
loadEditor(documentStore.currentDocument.id, documentStore.currentDocument.content || '');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -577,15 +505,6 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
await saveEditorContent(documentId);
|
||||
}
|
||||
|
||||
// 保存光标位置
|
||||
if (instance.view && instance.view.state) {
|
||||
const currentState: EditorViewState = {
|
||||
cursorPos: instance.view.state.selection.main.head
|
||||
};
|
||||
// 保存到 documentStore 用于持久化
|
||||
documentStore.documentStates[documentId] = currentState;
|
||||
}
|
||||
|
||||
// 清除自动保存定时器
|
||||
instance.autoSaveTimer.clear();
|
||||
|
||||
@@ -668,22 +587,10 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
operationManager.cancelAllOperations();
|
||||
|
||||
editorCache.clear((_documentId, instance) => {
|
||||
// 修复:清空前只保存光标位置
|
||||
if (instance.view) {
|
||||
const currentState: EditorViewState = {
|
||||
cursorPos: instance.view.state.selection.main.head
|
||||
};
|
||||
// 同时保存到实例和 documentStore
|
||||
instance.editorState = currentState;
|
||||
documentStore.documentStates[instance.documentId] = currentState;
|
||||
}
|
||||
|
||||
// 清除自动保存定时器
|
||||
instance.autoSaveTimer.clear();
|
||||
|
||||
// 从扩展管理器移除
|
||||
removeExtensionManagerView(instance.documentId);
|
||||
|
||||
// 移除DOM元素
|
||||
if (instance.view.dom.parentElement) {
|
||||
instance.view.dom.remove();
|
||||
@@ -696,50 +603,39 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
};
|
||||
|
||||
// 更新扩展
|
||||
const updateExtension = async (id: ExtensionID, enabled: boolean, config?: any) => {
|
||||
// 如果只是更新启用状态
|
||||
if (config === undefined) {
|
||||
await ExtensionService.UpdateExtensionEnabled(id, enabled);
|
||||
} else {
|
||||
// 如果需要更新配置
|
||||
await ExtensionService.UpdateExtensionState(id, enabled, config);
|
||||
const updateExtension = async (id: number, enabled: boolean, config?: any) => {
|
||||
// 更新启用状态
|
||||
await ExtensionService.UpdateExtensionEnabled(id, enabled);
|
||||
|
||||
// 如果需要更新配置
|
||||
if (config !== undefined) {
|
||||
await ExtensionService.UpdateExtensionConfig(id, config);
|
||||
}
|
||||
|
||||
// 重新加载扩展配置
|
||||
await extensionStore.loadExtensions();
|
||||
|
||||
// 获取更新后的扩展名称
|
||||
const extension = extensionStore.extensions.find(ext => ext.id === id);
|
||||
if (!extension) return;
|
||||
|
||||
// 更新前端编辑器扩展 - 应用于所有实例
|
||||
const manager = getExtensionManager();
|
||||
if (manager) {
|
||||
// 直接更新前端扩展至所有视图
|
||||
manager.updateExtension(id, enabled, config);
|
||||
}
|
||||
|
||||
// 重新加载扩展配置
|
||||
await extensionStore.loadExtensions();
|
||||
if (manager) {
|
||||
manager.initExtensions(extensionStore.extensions);
|
||||
manager.updateExtension(extension.name, enabled, config);
|
||||
}
|
||||
|
||||
await useKeybindingStore().loadKeyBindings();
|
||||
await applyKeymapSettings();
|
||||
};
|
||||
|
||||
// 监听文档切换
|
||||
watch(() => documentStore.currentDocument, async (newDoc, oldDoc) => {
|
||||
if (newDoc && containerElement.value) {
|
||||
// 修复:在切换到新文档前,只保存旧文档的光标位置
|
||||
if (oldDoc && oldDoc.id !== newDoc.id && currentEditor.value) {
|
||||
const oldInstance = editorCache.get(oldDoc.id);
|
||||
if (oldInstance) {
|
||||
const currentState: EditorViewState = {
|
||||
cursorPos: currentEditor.value.state.selection.main.head
|
||||
};
|
||||
// 同时保存到实例和 documentStore
|
||||
oldInstance.editorState = currentState;
|
||||
documentStore.documentStates[oldDoc.id] = currentState;
|
||||
}
|
||||
}
|
||||
|
||||
if (newDoc && newDoc.id !== undefined && containerElement.value) {
|
||||
// 等待 DOM 更新完成,再加载新文档的编辑器
|
||||
await nextTick();
|
||||
loadEditor(newDoc.id, newDoc.content);
|
||||
loadEditor(newDoc.id, newDoc.content || '');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,28 +1,19 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
import { Extension, ExtensionID } from '@/../bindings/voidraft/internal/models/models';
|
||||
import { Extension } from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
import { ExtensionService } from '@/../bindings/voidraft/internal/services';
|
||||
|
||||
export const useExtensionStore = defineStore('extension', () => {
|
||||
// 扩展配置数据
|
||||
const extensions = ref<Extension[]>([]);
|
||||
|
||||
// 获取启用的扩展
|
||||
const enabledExtensions = computed(() =>
|
||||
extensions.value.filter(ext => ext.enabled)
|
||||
);
|
||||
|
||||
// 获取启用的扩展ID列表
|
||||
const enabledExtensionIds = computed(() =>
|
||||
enabledExtensions.value.map(ext => ext.id)
|
||||
);
|
||||
|
||||
/**
|
||||
* 从后端加载扩展配置
|
||||
*/
|
||||
const loadExtensions = async (): Promise<void> => {
|
||||
try {
|
||||
extensions.value = await ExtensionService.GetAllExtensions();
|
||||
const result = await ExtensionService.GetExtensions();
|
||||
extensions.value = result.filter((ext): ext is Extension => ext !== null);
|
||||
} catch (err) {
|
||||
console.error('[ExtensionStore] Failed to load extensions:', err);
|
||||
}
|
||||
@@ -31,17 +22,19 @@ export const useExtensionStore = defineStore('extension', () => {
|
||||
/**
|
||||
* 获取扩展配置
|
||||
*/
|
||||
const getExtensionConfig = (id: ExtensionID): any => {
|
||||
const extension = extensions.value.find(ext => ext.id === id);
|
||||
return extension?.config ?? {};
|
||||
const getExtensionConfig = async (id: number): Promise<any> => {
|
||||
try {
|
||||
const config = await ExtensionService.GetExtensionConfig(id);
|
||||
return config ?? {};
|
||||
} catch (err) {
|
||||
console.error('[ExtensionStore] Failed to get extension config:', err);
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
// 状态
|
||||
extensions,
|
||||
enabledExtensions,
|
||||
enabledExtensionIds,
|
||||
|
||||
// 方法
|
||||
loadExtensions,
|
||||
getExtensionConfig,
|
||||
|
||||
@@ -1,82 +1,38 @@
|
||||
import {defineStore} from 'pinia';
|
||||
import {computed, ref} from 'vue';
|
||||
import {ExtensionID, KeyBinding, KeyBindingCommand} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {GetAllKeyBindings} from '@/../bindings/voidraft/internal/services/keybindingservice';
|
||||
import {KeyBinding} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
import {KeyBindingService} from '@/../bindings/voidraft/internal/services';
|
||||
import {KeyBindingType} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {useConfigStore} from './configStore';
|
||||
|
||||
export const useKeybindingStore = defineStore('keybinding', () => {
|
||||
const configStore = useConfigStore();
|
||||
|
||||
// 快捷键配置数据
|
||||
const keyBindings = ref<KeyBinding[]>([]);
|
||||
|
||||
// 获取启用的快捷键
|
||||
const enabledKeyBindings = computed(() =>
|
||||
keyBindings.value.filter(kb => kb.enabled)
|
||||
);
|
||||
|
||||
// 按扩展分组的快捷键
|
||||
const keyBindingsByExtension = computed(() => {
|
||||
const groups = new Map<ExtensionID, KeyBinding[]>();
|
||||
|
||||
for (const binding of keyBindings.value) {
|
||||
if (!groups.has(binding.extension)) {
|
||||
groups.set(binding.extension, []);
|
||||
}
|
||||
groups.get(binding.extension)!.push(binding);
|
||||
}
|
||||
|
||||
return groups;
|
||||
});
|
||||
|
||||
// 获取指定扩展的快捷键
|
||||
const getKeyBindingsByExtension = computed(() =>
|
||||
(extension: ExtensionID) =>
|
||||
keyBindings.value.filter(kb => kb.extension === extension)
|
||||
);
|
||||
|
||||
// 按命令获取快捷键
|
||||
const getKeyBindingByCommand = computed(() =>
|
||||
(command: KeyBindingCommand) =>
|
||||
keyBindings.value.find(kb => kb.command === command)
|
||||
);
|
||||
|
||||
/**
|
||||
* 从后端加载快捷键配置
|
||||
* 从后端加载快捷键配置(根据当前配置的模式)
|
||||
*/
|
||||
const loadKeyBindings = async (): Promise<void> => {
|
||||
keyBindings.value = await GetAllKeyBindings();
|
||||
const keymapMode = configStore.config.editing.keymapMode || KeyBindingType.Standard;
|
||||
const result = await KeyBindingService.GetKeyBindings(keymapMode);
|
||||
keyBindings.value = result.filter((kb): kb is KeyBinding => kb !== null);
|
||||
};
|
||||
|
||||
/**
|
||||
* 检查是否存在指定命令的快捷键
|
||||
* 更新快捷键绑定
|
||||
*/
|
||||
const hasCommand = (command: KeyBindingCommand): boolean => {
|
||||
return keyBindings.value.some(kb => kb.command === command && kb.enabled);
|
||||
const updateKeyBinding = async (id: number, key: string): Promise<void> => {
|
||||
await KeyBindingService.UpdateKeyBindingKeys(id, key);
|
||||
await loadKeyBindings();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* 获取扩展相关的所有扩展ID
|
||||
*/
|
||||
const getAllExtensionIds = computed(() => {
|
||||
const extensionIds = new Set<ExtensionID>();
|
||||
for (const binding of keyBindings.value) {
|
||||
extensionIds.add(binding.extension);
|
||||
}
|
||||
return Array.from(extensionIds);
|
||||
});
|
||||
|
||||
return {
|
||||
// 状态
|
||||
keyBindings,
|
||||
enabledKeyBindings,
|
||||
keyBindingsByExtension,
|
||||
getAllExtensionIds,
|
||||
|
||||
// 计算属性
|
||||
getKeyBindingByCommand,
|
||||
getKeyBindingsByExtension,
|
||||
|
||||
// 方法
|
||||
loadKeyBindings,
|
||||
hasCommand,
|
||||
updateKeyBinding,
|
||||
};
|
||||
});
|
||||
@@ -38,7 +38,7 @@ export const useSystemStore = defineStore('system', () => {
|
||||
});
|
||||
|
||||
// 初始化系统信息
|
||||
const initializeSystemInfo = async (): Promise<void> => {
|
||||
const initSystemInfo = async (): Promise<void> => {
|
||||
if (isLoading.value) return;
|
||||
|
||||
isLoading.value = true;
|
||||
@@ -102,7 +102,7 @@ export const useSystemStore = defineStore('system', () => {
|
||||
titleBarHeight,
|
||||
|
||||
// 方法
|
||||
initializeSystemInfo,
|
||||
initSystemInfo,
|
||||
setWindowOnTop,
|
||||
toggleWindowOnTop,
|
||||
resetWindowOnTop,
|
||||
|
||||
@@ -2,7 +2,7 @@ import {defineStore} from 'pinia';
|
||||
import {computed, readonly, ref} from 'vue';
|
||||
import {useConfigStore} from './configStore';
|
||||
import {useDocumentStore} from './documentStore';
|
||||
import type {Document} from '@/../bindings/voidraft/internal/models/models';
|
||||
import type {Document} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
|
||||
export interface Tab {
|
||||
documentId: number; // 直接使用文档ID作为唯一标识
|
||||
@@ -15,7 +15,7 @@ export const useTabStore = defineStore('tab', () => {
|
||||
const documentStore = useDocumentStore();
|
||||
|
||||
// === 核心状态 ===
|
||||
const tabsMap = ref<Map<number, Tab>>(new Map());
|
||||
const tabsMap = ref<Record<number, Tab>>({});
|
||||
const tabOrder = ref<number[]>([]); // 维护标签页顺序
|
||||
const draggedTabId = ref<number | null>(null);
|
||||
|
||||
@@ -28,21 +28,21 @@ export const useTabStore = defineStore('tab', () => {
|
||||
// 按顺序返回标签页数组(用于UI渲染)
|
||||
const tabs = computed(() => {
|
||||
return tabOrder.value
|
||||
.map(documentId => tabsMap.value.get(documentId))
|
||||
.map(documentId => tabsMap.value[documentId])
|
||||
.filter(tab => tab !== undefined) as Tab[];
|
||||
});
|
||||
|
||||
// === 私有方法 ===
|
||||
const hasTab = (documentId: number): boolean => {
|
||||
return tabsMap.value.has(documentId);
|
||||
return documentId in tabsMap.value;
|
||||
};
|
||||
|
||||
const getTab = (documentId: number): Tab | undefined => {
|
||||
return tabsMap.value.get(documentId);
|
||||
return tabsMap.value[documentId];
|
||||
};
|
||||
|
||||
const updateTabTitle = (documentId: number, title: string) => {
|
||||
const tab = tabsMap.value.get(documentId);
|
||||
const tab = tabsMap.value[documentId];
|
||||
if (tab) {
|
||||
tab.title = title;
|
||||
}
|
||||
@@ -55,6 +55,7 @@ export const useTabStore = defineStore('tab', () => {
|
||||
*/
|
||||
const addOrActivateTab = (document: Document) => {
|
||||
const documentId = document.id;
|
||||
if (documentId === undefined) return;
|
||||
|
||||
if (hasTab(documentId)) {
|
||||
// 标签页已存在,无需重复添加
|
||||
@@ -64,10 +65,10 @@ export const useTabStore = defineStore('tab', () => {
|
||||
// 创建新标签页
|
||||
const newTab: Tab = {
|
||||
documentId,
|
||||
title: document.title
|
||||
title: document.title || ''
|
||||
};
|
||||
|
||||
tabsMap.value.set(documentId, newTab);
|
||||
tabsMap.value[documentId] = newTab;
|
||||
tabOrder.value.push(documentId);
|
||||
};
|
||||
|
||||
@@ -81,7 +82,7 @@ export const useTabStore = defineStore('tab', () => {
|
||||
if (tabIndex === -1) return;
|
||||
|
||||
// 从映射和顺序数组中移除
|
||||
tabsMap.value.delete(documentId);
|
||||
delete tabsMap.value[documentId];
|
||||
tabOrder.value.splice(tabIndex, 1);
|
||||
|
||||
// 如果关闭的是当前文档,需要切换到其他文档
|
||||
@@ -111,7 +112,7 @@ export const useTabStore = defineStore('tab', () => {
|
||||
if (tabIndex === -1) return;
|
||||
|
||||
// 从映射和顺序数组中移除
|
||||
tabsMap.value.delete(documentId);
|
||||
delete tabsMap.value[documentId];
|
||||
tabOrder.value.splice(tabIndex, 1);
|
||||
});
|
||||
};
|
||||
@@ -150,10 +151,31 @@ export const useTabStore = defineStore('tab', () => {
|
||||
return tabOrder.value.indexOf(documentId);
|
||||
};
|
||||
|
||||
/**
|
||||
* 验证并清理无效的标签页
|
||||
*/
|
||||
const validateTabs = () => {
|
||||
const validDocIds = Object.keys(documentStore.documents).map(Number);
|
||||
|
||||
// 找出无效的标签页(文档已被删除)
|
||||
const invalidTabIds = tabOrder.value.filter(docId => !validDocIds.includes(docId));
|
||||
|
||||
if (invalidTabIds.length > 0) {
|
||||
// 批量清理无效标签页
|
||||
invalidTabIds.forEach(docId => {
|
||||
delete tabsMap.value[docId];
|
||||
});
|
||||
tabOrder.value = tabOrder.value.filter(docId => validDocIds.includes(docId));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化标签页(当前文档)
|
||||
*/
|
||||
const initializeTab = () => {
|
||||
// 先验证并清理无效的标签页(处理持久化的脏数据)
|
||||
validateTabs();
|
||||
|
||||
if (isTabsEnabled.value) {
|
||||
const currentDoc = documentStore.currentDocument;
|
||||
if (currentDoc) {
|
||||
@@ -224,12 +246,15 @@ export const useTabStore = defineStore('tab', () => {
|
||||
* 清空所有标签页
|
||||
*/
|
||||
const clearAllTabs = () => {
|
||||
tabsMap.value.clear();
|
||||
tabsMap.value = {};
|
||||
tabOrder.value = [];
|
||||
};
|
||||
|
||||
// === 公共API ===
|
||||
return {
|
||||
tabsMap,
|
||||
tabOrder,
|
||||
|
||||
// 状态
|
||||
tabs: readonly(tabs),
|
||||
draggedTabId,
|
||||
@@ -251,9 +276,12 @@ export const useTabStore = defineStore('tab', () => {
|
||||
initializeTab,
|
||||
clearAllTabs,
|
||||
updateTabTitle,
|
||||
validateTabs,
|
||||
|
||||
// 工具方法
|
||||
hasTab,
|
||||
getTab
|
||||
};
|
||||
}, {
|
||||
persist: false,
|
||||
});
|
||||
@@ -1,159 +1,170 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
import { SystemThemeType, ThemeType, ThemeColorConfig } from '@/../bindings/voidraft/internal/models/models';
|
||||
import { ThemeService } from '@/../bindings/voidraft/internal/services';
|
||||
import { useConfigStore } from './configStore';
|
||||
import { useEditorStore } from './editorStore';
|
||||
import type { ThemeColors } from '@/views/editor/theme/types';
|
||||
import { cloneThemeColors, FALLBACK_THEME_NAME, themePresetList, themePresetMap } from '@/views/editor/theme/presets';
|
||||
import {defineStore} from 'pinia';
|
||||
import {computed, ref} from 'vue';
|
||||
import {SystemThemeType} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {Type as ThemeType} from '@/../bindings/voidraft/internal/models/ent/theme/models';
|
||||
import {ThemeService} from '@/../bindings/voidraft/internal/services';
|
||||
import {useConfigStore} from './configStore';
|
||||
import {useEditorStore} from './editorStore';
|
||||
import type {ThemeColors} from '@/views/editor/theme/types';
|
||||
import {cloneThemeColors, FALLBACK_THEME_NAME, themePresetList, themePresetMap} from '@/views/editor/theme/presets';
|
||||
|
||||
type ThemeOption = { name: string; type: ThemeType };
|
||||
// 类型定义
|
||||
type ThemeOption = {name: string; type: ThemeType};
|
||||
|
||||
const resolveThemeName = (name?: string) =>
|
||||
name && themePresetMap[name] ? name : FALLBACK_THEME_NAME;
|
||||
// 解析主题名称,确保返回有效的主题
|
||||
const resolveThemeName = (name?: string): string =>
|
||||
name && themePresetMap[name] ? name : FALLBACK_THEME_NAME;
|
||||
|
||||
// 根据主题类型创建主题选项列表
|
||||
const createThemeOptions = (type: ThemeType): ThemeOption[] =>
|
||||
themePresetList
|
||||
.filter(preset => preset.type === type)
|
||||
.map(preset => ({ name: preset.name, type: preset.type }));
|
||||
|
||||
const darkThemeOptions = createThemeOptions(ThemeType.ThemeTypeDark);
|
||||
const lightThemeOptions = createThemeOptions(ThemeType.ThemeTypeLight);
|
||||
|
||||
const cloneColors = (colors: ThemeColorConfig): ThemeColors =>
|
||||
JSON.parse(JSON.stringify(colors)) as ThemeColors;
|
||||
|
||||
const getPresetColors = (name: string): ThemeColors => {
|
||||
const preset = themePresetMap[name] ?? themePresetMap[FALLBACK_THEME_NAME];
|
||||
const colors = cloneThemeColors(preset.colors);
|
||||
colors.themeName = name;
|
||||
return colors;
|
||||
};
|
||||
|
||||
const fetchThemeColors = async (themeName: string): Promise<ThemeColors> => {
|
||||
const safeName = resolveThemeName(themeName);
|
||||
try {
|
||||
const theme = await ThemeService.GetThemeByName(safeName);
|
||||
if (theme?.colors) {
|
||||
const colors = cloneColors(theme.colors);
|
||||
colors.themeName = safeName;
|
||||
return colors;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load theme override:', error);
|
||||
}
|
||||
return getPresetColors(safeName);
|
||||
};
|
||||
themePresetList
|
||||
.filter(preset => preset.type === type)
|
||||
.map(preset => ({name: preset.name, type: preset.type}));
|
||||
|
||||
export const useThemeStore = defineStore('theme', () => {
|
||||
const configStore = useConfigStore();
|
||||
const currentColors = ref<ThemeColors | null>(null);
|
||||
const configStore = useConfigStore();
|
||||
const currentColors = ref<ThemeColors | null>(null);
|
||||
|
||||
const currentTheme = computed(
|
||||
() => configStore.config?.appearance?.systemTheme || SystemThemeType.SystemThemeAuto
|
||||
);
|
||||
|
||||
const isDarkMode = computed(
|
||||
() =>
|
||||
currentTheme.value === SystemThemeType.SystemThemeDark ||
|
||||
(currentTheme.value === SystemThemeType.SystemThemeAuto &&
|
||||
window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
);
|
||||
|
||||
const availableThemes = computed<ThemeOption[]>(() =>
|
||||
isDarkMode.value ? darkThemeOptions : lightThemeOptions
|
||||
);
|
||||
|
||||
const applyThemeToDOM = (theme: SystemThemeType) => {
|
||||
const themeMap = {
|
||||
[SystemThemeType.SystemThemeAuto]: 'auto',
|
||||
[SystemThemeType.SystemThemeDark]: 'dark',
|
||||
[SystemThemeType.SystemThemeLight]: 'light',
|
||||
};
|
||||
document.documentElement.setAttribute('data-theme', themeMap[theme]);
|
||||
};
|
||||
|
||||
const loadThemeColors = async (themeName?: string) => {
|
||||
const targetName = resolveThemeName(
|
||||
themeName || configStore.config?.appearance?.currentTheme
|
||||
const currentTheme = computed(
|
||||
() => configStore.config?.appearance?.systemTheme || SystemThemeType.SystemThemeAuto
|
||||
);
|
||||
currentColors.value = await fetchThemeColors(targetName);
|
||||
};
|
||||
|
||||
const initializeTheme = async () => {
|
||||
applyThemeToDOM(currentTheme.value);
|
||||
await loadThemeColors();
|
||||
};
|
||||
const isDarkMode = computed(
|
||||
() =>
|
||||
currentTheme.value === SystemThemeType.SystemThemeDark ||
|
||||
(currentTheme.value === SystemThemeType.SystemThemeAuto &&
|
||||
window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
);
|
||||
|
||||
const setTheme = async (theme: SystemThemeType) => {
|
||||
await configStore.setSystemTheme(theme);
|
||||
applyThemeToDOM(theme);
|
||||
refreshEditorTheme();
|
||||
};
|
||||
// 根据当前模式动态计算可用主题列表
|
||||
const availableThemes = computed<ThemeOption[]>(() =>
|
||||
createThemeOptions(isDarkMode.value ? ThemeType.TypeDark : ThemeType.TypeLight)
|
||||
);
|
||||
|
||||
const switchToTheme = async (themeName: string) => {
|
||||
if (!themePresetMap[themeName]) {
|
||||
console.error('Theme not found:', themeName);
|
||||
return false;
|
||||
}
|
||||
// 应用主题到 DOM
|
||||
const applyThemeToDOM = (theme: SystemThemeType) => {
|
||||
const themeMap = {
|
||||
[SystemThemeType.SystemThemeAuto]: 'auto',
|
||||
[SystemThemeType.SystemThemeDark]: 'dark',
|
||||
[SystemThemeType.SystemThemeLight]: 'light',
|
||||
};
|
||||
document.documentElement.setAttribute('data-theme', themeMap[theme]);
|
||||
};
|
||||
|
||||
await loadThemeColors(themeName);
|
||||
await configStore.setCurrentTheme(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
// 获取预设主题颜色
|
||||
const getPresetColors = (name: string): ThemeColors => {
|
||||
const preset = themePresetMap[name] ?? themePresetMap[FALLBACK_THEME_NAME];
|
||||
const colors = cloneThemeColors(preset.colors);
|
||||
colors.themeName = name;
|
||||
return colors;
|
||||
};
|
||||
|
||||
const updateCurrentColors = (colors: Partial<ThemeColors>) => {
|
||||
if (!currentColors.value) return;
|
||||
Object.assign(currentColors.value, colors);
|
||||
};
|
||||
// 从服务器获取主题颜色
|
||||
const fetchThemeColors = async (themeName: string): Promise<ThemeColors> => {
|
||||
const safeName = resolveThemeName(themeName);
|
||||
try {
|
||||
const theme = await ThemeService.GetThemeByName(safeName);
|
||||
if (theme?.colors) {
|
||||
const colors = cloneThemeColors(theme.colors as ThemeColors);
|
||||
colors.themeName = safeName;
|
||||
return colors;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load theme override:', error);
|
||||
}
|
||||
return getPresetColors(safeName);
|
||||
};
|
||||
|
||||
const saveCurrentTheme = async () => {
|
||||
if (!currentColors.value) {
|
||||
throw new Error('No theme selected');
|
||||
}
|
||||
// 加载主题颜色
|
||||
const loadThemeColors = async (themeName?: string) => {
|
||||
const targetName = resolveThemeName(
|
||||
themeName || configStore.config?.appearance?.currentTheme
|
||||
);
|
||||
currentColors.value = await fetchThemeColors(targetName);
|
||||
};
|
||||
|
||||
const themeName = resolveThemeName(currentColors.value.themeName);
|
||||
currentColors.value.themeName = themeName;
|
||||
// 初始化主题
|
||||
const initTheme = async () => {
|
||||
applyThemeToDOM(currentTheme.value);
|
||||
await loadThemeColors();
|
||||
refreshEditorTheme();
|
||||
};
|
||||
|
||||
await ThemeService.UpdateTheme(themeName, currentColors.value as unknown as ThemeColorConfig);
|
||||
// 设置系统主题
|
||||
const setTheme = async (theme: SystemThemeType) => {
|
||||
await configStore.setSystemTheme(theme);
|
||||
applyThemeToDOM(theme);
|
||||
refreshEditorTheme();
|
||||
};
|
||||
|
||||
await loadThemeColors(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
// 切换到指定主题
|
||||
const switchToTheme = async (themeName: string) => {
|
||||
if (!themePresetMap[themeName]) {
|
||||
console.error('Theme not found:', themeName);
|
||||
return false;
|
||||
}
|
||||
|
||||
const resetCurrentTheme = async () => {
|
||||
if (!currentColors.value) {
|
||||
throw new Error('No theme selected');
|
||||
}
|
||||
await loadThemeColors(themeName);
|
||||
await configStore.setCurrentTheme(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
|
||||
const themeName = resolveThemeName(currentColors.value.themeName);
|
||||
await ThemeService.ResetTheme(themeName);
|
||||
// 更新当前主题颜色
|
||||
const updateCurrentColors = (colors: Partial<ThemeColors>) => {
|
||||
if (!currentColors.value) return;
|
||||
Object.assign(currentColors.value, colors);
|
||||
};
|
||||
|
||||
await loadThemeColors(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
// 保存当前主题
|
||||
const saveCurrentTheme = async () => {
|
||||
if (!currentColors.value) {
|
||||
throw new Error('No theme selected');
|
||||
}
|
||||
|
||||
const refreshEditorTheme = () => {
|
||||
applyThemeToDOM(currentTheme.value);
|
||||
const editorStore = useEditorStore();
|
||||
editorStore?.applyThemeSettings();
|
||||
};
|
||||
const themeName = resolveThemeName(currentColors.value.themeName);
|
||||
currentColors.value.themeName = themeName;
|
||||
|
||||
return {
|
||||
availableThemes,
|
||||
currentTheme,
|
||||
currentColors,
|
||||
isDarkMode,
|
||||
setTheme,
|
||||
switchToTheme,
|
||||
initializeTheme,
|
||||
updateCurrentColors,
|
||||
saveCurrentTheme,
|
||||
resetCurrentTheme,
|
||||
refreshEditorTheme,
|
||||
applyThemeToDOM,
|
||||
};
|
||||
await ThemeService.UpdateTheme(themeName, currentColors.value);
|
||||
|
||||
await loadThemeColors(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
|
||||
// 重置当前主题到默认值
|
||||
const resetCurrentTheme = async () => {
|
||||
if (!currentColors.value) {
|
||||
throw new Error('No theme selected');
|
||||
}
|
||||
|
||||
const themeName = resolveThemeName(currentColors.value.themeName);
|
||||
await ThemeService.ResetTheme(themeName);
|
||||
|
||||
await loadThemeColors(themeName);
|
||||
refreshEditorTheme();
|
||||
return true;
|
||||
};
|
||||
|
||||
// 刷新编辑器主题
|
||||
const refreshEditorTheme = () => {
|
||||
applyThemeToDOM(currentTheme.value);
|
||||
const editorStore = useEditorStore();
|
||||
editorStore?.applyThemeSettings();
|
||||
};
|
||||
|
||||
return {
|
||||
availableThemes,
|
||||
currentTheme,
|
||||
currentColors,
|
||||
isDarkMode,
|
||||
setTheme,
|
||||
switchToTheme,
|
||||
initTheme,
|
||||
updateCurrentColors,
|
||||
saveCurrentTheme,
|
||||
resetCurrentTheme,
|
||||
refreshEditorTheme,
|
||||
applyThemeToDOM,
|
||||
};
|
||||
});
|
||||
|
||||
68
frontend/src/views/editor/basic/cursorPositionExtension.ts
Normal file
68
frontend/src/views/editor/basic/cursorPositionExtension.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import {EditorView, ViewPlugin, ViewUpdate} from '@codemirror/view';
|
||||
import {useDocumentStore} from '@/stores/documentStore';
|
||||
import {createDebounce} from '@/common/utils/debounce';
|
||||
|
||||
/**
|
||||
* 光标位置持久化扩展
|
||||
* 实时监听光标位置变化并持久化到 documentStore
|
||||
*/
|
||||
export function createCursorPositionExtension(documentId: number) {
|
||||
return ViewPlugin.fromClass(
|
||||
class CursorPositionPlugin {
|
||||
private readonly documentStore = useDocumentStore();
|
||||
private readonly debouncedSave;
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
const {debouncedFn, flush} = createDebounce(
|
||||
() => this.saveCursorPosition(),
|
||||
{delay: 1000}
|
||||
);
|
||||
this.debouncedSave = {fn: debouncedFn, flush};
|
||||
|
||||
// 初始化时保存一次光标位置
|
||||
this.saveCursorPosition();
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
// 只在选择变化时触发
|
||||
if (!update.selectionSet) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 防抖保存光标位置
|
||||
this.debouncedSave.fn();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
// 销毁时立即执行待保存的操作
|
||||
this.debouncedSave.flush();
|
||||
// 再保存一次确保最新状态
|
||||
this.saveCursorPosition();
|
||||
}
|
||||
|
||||
private saveCursorPosition() {
|
||||
const cursorPos = this.view.state.selection.main.head;
|
||||
if (!this.documentStore.documentStates[documentId]) {
|
||||
this.documentStore.documentStates[documentId] = {cursorPos};
|
||||
} else {
|
||||
this.documentStore.documentStates[documentId].cursorPos = cursorPos;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动到当前光标位置(视口中心)
|
||||
* @param view 编辑器视图
|
||||
*/
|
||||
export function scrollToCursor(view: EditorView) {
|
||||
const cursorPos = view.state.selection.main.head;
|
||||
view.dispatch({
|
||||
effects: EditorView.scrollIntoView(cursorPos, {
|
||||
y: 'center',
|
||||
x: 'center'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type {MenuSchemaNode} from '../contextMenu/menuSchema';
|
||||
import {getActiveNoteBlock} from '../codeblock/state';
|
||||
import {blockImageEnabledFacet, copyBlockImageCommand} from './index';
|
||||
|
||||
|
||||
export const blockImageMenuNodes: MenuSchemaNode[] = [
|
||||
{
|
||||
id: 'copy-block-image',
|
||||
labelKey: 'extensions.blockImage.copyMenu',
|
||||
command: copyBlockImageCommand,
|
||||
visible: context =>
|
||||
context.view.state.facet(blockImageEnabledFacet) &&
|
||||
Boolean(getActiveNoteBlock(context.view.state)),
|
||||
enabled: context =>
|
||||
context.view.state.facet(blockImageEnabledFacet) &&
|
||||
Boolean(getActiveNoteBlock(context.view.state)),
|
||||
},
|
||||
];
|
||||
|
||||
319
frontend/src/views/editor/extensions/blockImage/index.ts
Normal file
319
frontend/src/views/editor/extensions/blockImage/index.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
import {snapdom} from '@zumer/snapdom';
|
||||
import {syntaxTree, highlightingFor} from '@codemirror/language';
|
||||
import {Highlighter, highlightTree} from '@lezer/highlight';
|
||||
import {Facet, type Extension} from '@codemirror/state';
|
||||
import {EditorView, Command} from '@codemirror/view';
|
||||
import type {Block} from '../codeblock/types';
|
||||
import {blockState, getActiveNoteBlock} from '../codeblock/state';
|
||||
|
||||
/**
|
||||
* 高亮片段信息
|
||||
*/
|
||||
interface HighlightSpan {
|
||||
from: number;
|
||||
to: number;
|
||||
cssClass: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从语法树获取指定范围的高亮信息
|
||||
*/
|
||||
function getHighlights(view: EditorView, from: number, to: number): HighlightSpan[] {
|
||||
const tree = syntaxTree(view.state);
|
||||
const highlights: HighlightSpan[] = [];
|
||||
|
||||
if (tree.length === 0) {
|
||||
return highlights;
|
||||
}
|
||||
|
||||
const highlighter: Highlighter = {
|
||||
style: tags => highlightingFor(view.state, tags),
|
||||
};
|
||||
|
||||
highlightTree(
|
||||
tree,
|
||||
highlighter,
|
||||
(hlFrom, hlTo, cssClass) => {
|
||||
if (hlFrom < to && hlTo > from) {
|
||||
highlights.push({
|
||||
from: Math.max(hlFrom, from),
|
||||
to: Math.min(hlTo, to),
|
||||
cssClass: cssClass || '',
|
||||
});
|
||||
}
|
||||
},
|
||||
from,
|
||||
to,
|
||||
);
|
||||
|
||||
return highlights;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建带高亮的单行元素
|
||||
*/
|
||||
function createHighlightedLine(
|
||||
lineText: string,
|
||||
lineFrom: number,
|
||||
lineTo: number,
|
||||
highlights: HighlightSpan[],
|
||||
): HTMLElement {
|
||||
const lineElement = document.createElement('div');
|
||||
lineElement.className = 'cm-line';
|
||||
lineElement.style.whiteSpace = 'pre';
|
||||
|
||||
if (highlights.length === 0 || lineText.length === 0) {
|
||||
lineElement.textContent = lineText || ' ';
|
||||
return lineElement;
|
||||
}
|
||||
|
||||
const spans: Array<{text: string; cssClass: string}> = [];
|
||||
let pos = lineFrom;
|
||||
|
||||
const lineHighlights = highlights
|
||||
.filter(h => h.from < lineTo && h.to > lineFrom)
|
||||
.sort((a, b) => a.from - b.from);
|
||||
|
||||
for (const hl of lineHighlights) {
|
||||
if (hl.from > pos) {
|
||||
spans.push({
|
||||
text: lineText.slice(pos - lineFrom, hl.from - lineFrom),
|
||||
cssClass: '',
|
||||
});
|
||||
}
|
||||
|
||||
const hlStart = Math.max(hl.from, lineFrom);
|
||||
const hlEnd = Math.min(hl.to, lineTo);
|
||||
spans.push({
|
||||
text: lineText.slice(hlStart - lineFrom, hlEnd - lineFrom),
|
||||
cssClass: hl.cssClass,
|
||||
});
|
||||
|
||||
pos = hlEnd;
|
||||
}
|
||||
|
||||
if (pos < lineTo) {
|
||||
spans.push({
|
||||
text: lineText.slice(pos - lineFrom),
|
||||
cssClass: '',
|
||||
});
|
||||
}
|
||||
|
||||
for (const span of spans) {
|
||||
if (span.cssClass) {
|
||||
const spanElement = document.createElement('span');
|
||||
spanElement.className = span.cssClass;
|
||||
spanElement.textContent = span.text;
|
||||
lineElement.appendChild(spanElement);
|
||||
} else {
|
||||
lineElement.appendChild(document.createTextNode(span.text));
|
||||
}
|
||||
}
|
||||
|
||||
return lineElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建用于截图的块 DOM
|
||||
*/
|
||||
function inlineStyle(style: CSSStyleDeclaration, props: string[]): string {
|
||||
return props
|
||||
.map(prop => {
|
||||
const val = style.getPropertyValue(prop);
|
||||
return val ? `${prop}:${val};` : '';
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
function getBlockDomElement(view: EditorView, block: Block): HTMLElement | null {
|
||||
try {
|
||||
const blocks = view.state.field(blockState, false);
|
||||
if (!blocks) return null;
|
||||
|
||||
const blockIndex = blocks.indexOf(block);
|
||||
const isEvenBlock = blockIndex % 2 === 0;
|
||||
|
||||
const blockLayerElem = view.dom.querySelector(
|
||||
`.code-blocks-layer .${isEvenBlock ? 'block-even' : 'block-odd'}`,
|
||||
) as HTMLElement | null;
|
||||
const backgroundColor =
|
||||
blockLayerElem?.ownerDocument
|
||||
? getComputedStyle(blockLayerElem).backgroundColor
|
||||
: isEvenBlock
|
||||
? '#252B37'
|
||||
: '#213644';
|
||||
|
||||
const contentDom = view.dom.querySelector('.cm-content') as HTMLElement | null;
|
||||
const sourceStyle = contentDom ? getComputedStyle(contentDom) : getComputedStyle(view.dom);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.className = 'cm-editor cm-focused block-export-wrapper';
|
||||
container.style.cssText = `
|
||||
padding: 18px 22px;
|
||||
background-color: ${backgroundColor};
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
|
||||
display: inline-block;
|
||||
min-width: 360px;
|
||||
max-width: 960px;
|
||||
color: ${sourceStyle.color};
|
||||
font-family: ${sourceStyle.fontFamily};
|
||||
font-size: ${sourceStyle.fontSize};
|
||||
line-height: ${sourceStyle.lineHeight};
|
||||
position: relative;
|
||||
`;
|
||||
|
||||
const contentWrapper = document.createElement('div');
|
||||
contentWrapper.className = 'cm-content';
|
||||
contentWrapper.style.whiteSpace = 'pre';
|
||||
contentWrapper.style.cssText += inlineStyle(sourceStyle, [
|
||||
'color',
|
||||
'font-family',
|
||||
'font-size',
|
||||
'font-weight',
|
||||
'font-style',
|
||||
'line-height',
|
||||
'letter-spacing',
|
||||
'tab-size',
|
||||
'text-rendering',
|
||||
'background',
|
||||
'background-color',
|
||||
'text-shadow',
|
||||
]);
|
||||
|
||||
const highlights = getHighlights(view, block.content.from, block.content.to);
|
||||
const fromLine = view.state.doc.lineAt(block.content.from);
|
||||
const toLine = view.state.doc.lineAt(block.content.to);
|
||||
for (let lineNum = fromLine.number; lineNum <= toLine.number; lineNum++) {
|
||||
const line = view.state.doc.line(lineNum);
|
||||
const lineElement = createHighlightedLine(line.text, line.from, line.to, highlights);
|
||||
contentWrapper.appendChild(lineElement);
|
||||
}
|
||||
|
||||
if (block.language.name && block.language.name !== 'text') {
|
||||
const langLabel = document.createElement('div');
|
||||
langLabel.className = 'block-language-label';
|
||||
langLabel.textContent = block.language.name;
|
||||
langLabel.style.cssText = `
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 10px;
|
||||
padding: 3px 8px;
|
||||
background-color: rgba(0, 0, 0, 0.35);
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
font-size: 11px;
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
font-weight: 600;
|
||||
border-radius: 4px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
pointer-events: none;
|
||||
`;
|
||||
container.appendChild(langLabel);
|
||||
}
|
||||
|
||||
container.appendChild(contentWrapper);
|
||||
return container;
|
||||
} catch (error) {
|
||||
console.error('[blockImage] Failed to build block DOM:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Canvas 转换为 PNG Blob
|
||||
*/
|
||||
function canvasToPngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(blob => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject(new Error('Canvas toBlob returned null'));
|
||||
}
|
||||
}, 'image/png');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入剪贴板(PNG)
|
||||
*/
|
||||
async function writeImageToClipboard(blob: Blob): Promise<void> {
|
||||
const ClipboardItemCtor = (window as any).ClipboardItem;
|
||||
if (ClipboardItemCtor && navigator.clipboard?.write) {
|
||||
const item = new ClipboardItemCtor({'image/png': blob});
|
||||
await navigator.clipboard.write([item]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将当前活动块导出为图片并复制到剪贴板
|
||||
*/
|
||||
async function copyActiveBlockAsImage(view: EditorView): Promise<boolean> {
|
||||
const activeBlock = getActiveNoteBlock(view.state);
|
||||
if (!activeBlock) {
|
||||
console.warn('[blockImage] No active block found');
|
||||
return false;
|
||||
}
|
||||
|
||||
const targetDom = view.scrollDOM || document.body;
|
||||
const prevCursor = (targetDom as HTMLElement).style.cursor;
|
||||
(targetDom as HTMLElement).style.cursor = 'progress';
|
||||
|
||||
const blockDom = getBlockDomElement(view, activeBlock);
|
||||
if (!blockDom) {
|
||||
console.warn('[blockImage] Cannot create block DOM');
|
||||
(targetDom as HTMLElement).style.cursor = prevCursor;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 将节点挂到文档外层,确保样式可用
|
||||
const mount = document.createElement('div');
|
||||
mount.style.cssText = 'position: fixed; left: -10000px; top: -10000px; pointer-events: none; z-index: -1;';
|
||||
mount.appendChild(blockDom);
|
||||
document.body.appendChild(mount);
|
||||
|
||||
try {
|
||||
const canvas = await snapdom.toCanvas(blockDom, {
|
||||
scale: 2,
|
||||
dpr: window.devicePixelRatio || 1,
|
||||
cache: 'auto',
|
||||
backgroundColor: getComputedStyle(blockDom).backgroundColor,
|
||||
outerShadows: false,
|
||||
});
|
||||
|
||||
const blob = await canvasToPngBlob(canvas);
|
||||
await writeImageToClipboard(blob);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[blockImage] Failed to copy block image:', error);
|
||||
return false;
|
||||
} finally {
|
||||
mount.remove();
|
||||
(targetDom as HTMLElement).style.cursor = prevCursor;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 命令:复制当前块为图片
|
||||
*/
|
||||
export const copyBlockImageCommand: Command = view => {
|
||||
void copyActiveBlockAsImage(view);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const blockImageEnabledFacet = Facet.define<boolean, boolean>({
|
||||
combine: values => values.some(Boolean),
|
||||
});
|
||||
|
||||
/**
|
||||
* BlockImage 扩展入口
|
||||
*/
|
||||
export function createBlockImageExtension(): Extension {
|
||||
return [
|
||||
blockImageEnabledFacet.of(true),
|
||||
];
|
||||
}
|
||||
|
||||
export default createBlockImageExtension;
|
||||
@@ -7,6 +7,9 @@ import { StateField, RangeSetBuilder, EditorState, Transaction } from "@codemirr
|
||||
import { blockState } from "./state";
|
||||
import { codeBlockEvent, USER_EVENTS } from "./annotation";
|
||||
|
||||
// IME 输入状态
|
||||
let isComposing = false;
|
||||
|
||||
/**
|
||||
* 块开始装饰组件
|
||||
*/
|
||||
@@ -151,14 +154,18 @@ const blockLayer = layer({
|
||||
const fromCoordsTop = fromLineBlock.top + view.documentTop;
|
||||
let toCoordsBottom = toLineBlock.bottom + view.documentTop;
|
||||
|
||||
// 对最后一个块进行特殊处理,让它直接延伸到底部
|
||||
if (idx === blocks.length - 1) {
|
||||
const editorHeight = view.dom.clientHeight;
|
||||
const contentBottom = toCoordsBottom - view.documentTop + view.documentPadding.top;
|
||||
// 计算需要添加到最后一个块的额外高度,以覆盖 scrollPastEnd 添加的额外滚动空间
|
||||
// scrollPastEnd 会在文档底部添加相当于 scrollDOM.clientHeight 的额外空间
|
||||
// 当滚动到最底部时,顶部仍会显示一行(defaultLineHeight),需要减去这部分
|
||||
const editorHeight = view.scrollDOM.clientHeight;
|
||||
const extraHeight = editorHeight - (
|
||||
view.defaultLineHeight + // 当滚动到最底部时,顶部仍显示一行
|
||||
view.documentPadding.top +
|
||||
8 // 额外的边距调整
|
||||
);
|
||||
|
||||
// 让最后一个块直接延伸到编辑器底部
|
||||
if (contentBottom < editorHeight) {
|
||||
const extraHeight = editorHeight - contentBottom - 10;
|
||||
if (extraHeight > 0) {
|
||||
toCoordsBottom += extraHeight;
|
||||
}
|
||||
}
|
||||
@@ -218,9 +225,10 @@ const preventFirstBlockFromBeingDeleted = EditorState.changeFilter.of((tr: any)
|
||||
|
||||
/**
|
||||
* 防止选择在第一个块之前
|
||||
* 使用 transactionFilter 来确保选择不会在第一个块之前
|
||||
*/
|
||||
const preventSelectionBeforeFirstBlock = EditorState.transactionFilter.of((tr: any) => {
|
||||
if (isComposing) return tr;
|
||||
|
||||
if (tr.annotation(codeBlockEvent)) {
|
||||
return tr;
|
||||
}
|
||||
@@ -252,6 +260,24 @@ const preventSelectionBeforeFirstBlock = EditorState.transactionFilter.of((tr: a
|
||||
return tr;
|
||||
});
|
||||
|
||||
// IME 状态同步
|
||||
const imeStateSynchronizer = ViewPlugin.fromClass(
|
||||
class {
|
||||
constructor(view: EditorView) {
|
||||
isComposing = view.composing || view.compositionStarted;
|
||||
}
|
||||
|
||||
update(update: any) {
|
||||
const view = update.view as EditorView;
|
||||
isComposing = view.composing || view.compositionStarted;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
isComposing = false;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取块装饰扩展 - 简化选项
|
||||
*/
|
||||
@@ -267,6 +293,7 @@ export function getBlockDecorationExtensions(options: {
|
||||
atomicNoteBlock,
|
||||
preventFirstBlockFromBeingDeleted,
|
||||
preventSelectionBeforeFirstBlock,
|
||||
imeStateSynchronizer,
|
||||
];
|
||||
|
||||
if (showBackground) {
|
||||
|
||||
@@ -1,141 +1,137 @@
|
||||
import { EditorView } from '@codemirror/view';
|
||||
import { Extension } from '@codemirror/state';
|
||||
import { copyCommand, cutCommand, pasteCommand } from '../codeblock/copyPaste';
|
||||
import { KeyBindingCommand } from '../../../../../bindings/voidraft/internal/models/models';
|
||||
import { useKeybindingStore } from '@/stores/keybindingStore';
|
||||
import { undo, redo } from '@codemirror/commands';
|
||||
import {EditorView} from '@codemirror/view';
|
||||
import {Extension} from '@codemirror/state';
|
||||
import {copyCommand, cutCommand, pasteCommand} from '../codeblock/copyPaste';
|
||||
import {KeyBindingName} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {useKeybindingStore} from '@/stores/keybindingStore';
|
||||
import {redo, undo} from '@codemirror/commands';
|
||||
import i18n from '@/i18n';
|
||||
import { useSystemStore } from '@/stores/systemStore';
|
||||
import { showContextMenu } from './manager';
|
||||
import {
|
||||
buildRegisteredMenu,
|
||||
createMenuContext,
|
||||
registerMenuNodes
|
||||
} from './menuSchema';
|
||||
import type { MenuSchemaNode } from './menuSchema';
|
||||
import {useSystemStore} from '@/stores/systemStore';
|
||||
import {showContextMenu} from './manager';
|
||||
import type {MenuSchemaNode} from './menuSchema';
|
||||
import {buildRegisteredMenu, createMenuContext, registerMenuNodes} from './menuSchema';
|
||||
import {blockImageMenuNodes} from '../blockImage/contextMenu';
|
||||
|
||||
|
||||
function t(key: string): string {
|
||||
return i18n.global.t(key);
|
||||
return i18n.global.t(key);
|
||||
}
|
||||
|
||||
|
||||
function formatKeyBinding(keyBinding: string): string {
|
||||
const systemStore = useSystemStore();
|
||||
const isMac = systemStore.isMacOS;
|
||||
const systemStore = useSystemStore();
|
||||
const isMac = systemStore.isMacOS;
|
||||
|
||||
return keyBinding
|
||||
.replace("Mod", isMac ? "Cmd" : "Ctrl")
|
||||
.replace("Shift", "Shift")
|
||||
.replace("Alt", isMac ? "Option" : "Alt")
|
||||
.replace("Ctrl", isMac ? "Ctrl" : "Ctrl")
|
||||
.replace(/-/g, " + ");
|
||||
return keyBinding
|
||||
.replace("Mod", isMac ? "Cmd" : "Ctrl")
|
||||
.replace("Alt", isMac ? "Option" : "Alt")
|
||||
.replace(/-/g, " + ");
|
||||
}
|
||||
|
||||
const shortcutCache = new Map<KeyBindingCommand, string>();
|
||||
const shortcutCache = new Map<KeyBindingName, string>();
|
||||
|
||||
|
||||
function getShortcutText(command?: KeyBindingCommand): string {
|
||||
if (command === undefined) {
|
||||
function getShortcutText(keyBindingKey?: KeyBindingName): string {
|
||||
if (keyBindingKey === undefined) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const cached = shortcutCache.get(keyBindingKey);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const keybindingStore = useKeybindingStore();
|
||||
// binding.key 是命令标识符,binding.command 是快捷键组合
|
||||
const binding = keybindingStore.keyBindings.find(
|
||||
(kb) => kb.key === keyBindingKey && kb.enabled
|
||||
);
|
||||
|
||||
if (binding?.key) {
|
||||
const formatted = formatKeyBinding(binding.key);
|
||||
shortcutCache.set(keyBindingKey, formatted);
|
||||
return formatted;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("An error occurred while getting the shortcut:", error);
|
||||
}
|
||||
|
||||
shortcutCache.set(keyBindingKey, "");
|
||||
return "";
|
||||
}
|
||||
|
||||
const cached = shortcutCache.get(command);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const keybindingStore = useKeybindingStore();
|
||||
const binding = keybindingStore.keyBindings.find(
|
||||
(kb) => kb.command === command && kb.enabled
|
||||
);
|
||||
|
||||
if (binding?.key) {
|
||||
const formatted = formatKeyBinding(binding.key);
|
||||
shortcutCache.set(command, formatted);
|
||||
return formatted;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("An error occurred while getting the shortcut:", error);
|
||||
}
|
||||
|
||||
shortcutCache.set(command, "");
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
function getBuiltinMenuNodes(): MenuSchemaNode[] {
|
||||
return [
|
||||
{
|
||||
id: "copy",
|
||||
labelKey: "keybindings.commands.blockCopy",
|
||||
command: copyCommand,
|
||||
shortcutCommand: KeyBindingCommand.BlockCopyCommand,
|
||||
enabled: (context) => context.hasSelection
|
||||
},
|
||||
{
|
||||
id: "cut",
|
||||
labelKey: "keybindings.commands.blockCut",
|
||||
command: cutCommand,
|
||||
shortcutCommand: KeyBindingCommand.BlockCutCommand,
|
||||
visible: (context) => context.isEditable,
|
||||
enabled: (context) => context.hasSelection && context.isEditable
|
||||
},
|
||||
{
|
||||
id: "paste",
|
||||
labelKey: "keybindings.commands.blockPaste",
|
||||
command: pasteCommand,
|
||||
shortcutCommand: KeyBindingCommand.BlockPasteCommand,
|
||||
visible: (context) => context.isEditable
|
||||
},
|
||||
{
|
||||
id: "undo",
|
||||
labelKey: "keybindings.commands.historyUndo",
|
||||
command: undo,
|
||||
shortcutCommand: KeyBindingCommand.HistoryUndoCommand,
|
||||
visible: (context) => context.isEditable
|
||||
},
|
||||
{
|
||||
id: "redo",
|
||||
labelKey: "keybindings.commands.historyRedo",
|
||||
command: redo,
|
||||
shortcutCommand: KeyBindingCommand.HistoryRedoCommand,
|
||||
visible: (context) => context.isEditable
|
||||
}
|
||||
];
|
||||
function builtinMenuNodes(): MenuSchemaNode[] {
|
||||
return [
|
||||
{
|
||||
id: "copy",
|
||||
labelKey: "keybindings.commands.blockCopy",
|
||||
command: copyCommand,
|
||||
keyBindingName: KeyBindingName.BlockCopy,
|
||||
enabled: (context) => context.hasSelection
|
||||
},
|
||||
{
|
||||
id: "cut",
|
||||
labelKey: "keybindings.commands.blockCut",
|
||||
command: cutCommand,
|
||||
keyBindingName: KeyBindingName.BlockCut,
|
||||
visible: (context) => context.isEditable,
|
||||
enabled: (context) => context.hasSelection && context.isEditable
|
||||
},
|
||||
{
|
||||
id: "paste",
|
||||
labelKey: "keybindings.commands.blockPaste",
|
||||
command: pasteCommand,
|
||||
keyBindingName: KeyBindingName.BlockPaste,
|
||||
visible: (context) => context.isEditable
|
||||
},
|
||||
{
|
||||
id: "undo",
|
||||
labelKey: "keybindings.commands.historyUndo",
|
||||
command: undo,
|
||||
keyBindingName: KeyBindingName.HistoryUndo,
|
||||
visible: (context) => context.isEditable
|
||||
},
|
||||
{
|
||||
id: "redo",
|
||||
labelKey: "keybindings.commands.historyRedo",
|
||||
command: redo,
|
||||
keyBindingName: KeyBindingName.HistoryRedo,
|
||||
visible: (context) => context.isEditable
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
let builtinMenuRegistered = false;
|
||||
|
||||
function ensureBuiltinMenuRegistered(): void {
|
||||
if (builtinMenuRegistered) return;
|
||||
registerMenuNodes(getBuiltinMenuNodes());
|
||||
builtinMenuRegistered = true;
|
||||
if (builtinMenuRegistered) return;
|
||||
registerMenuNodes([...builtinMenuNodes(), ...blockImageMenuNodes]);
|
||||
builtinMenuRegistered = true;
|
||||
}
|
||||
|
||||
|
||||
export function createEditorContextMenu(): Extension {
|
||||
ensureBuiltinMenuRegistered();
|
||||
ensureBuiltinMenuRegistered();
|
||||
|
||||
return EditorView.domEventHandlers({
|
||||
contextmenu: (event, view) => {
|
||||
event.preventDefault();
|
||||
return EditorView.domEventHandlers({
|
||||
contextmenu: (event, view) => {
|
||||
event.preventDefault();
|
||||
|
||||
const context = createMenuContext(view, event as MouseEvent);
|
||||
const menuItems = buildRegisteredMenu(context, {
|
||||
translate: t,
|
||||
formatShortcut: getShortcutText
|
||||
});
|
||||
const context = createMenuContext(view, event as MouseEvent);
|
||||
const menuItems = buildRegisteredMenu(context, {
|
||||
translate: t,
|
||||
formatShortcut: getShortcutText
|
||||
});
|
||||
|
||||
if (menuItems.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if (menuItems.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
showContextMenu(view, event.clientX, event.clientY, menuItems);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
showContextMenu(view, event.clientX, event.clientY, menuItems);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default createEditorContextMenu;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EditorView } from '@codemirror/view';
|
||||
import { EditorState } from '@codemirror/state';
|
||||
import type { KeyBindingCommand } from '../../../../../bindings/voidraft/internal/models/models';
|
||||
import { KeyBindingName } from '@/../bindings/voidraft/internal/models/models';
|
||||
|
||||
export interface MenuContext {
|
||||
view: EditorView;
|
||||
@@ -16,7 +16,7 @@ export type MenuSchemaNode =
|
||||
type?: "action";
|
||||
labelKey: string;
|
||||
command?: (view: EditorView) => boolean;
|
||||
shortcutCommand?: KeyBindingCommand;
|
||||
keyBindingName?: KeyBindingName;
|
||||
visible?: (context: MenuContext) => boolean;
|
||||
enabled?: (context: MenuContext) => boolean;
|
||||
}
|
||||
@@ -37,7 +37,7 @@ export interface RenderMenuItem {
|
||||
|
||||
interface MenuBuildOptions {
|
||||
translate: (key: string) => string;
|
||||
formatShortcut: (command?: KeyBindingCommand) => string;
|
||||
formatShortcut: (keyBindingKey?: KeyBindingName) => string;
|
||||
}
|
||||
|
||||
const menuRegistry: MenuSchemaNode[] = [];
|
||||
@@ -89,7 +89,7 @@ function convertNode(
|
||||
}
|
||||
|
||||
const disabled = node.enabled ? !node.enabled(context) : false;
|
||||
const shortcut = options.formatShortcut(node.shortcutCommand);
|
||||
const shortcut = options.formatShortcut(node.keyBindingName);
|
||||
|
||||
return {
|
||||
id: node.id,
|
||||
|
||||
@@ -66,8 +66,14 @@ export function handleCodeBlock(
|
||||
ctx.seen.add(nf);
|
||||
ranges.push([nf, nt]);
|
||||
|
||||
// When cursor/selection is in this code block, don't add any decorations
|
||||
// This allows the selection background to be visible
|
||||
if (inCursor) return;
|
||||
|
||||
const startLine = ctx.view.state.doc.lineAt(nf);
|
||||
const endLine = ctx.view.state.doc.lineAt(nt);
|
||||
|
||||
// Add background decorations for each line
|
||||
for (let num = startLine.number; num <= endLine.number; num++) {
|
||||
const line = ctx.view.state.doc.line(num);
|
||||
let deco = DECO_CODEBLOCK_LINE;
|
||||
@@ -76,14 +82,14 @@ export function handleCodeBlock(
|
||||
else if (num === endLine.number) deco = DECO_CODEBLOCK_END;
|
||||
ctx.items.push({ from: line.from, to: line.from, deco });
|
||||
}
|
||||
if (!inCursor) {
|
||||
const codeInfo = node.getChild('CodeInfo');
|
||||
const codeMarks = node.getChildren('CodeMark');
|
||||
const language = codeInfo ? ctx.view.state.doc.sliceString(codeInfo.from, codeInfo.to).trim() : null;
|
||||
ctx.items.push({ from: startLine.to, to: startLine.to, deco: Decoration.widget({ widget: new CodeBlockInfoWidget(nf, nt, language), side: 1 }), priority: 1 });
|
||||
if (codeInfo) ctx.items.push({ from: codeInfo.from, to: codeInfo.to, deco: invisibleDecoration });
|
||||
for (const mark of codeMarks) ctx.items.push({ from: mark.from, to: mark.to, deco: invisibleDecoration });
|
||||
}
|
||||
|
||||
// Add language info widget and hide code marks
|
||||
const codeInfo = node.getChild('CodeInfo');
|
||||
const codeMarks = node.getChildren('CodeMark');
|
||||
const language = codeInfo ? ctx.view.state.doc.sliceString(codeInfo.from, codeInfo.to).trim() : null;
|
||||
ctx.items.push({ from: startLine.to, to: startLine.to, deco: Decoration.widget({ widget: new CodeBlockInfoWidget(nf, nt, language), side: 1 }), priority: 1 });
|
||||
if (codeInfo) ctx.items.push({ from: codeInfo.from, to: codeInfo.to, deco: invisibleDecoration });
|
||||
for (const mark of codeMarks) ctx.items.push({ from: mark.from, to: mark.to, deco: invisibleDecoration });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
572
frontend/src/views/editor/extensions/minimap/blockManager.ts
Normal file
572
frontend/src/views/editor/extensions/minimap/blockManager.ts
Normal file
@@ -0,0 +1,572 @@
|
||||
import { EditorView } from '@codemirror/view';
|
||||
import { EditorState, ChangeSet } from '@codemirror/state';
|
||||
import { syntaxTree, highlightingFor } from '@codemirror/language';
|
||||
import { Highlighter, highlightTree } from '@lezer/highlight';
|
||||
import { Scale } from './config';
|
||||
import { LinesState, getLinesSnapshot } from './linesState';
|
||||
import {
|
||||
ToWorkerMessage,
|
||||
ToMainMessage,
|
||||
BlockRequest,
|
||||
Highlight,
|
||||
LineSpan,
|
||||
FontInfo,
|
||||
UpdateFontInfoRequest,
|
||||
} from './worker/protocol';
|
||||
import crelt from 'crelt';
|
||||
|
||||
const BLOCK_LINES = 50;
|
||||
const MAX_BLOCKS = 20;
|
||||
|
||||
interface Block {
|
||||
index: number;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
bitmap: ImageBitmap | null;
|
||||
dirty: boolean;
|
||||
rendering: boolean;
|
||||
requestId: number;
|
||||
lastUsed: number; // LRU 时间戳
|
||||
// 高亮缓存
|
||||
cachedHighlights: Highlight[] | null;
|
||||
cachedLines: LineSpan[][] | null;
|
||||
cachedTextSlice: string | null;
|
||||
cachedTextOffset: number;
|
||||
}
|
||||
|
||||
export class BlockManager {
|
||||
private worker: Worker | null = null;
|
||||
private blocks = new Map<number, Block>();
|
||||
private fontInfoMap = new Map<string, FontInfo>();
|
||||
private fontDirty = true;
|
||||
private fontVersion = 0;
|
||||
private sentFontTags = new Set<string>(); // 已发送给 Worker 的字体标签
|
||||
private measureCache: { charWidth: number; lineHeight: number; version: number } | null = null;
|
||||
private displayText: 'blocks' | 'characters' = 'characters';
|
||||
private themeClasses: Set<string>;
|
||||
private requestId = 0;
|
||||
private onBlockReady: (() => void) | null = null;
|
||||
|
||||
// 批量处理块完成事件
|
||||
private pendingBlockReadyHandle: ReturnType<typeof setTimeout> | null = null;
|
||||
private renderingCount = 0;
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
this.themeClasses = new Set(Array.from(view.dom.classList));
|
||||
this.initWorker();
|
||||
}
|
||||
|
||||
private initWorker(): void {
|
||||
this.worker = new Worker(
|
||||
new URL('./worker/block.worker.ts', import.meta.url),
|
||||
{ type: 'module' }
|
||||
);
|
||||
|
||||
this.worker.onmessage = (e: MessageEvent<ToMainMessage>) => {
|
||||
this.handleWorkerMessage(e.data);
|
||||
};
|
||||
|
||||
this.worker.onerror = (e) => {
|
||||
console.error('[BlockManager] Worker error:', e);
|
||||
};
|
||||
|
||||
this.worker.postMessage({ type: 'init' } as ToWorkerMessage);
|
||||
}
|
||||
|
||||
private handleWorkerMessage(msg: ToMainMessage): void {
|
||||
switch (msg.type) {
|
||||
case 'ready':
|
||||
break;
|
||||
case 'blockComplete': {
|
||||
const block = this.blocks.get(msg.blockIndex);
|
||||
if (block && block.requestId === msg.blockId) {
|
||||
block.bitmap = msg.bitmap;
|
||||
block.dirty = false;
|
||||
block.rendering = false;
|
||||
this.renderingCount = Math.max(0, this.renderingCount - 1);
|
||||
this.scheduleBlockReady();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'error':
|
||||
console.error('[BlockManager] Worker error:', msg.message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 批量触发块就绪回调
|
||||
// 策略:等 30ms,让多个块完成事件合并
|
||||
private scheduleBlockReady(): void {
|
||||
if (this.pendingBlockReadyHandle !== null) {
|
||||
clearTimeout(this.pendingBlockReadyHandle);
|
||||
}
|
||||
|
||||
this.pendingBlockReadyHandle = setTimeout(() => {
|
||||
this.pendingBlockReadyHandle = null;
|
||||
if (this.renderingCount === 0) {
|
||||
this.onBlockReady?.();
|
||||
}
|
||||
}, 30);
|
||||
}
|
||||
|
||||
setOnBlockReady(callback: () => void): void {
|
||||
this.onBlockReady = callback;
|
||||
}
|
||||
|
||||
setDisplayText(mode: 'blocks' | 'characters'): void {
|
||||
if (this.displayText !== mode) {
|
||||
this.displayText = mode;
|
||||
this.markAllDirty();
|
||||
}
|
||||
}
|
||||
|
||||
checkThemeChange(): boolean {
|
||||
const nowClasses = Array.from(this.view.dom.classList);
|
||||
const now = new Set(nowClasses);
|
||||
const prev = this.themeClasses;
|
||||
this.themeClasses = now;
|
||||
|
||||
if (!prev) {
|
||||
this.fontDirty = true;
|
||||
this.markAllDirty();
|
||||
return true;
|
||||
}
|
||||
|
||||
const prevSet = new Set(prev);
|
||||
const nowSet = new Set(now);
|
||||
prevSet.delete('cm-focused');
|
||||
nowSet.delete('cm-focused');
|
||||
|
||||
if (prevSet.size !== nowSet.size) {
|
||||
this.fontDirty = true;
|
||||
this.markAllDirty();
|
||||
return true;
|
||||
}
|
||||
|
||||
for (const cls of prevSet) {
|
||||
if (!nowSet.has(cls)) {
|
||||
this.fontDirty = true;
|
||||
this.markAllDirty();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
markAllDirty(): void {
|
||||
for (const block of this.blocks.values()) {
|
||||
block.dirty = true;
|
||||
// 清除缓存,强制重新收集数据
|
||||
block.cachedHighlights = null;
|
||||
block.cachedLines = null;
|
||||
block.cachedTextSlice = null;
|
||||
}
|
||||
}
|
||||
|
||||
handleDocChange(state: EditorState, changes: ChangeSet, oldLineCount: number): void {
|
||||
const totalLines = state.doc.lines;
|
||||
const maxIndex = Math.ceil(totalLines / BLOCK_LINES) - 1;
|
||||
|
||||
// 找出变化影响的块
|
||||
const affectedBlocks = new Set<number>();
|
||||
|
||||
// 正确检测行数变化:比较新旧文档总行数
|
||||
const hasLineCountChange = totalLines !== oldLineCount;
|
||||
|
||||
changes.iterChanges((fromA, toA, fromB, toB) => {
|
||||
// 找出新文档中受影响的行范围
|
||||
const startLine = state.doc.lineAt(fromB).number;
|
||||
const endLine = state.doc.lineAt(Math.min(toB, state.doc.length)).number;
|
||||
|
||||
const startBlock = Math.floor((startLine - 1) / BLOCK_LINES);
|
||||
const endBlock = Math.floor((endLine - 1) / BLOCK_LINES);
|
||||
|
||||
for (let i = startBlock; i <= endBlock; i++) {
|
||||
affectedBlocks.add(i);
|
||||
}
|
||||
});
|
||||
|
||||
// 如果行数变化,后续所有块都需要标记为 dirty
|
||||
let markRest = false;
|
||||
|
||||
for (const [index, block] of this.blocks) {
|
||||
if (index > maxIndex) {
|
||||
block.bitmap?.close();
|
||||
this.blocks.delete(index);
|
||||
} else if (affectedBlocks.has(index)) {
|
||||
block.dirty = true;
|
||||
// 清除缓存
|
||||
block.cachedHighlights = null;
|
||||
block.cachedLines = null;
|
||||
block.cachedTextSlice = null;
|
||||
if (hasLineCountChange) {
|
||||
markRest = true; // 从这个块开始,后续块都需要更新
|
||||
}
|
||||
} else if (markRest) {
|
||||
block.dirty = true;
|
||||
// 清除缓存
|
||||
block.cachedHighlights = null;
|
||||
block.cachedLines = null;
|
||||
block.cachedTextSlice = null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算可见范围(提取公共计算逻辑)
|
||||
*/
|
||||
private getVisibleRange(
|
||||
canvasHeight: number,
|
||||
lineHeight: number,
|
||||
scrollInfo: { scrollTop: number; clientHeight: number; scrollHeight: number }
|
||||
): {
|
||||
valid: boolean;
|
||||
totalLines: number;
|
||||
scaledPTop: number;
|
||||
canvasTop: number;
|
||||
startBlock: number;
|
||||
endBlock: number;
|
||||
} | null {
|
||||
const totalLines = this.view.state.field(LinesState).length;
|
||||
if (totalLines === 0 || canvasHeight <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { top: pTop, bottom: pBottom } = this.view.documentPadding;
|
||||
const scaledPTop = pTop / Scale.SizeRatio;
|
||||
const scaledPBottom = pBottom / Scale.SizeRatio;
|
||||
const totalHeight = scaledPTop + scaledPBottom + totalLines * lineHeight;
|
||||
|
||||
const { scrollTop, clientHeight, scrollHeight } = scrollInfo;
|
||||
const scrollPercent = Math.max(0, Math.min(1, scrollTop / (scrollHeight - clientHeight))) || 0;
|
||||
const canvasTop = Math.max(0, scrollPercent * (totalHeight - canvasHeight));
|
||||
|
||||
const visibleStart = Math.max(1, Math.floor((canvasTop - scaledPTop) / lineHeight) + 1);
|
||||
const visibleEnd = Math.min(totalLines, Math.ceil((canvasTop + canvasHeight - scaledPTop) / lineHeight));
|
||||
|
||||
if (visibleEnd < visibleStart) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
totalLines,
|
||||
scaledPTop,
|
||||
canvasTop,
|
||||
startBlock: Math.floor((visibleStart - 1) / BLOCK_LINES),
|
||||
endBlock: Math.floor((visibleEnd - 1) / BLOCK_LINES),
|
||||
};
|
||||
}
|
||||
|
||||
render(
|
||||
canvas: HTMLCanvasElement,
|
||||
ctx: CanvasRenderingContext2D,
|
||||
scrollInfo: { scrollTop: number; clientHeight: number; scrollHeight: number }
|
||||
): void {
|
||||
if (this.fontDirty) {
|
||||
this.refreshFontCache();
|
||||
}
|
||||
|
||||
const { charWidth, lineHeight } = this.measure(ctx);
|
||||
const range = this.getVisibleRange(canvas.height, lineHeight, scrollInfo);
|
||||
if (!range) return;
|
||||
|
||||
const { totalLines, scaledPTop, canvasTop, startBlock, endBlock } = range;
|
||||
const state = this.view.state;
|
||||
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
for (let i = startBlock; i <= endBlock; i++) {
|
||||
const block = this.getOrCreateBlock(i, state, totalLines);
|
||||
if (!block) continue;
|
||||
|
||||
if (block.dirty && !block.rendering) {
|
||||
this.requestBlockRender(block, state, charWidth, lineHeight);
|
||||
}
|
||||
|
||||
if (block.bitmap) {
|
||||
const blockY = scaledPTop + (block.startLine - 1) * lineHeight - canvasTop;
|
||||
ctx.drawImage(block.bitmap, 0, blockY);
|
||||
}
|
||||
}
|
||||
|
||||
this.fontDirty = false;
|
||||
this.evictOldBlocks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 只绘制缓存的块,不请求新渲染(用于 overlay-only 更新)
|
||||
*/
|
||||
drawCachedBlocks(
|
||||
canvas: HTMLCanvasElement,
|
||||
ctx: CanvasRenderingContext2D,
|
||||
scrollInfo: { scrollTop: number; clientHeight: number; scrollHeight: number }
|
||||
): void {
|
||||
const { lineHeight } = this.measure(ctx);
|
||||
const range = this.getVisibleRange(canvas.height, lineHeight, scrollInfo);
|
||||
if (!range) return;
|
||||
|
||||
const { scaledPTop, canvasTop, startBlock, endBlock } = range;
|
||||
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
for (let i = startBlock; i <= endBlock; i++) {
|
||||
const block = this.blocks.get(i);
|
||||
if (block?.bitmap) {
|
||||
const blockY = scaledPTop + (block.startLine - 1) * lineHeight - canvasTop;
|
||||
ctx.drawImage(block.bitmap, 0, blockY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getOrCreateBlock(index: number, state: EditorState, totalLines: number): Block | null {
|
||||
const startLine = index * BLOCK_LINES + 1;
|
||||
if (startLine > totalLines) return null;
|
||||
|
||||
const endLine = Math.min((index + 1) * BLOCK_LINES, totalLines);
|
||||
const now = performance.now();
|
||||
|
||||
let block = this.blocks.get(index);
|
||||
if (!block) {
|
||||
block = {
|
||||
index,
|
||||
startLine,
|
||||
endLine,
|
||||
bitmap: null,
|
||||
dirty: true,
|
||||
rendering: false,
|
||||
requestId: 0,
|
||||
lastUsed: now,
|
||||
cachedHighlights: null,
|
||||
cachedLines: null,
|
||||
cachedTextSlice: null,
|
||||
cachedTextOffset: 0,
|
||||
};
|
||||
this.blocks.set(index, block);
|
||||
} else {
|
||||
block.startLine = startLine;
|
||||
block.endLine = endLine;
|
||||
block.lastUsed = now; // 更新 LRU 时间戳
|
||||
}
|
||||
|
||||
return block;
|
||||
}
|
||||
|
||||
private requestBlockRender(
|
||||
block: Block,
|
||||
state: EditorState,
|
||||
charWidth: number,
|
||||
lineHeight: number
|
||||
): void {
|
||||
if (!this.worker) return;
|
||||
|
||||
block.rendering = true;
|
||||
block.requestId = ++this.requestId;
|
||||
this.renderingCount++;
|
||||
|
||||
const { startLine, endLine } = block;
|
||||
|
||||
let highlights: Highlight[];
|
||||
let lines: LineSpan[][];
|
||||
let textSlice: string;
|
||||
let textOffset: number;
|
||||
|
||||
// 只有当块是 dirty 时才重新收集数据,否则使用缓存
|
||||
if (block.dirty || !block.cachedHighlights) {
|
||||
const linesSnapshot = getLinesSnapshot(state);
|
||||
const tree = syntaxTree(state);
|
||||
|
||||
// Collect highlights
|
||||
highlights = [];
|
||||
if (tree.length > 0 && startLine <= state.doc.lines) {
|
||||
const highlighter: Highlighter = {
|
||||
style: (tags) => highlightingFor(state, tags),
|
||||
};
|
||||
const startPos = state.doc.line(startLine).from;
|
||||
const endPos = state.doc.line(Math.min(endLine, state.doc.lines)).to;
|
||||
|
||||
highlightTree(tree, highlighter, (from, to, tags) => {
|
||||
highlights.push({ from, to, tags });
|
||||
}, startPos, endPos);
|
||||
}
|
||||
|
||||
// Extract relevant lines
|
||||
const startIdx = startLine - 1;
|
||||
const endIdx = Math.min(endLine, linesSnapshot.length);
|
||||
lines = linesSnapshot.slice(startIdx, endIdx).map(line =>
|
||||
line.map(span => ({ from: span.from, to: span.to, folded: span.folded }))
|
||||
);
|
||||
|
||||
// Get text slice
|
||||
textOffset = 0;
|
||||
let textEnd = 0;
|
||||
if (lines.length > 0 && lines[0].length > 0) {
|
||||
textOffset = lines[0][0].from;
|
||||
const lastLine = lines[lines.length - 1];
|
||||
if (lastLine.length > 0) {
|
||||
textEnd = lastLine[lastLine.length - 1].to;
|
||||
}
|
||||
}
|
||||
textSlice = state.doc.sliceString(textOffset, textEnd);
|
||||
|
||||
// 缓存数据
|
||||
block.cachedHighlights = highlights;
|
||||
block.cachedLines = lines;
|
||||
block.cachedTextSlice = textSlice;
|
||||
block.cachedTextOffset = textOffset;
|
||||
} else {
|
||||
// 使用缓存的数据
|
||||
highlights = block.cachedHighlights;
|
||||
lines = block.cachedLines!;
|
||||
textSlice = block.cachedTextSlice!;
|
||||
textOffset = block.cachedTextOffset;
|
||||
}
|
||||
|
||||
// 确保字体信息已发送给 Worker
|
||||
this.ensureFontInfoSent(highlights);
|
||||
|
||||
const blockLines = endLine - startLine + 1;
|
||||
const request: BlockRequest = {
|
||||
type: 'renderBlock',
|
||||
blockId: block.requestId,
|
||||
blockIndex: block.index,
|
||||
startLine,
|
||||
endLine,
|
||||
width: Math.ceil(Scale.MaxWidth * Scale.PixelMultiplier),
|
||||
height: Math.ceil(blockLines * lineHeight),
|
||||
highlights,
|
||||
lines,
|
||||
textSlice,
|
||||
textOffset,
|
||||
displayText: this.displayText,
|
||||
charWidth,
|
||||
lineHeight,
|
||||
gutterOffset: 0,
|
||||
};
|
||||
|
||||
this.worker.postMessage(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保字体信息已发送给 Worker
|
||||
* 增量发送:只发送新的标签
|
||||
*/
|
||||
private ensureFontInfoSent(highlights: Highlight[]): void {
|
||||
if (!this.worker) return;
|
||||
|
||||
// 收集新的标签
|
||||
const newTags: string[] = [];
|
||||
for (const hl of highlights) {
|
||||
if (!this.sentFontTags.has(hl.tags)) {
|
||||
newTags.push(hl.tags);
|
||||
}
|
||||
}
|
||||
// 默认字体标签
|
||||
if (!this.sentFontTags.has('')) {
|
||||
newTags.push('');
|
||||
}
|
||||
|
||||
// 如果没有新标签,不需要发送
|
||||
if (newTags.length === 0) return;
|
||||
|
||||
// 构建新标签的字体信息
|
||||
const fontInfoMap: Record<string, FontInfo> = {};
|
||||
for (const tag of newTags) {
|
||||
fontInfoMap[tag] = this.getFontInfo(tag);
|
||||
this.sentFontTags.add(tag);
|
||||
}
|
||||
|
||||
const updateRequest: UpdateFontInfoRequest = {
|
||||
type: 'updateFontInfo',
|
||||
fontInfoMap,
|
||||
defaultFont: this.getFontInfo(''),
|
||||
};
|
||||
this.worker.postMessage(updateRequest);
|
||||
}
|
||||
|
||||
private evictOldBlocks(): void {
|
||||
if (this.blocks.size <= MAX_BLOCKS) return;
|
||||
|
||||
// LRU 驱逐:按 lastUsed 升序排序,驱逐最久未使用的块
|
||||
const sorted = Array.from(this.blocks.entries())
|
||||
.filter(([, b]) => !b.rendering)
|
||||
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
|
||||
|
||||
const toRemove = sorted.slice(0, this.blocks.size - MAX_BLOCKS);
|
||||
for (const [index, block] of toRemove) {
|
||||
block.bitmap?.close();
|
||||
this.blocks.delete(index);
|
||||
}
|
||||
}
|
||||
|
||||
private refreshFontCache(): void {
|
||||
this.fontInfoMap.clear();
|
||||
this.measureCache = null;
|
||||
this.sentFontTags.clear(); // 需要重新发送字体信息给 Worker
|
||||
// 注意:fontDirty 在成功渲染块后才设为 false
|
||||
this.fontVersion++;
|
||||
this.markAllDirty();
|
||||
}
|
||||
|
||||
measure(ctx: CanvasRenderingContext2D): { charWidth: number; lineHeight: number } {
|
||||
const info = this.getFontInfo('');
|
||||
ctx.textBaseline = 'ideographic';
|
||||
ctx.fillStyle = info.color;
|
||||
ctx.font = info.font;
|
||||
|
||||
if (this.measureCache?.version === this.fontVersion) {
|
||||
return { charWidth: this.measureCache.charWidth, lineHeight: this.measureCache.lineHeight };
|
||||
}
|
||||
|
||||
const charWidth = ctx.measureText('_').width;
|
||||
this.measureCache = { charWidth, lineHeight: info.lineHeight, version: this.fontVersion };
|
||||
return { charWidth, lineHeight: info.lineHeight };
|
||||
}
|
||||
|
||||
private getFontInfo(tags: string): FontInfo {
|
||||
const cached = this.fontInfoMap.get(tags);
|
||||
if (cached) return cached;
|
||||
|
||||
const mockToken = crelt('span', { class: tags });
|
||||
const mockLine = crelt('div', { class: 'cm-line', style: 'display: none' }, mockToken);
|
||||
this.view.contentDOM.appendChild(mockLine);
|
||||
|
||||
const style = window.getComputedStyle(mockToken);
|
||||
|
||||
// 获取字体大小(用于渲染字符)
|
||||
const fontSize = parseFloat(style.fontSize) || this.view.defaultLineHeight;
|
||||
const scaledFontSize = Math.max(1, fontSize / Scale.SizeRatio);
|
||||
|
||||
// 获取行高(用于行间距)
|
||||
const rawLineHeight = parseFloat(style.lineHeight);
|
||||
const resolvedLineHeight = Number.isFinite(rawLineHeight) && rawLineHeight > 0 ? rawLineHeight : fontSize;
|
||||
const lineHeight = Math.max(1, resolvedLineHeight / Scale.SizeRatio);
|
||||
|
||||
const result: FontInfo = {
|
||||
color: style.color,
|
||||
font: `${style.fontStyle} ${style.fontWeight} ${scaledFontSize}px ${style.fontFamily}`,
|
||||
lineHeight,
|
||||
};
|
||||
|
||||
this.view.contentDOM.removeChild(mockLine);
|
||||
this.fontInfoMap.set(tags, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
if (this.pendingBlockReadyHandle !== null) {
|
||||
clearTimeout(this.pendingBlockReadyHandle);
|
||||
}
|
||||
for (const block of this.blocks.values()) {
|
||||
block.bitmap?.close();
|
||||
}
|
||||
this.blocks.clear();
|
||||
this.worker?.postMessage({ type: 'destroy' } as ToWorkerMessage);
|
||||
this.worker?.terminate();
|
||||
this.worker = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,21 @@ import {
|
||||
|
||||
import { LineBasedState } from "./linebasedstate";
|
||||
import { DrawContext } from "./types";
|
||||
import { Lines, LinesState, foldsChanged } from "./linesState";
|
||||
import { Config } from "./config";
|
||||
import { LinesState, foldsChanged } from "./linesState";
|
||||
import { Config, Scale } from "./config";
|
||||
import { lineLength, lineNumberAt, offsetWithinLine } from "./lineGeometry";
|
||||
|
||||
type Severity = Diagnostic["severity"];
|
||||
type DiagnosticRange = { from: number; to: number };
|
||||
type LineDiagnostics = {
|
||||
severity: Severity;
|
||||
ranges: Array<DiagnosticRange>;
|
||||
};
|
||||
const MIN_PIXEL_WIDTH = 1 / Scale.PixelMultiplier;
|
||||
const snapToDevice = (value: number) =>
|
||||
Math.round(value * Scale.PixelMultiplier) / Scale.PixelMultiplier;
|
||||
|
||||
export class DiagnosticState extends LineBasedState<Severity> {
|
||||
export class DiagnosticState extends LineBasedState<LineDiagnostics> {
|
||||
private count: number | undefined = undefined;
|
||||
|
||||
public constructor(view: EditorView) {
|
||||
@@ -63,70 +72,74 @@ export class DiagnosticState extends LineBasedState<Severity> {
|
||||
this.count = diagnosticCount(update.state);
|
||||
|
||||
forEachDiagnostic(update.state, (diagnostic, from, to) => {
|
||||
// Find the start and end lines for the diagnostic
|
||||
const lineStart = this.findLine(from, lines);
|
||||
const lineEnd = this.findLine(to, lines);
|
||||
const lineStart = lineNumberAt(lines, from);
|
||||
const lineEnd = lineNumberAt(lines, to);
|
||||
if (lineStart <= 0 || lineEnd <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Populate each line in the range with the highest severity diagnostic
|
||||
let severity = diagnostic.severity;
|
||||
for (let i = lineStart; i <= lineEnd; i++) {
|
||||
const previous = this.get(i);
|
||||
if (previous) {
|
||||
severity = [severity, previous]
|
||||
.sort(this.sort.bind(this))
|
||||
.slice(0, 1)[0];
|
||||
for (let lineNumber = lineStart; lineNumber <= lineEnd; lineNumber++) {
|
||||
const spans = lines[lineNumber - 1];
|
||||
if (!spans || spans.length === 0) {
|
||||
continue;
|
||||
}
|
||||
this.set(i, severity);
|
||||
|
||||
const length = lineLength(spans);
|
||||
|
||||
const startOffset =
|
||||
lineNumber === lineStart
|
||||
? offsetWithinLine(from, spans)
|
||||
: 0;
|
||||
const endOffset =
|
||||
lineNumber === lineEnd ? offsetWithinLine(to, spans) : length;
|
||||
|
||||
const fromOffset = Math.max(0, Math.min(length, startOffset));
|
||||
let toOffset = Math.max(fromOffset, Math.min(length, endOffset));
|
||||
if (toOffset === fromOffset) {
|
||||
toOffset = Math.min(length, fromOffset + 1);
|
||||
}
|
||||
|
||||
this.pushRange(lineNumber, diagnostic.severity, {
|
||||
from: fromOffset,
|
||||
to: toOffset,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
this.mergeRanges();
|
||||
}
|
||||
|
||||
public drawLine(ctx: DrawContext, lineNumber: number) {
|
||||
const { context, lineHeight, offsetX, offsetY } = ctx;
|
||||
const severity = this.get(lineNumber);
|
||||
if (!severity) {
|
||||
const diagnostics = this.get(lineNumber);
|
||||
if (!diagnostics) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Draw the full line width rectangle in the background
|
||||
context.globalAlpha = 0.65;
|
||||
context.beginPath();
|
||||
context.rect(
|
||||
offsetX,
|
||||
offsetY /* TODO Scaling causes anti-aliasing in rectangles */,
|
||||
context.canvas.width - offsetX,
|
||||
lineHeight
|
||||
);
|
||||
context.fillStyle = this.color(severity);
|
||||
context.fill();
|
||||
const { context, lineHeight, charWidth, offsetX, offsetY } = ctx;
|
||||
const color = this.color(diagnostics.severity);
|
||||
const snappedY = snapToDevice(offsetY);
|
||||
const snappedHeight =
|
||||
Math.max(MIN_PIXEL_WIDTH, snapToDevice(offsetY + lineHeight) - snappedY) ||
|
||||
MIN_PIXEL_WIDTH;
|
||||
|
||||
// Draw diagnostic range rectangle in the foreground
|
||||
// TODO: We need to update the state to have specific ranges
|
||||
// context.globalAlpha = 1;
|
||||
// context.beginPath();
|
||||
// context.rect(offsetX, offsetY, textWidth, lineHeight);
|
||||
// context.fillStyle = this.color(severity);
|
||||
// context.fill();
|
||||
}
|
||||
context.fillStyle = color;
|
||||
for (const range of diagnostics.ranges) {
|
||||
const startX = offsetX + range.from * charWidth;
|
||||
const width = Math.max(
|
||||
MIN_PIXEL_WIDTH,
|
||||
(range.to - range.from) * charWidth
|
||||
);
|
||||
const snappedX = snapToDevice(startX);
|
||||
const snappedWidth =
|
||||
Math.max(MIN_PIXEL_WIDTH, snapToDevice(startX + width) - snappedX) ||
|
||||
MIN_PIXEL_WIDTH;
|
||||
|
||||
/**
|
||||
* Given a position and a set of line ranges, return
|
||||
* the line number the position falls within
|
||||
*/
|
||||
private findLine(pos: number, lines: Lines) {
|
||||
const index = lines.findIndex((spans) => {
|
||||
const start = spans.slice(0, 1)[0];
|
||||
const end = spans.slice(-1)[0];
|
||||
|
||||
if (!start || !end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return start.from <= pos && pos <= end.to;
|
||||
});
|
||||
|
||||
// Line numbers begin at 1
|
||||
return index + 1;
|
||||
context.globalAlpha = 0.65;
|
||||
context.beginPath();
|
||||
context.rect(snappedX, snappedY, snappedWidth, snappedHeight);
|
||||
context.fill();
|
||||
}
|
||||
context.globalAlpha = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,12 +154,6 @@ export class DiagnosticState extends LineBasedState<Severity> {
|
||||
: "#999";
|
||||
}
|
||||
|
||||
/** Sorts severity from most to least severe */
|
||||
private sort(a: Severity, b: Severity) {
|
||||
return this.score(b) - this.score(a);
|
||||
}
|
||||
|
||||
/** Assigns a score to severity, with most severe being the highest */
|
||||
private score(s: Severity) {
|
||||
switch (s) {
|
||||
case "error": {
|
||||
@@ -160,6 +167,47 @@ export class DiagnosticState extends LineBasedState<Severity> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private pushRange(
|
||||
lineNumber: number,
|
||||
severity: Severity,
|
||||
range: DiagnosticRange
|
||||
) {
|
||||
let entry = this.get(lineNumber);
|
||||
if (!entry) {
|
||||
entry = { severity, ranges: [range] };
|
||||
this.set(lineNumber, entry);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.score(severity) > this.score(entry.severity)) {
|
||||
entry.severity = severity;
|
||||
}
|
||||
|
||||
entry.ranges.push(range);
|
||||
}
|
||||
|
||||
private mergeRanges() {
|
||||
for (const entry of this.map.values()) {
|
||||
if (entry.ranges.length <= 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
entry.ranges.sort((a, b) => a.from - b.from);
|
||||
const merged: Array<DiagnosticRange> = [];
|
||||
|
||||
for (const range of entry.ranges) {
|
||||
const last = merged[merged.length - 1];
|
||||
if (last && range.from <= last.to) {
|
||||
last.to = Math.max(last.to, range.to);
|
||||
} else {
|
||||
merged.push({ ...range });
|
||||
}
|
||||
}
|
||||
|
||||
entry.ranges = merged;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function diagnostics(view: EditorView): DiagnosticState {
|
||||
|
||||
@@ -1,27 +1,37 @@
|
||||
import { Facet } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, ViewUpdate } from "@codemirror/view";
|
||||
import { Overlay } from "./overlay";
|
||||
import { Config, Options, Scale } from "./config";
|
||||
import { DiagnosticState, diagnostics } from "./diagnostics";
|
||||
import { SelectionState, selections } from "./selections";
|
||||
import { TextState, text } from "./text";
|
||||
import { LinesState } from "./linesState";
|
||||
import crelt from "crelt";
|
||||
import { GUTTER_WIDTH, drawLineGutter } from "./gutters";
|
||||
/**
|
||||
* Minimap Extension Entry
|
||||
* Uses block rendering for visible area only
|
||||
*/
|
||||
|
||||
import { Facet } from '@codemirror/state';
|
||||
import { EditorView, ViewPlugin, ViewUpdate } from '@codemirror/view';
|
||||
import { Overlay } from './overlay';
|
||||
import { Config, Options, Scale } from './config';
|
||||
import { DiagnosticState, diagnostics } from './diagnostics';
|
||||
import { SelectionState, selections } from './selections';
|
||||
import { LinesState, foldsChanged } from './linesState';
|
||||
import { BlockManager } from './blockManager';
|
||||
import crelt from 'crelt';
|
||||
import { GUTTER_WIDTH, drawLineGutter } from './gutters';
|
||||
import { createDebounce } from '@/common/utils/debounce';
|
||||
|
||||
const Theme = EditorView.theme({
|
||||
"&": {
|
||||
height: "100%",
|
||||
overflowY: "auto",
|
||||
'&': {
|
||||
height: '100%',
|
||||
overflowY: 'auto',
|
||||
},
|
||||
"& .cm-minimap-gutter": {
|
||||
'& .cm-minimap-gutter': {
|
||||
borderRight: 0,
|
||||
flexShrink: 0,
|
||||
left: "unset",
|
||||
position: "sticky",
|
||||
left: 'unset',
|
||||
position: 'sticky',
|
||||
right: 0,
|
||||
top: 0,
|
||||
},
|
||||
// 初始化时隐藏,避免宽度未设置时闪烁
|
||||
'& .cm-minimap-initializing': {
|
||||
opacity: 0,
|
||||
},
|
||||
'& .cm-minimap-autohide': {
|
||||
opacity: 0.0,
|
||||
transition: 'opacity 0.3s',
|
||||
@@ -29,62 +39,130 @@ const Theme = EditorView.theme({
|
||||
'& .cm-minimap-autohide:hover': {
|
||||
opacity: 1.0,
|
||||
},
|
||||
"& .cm-minimap-inner": {
|
||||
height: "100%",
|
||||
position: "absolute",
|
||||
'& .cm-minimap-inner': {
|
||||
height: '100%',
|
||||
position: 'absolute',
|
||||
right: 0,
|
||||
top: 0,
|
||||
overflowY: "hidden",
|
||||
"& canvas": {
|
||||
display: "block",
|
||||
overflowY: 'hidden',
|
||||
'& canvas': {
|
||||
display: 'block',
|
||||
willChange: 'transform, opacity',
|
||||
},
|
||||
},
|
||||
"& .cm-minimap-box-shadow": {
|
||||
boxShadow: "12px 0px 20px 5px #6c6c6c",
|
||||
'& .cm-minimap-box-shadow': {
|
||||
boxShadow: '12px 0px 20px 5px #6c6c6c',
|
||||
},
|
||||
});
|
||||
|
||||
const WIDTH_RATIO = 6;
|
||||
type RenderReason = 'scroll' | 'data';
|
||||
|
||||
// 渲染类型:blocks=块内容变化需要重渲染, overlays=只需重绘选区等覆盖层
|
||||
type RenderType = 'blocks' | 'overlays';
|
||||
|
||||
const minimapClass = ViewPlugin.fromClass(
|
||||
class {
|
||||
private dom: HTMLElement | undefined;
|
||||
private inner: HTMLElement | undefined;
|
||||
private canvas: HTMLCanvasElement | undefined;
|
||||
private renderHandle: number | ReturnType<typeof setTimeout> | null = null;
|
||||
private cancelRender: (() => void) | null = null;
|
||||
private pendingScrollTop: number | null = null;
|
||||
private lastRenderedScrollTop: number = -1;
|
||||
private pendingRenderReason: RenderReason | null = null;
|
||||
private pendingRenderType: RenderType | null = null;
|
||||
|
||||
public text: TextState;
|
||||
// 块管理器(Worker 渲染)
|
||||
private blockManager: BlockManager;
|
||||
public selection: SelectionState;
|
||||
public diagnostic: DiagnosticState;
|
||||
|
||||
// 等待滚动位置稳定
|
||||
private initialRenderDelay: ReturnType<typeof setTimeout> | null = null;
|
||||
private isInitialized = false;
|
||||
private hasRenderedOnce = false; // 是否已首次渲染
|
||||
private lastScrollTop = -1;
|
||||
private scrollStableCount = 0;
|
||||
|
||||
// 块渲染防抖(500ms)
|
||||
private debouncedBlockRender: ReturnType<typeof createDebounce>['debouncedFn'];
|
||||
private cancelDebounce: () => void;
|
||||
|
||||
public constructor(private view: EditorView) {
|
||||
this.text = text(view);
|
||||
this.blockManager = new BlockManager(view);
|
||||
this.selection = selections(view);
|
||||
this.diagnostic = diagnostics(view);
|
||||
|
||||
// 创建防抖的块渲染函数
|
||||
const { debouncedFn, cancel } = createDebounce(() => {
|
||||
this.requestRender('data', 'blocks');
|
||||
}, { delay: 1000 });
|
||||
this.debouncedBlockRender = debouncedFn;
|
||||
this.cancelDebounce = cancel;
|
||||
|
||||
// 当块渲染完成时,请求重新渲染(只渲染 overlays)
|
||||
this.blockManager.setOnBlockReady(() => {
|
||||
if (this.isInitialized) {
|
||||
this.requestRender('data', 'overlays');
|
||||
}
|
||||
});
|
||||
|
||||
if (view.state.facet(showMinimapFacet)) {
|
||||
this.create(view);
|
||||
this.waitForScrollStable();
|
||||
}
|
||||
}
|
||||
|
||||
// 等待滚动位置稳定后再渲染
|
||||
private waitForScrollStable(): void {
|
||||
const check = () => {
|
||||
const scrollTop = this.view.scrollDOM.scrollTop;
|
||||
|
||||
if (scrollTop === this.lastScrollTop) {
|
||||
this.scrollStableCount++;
|
||||
// 连续 3 次检测位置不变,认为稳定
|
||||
if (this.scrollStableCount >= 3) {
|
||||
this.isInitialized = true;
|
||||
this.initialRenderDelay = null;
|
||||
this.requestRender('data', 'blocks');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.scrollStableCount = 0;
|
||||
this.lastScrollTop = scrollTop;
|
||||
}
|
||||
|
||||
// 每 20ms 检测一次,最多等待 200ms
|
||||
if (this.scrollStableCount < 10) {
|
||||
this.initialRenderDelay = setTimeout(check, 20);
|
||||
} else {
|
||||
this.isInitialized = true;
|
||||
this.initialRenderDelay = null;
|
||||
this.requestRender('data', 'blocks');
|
||||
}
|
||||
};
|
||||
|
||||
this.initialRenderDelay = setTimeout(check, 20);
|
||||
}
|
||||
|
||||
private create(view: EditorView) {
|
||||
const config = view.state.facet(showMinimapFacet);
|
||||
if (!config) {
|
||||
throw Error("Expected nonnull");
|
||||
throw Error('Expected nonnull');
|
||||
}
|
||||
|
||||
this.inner = crelt("div", { class: "cm-minimap-inner" });
|
||||
this.canvas = crelt("canvas") as HTMLCanvasElement;
|
||||
this.inner = crelt('div', { class: 'cm-minimap-inner' });
|
||||
this.canvas = crelt('canvas') as HTMLCanvasElement;
|
||||
|
||||
this.dom = config.create(view).dom;
|
||||
this.dom.classList.add("cm-gutters");
|
||||
this.dom.classList.add("cm-minimap-gutter");
|
||||
this.dom.classList.add('cm-gutters');
|
||||
this.dom.classList.add('cm-minimap-gutter');
|
||||
this.dom.classList.add('cm-minimap-initializing'); // 初始隐藏
|
||||
|
||||
this.inner.appendChild(this.canvas);
|
||||
this.dom.appendChild(this.inner);
|
||||
|
||||
// For now let's keep this same behavior. We might want to change
|
||||
// this in the future and have the extension figure out how to mount.
|
||||
// Or expose some more generic right gutter api and use that
|
||||
this.view.scrollDOM.insertBefore(
|
||||
this.dom,
|
||||
this.view.contentDOM.nextSibling
|
||||
@@ -97,35 +175,23 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
}
|
||||
}
|
||||
|
||||
// 阻止小地图上的右键菜单
|
||||
this.dom.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
});
|
||||
|
||||
// 阻止小地图内部元素和画布上的右键菜单
|
||||
this.inner.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
});
|
||||
|
||||
this.canvas.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
});
|
||||
|
||||
if (config.autohide) {
|
||||
this.dom.classList.add('cm-minimap-autohide');
|
||||
}
|
||||
|
||||
// 设置显示模式
|
||||
this.blockManager.setDisplayText(view.state.facet(Config).displayText);
|
||||
}
|
||||
|
||||
private remove() {
|
||||
this.cancelRenderRequest();
|
||||
if (this.dom) {
|
||||
this.dom.remove();
|
||||
}
|
||||
this.dom = undefined;
|
||||
this.inner = undefined;
|
||||
this.canvas = undefined;
|
||||
this.hasRenderedOnce = false; // 重置首次渲染标记
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
@@ -142,6 +208,9 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
}
|
||||
|
||||
if (now) {
|
||||
let needBlockRender = false;
|
||||
let needOverlayRender = false;
|
||||
|
||||
if (prev && this.dom && prev.autohide !== now.autohide) {
|
||||
if (now.autohide) {
|
||||
this.dom.classList.add('cm-minimap-autohide');
|
||||
@@ -150,10 +219,45 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
}
|
||||
}
|
||||
|
||||
this.text.update(update);
|
||||
// Check theme change
|
||||
if (this.blockManager.checkThemeChange()) {
|
||||
needBlockRender = true;
|
||||
}
|
||||
|
||||
// Check config change
|
||||
const prevConfig = update.startState.facet(Config);
|
||||
const nowConfig = update.state.facet(Config);
|
||||
if (prevConfig.displayText !== nowConfig.displayText) {
|
||||
this.blockManager.setDisplayText(nowConfig.displayText);
|
||||
needBlockRender = true;
|
||||
}
|
||||
|
||||
// Check doc change
|
||||
if (update.docChanged) {
|
||||
const oldLineCount = update.startState.doc.lines;
|
||||
this.blockManager.handleDocChange(update.state, update.changes, oldLineCount);
|
||||
needBlockRender = true;
|
||||
}
|
||||
|
||||
// Check fold change
|
||||
if (foldsChanged(update.transactions)) {
|
||||
this.blockManager.markAllDirty();
|
||||
needBlockRender = true;
|
||||
}
|
||||
|
||||
// Update selection and diagnostics
|
||||
this.selection.update(update);
|
||||
this.diagnostic.update(update);
|
||||
this.render();
|
||||
if (update.selectionSet) {
|
||||
needOverlayRender = true;
|
||||
}
|
||||
|
||||
// 根据变化类型决定渲染方式
|
||||
if (needBlockRender) {
|
||||
this.debouncedBlockRender();
|
||||
} else if (needOverlayRender) {
|
||||
this.requestRender('data', 'overlays');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,85 +271,182 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
}
|
||||
|
||||
render() {
|
||||
// If we don't have elements to draw to exit early
|
||||
if (!this.dom || !this.canvas || !this.inner) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.text.beforeDraw();
|
||||
const effectiveScrollTop = this.pendingScrollTop ?? this.view.scrollDOM.scrollTop;
|
||||
const renderType = this.pendingRenderType ?? 'blocks';
|
||||
this.pendingScrollTop = null;
|
||||
this.pendingRenderReason = null;
|
||||
this.pendingRenderType = null;
|
||||
this.lastRenderedScrollTop = effectiveScrollTop;
|
||||
|
||||
this.updateBoxShadow();
|
||||
|
||||
this.dom.style.width = this.getWidth() + "px";
|
||||
this.canvas.style.maxWidth = this.getWidth() + "px";
|
||||
this.canvas.width = this.getWidth() * Scale.PixelMultiplier;
|
||||
// Set canvas size
|
||||
const width = this.getWidth();
|
||||
this.dom.style.width = width + 'px';
|
||||
this.canvas.style.maxWidth = width + 'px';
|
||||
this.canvas.width = width * Scale.PixelMultiplier;
|
||||
|
||||
const domHeight = this.view.dom.getBoundingClientRect().height;
|
||||
this.inner.style.minHeight = domHeight + "px";
|
||||
this.inner.style.minHeight = domHeight + 'px';
|
||||
this.canvas.height = domHeight * Scale.PixelMultiplier;
|
||||
this.canvas.style.height = domHeight + "px";
|
||||
this.canvas.style.height = domHeight + 'px';
|
||||
|
||||
const context = this.canvas.getContext("2d");
|
||||
const context = this.canvas.getContext('2d');
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||
// Get scroll info
|
||||
const scrollInfo = {
|
||||
scrollTop: effectiveScrollTop,
|
||||
clientHeight: this.view.scrollDOM.clientHeight,
|
||||
scrollHeight: this.view.scrollDOM.scrollHeight,
|
||||
};
|
||||
|
||||
/* We need to get the correct font dimensions before this to measure characters */
|
||||
const { charWidth, lineHeight } = this.text.measure(context);
|
||||
// 渲染块
|
||||
if (renderType === 'blocks') {
|
||||
this.blockManager.render(this.canvas, context, scrollInfo);
|
||||
} else {
|
||||
this.blockManager.drawCachedBlocks(this.canvas, context, scrollInfo);
|
||||
}
|
||||
|
||||
let { startIndex, endIndex, offsetY } = this.canvasStartAndEndIndex(
|
||||
// Render overlays (gutters, selections, diagnostics)
|
||||
const gutters = this.view.state.facet(Config).gutters;
|
||||
this.renderOverlays(context, effectiveScrollTop, gutters);
|
||||
|
||||
// 首次渲染完成后显示 minimap
|
||||
if (!this.hasRenderedOnce && this.dom) {
|
||||
this.hasRenderedOnce = true;
|
||||
this.dom.classList.remove('cm-minimap-initializing');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染覆盖层(gutters、选区、诊断)
|
||||
*/
|
||||
private renderOverlays(
|
||||
context: CanvasRenderingContext2D,
|
||||
scrollTop: number,
|
||||
gutters: Required<Options>['gutters']
|
||||
) {
|
||||
const { charWidth, lineHeight } = this.blockManager.measure(context);
|
||||
const { startIndex, endIndex, offsetY: initialOffsetY } = this.canvasStartAndEndIndex(
|
||||
context,
|
||||
lineHeight
|
||||
lineHeight,
|
||||
scrollTop
|
||||
);
|
||||
|
||||
const gutters = this.view.state.facet(Config).gutters;
|
||||
const lines = this.view.state.field(LinesState);
|
||||
let offsetY = initialOffsetY;
|
||||
|
||||
for (let i = startIndex; i < endIndex; i++) {
|
||||
const lines = this.view.state.field(LinesState);
|
||||
if (i >= lines.length) break;
|
||||
|
||||
const drawContext = {
|
||||
offsetX: 0,
|
||||
offsetY,
|
||||
context,
|
||||
lineHeight,
|
||||
charWidth,
|
||||
};
|
||||
let offsetX = 0;
|
||||
const lineNumber = i + 1;
|
||||
|
||||
// 渲染 gutters
|
||||
if (gutters.length) {
|
||||
/* Small leading buffer */
|
||||
drawContext.offsetX += 2;
|
||||
|
||||
offsetX += 2;
|
||||
for (const gutter of gutters) {
|
||||
drawLineGutter(gutter, drawContext, i + 1);
|
||||
drawContext.offsetX += GUTTER_WIDTH;
|
||||
drawLineGutter(gutter, { offsetX, offsetY, context, lineHeight, charWidth }, lineNumber);
|
||||
offsetX += GUTTER_WIDTH;
|
||||
}
|
||||
|
||||
/* Small trailing buffer */
|
||||
drawContext.offsetX += 2;
|
||||
offsetX += 2;
|
||||
}
|
||||
|
||||
this.text.drawLine(drawContext, i + 1);
|
||||
this.selection.drawLine(drawContext, i + 1);
|
||||
this.diagnostic.drawLine(drawContext, i + 1);
|
||||
// 渲染选区
|
||||
this.selection.drawLine({ offsetX, offsetY, context, lineHeight, charWidth }, lineNumber);
|
||||
|
||||
// 渲染诊断
|
||||
if (this.diagnostic.has(lineNumber)) {
|
||||
this.diagnostic.drawLine({ offsetX, offsetY, context, lineHeight, charWidth }, lineNumber);
|
||||
}
|
||||
|
||||
offsetY += lineHeight;
|
||||
}
|
||||
}
|
||||
|
||||
context.restore();
|
||||
requestRender(reason: RenderReason = 'data', type: RenderType = 'blocks') {
|
||||
if (!this.isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (reason === 'scroll') {
|
||||
const scrollTop = this.view.scrollDOM.scrollTop;
|
||||
if (this.lastRenderedScrollTop === scrollTop && !this.pendingRenderReason) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.pendingRenderReason === 'scroll' &&
|
||||
this.pendingScrollTop === scrollTop
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.pendingScrollTop = scrollTop;
|
||||
} else {
|
||||
this.pendingScrollTop = null;
|
||||
}
|
||||
|
||||
if (reason === 'data' || this.pendingRenderReason === null) {
|
||||
this.pendingRenderReason = reason;
|
||||
}
|
||||
|
||||
// 合并渲染类型:blocks > overlays
|
||||
if (this.pendingRenderType === null || type === 'blocks') {
|
||||
this.pendingRenderType = type;
|
||||
}
|
||||
|
||||
if (this.renderHandle !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
const handle = requestAnimationFrame(() => {
|
||||
this.renderHandle = null;
|
||||
this.cancelRender = null;
|
||||
this.render();
|
||||
});
|
||||
this.renderHandle = handle;
|
||||
this.cancelRender = () => cancelAnimationFrame(handle);
|
||||
return;
|
||||
}
|
||||
|
||||
const handle = setTimeout(() => {
|
||||
this.renderHandle = null;
|
||||
this.cancelRender = null;
|
||||
this.render();
|
||||
}, 16);
|
||||
this.renderHandle = handle;
|
||||
this.cancelRender = () => clearTimeout(handle);
|
||||
}
|
||||
|
||||
cancelRenderRequest() {
|
||||
if (!this.cancelRender) {
|
||||
return;
|
||||
}
|
||||
this.cancelRender();
|
||||
this.renderHandle = null;
|
||||
this.cancelRender = null;
|
||||
this.pendingScrollTop = null;
|
||||
this.pendingRenderReason = null;
|
||||
}
|
||||
|
||||
private canvasStartAndEndIndex(
|
||||
context: CanvasRenderingContext2D,
|
||||
lineHeight: number
|
||||
lineHeight: number,
|
||||
scrollTopOverride?: number
|
||||
) {
|
||||
let { top: pTop, bottom: pBottom } = this.view.documentPadding;
|
||||
(pTop /= Scale.SizeRatio), (pBottom /= Scale.SizeRatio);
|
||||
|
||||
const canvasHeight = context.canvas.height;
|
||||
const { clientHeight, scrollHeight, scrollTop } = this.view.scrollDOM;
|
||||
const { clientHeight, scrollHeight } = this.view.scrollDOM;
|
||||
const scrollTop = scrollTopOverride ?? this.view.scrollDOM.scrollTop;
|
||||
let scrollPercent = scrollTop / (scrollHeight - clientHeight);
|
||||
if (isNaN(scrollPercent)) {
|
||||
scrollPercent = 0;
|
||||
@@ -278,20 +479,26 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
const { clientWidth, scrollWidth, scrollLeft } = this.view.scrollDOM;
|
||||
|
||||
if (clientWidth + scrollLeft < scrollWidth) {
|
||||
this.canvas.classList.add("cm-minimap-box-shadow");
|
||||
this.canvas.classList.add('cm-minimap-box-shadow');
|
||||
} else {
|
||||
this.canvas.classList.remove("cm-minimap-box-shadow");
|
||||
this.canvas.classList.remove('cm-minimap-box-shadow');
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.initialRenderDelay) {
|
||||
clearTimeout(this.initialRenderDelay);
|
||||
this.initialRenderDelay = null;
|
||||
}
|
||||
this.cancelDebounce();
|
||||
this.blockManager.destroy();
|
||||
this.remove();
|
||||
}
|
||||
},
|
||||
{
|
||||
eventHandlers: {
|
||||
scroll() {
|
||||
requestAnimationFrame(() => this.render());
|
||||
this.requestRender('scroll', 'blocks');
|
||||
},
|
||||
},
|
||||
provide: (plugin) => {
|
||||
@@ -307,8 +514,7 @@ const minimapClass = ViewPlugin.fromClass(
|
||||
}
|
||||
);
|
||||
|
||||
// 使用type定义
|
||||
export type MinimapConfig = Omit<Options, "enabled"> & {
|
||||
export type MinimapConfig = Omit<Options, 'enabled'> & {
|
||||
/**
|
||||
* A function that creates the element that contains the minimap
|
||||
*/
|
||||
@@ -318,43 +524,35 @@ export type MinimapConfig = Omit<Options, "enabled"> & {
|
||||
/**
|
||||
* Facet used to show a minimap in the right gutter of the editor using the
|
||||
* provided configuration.
|
||||
*
|
||||
* If you return `null`, a minimap will not be shown.
|
||||
*/
|
||||
const showMinimapFacet = Facet.define<MinimapConfig | null, MinimapConfig | null>({
|
||||
combine: (c) => c.find((o) => o !== null) ?? null,
|
||||
enables: (f) => {
|
||||
return [
|
||||
[
|
||||
Config.compute([f], (s) => s.facet(f)),
|
||||
Theme,
|
||||
LinesState,
|
||||
minimapClass, // TODO, codemirror-ify this one better
|
||||
Overlay,
|
||||
],
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 创建默认的minimap DOM元素
|
||||
* 创建默认的 minimap DOM 元素
|
||||
*/
|
||||
const defaultCreateFn = (view: EditorView) => {
|
||||
const defaultCreateFn = (_view: EditorView) => {
|
||||
const dom = document.createElement('div');
|
||||
return { dom };
|
||||
};
|
||||
|
||||
/**
|
||||
* 添加minimap到编辑器
|
||||
* @param options Minimap配置项
|
||||
* @returns
|
||||
* 添加 minimap 到编辑器
|
||||
* @param options Minimap 配置项
|
||||
*/
|
||||
export function minimap(options: Partial<Omit<MinimapConfig, 'create'>> = {}) {
|
||||
return showMinimapFacet.of({
|
||||
const config: MinimapConfig = {
|
||||
create: defaultCreateFn,
|
||||
...options
|
||||
});
|
||||
}
|
||||
...options,
|
||||
};
|
||||
|
||||
// 保持原始接口兼容性
|
||||
export { showMinimapFacet as showMinimap };
|
||||
return [
|
||||
showMinimapFacet.of(config),
|
||||
Config.compute([showMinimapFacet], (s) => s.facet(showMinimapFacet)),
|
||||
Theme,
|
||||
LinesState,
|
||||
minimapClass,
|
||||
Overlay,
|
||||
];
|
||||
}
|
||||
|
||||
85
frontend/src/views/editor/extensions/minimap/lineGeometry.ts
Normal file
85
frontend/src/views/editor/extensions/minimap/lineGeometry.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { Lines } from "./linesState";
|
||||
|
||||
const DEFAULT_LINE_NUMBER = 0;
|
||||
|
||||
function lineBoundary(spans: Lines[number]) {
|
||||
if (!spans || spans.length === 0) {
|
||||
return { start: 0, end: 0 };
|
||||
}
|
||||
const start = spans[0].from;
|
||||
const end = spans[spans.length - 1].to;
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export function lineNumberAt(lines: Lines, position: number): number {
|
||||
if (!lines.length) {
|
||||
return DEFAULT_LINE_NUMBER;
|
||||
}
|
||||
|
||||
const first = lineBoundary(lines[0]);
|
||||
const last = lineBoundary(lines[lines.length - 1]);
|
||||
|
||||
let target = position;
|
||||
if (target < first.start) {
|
||||
target = first.start;
|
||||
} else if (target > last.end) {
|
||||
target = last.end;
|
||||
}
|
||||
|
||||
let low = 0;
|
||||
let high = lines.length - 1;
|
||||
|
||||
while (low <= high) {
|
||||
const mid = (low + high) >> 1;
|
||||
const spans = lines[mid];
|
||||
const { start, end } = lineBoundary(spans);
|
||||
|
||||
if (target < start) {
|
||||
high = mid - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (target > end) {
|
||||
low = mid + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
return mid + 1;
|
||||
}
|
||||
|
||||
return Math.max(1, Math.min(lines.length, low + 1));
|
||||
}
|
||||
|
||||
export function lineLength(spans: Lines[number]) {
|
||||
if (!spans) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
let length = 0;
|
||||
for (const span of spans) {
|
||||
length += span.folded ? 1 : Math.max(0, span.to - span.from);
|
||||
}
|
||||
|
||||
return Math.max(1, length);
|
||||
}
|
||||
|
||||
export function offsetWithinLine(pos: number, spans: Lines[number]) {
|
||||
if (!spans) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let offset = 0;
|
||||
|
||||
for (const span of spans) {
|
||||
const spanLength = span.folded ? 1 : Math.max(0, span.to - span.from);
|
||||
if (!span.folded && pos < span.to) {
|
||||
return offset + Math.max(0, pos - span.from);
|
||||
}
|
||||
if (span.folded && pos <= span.to) {
|
||||
return offset;
|
||||
}
|
||||
offset += spanLength;
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
@@ -14,6 +14,10 @@ export abstract class LineBasedState<TValue> {
|
||||
return this.map.get(lineNumber);
|
||||
}
|
||||
|
||||
public has(lineNumber: number): boolean {
|
||||
return this.map.has(lineNumber);
|
||||
}
|
||||
|
||||
protected set(lineNumber: number, value: TValue) {
|
||||
this.map.set(lineNumber, value);
|
||||
}
|
||||
|
||||
@@ -77,6 +77,12 @@ function computeLinesState(state: EditorState): Lines {
|
||||
const LinesState = StateField.define<Lines>({
|
||||
create: (state) => computeLinesState(state),
|
||||
update: (current, tr) => {
|
||||
const prevEnabled = tr.startState.facet(Config).enabled;
|
||||
const nextEnabled = tr.state.facet(Config).enabled;
|
||||
if (prevEnabled !== nextEnabled) {
|
||||
return computeLinesState(tr.state);
|
||||
}
|
||||
|
||||
if (foldsChanged([tr]) || tr.docChanged) {
|
||||
return computeLinesState(tr.state);
|
||||
}
|
||||
@@ -93,3 +99,11 @@ function foldsChanged(transactions: readonly Transaction[]) {
|
||||
}
|
||||
|
||||
export { foldsChanged, LinesState };
|
||||
|
||||
export function getLinesSnapshot(state: EditorState): Lines {
|
||||
const lines = state.field(LinesState);
|
||||
if (lines.length || !state.facet(Config).enabled) {
|
||||
return lines;
|
||||
}
|
||||
return computeLinesState(state);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,10 @@ const OverlayView = ViewPlugin.fromClass(
|
||||
|
||||
private _isDragging: boolean = false;
|
||||
private _dragStartY: number | undefined;
|
||||
private abortController: AbortController | undefined;
|
||||
private readonly _boundMouseDown = (event: MouseEvent) => this.onMouseDown(event);
|
||||
private readonly _boundMouseUp = (event: MouseEvent) => this.onMouseUp(event);
|
||||
private readonly _boundMouseMove = (event: MouseEvent) => this.onMouseMove(event);
|
||||
|
||||
public constructor(private view: EditorView) {
|
||||
if (view.state.facet(Config).enabled) {
|
||||
@@ -59,14 +63,19 @@ const OverlayView = ViewPlugin.fromClass(
|
||||
}
|
||||
|
||||
private create(view: EditorView) {
|
||||
this.remove();
|
||||
|
||||
this.abortController = new AbortController();
|
||||
const signal = this.abortController.signal;
|
||||
|
||||
this.container = crelt("div", { class: "cm-minimap-overlay-container" });
|
||||
this.dom = crelt("div", { class: "cm-minimap-overlay" });
|
||||
this.container.appendChild(this.dom);
|
||||
|
||||
// Attach event listeners for overlay
|
||||
this.container.addEventListener("mousedown", this.onMouseDown.bind(this));
|
||||
window.addEventListener("mouseup", this.onMouseUp.bind(this));
|
||||
window.addEventListener("mousemove", this.onMouseMove.bind(this));
|
||||
this.container.addEventListener("mousedown", this._boundMouseDown, { signal });
|
||||
window.addEventListener("mouseup", this._boundMouseUp, { signal });
|
||||
window.addEventListener("mousemove", this._boundMouseMove, { signal });
|
||||
|
||||
// Attach the overlay elements to the minimap
|
||||
const inner = view.dom.querySelector(".cm-minimap-inner");
|
||||
@@ -81,11 +90,15 @@ const OverlayView = ViewPlugin.fromClass(
|
||||
}
|
||||
|
||||
private remove() {
|
||||
if (this.abortController) {
|
||||
this.abortController.abort();
|
||||
this.abortController = undefined;
|
||||
}
|
||||
|
||||
if (this.container) {
|
||||
this.container.removeEventListener("mousedown", this.onMouseDown);
|
||||
window.removeEventListener("mouseup", this.onMouseUp);
|
||||
window.removeEventListener("mousemove", this.onMouseMove);
|
||||
this.container.remove();
|
||||
this.container = undefined;
|
||||
this.dom = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
import { LineBasedState } from "./linebasedstate";
|
||||
import { EditorView, ViewUpdate } from "@codemirror/view";
|
||||
import { LinesState, foldsChanged } from "./linesState";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { Lines, foldsChanged, getLinesSnapshot } from "./linesState";
|
||||
import { DrawContext } from "./types";
|
||||
import { Config } from "./config";
|
||||
import { lineLength, lineNumberAt, offsetWithinLine } from "./lineGeometry";
|
||||
|
||||
type Selection = { from: number; to: number; extends: boolean };
|
||||
type DrawInfo = { backgroundColor: string };
|
||||
type RangeInfo = {
|
||||
from: number;
|
||||
to: number;
|
||||
lineFrom: number;
|
||||
lineTo: number;
|
||||
};
|
||||
|
||||
const MAX_CACHED_LINES = 800;
|
||||
|
||||
export class SelectionState extends LineBasedState<Array<Selection>> {
|
||||
private _drawInfo: DrawInfo | undefined;
|
||||
private _themeClasses: string;
|
||||
private _rangeInfo: Array<RangeInfo> = [];
|
||||
private _linesSnapshot: Lines = [];
|
||||
|
||||
public constructor(view: EditorView) {
|
||||
super(view);
|
||||
@@ -52,95 +64,7 @@ export class SelectionState extends LineBasedState<Array<Selection>> {
|
||||
return;
|
||||
}
|
||||
|
||||
this.map.clear();
|
||||
|
||||
/* If class list has changed, clear and recalculate the selection style */
|
||||
if (this._themeClasses !== this.view.dom.classList.value) {
|
||||
this._drawInfo = undefined;
|
||||
this._themeClasses = this.view.dom.classList.value;
|
||||
}
|
||||
|
||||
const { ranges } = update.state.selection;
|
||||
|
||||
let selectionIndex = 0;
|
||||
for (const [index, line] of update.state.field(LinesState).entries()) {
|
||||
const selections: Array<Selection> = [];
|
||||
|
||||
let offset = 0;
|
||||
for (const span of line) {
|
||||
do {
|
||||
// We've already processed all selections
|
||||
if (selectionIndex >= ranges.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The next selection begins after this span
|
||||
if (span.to < ranges[selectionIndex].from) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ignore 0-length selections
|
||||
if (ranges[selectionIndex].from === ranges[selectionIndex].to) {
|
||||
selectionIndex++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Build the selection for the current span
|
||||
const range = ranges[selectionIndex];
|
||||
const selection = {
|
||||
from: offset + Math.max(span.from, range.from) - span.from,
|
||||
to: offset + Math.min(span.to, range.to) - span.from,
|
||||
extends: range.to > span.to,
|
||||
};
|
||||
|
||||
const lastSelection = selections.slice(-1)[0];
|
||||
if (lastSelection && lastSelection.to === selection.from) {
|
||||
// The selection in this span may just be a continuation of the
|
||||
// selection in the previous span
|
||||
|
||||
// Adjust `to` depending on if we're in a folded span
|
||||
let { to } = selection;
|
||||
if (span.folded && selection.extends) {
|
||||
to = selection.from + 1;
|
||||
} else if (span.folded && !selection.extends) {
|
||||
to = lastSelection.to;
|
||||
}
|
||||
|
||||
selections[selections.length - 1] = {
|
||||
...lastSelection,
|
||||
to,
|
||||
extends: selection.extends,
|
||||
};
|
||||
} else if (!span.folded) {
|
||||
// It's a new selection; if we're not in a folded span we
|
||||
// should push it onto the stack
|
||||
selections.push(selection);
|
||||
}
|
||||
|
||||
// If the selection doesn't end in this span, break out of the loop
|
||||
if (selection.extends) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Otherwise, move to the next selection
|
||||
selectionIndex++;
|
||||
} while (
|
||||
selectionIndex < ranges.length &&
|
||||
span.to >= ranges[selectionIndex].from
|
||||
);
|
||||
|
||||
offset += span.folded ? 1 : span.to - span.from;
|
||||
}
|
||||
|
||||
// If we don't have any selections on this line, we don't need to store anything
|
||||
if (selections.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lines are indexed beginning at 1 instead of 0
|
||||
const lineNumber = index + 1;
|
||||
this.map.set(lineNumber, selections);
|
||||
}
|
||||
this.rebuild(update.state);
|
||||
}
|
||||
|
||||
public drawLine(ctx: DrawContext, lineNumber: number) {
|
||||
@@ -151,7 +75,7 @@ export class SelectionState extends LineBasedState<Array<Selection>> {
|
||||
offsetX: startOffsetX,
|
||||
offsetY,
|
||||
} = ctx;
|
||||
const selections = this.get(lineNumber);
|
||||
const selections = this.ensureSelections(lineNumber);
|
||||
if (!selections) {
|
||||
return;
|
||||
}
|
||||
@@ -199,6 +123,123 @@ export class SelectionState extends LineBasedState<Array<Selection>> {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private appendSelection(target: Array<Selection>, entry: Selection) {
|
||||
const last = target[target.length - 1];
|
||||
if (last && entry.from <= last.to) {
|
||||
target[target.length - 1] = {
|
||||
from: Math.min(last.from, entry.from),
|
||||
to: Math.max(last.to, entry.to),
|
||||
extends: entry.extends || last.extends,
|
||||
};
|
||||
return;
|
||||
}
|
||||
target.push(entry);
|
||||
}
|
||||
private rebuild(state: EditorState) {
|
||||
if (this._themeClasses !== this.view.dom.classList.value) {
|
||||
this._drawInfo = undefined;
|
||||
this._themeClasses = this.view.dom.classList.value;
|
||||
}
|
||||
|
||||
this._linesSnapshot = getLinesSnapshot(state);
|
||||
this._rangeInfo = this.buildRangeInfo(state, this._linesSnapshot);
|
||||
this.map.clear();
|
||||
}
|
||||
|
||||
private buildRangeInfo(state: EditorState, lines: Lines) {
|
||||
const info: Array<RangeInfo> = [];
|
||||
for (const range of state.selection.ranges) {
|
||||
if (range.empty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const startLine = lineNumberAt(lines, range.from);
|
||||
const endLine = lineNumberAt(lines, Math.max(range.from, range.to - 1));
|
||||
if (startLine <= 0 || endLine <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
info.push({
|
||||
from: range.from,
|
||||
to: range.to,
|
||||
lineFrom: startLine,
|
||||
lineTo: endLine,
|
||||
});
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
private ensureSelections(lineNumber: number) {
|
||||
const cached = this.get(lineNumber);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const computed = this.buildSelectionsForLine(lineNumber);
|
||||
if (!computed || computed.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (this.map.has(lineNumber)) {
|
||||
this.map.delete(lineNumber);
|
||||
}
|
||||
this.map.set(lineNumber, computed);
|
||||
while (this.map.size > MAX_CACHED_LINES) {
|
||||
const oldest = this.map.keys().next();
|
||||
if (oldest.done) {
|
||||
break;
|
||||
}
|
||||
this.map.delete(oldest.value);
|
||||
}
|
||||
|
||||
return computed;
|
||||
}
|
||||
|
||||
private buildSelectionsForLine(lineNumber: number) {
|
||||
const spans = this._linesSnapshot[lineNumber - 1];
|
||||
if (!spans || spans.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const relevant = this._rangeInfo.filter(
|
||||
(info) => lineNumber >= info.lineFrom && lineNumber <= info.lineTo
|
||||
);
|
||||
if (!relevant.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const selections: Array<Selection> = [];
|
||||
for (const range of relevant) {
|
||||
const length = lineLength(spans);
|
||||
const fromOffset =
|
||||
lineNumber === range.lineFrom
|
||||
? offsetWithinLine(range.from, spans)
|
||||
: 0;
|
||||
|
||||
let toOffset =
|
||||
lineNumber === range.lineTo
|
||||
? offsetWithinLine(range.to, spans)
|
||||
: length;
|
||||
if (toOffset === fromOffset) {
|
||||
toOffset = Math.min(length, fromOffset + 1);
|
||||
}
|
||||
|
||||
const lastSpan = spans[spans.length - 1];
|
||||
const spanEnd = lastSpan ? lastSpan.to : range.to;
|
||||
const extendsLine =
|
||||
lineNumber < range.lineTo ||
|
||||
(lineNumber === range.lineTo && range.to > spanEnd);
|
||||
|
||||
this.appendSelection(selections, {
|
||||
from: fromOffset,
|
||||
to: toOffset,
|
||||
extends: extendsLine,
|
||||
});
|
||||
}
|
||||
|
||||
return selections;
|
||||
}
|
||||
}
|
||||
|
||||
export function selections(view: EditorView): SelectionState {
|
||||
|
||||
@@ -1,415 +0,0 @@
|
||||
import { LineBasedState } from "./linebasedstate";
|
||||
import { Highlighter, highlightTree } from "@lezer/highlight";
|
||||
import { ChangedRange, Tree, TreeFragment } from "@lezer/common";
|
||||
import { highlightingFor, language } from "@codemirror/language";
|
||||
import { EditorView, ViewUpdate } from "@codemirror/view";
|
||||
import { DrawContext } from "./types";
|
||||
import { Config, Options, Scale } from "./config";
|
||||
import { LinesState, foldsChanged } from "./linesState";
|
||||
import crelt from "crelt";
|
||||
import { ChangeSet, EditorState } from "@codemirror/state";
|
||||
|
||||
type TagSpan = { text: string; tags: string };
|
||||
type FontInfo = { color: string; font: string; lineHeight: number };
|
||||
|
||||
export class TextState extends LineBasedState<Array<TagSpan>> {
|
||||
private _previousTree: Tree | undefined;
|
||||
private _displayText: Required<Options>["displayText"] | undefined;
|
||||
private _fontInfoMap: Map<string, FontInfo> = new Map();
|
||||
private _themeClasses: Set<string> | undefined;
|
||||
private _highlightingCallbackId: number | NodeJS.Timeout | undefined;
|
||||
|
||||
public constructor(view: EditorView) {
|
||||
super(view);
|
||||
|
||||
this._themeClasses = new Set(Array.from(view.dom.classList));
|
||||
|
||||
if (view.state.facet(Config).enabled) {
|
||||
this.updateImpl(view.state);
|
||||
}
|
||||
}
|
||||
|
||||
private shouldUpdate(update: ViewUpdate) {
|
||||
// If the doc changed
|
||||
if (update.docChanged) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If configuration settings changed
|
||||
if (update.state.facet(Config) !== update.startState.facet(Config)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the theme changed
|
||||
if (this.themeChanged()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the folds changed
|
||||
if (foldsChanged(update.transactions)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public update(update: ViewUpdate) {
|
||||
if (!this.shouldUpdate(update)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._highlightingCallbackId) {
|
||||
typeof window.requestIdleCallback !== "undefined"
|
||||
? cancelIdleCallback(this._highlightingCallbackId as number)
|
||||
: clearTimeout(this._highlightingCallbackId);
|
||||
}
|
||||
|
||||
this.updateImpl(update.state, update.changes);
|
||||
}
|
||||
|
||||
private updateImpl(state: EditorState, changes?: ChangeSet) {
|
||||
this.map.clear();
|
||||
|
||||
/* Store display text setting for rendering */
|
||||
this._displayText = state.facet(Config).displayText;
|
||||
|
||||
/* If class list has changed, clear and recalculate the font info map */
|
||||
if (this.themeChanged()) {
|
||||
this._fontInfoMap.clear();
|
||||
}
|
||||
|
||||
/* Incrementally parse the tree based on previous tree + changes */
|
||||
let treeFragments: ReadonlyArray<TreeFragment> | undefined = undefined;
|
||||
if (this._previousTree && changes) {
|
||||
const previousFragments = TreeFragment.addTree(this._previousTree);
|
||||
|
||||
const changedRanges: Array<ChangedRange> = [];
|
||||
changes.iterChangedRanges((fromA, toA, fromB, toB) =>
|
||||
changedRanges.push({ fromA, toA, fromB, toB })
|
||||
);
|
||||
|
||||
treeFragments = TreeFragment.applyChanges(
|
||||
previousFragments,
|
||||
changedRanges
|
||||
);
|
||||
}
|
||||
|
||||
/* Parse the document into a lezer tree */
|
||||
const docToString = state.doc.toString();
|
||||
const parser = state.facet(language)?.parser;
|
||||
const tree = parser ? parser.parse(docToString, treeFragments) : undefined;
|
||||
this._previousTree = tree;
|
||||
|
||||
/* Highlight the document, and store the text and tags for each line */
|
||||
const highlighter: Highlighter = {
|
||||
style: (tags) => highlightingFor(state, tags),
|
||||
};
|
||||
|
||||
let highlights: Array<{ from: number; to: number; tags: string }> = [];
|
||||
|
||||
if (tree) {
|
||||
/**
|
||||
* The viewport renders a few extra lines above and below the editor view. To approximate
|
||||
* the lines visible in the minimap, we multiply the lines in the viewport by the scale multipliers.
|
||||
*
|
||||
* Based on the current scroll position, the minimap may show a larger portion of lines above or
|
||||
* below the lines currently in the editor view. On a long document, when the scroll position is
|
||||
* near the top of the document, the minimap will show a small number of lines above the lines
|
||||
* in the editor view, and a large number of lines below the lines in the editor view.
|
||||
*
|
||||
* To approximate this ratio, we can use the viewport scroll percentage
|
||||
*
|
||||
* ┌─────────────────────┐
|
||||
* │ │
|
||||
* │ Extra viewport │
|
||||
* │ buffer │
|
||||
* ├─────────────────────┼───────┐
|
||||
* │ │Minimap│
|
||||
* │ │Gutter │
|
||||
* │ ├───────┤
|
||||
* │ Editor View │Scaled │
|
||||
* │ │View │
|
||||
* │ │Overlay│
|
||||
* │ ├───────┤
|
||||
* │ │ │
|
||||
* │ │ │
|
||||
* ├─────────────────────┼───────┘
|
||||
* │ │
|
||||
* │ Extra viewport │
|
||||
* │ buffer │
|
||||
* └─────────────────────┘
|
||||
*
|
||||
**/
|
||||
|
||||
const vpLineTop = state.doc.lineAt(this.view.viewport.from).number;
|
||||
const vpLineBottom = state.doc.lineAt(this.view.viewport.to).number;
|
||||
const vpLineCount = vpLineBottom - vpLineTop;
|
||||
const vpScroll = vpLineTop / (state.doc.lines - vpLineCount);
|
||||
|
||||
const { SizeRatio, PixelMultiplier } = Scale;
|
||||
const mmLineCount = vpLineCount * SizeRatio * PixelMultiplier;
|
||||
const mmLineRatio = vpScroll * mmLineCount;
|
||||
|
||||
const mmLineTop = Math.max(1, Math.floor(vpLineTop - mmLineRatio));
|
||||
const mmLineBottom = Math.min(
|
||||
vpLineBottom + Math.floor(mmLineCount - mmLineRatio),
|
||||
state.doc.lines
|
||||
);
|
||||
|
||||
// Highlight the in-view lines synchronously
|
||||
highlightTree(
|
||||
tree,
|
||||
highlighter,
|
||||
(from, to, tags) => {
|
||||
highlights.push({ from, to, tags });
|
||||
},
|
||||
state.doc.line(mmLineTop).from,
|
||||
state.doc.line(mmLineBottom).to
|
||||
);
|
||||
}
|
||||
|
||||
// Update the map
|
||||
this.updateMapImpl(state, highlights);
|
||||
|
||||
// Highlight the entire tree in an idle callback
|
||||
highlights = [];
|
||||
const highlightingCallback = () => {
|
||||
if (tree) {
|
||||
highlightTree(tree, highlighter, (from, to, tags) => {
|
||||
highlights.push({ from, to, tags });
|
||||
});
|
||||
this.updateMapImpl(state, highlights);
|
||||
this._highlightingCallbackId = undefined;
|
||||
}
|
||||
};
|
||||
this._highlightingCallbackId =
|
||||
typeof window.requestIdleCallback !== "undefined"
|
||||
? requestIdleCallback(highlightingCallback)
|
||||
: setTimeout(highlightingCallback);
|
||||
}
|
||||
|
||||
private updateMapImpl(
|
||||
state: EditorState,
|
||||
highlights: Array<{ from: number; to: number; tags: string }>
|
||||
) {
|
||||
this.map.clear();
|
||||
|
||||
const docToString = state.doc.toString();
|
||||
const highlightsIterator = highlights.values();
|
||||
let highlightPtr = highlightsIterator.next();
|
||||
|
||||
for (const [index, line] of state.field(LinesState).entries()) {
|
||||
const spans: Array<TagSpan> = [];
|
||||
|
||||
for (const span of line) {
|
||||
// Skip if it's a 0-length span
|
||||
if (span.from === span.to) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Append a placeholder for a folded span
|
||||
if (span.folded) {
|
||||
spans.push({ text: "…", tags: "" });
|
||||
continue;
|
||||
}
|
||||
|
||||
let position = span.from;
|
||||
while (!highlightPtr.done && highlightPtr.value.from < span.to) {
|
||||
const { from, to, tags } = highlightPtr.value;
|
||||
|
||||
// Iterate until our highlight is over the current span
|
||||
if (to < position) {
|
||||
highlightPtr = highlightsIterator.next();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Append unstyled text before the highlight begins
|
||||
if (from > position) {
|
||||
spans.push({ text: docToString.slice(position, from), tags: "" });
|
||||
}
|
||||
|
||||
// A highlight may start before and extend beyond the current span
|
||||
const start = Math.max(from, span.from);
|
||||
const end = Math.min(to, span.to);
|
||||
|
||||
// Append the highlighted text
|
||||
spans.push({ text: docToString.slice(start, end), tags });
|
||||
position = end;
|
||||
|
||||
// If the highlight continues beyond this span, break from this loop
|
||||
if (to > end) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Otherwise, move to the next highlight
|
||||
highlightPtr = highlightsIterator.next();
|
||||
}
|
||||
|
||||
// If there are remaining spans that did not get highlighted, append them unstyled
|
||||
if (position !== span.to) {
|
||||
spans.push({
|
||||
text: docToString.slice(position, span.to),
|
||||
tags: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Lines are indexed beginning at 1 instead of 0
|
||||
const lineNumber = index + 1;
|
||||
this.map.set(lineNumber, spans);
|
||||
}
|
||||
}
|
||||
|
||||
public measure(context: CanvasRenderingContext2D): {
|
||||
charWidth: number;
|
||||
lineHeight: number;
|
||||
} {
|
||||
const { color, font, lineHeight } = this.getFontInfo("");
|
||||
|
||||
context.textBaseline = "ideographic";
|
||||
context.fillStyle = color;
|
||||
context.font = font;
|
||||
|
||||
return {
|
||||
charWidth: context.measureText("_").width,
|
||||
lineHeight: lineHeight,
|
||||
};
|
||||
}
|
||||
|
||||
public beforeDraw() {
|
||||
this._fontInfoMap.clear(); // Confirm this worked for theme changes or get rid of it because it's slow
|
||||
}
|
||||
|
||||
public drawLine(ctx: DrawContext, lineNumber: number) {
|
||||
const line = this.get(lineNumber);
|
||||
if (!line) {
|
||||
return;
|
||||
}
|
||||
|
||||
let { context, charWidth, lineHeight, offsetX, offsetY } = ctx;
|
||||
|
||||
let prevInfo: FontInfo | undefined;
|
||||
context.textBaseline = "ideographic";
|
||||
|
||||
for (const span of line) {
|
||||
const info = this.getFontInfo(span.tags);
|
||||
|
||||
if (!prevInfo || prevInfo.color !== info.color) {
|
||||
context.fillStyle = info.color;
|
||||
}
|
||||
|
||||
if (!prevInfo || prevInfo.font !== info.font) {
|
||||
context.font = info.font;
|
||||
}
|
||||
|
||||
prevInfo = info;
|
||||
|
||||
lineHeight = Math.max(lineHeight, info.lineHeight);
|
||||
|
||||
switch (this._displayText) {
|
||||
case "characters": {
|
||||
// TODO: `fillText` takes up the majority of profiling time in `render`
|
||||
// Try speeding it up with `drawImage`
|
||||
// https://stackoverflow.com/questions/8237030/html5-canvas-faster-filltext-vs-drawimage/8237081
|
||||
|
||||
context.fillText(span.text, offsetX, offsetY + lineHeight);
|
||||
offsetX += span.text.length * charWidth;
|
||||
break;
|
||||
}
|
||||
|
||||
case "blocks": {
|
||||
const nonWhitespace = /\S+/g;
|
||||
let start: RegExpExecArray | null;
|
||||
while ((start = nonWhitespace.exec(span.text)) !== null) {
|
||||
const startX = offsetX + start.index * charWidth;
|
||||
let width = (nonWhitespace.lastIndex - start.index) * charWidth;
|
||||
|
||||
// Reached the edge of the minimap
|
||||
if (startX > context.canvas.width) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Limit width to edge of minimap
|
||||
if (startX + width > context.canvas.width) {
|
||||
width = context.canvas.width - startX;
|
||||
}
|
||||
|
||||
// Scaled 2px buffer between lines
|
||||
const yBuffer = 2 / Scale.SizeRatio;
|
||||
const height = lineHeight - yBuffer;
|
||||
|
||||
context.fillStyle = info.color;
|
||||
context.globalAlpha = 0.65; // Make the blocks a bit faded
|
||||
context.beginPath();
|
||||
context.rect(startX, offsetY, width, height);
|
||||
context.fill();
|
||||
}
|
||||
|
||||
offsetX += span.text.length * charWidth;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getFontInfo(tags: string): FontInfo {
|
||||
const cached = this._fontInfoMap.get(tags);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Create a mock token wrapped in a cm-line
|
||||
const mockToken = crelt("span", { class: tags });
|
||||
const mockLine = crelt(
|
||||
"div",
|
||||
{ class: "cm-line", style: "display: none" },
|
||||
mockToken
|
||||
);
|
||||
this.view.contentDOM.appendChild(mockLine);
|
||||
|
||||
// Get style information and store it
|
||||
const style = window.getComputedStyle(mockToken);
|
||||
const lineHeight = parseFloat(style.lineHeight) / Scale.SizeRatio;
|
||||
const result = {
|
||||
color: style.color,
|
||||
font: `${style.fontStyle} ${style.fontWeight} ${lineHeight}px ${style.fontFamily}`,
|
||||
lineHeight,
|
||||
};
|
||||
this._fontInfoMap.set(tags, result);
|
||||
|
||||
// Clean up and return
|
||||
this.view.contentDOM.removeChild(mockLine);
|
||||
return result;
|
||||
}
|
||||
|
||||
private themeChanged(): boolean {
|
||||
const previous = this._themeClasses;
|
||||
const now = new Set<string>(Array.from(this.view.dom.classList));
|
||||
this._themeClasses = now;
|
||||
|
||||
if (!previous) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ignore certain classes being added/removed
|
||||
previous.delete("cm-focused");
|
||||
now.delete("cm-focused");
|
||||
|
||||
if (previous.size !== now.size) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let containsAll = true;
|
||||
previous.forEach((theme) => {
|
||||
if (!now.has(theme)) {
|
||||
containsAll = false;
|
||||
}
|
||||
});
|
||||
|
||||
return !containsAll;
|
||||
}
|
||||
}
|
||||
|
||||
export function text(view: EditorView): TextState {
|
||||
return new TextState(view);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import {
|
||||
ToWorkerMessage,
|
||||
ToMainMessage,
|
||||
BlockRequest,
|
||||
TagSpan,
|
||||
FontInfo,
|
||||
} from './protocol';
|
||||
|
||||
// 缓存字体信息,只在主题变化时更新
|
||||
let cachedFontInfoMap: Record<string, FontInfo> = {};
|
||||
let cachedDefaultFont: FontInfo = { color: '#000', font: '12px monospace', lineHeight: 14 };
|
||||
|
||||
function post(msg: ToMainMessage, transfer?: Transferable[]): void {
|
||||
self.postMessage(msg, { transfer });
|
||||
}
|
||||
|
||||
/**
|
||||
* 二分查找:找到第一个 to > pos 的高亮索引
|
||||
*/
|
||||
function findHighlightStart(highlights: BlockRequest['highlights'], pos: number): number {
|
||||
let left = 0;
|
||||
let right = highlights.length;
|
||||
while (left < right) {
|
||||
const mid = (left + right) >>> 1;
|
||||
if (highlights[mid].to <= pos) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
right = mid;
|
||||
}
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
function buildLineSpans(
|
||||
request: BlockRequest
|
||||
): Map<number, TagSpan[]> {
|
||||
const { highlights, lines, textSlice, textOffset, startLine, endLine } = request;
|
||||
const result = new Map<number, TagSpan[]>();
|
||||
|
||||
const slice = (from: number, to: number): string => {
|
||||
return textSlice.slice(from - textOffset, to - textOffset);
|
||||
};
|
||||
|
||||
// 使用二分查找找到起始高亮索引
|
||||
const firstSpanPos = lines[0]?.[0]?.from ?? 0;
|
||||
let hlIndex = findHighlightStart(highlights, firstSpanPos);
|
||||
|
||||
for (let i = 0; i < lines.length && i < endLine - startLine + 1; i++) {
|
||||
const lineNumber = startLine + i;
|
||||
const line = lines[i];
|
||||
if (!line) continue;
|
||||
|
||||
const spans: TagSpan[] = [];
|
||||
|
||||
for (const span of line) {
|
||||
if (span.from === span.to) continue;
|
||||
|
||||
if (span.folded) {
|
||||
spans.push({ text: '…', tags: '' });
|
||||
continue;
|
||||
}
|
||||
|
||||
let pos = span.from;
|
||||
|
||||
// 从当前索引继续查找
|
||||
while (hlIndex < highlights.length && highlights[hlIndex].from < span.to) {
|
||||
const hl = highlights[hlIndex];
|
||||
|
||||
if (hl.to <= pos) {
|
||||
hlIndex++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hl.from > pos) {
|
||||
spans.push({ text: slice(pos, Math.min(hl.from, span.to)), tags: '' });
|
||||
pos = Math.min(hl.from, span.to);
|
||||
}
|
||||
|
||||
if (hl.from < span.to) {
|
||||
const start = Math.max(hl.from, span.from);
|
||||
const end = Math.min(hl.to, span.to);
|
||||
if (start < end) {
|
||||
spans.push({ text: slice(start, end), tags: hl.tags });
|
||||
pos = end;
|
||||
}
|
||||
}
|
||||
|
||||
if (hl.to <= span.to) {
|
||||
hlIndex++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pos < span.to) {
|
||||
spans.push({ text: slice(pos, span.to), tags: '' });
|
||||
}
|
||||
}
|
||||
|
||||
result.set(lineNumber, spans);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function renderBlock(request: BlockRequest): void {
|
||||
const {
|
||||
blockId,
|
||||
blockIndex,
|
||||
startLine,
|
||||
endLine,
|
||||
width,
|
||||
height,
|
||||
displayText,
|
||||
charWidth,
|
||||
lineHeight,
|
||||
gutterOffset,
|
||||
} = request;
|
||||
|
||||
// 使用缓存的字体信息
|
||||
const fontInfoMap = cachedFontInfoMap;
|
||||
const defaultFont = cachedDefaultFont;
|
||||
|
||||
// Create OffscreenCanvas for this block
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) {
|
||||
post({ type: 'error', message: 'Failed to get 2d context' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Build line data
|
||||
const lineSpans = buildLineSpans(request);
|
||||
|
||||
// Render each line
|
||||
ctx.textBaseline = 'ideographic';
|
||||
let offsetY = 0;
|
||||
|
||||
for (let lineNum = startLine; lineNum <= endLine; lineNum++) {
|
||||
const spans = lineSpans.get(lineNum);
|
||||
if (spans && spans.length > 0) {
|
||||
drawLine(ctx, spans, fontInfoMap, defaultFont, displayText, gutterOffset, offsetY, charWidth, lineHeight, width);
|
||||
}
|
||||
offsetY += lineHeight;
|
||||
}
|
||||
|
||||
// Convert to ImageBitmap and send back
|
||||
const bitmap = canvas.transferToImageBitmap();
|
||||
post({ type: 'blockComplete', blockId, blockIndex, bitmap }, [bitmap]);
|
||||
}
|
||||
|
||||
function drawLine(
|
||||
ctx: OffscreenCanvasRenderingContext2D,
|
||||
spans: TagSpan[],
|
||||
fontInfoMap: Record<string, FontInfo>,
|
||||
defaultFont: FontInfo,
|
||||
displayText: 'blocks' | 'characters',
|
||||
offsetX: number,
|
||||
offsetY: number,
|
||||
charWidth: number,
|
||||
lineHeight: number,
|
||||
availableWidth: number
|
||||
): void {
|
||||
let cursorX = offsetX;
|
||||
let prevFont: FontInfo | null = null;
|
||||
|
||||
for (const span of spans) {
|
||||
const info = fontInfoMap[span.tags] || defaultFont;
|
||||
|
||||
if (!prevFont || prevFont.color !== info.color) {
|
||||
ctx.fillStyle = info.color;
|
||||
}
|
||||
if (!prevFont || prevFont.font !== info.font) {
|
||||
ctx.font = info.font;
|
||||
}
|
||||
prevFont = info;
|
||||
|
||||
if (displayText === 'characters') {
|
||||
cursorX = drawCharacters(ctx, span.text, cursorX, offsetY, charWidth, lineHeight);
|
||||
} else {
|
||||
cursorX = drawTextBlocks(ctx, span.text, cursorX, offsetY, charWidth, lineHeight, availableWidth - offsetX);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawCharacters(
|
||||
ctx: OffscreenCanvasRenderingContext2D,
|
||||
text: string,
|
||||
x: number,
|
||||
y: number,
|
||||
charWidth: number,
|
||||
lineHeight: number
|
||||
): number {
|
||||
const yPos = y + lineHeight;
|
||||
let batchStart = -1;
|
||||
let batchX = x;
|
||||
|
||||
for (let i = 0; i <= text.length; i++) {
|
||||
const char = text[i];
|
||||
const isWhitespace = !char || char === ' ' || char === '\t';
|
||||
|
||||
if (isWhitespace) {
|
||||
// 输出之前积累的批次
|
||||
if (batchStart !== -1) {
|
||||
ctx.fillText(text.slice(batchStart, i), batchX, yPos);
|
||||
batchStart = -1;
|
||||
}
|
||||
if (char) x += charWidth;
|
||||
} else {
|
||||
// 开始新批次
|
||||
if (batchStart === -1) {
|
||||
batchStart = i;
|
||||
batchX = x;
|
||||
}
|
||||
x += charWidth;
|
||||
}
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
function drawTextBlocks(
|
||||
ctx: OffscreenCanvasRenderingContext2D,
|
||||
text: string,
|
||||
x: number,
|
||||
y: number,
|
||||
charWidth: number,
|
||||
lineHeight: number,
|
||||
availableWidth: number
|
||||
): number {
|
||||
const nonWhitespace = /\S+/g;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = nonWhitespace.exec(text)) !== null) {
|
||||
const startX = x + match.index * charWidth;
|
||||
let width = (nonWhitespace.lastIndex - match.index) * charWidth;
|
||||
|
||||
if (startX > availableWidth) break;
|
||||
if (startX + width > availableWidth) {
|
||||
width = availableWidth - startX;
|
||||
}
|
||||
|
||||
if (width > 0) {
|
||||
ctx.fillRect(startX, y, width, lineHeight);
|
||||
}
|
||||
}
|
||||
|
||||
return x + text.length * charWidth;
|
||||
}
|
||||
|
||||
function handleMessage(msg: ToWorkerMessage): void {
|
||||
switch (msg.type) {
|
||||
case 'init':
|
||||
// 重置字体缓存
|
||||
cachedFontInfoMap = {};
|
||||
cachedDefaultFont = { color: '#000', font: '12px monospace', lineHeight: 14 };
|
||||
post({ type: 'ready' });
|
||||
break;
|
||||
case 'updateFontInfo':
|
||||
// 增量合并字体信息
|
||||
Object.assign(cachedFontInfoMap, msg.fontInfoMap);
|
||||
cachedDefaultFont = msg.defaultFont;
|
||||
break;
|
||||
case 'renderBlock':
|
||||
renderBlock(msg);
|
||||
break;
|
||||
case 'destroy':
|
||||
// 清理缓存
|
||||
cachedFontInfoMap = {};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
self.onmessage = (e: MessageEvent<ToWorkerMessage>) => {
|
||||
try {
|
||||
handleMessage(e.data);
|
||||
} catch (err) {
|
||||
post({ type: 'error', message: String(err) });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Worker Communication Protocol
|
||||
*/
|
||||
|
||||
export interface TagSpan {
|
||||
text: string;
|
||||
tags: string;
|
||||
}
|
||||
|
||||
export interface Highlight {
|
||||
from: number;
|
||||
to: number;
|
||||
tags: string;
|
||||
}
|
||||
|
||||
export interface LineSpan {
|
||||
from: number;
|
||||
to: number;
|
||||
folded: boolean;
|
||||
}
|
||||
|
||||
export interface FontInfo {
|
||||
color: string;
|
||||
font: string;
|
||||
lineHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新字体信息(主题变化时发送一次)
|
||||
*/
|
||||
export interface UpdateFontInfoRequest {
|
||||
type: 'updateFontInfo';
|
||||
fontInfoMap: Record<string, FontInfo>;
|
||||
defaultFont: FontInfo;
|
||||
}
|
||||
|
||||
export interface BlockRequest {
|
||||
type: 'renderBlock';
|
||||
blockId: number;
|
||||
blockIndex: number;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
width: number;
|
||||
height: number;
|
||||
highlights: Highlight[];
|
||||
lines: LineSpan[][];
|
||||
textSlice: string;
|
||||
textOffset: number;
|
||||
displayText: 'blocks' | 'characters';
|
||||
charWidth: number;
|
||||
lineHeight: number;
|
||||
gutterOffset: number;
|
||||
}
|
||||
|
||||
export interface InitRequest {
|
||||
type: 'init';
|
||||
}
|
||||
|
||||
export interface DestroyRequest {
|
||||
type: 'destroy';
|
||||
}
|
||||
|
||||
export type ToWorkerMessage = BlockRequest | InitRequest | DestroyRequest | UpdateFontInfoRequest;
|
||||
|
||||
export interface BlockComplete {
|
||||
type: 'blockComplete';
|
||||
blockId: number;
|
||||
blockIndex: number;
|
||||
bitmap: ImageBitmap;
|
||||
}
|
||||
|
||||
export interface WorkerReady {
|
||||
type: 'ready';
|
||||
}
|
||||
|
||||
export interface WorkerError {
|
||||
type: 'error';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type ToMainMessage = BlockComplete | WorkerReady | WorkerError;
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Extension, StateField } from '@codemirror/state';
|
||||
import { EditorView, showTooltip, Tooltip } from '@codemirror/view';
|
||||
import { translatorManager } from './manager';
|
||||
import { TRANSLATION_ICON_SVG } from '@/common/constant/translation';
|
||||
|
||||
const TRANSLATION_ICON_SVG = `
|
||||
<svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
|
||||
<path d="M599.68 485.056h-8l30.592 164.672c20.352-7.04 38.72-17.344 54.912-31.104a271.36 271.36 0 0 1-40.704-64.64l32.256-4.032c8.896 17.664 19.072 33.28 30.592 46.72 23.872-27.968 42.24-65.152 55.04-111.744l-154.688 0.128z m121.92 133.76c18.368 15.36 39.36 26.56 62.848 33.472l14.784 4.416-8.64 30.336-14.72-4.352a205.696 205.696 0 0 1-76.48-41.728c-20.672 17.92-44.928 31.552-71.232 40.064l20.736 110.912H519.424l-9.984 72.512h385.152c18.112 0 32.704-14.144 32.704-31.616V295.424a32.128 32.128 0 0 0-32.704-31.552H550.528l35.2 189.696h79.424v-31.552h61.44v31.552h102.4v31.616h-42.688c-14.272 55.488-35.712 100.096-64.64 133.568zM479.36 791.68H193.472c-36.224 0-65.472-28.288-65.472-63.168V191.168C128 156.16 157.312 128 193.472 128h327.68l20.544 104.32h352.832c36.224 0 65.472 28.224 65.472 63.104v537.408c0 34.944-29.312 63.168-65.472 63.168H468.608l10.688-104.32zM337.472 548.352v-33.28H272.768v-48.896h60.16V433.28h-60.16v-41.728h64.704v-32.896h-102.4v189.632h102.4z m158.272 0V453.76c0-17.216-4.032-30.272-12.16-39.488-8.192-9.152-20.288-13.696-36.032-13.696a55.04 55.04 0 0 0-24.768 5.376 39.04 39.04 0 0 0-17.088 15.936h-1.984l-5.056-18.56h-28.352V548.48h37.12V480c0-17.088 2.304-29.376 6.912-36.736 4.608-7.424 12.16-11.072 22.528-11.072 7.616 0 13.248 2.56 16.64 7.872 3.52 5.248 5.312 13.056 5.312 23.488v84.736h36.928z" fill="currentColor"></path>
|
||||
</svg>`;
|
||||
|
||||
function TranslationTooltips(state: any): readonly Tooltip[] {
|
||||
const selection = state.selection.main;
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {KeyBindingCommand} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {
|
||||
openSearchPanel,
|
||||
closeSearchPanel,
|
||||
} from '@codemirror/search';
|
||||
import {closeSearchPanel, openSearchPanel,} from '@codemirror/search';
|
||||
import {
|
||||
addNewBlockAfterCurrent,
|
||||
addNewBlockAfterLast,
|
||||
@@ -22,8 +18,22 @@ import {moveLineDown, moveLineUp} from '../extensions/codeblock/moveLines';
|
||||
import {transposeChars} from '../extensions/codeblock';
|
||||
import {copyCommand, cutCommand, pasteCommand} from '../extensions/codeblock/copyPaste';
|
||||
import {
|
||||
addCursorAbove,
|
||||
addCursorBelow,
|
||||
copyLineDown,
|
||||
copyLineUp,
|
||||
cursorCharLeft,
|
||||
cursorCharRight,
|
||||
cursorLineDown,
|
||||
cursorLineUp,
|
||||
cursorPageDown,
|
||||
cursorPageUp,
|
||||
cursorDocEnd,
|
||||
cursorDocStart,
|
||||
cursorGroupLeft,
|
||||
cursorGroupRight,
|
||||
cursorLineEnd,
|
||||
cursorLineStart,
|
||||
cursorMatchingBracket,
|
||||
cursorSyntaxLeft,
|
||||
cursorSyntaxRight,
|
||||
@@ -31,6 +41,8 @@ import {
|
||||
deleteCharForward,
|
||||
deleteGroupBackward,
|
||||
deleteGroupForward,
|
||||
deleteToLineEnd,
|
||||
deleteToLineStart,
|
||||
indentLess,
|
||||
indentMore,
|
||||
indentSelection,
|
||||
@@ -38,10 +50,23 @@ import {
|
||||
insertNewlineAndIndent,
|
||||
redo,
|
||||
redoSelection,
|
||||
selectCharLeft,
|
||||
selectCharRight,
|
||||
selectLineDown,
|
||||
selectLineUp,
|
||||
selectDocEnd,
|
||||
selectDocStart,
|
||||
selectGroupLeft,
|
||||
selectGroupRight,
|
||||
selectLine,
|
||||
selectLineEnd,
|
||||
selectLineStart,
|
||||
selectMatchingBracket,
|
||||
selectParentSyntax,
|
||||
selectSyntaxLeft,
|
||||
selectSyntaxRight,
|
||||
simplifySelection,
|
||||
splitLine,
|
||||
toggleBlockComment,
|
||||
toggleComment,
|
||||
undo,
|
||||
@@ -49,249 +74,371 @@ import {
|
||||
} from '@codemirror/commands';
|
||||
import {foldAll, foldCode, unfoldAll, unfoldCode} from '@codemirror/language';
|
||||
import i18n from '@/i18n';
|
||||
import {KeyBindingName} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {copyBlockImageCommand} from '../extensions/blockImage';
|
||||
|
||||
// 默认编辑器选项
|
||||
const defaultEditorOptions = {
|
||||
const defaultBlockExtensionOptions = {
|
||||
defaultBlockToken: 'text',
|
||||
defaultBlockAutoDetect: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* 前端命令注册表
|
||||
* 将后端定义的command字段映射到具体的前端方法和翻译键
|
||||
* 将后端定义的key字段映射到具体的前端方法和翻译键
|
||||
*/
|
||||
export const commands = {
|
||||
[KeyBindingCommand.ShowSearchCommand]: {
|
||||
export const commands: Record<string, { handler: any; descriptionKey: string }> = {
|
||||
[KeyBindingName.ShowSearch]: {
|
||||
handler: openSearchPanel,
|
||||
descriptionKey: 'keybindings.commands.showSearch'
|
||||
},
|
||||
[KeyBindingCommand.HideSearchCommand]: {
|
||||
[KeyBindingName.HideSearch]: {
|
||||
handler: closeSearchPanel,
|
||||
descriptionKey: 'keybindings.commands.hideSearch'
|
||||
},
|
||||
// 代码块操作命令
|
||||
[KeyBindingCommand.BlockSelectAllCommand]: {
|
||||
[KeyBindingName.BlockSelectAll]: {
|
||||
handler: selectAll,
|
||||
descriptionKey: 'keybindings.commands.blockSelectAll'
|
||||
},
|
||||
[KeyBindingCommand.BlockAddAfterCurrentCommand]: {
|
||||
handler: addNewBlockAfterCurrent(defaultEditorOptions),
|
||||
[KeyBindingName.BlockAddAfterCurrent]: {
|
||||
handler: addNewBlockAfterCurrent(defaultBlockExtensionOptions),
|
||||
descriptionKey: 'keybindings.commands.blockAddAfterCurrent'
|
||||
},
|
||||
[KeyBindingCommand.BlockAddAfterLastCommand]: {
|
||||
handler: addNewBlockAfterLast(defaultEditorOptions),
|
||||
[KeyBindingName.BlockAddAfterLast]: {
|
||||
handler: addNewBlockAfterLast(defaultBlockExtensionOptions),
|
||||
descriptionKey: 'keybindings.commands.blockAddAfterLast'
|
||||
},
|
||||
[KeyBindingCommand.BlockAddBeforeCurrentCommand]: {
|
||||
handler: addNewBlockBeforeCurrent(defaultEditorOptions),
|
||||
[KeyBindingName.BlockAddBeforeCurrent]: {
|
||||
handler: addNewBlockBeforeCurrent(defaultBlockExtensionOptions),
|
||||
descriptionKey: 'keybindings.commands.blockAddBeforeCurrent'
|
||||
},
|
||||
[KeyBindingCommand.BlockGotoPreviousCommand]: {
|
||||
[KeyBindingName.BlockGotoPrevious]: {
|
||||
handler: gotoPreviousBlock,
|
||||
descriptionKey: 'keybindings.commands.blockGotoPrevious'
|
||||
},
|
||||
[KeyBindingCommand.BlockGotoNextCommand]: {
|
||||
[KeyBindingName.BlockGotoNext]: {
|
||||
handler: gotoNextBlock,
|
||||
descriptionKey: 'keybindings.commands.blockGotoNext'
|
||||
},
|
||||
[KeyBindingCommand.BlockSelectPreviousCommand]: {
|
||||
[KeyBindingName.BlockSelectPrevious]: {
|
||||
handler: selectPreviousBlock,
|
||||
descriptionKey: 'keybindings.commands.blockSelectPrevious'
|
||||
},
|
||||
[KeyBindingCommand.BlockSelectNextCommand]: {
|
||||
[KeyBindingName.BlockSelectNext]: {
|
||||
handler: selectNextBlock,
|
||||
descriptionKey: 'keybindings.commands.blockSelectNext'
|
||||
},
|
||||
[KeyBindingCommand.BlockDeleteCommand]: {
|
||||
handler: deleteBlock(defaultEditorOptions),
|
||||
[KeyBindingName.BlockDelete]: {
|
||||
handler: deleteBlock(defaultBlockExtensionOptions),
|
||||
descriptionKey: 'keybindings.commands.blockDelete'
|
||||
},
|
||||
[KeyBindingCommand.BlockMoveUpCommand]: {
|
||||
[KeyBindingName.BlockMoveUp]: {
|
||||
handler: moveCurrentBlockUp,
|
||||
descriptionKey: 'keybindings.commands.blockMoveUp'
|
||||
},
|
||||
[KeyBindingCommand.BlockMoveDownCommand]: {
|
||||
[KeyBindingName.BlockMoveDown]: {
|
||||
handler: moveCurrentBlockDown,
|
||||
descriptionKey: 'keybindings.commands.blockMoveDown'
|
||||
},
|
||||
[KeyBindingCommand.BlockDeleteLineCommand]: {
|
||||
[KeyBindingName.BlockDeleteLine]: {
|
||||
handler: deleteLineCommand,
|
||||
descriptionKey: 'keybindings.commands.blockDeleteLine'
|
||||
},
|
||||
[KeyBindingCommand.BlockMoveLineUpCommand]: {
|
||||
[KeyBindingName.BlockMoveLineUp]: {
|
||||
handler: moveLineUp,
|
||||
descriptionKey: 'keybindings.commands.blockMoveLineUp'
|
||||
},
|
||||
[KeyBindingCommand.BlockMoveLineDownCommand]: {
|
||||
[KeyBindingName.BlockMoveLineDown]: {
|
||||
handler: moveLineDown,
|
||||
descriptionKey: 'keybindings.commands.blockMoveLineDown'
|
||||
},
|
||||
[KeyBindingCommand.BlockTransposeCharsCommand]: {
|
||||
[KeyBindingName.BlockTransposeChars]: {
|
||||
handler: transposeChars,
|
||||
descriptionKey: 'keybindings.commands.blockTransposeChars'
|
||||
},
|
||||
[KeyBindingCommand.BlockFormatCommand]: {
|
||||
[KeyBindingName.BlockFormat]: {
|
||||
handler: formatCurrentBlock,
|
||||
descriptionKey: 'keybindings.commands.blockFormat'
|
||||
},
|
||||
[KeyBindingCommand.BlockCopyCommand]: {
|
||||
[KeyBindingName.BlockCopy]: {
|
||||
handler: copyCommand,
|
||||
descriptionKey: 'keybindings.commands.blockCopy'
|
||||
},
|
||||
[KeyBindingCommand.BlockCutCommand]: {
|
||||
[KeyBindingName.BlockCut]: {
|
||||
handler: cutCommand,
|
||||
descriptionKey: 'keybindings.commands.blockCut'
|
||||
},
|
||||
[KeyBindingCommand.BlockPasteCommand]: {
|
||||
[KeyBindingName.BlockPaste]: {
|
||||
handler: pasteCommand,
|
||||
descriptionKey: 'keybindings.commands.blockPaste'
|
||||
},
|
||||
[KeyBindingCommand.HistoryUndoCommand]: {
|
||||
[KeyBindingName.CopyBlockImage]: {
|
||||
handler: copyBlockImageCommand,
|
||||
descriptionKey: 'keybindings.commands.copyBlockImage'
|
||||
},
|
||||
[KeyBindingName.HistoryUndo]: {
|
||||
handler: undo,
|
||||
descriptionKey: 'keybindings.commands.historyUndo'
|
||||
},
|
||||
[KeyBindingCommand.HistoryRedoCommand]: {
|
||||
[KeyBindingName.HistoryRedo]: {
|
||||
handler: redo,
|
||||
descriptionKey: 'keybindings.commands.historyRedo'
|
||||
},
|
||||
[KeyBindingCommand.HistoryUndoSelectionCommand]: {
|
||||
[KeyBindingName.HistoryUndoSelection]: {
|
||||
handler: undoSelection,
|
||||
descriptionKey: 'keybindings.commands.historyUndoSelection'
|
||||
},
|
||||
[KeyBindingCommand.HistoryRedoSelectionCommand]: {
|
||||
[KeyBindingName.HistoryRedoSelection]: {
|
||||
handler: redoSelection,
|
||||
descriptionKey: 'keybindings.commands.historyRedoSelection'
|
||||
},
|
||||
[KeyBindingCommand.FoldCodeCommand]: {
|
||||
[KeyBindingName.FoldCode]: {
|
||||
handler: foldCode,
|
||||
descriptionKey: 'keybindings.commands.foldCode'
|
||||
},
|
||||
[KeyBindingCommand.UnfoldCodeCommand]: {
|
||||
[KeyBindingName.UnfoldCode]: {
|
||||
handler: unfoldCode,
|
||||
descriptionKey: 'keybindings.commands.unfoldCode'
|
||||
},
|
||||
[KeyBindingCommand.FoldAllCommand]: {
|
||||
[KeyBindingName.FoldAll]: {
|
||||
handler: foldAll,
|
||||
descriptionKey: 'keybindings.commands.foldAll'
|
||||
},
|
||||
[KeyBindingCommand.UnfoldAllCommand]: {
|
||||
[KeyBindingName.UnfoldAll]: {
|
||||
handler: unfoldAll,
|
||||
descriptionKey: 'keybindings.commands.unfoldAll'
|
||||
},
|
||||
[KeyBindingCommand.CursorSyntaxLeftCommand]: {
|
||||
[KeyBindingName.CursorSyntaxLeft]: {
|
||||
handler: cursorSyntaxLeft,
|
||||
descriptionKey: 'keybindings.commands.cursorSyntaxLeft'
|
||||
},
|
||||
[KeyBindingCommand.CursorSyntaxRightCommand]: {
|
||||
[KeyBindingName.CursorSyntaxRight]: {
|
||||
handler: cursorSyntaxRight,
|
||||
descriptionKey: 'keybindings.commands.cursorSyntaxRight'
|
||||
},
|
||||
[KeyBindingCommand.SelectSyntaxLeftCommand]: {
|
||||
[KeyBindingName.SelectSyntaxLeft]: {
|
||||
handler: selectSyntaxLeft,
|
||||
descriptionKey: 'keybindings.commands.selectSyntaxLeft'
|
||||
},
|
||||
[KeyBindingCommand.SelectSyntaxRightCommand]: {
|
||||
[KeyBindingName.SelectSyntaxRight]: {
|
||||
handler: selectSyntaxRight,
|
||||
descriptionKey: 'keybindings.commands.selectSyntaxRight'
|
||||
},
|
||||
[KeyBindingCommand.CopyLineUpCommand]: {
|
||||
[KeyBindingName.CopyLineUp]: {
|
||||
handler: copyLineUp,
|
||||
descriptionKey: 'keybindings.commands.copyLineUp'
|
||||
},
|
||||
[KeyBindingCommand.CopyLineDownCommand]: {
|
||||
[KeyBindingName.CopyLineDown]: {
|
||||
handler: copyLineDown,
|
||||
descriptionKey: 'keybindings.commands.copyLineDown'
|
||||
},
|
||||
[KeyBindingCommand.InsertBlankLineCommand]: {
|
||||
[KeyBindingName.InsertBlankLine]: {
|
||||
handler: insertBlankLine,
|
||||
descriptionKey: 'keybindings.commands.insertBlankLine'
|
||||
},
|
||||
[KeyBindingCommand.SelectLineCommand]: {
|
||||
[KeyBindingName.SelectLine]: {
|
||||
handler: selectLine,
|
||||
descriptionKey: 'keybindings.commands.selectLine'
|
||||
},
|
||||
[KeyBindingCommand.SelectParentSyntaxCommand]: {
|
||||
[KeyBindingName.SelectParentSyntax]: {
|
||||
handler: selectParentSyntax,
|
||||
descriptionKey: 'keybindings.commands.selectParentSyntax'
|
||||
},
|
||||
[KeyBindingCommand.IndentLessCommand]: {
|
||||
[KeyBindingName.SimplifySelection]: {
|
||||
handler: simplifySelection,
|
||||
descriptionKey: 'keybindings.commands.simplifySelection'
|
||||
},
|
||||
[KeyBindingName.AddCursorAbove]: {
|
||||
handler: addCursorAbove,
|
||||
descriptionKey: 'keybindings.commands.addCursorAbove'
|
||||
},
|
||||
[KeyBindingName.AddCursorBelow]: {
|
||||
handler: addCursorBelow,
|
||||
descriptionKey: 'keybindings.commands.addCursorBelow'
|
||||
},
|
||||
[KeyBindingName.CursorGroupLeft]: {
|
||||
handler: cursorGroupLeft,
|
||||
descriptionKey: 'keybindings.commands.cursorGroupLeft'
|
||||
},
|
||||
[KeyBindingName.CursorGroupRight]: {
|
||||
handler: cursorGroupRight,
|
||||
descriptionKey: 'keybindings.commands.cursorGroupRight'
|
||||
},
|
||||
[KeyBindingName.SelectGroupLeft]: {
|
||||
handler: selectGroupLeft,
|
||||
descriptionKey: 'keybindings.commands.selectGroupLeft'
|
||||
},
|
||||
[KeyBindingName.SelectGroupRight]: {
|
||||
handler: selectGroupRight,
|
||||
descriptionKey: 'keybindings.commands.selectGroupRight'
|
||||
},
|
||||
[KeyBindingName.DeleteToLineEnd]: {
|
||||
handler: deleteToLineEnd,
|
||||
descriptionKey: 'keybindings.commands.deleteToLineEnd'
|
||||
},
|
||||
[KeyBindingName.DeleteToLineStart]: {
|
||||
handler: deleteToLineStart,
|
||||
descriptionKey: 'keybindings.commands.deleteToLineStart'
|
||||
},
|
||||
[KeyBindingName.CursorLineStart]: {
|
||||
handler: cursorLineStart,
|
||||
descriptionKey: 'keybindings.commands.cursorLineStart'
|
||||
},
|
||||
[KeyBindingName.CursorLineEnd]: {
|
||||
handler: cursorLineEnd,
|
||||
descriptionKey: 'keybindings.commands.cursorLineEnd'
|
||||
},
|
||||
[KeyBindingName.SelectLineStart]: {
|
||||
handler: selectLineStart,
|
||||
descriptionKey: 'keybindings.commands.selectLineStart'
|
||||
},
|
||||
[KeyBindingName.SelectLineEnd]: {
|
||||
handler: selectLineEnd,
|
||||
descriptionKey: 'keybindings.commands.selectLineEnd'
|
||||
},
|
||||
[KeyBindingName.CursorDocStart]: {
|
||||
handler: cursorDocStart,
|
||||
descriptionKey: 'keybindings.commands.cursorDocStart'
|
||||
},
|
||||
[KeyBindingName.CursorDocEnd]: {
|
||||
handler: cursorDocEnd,
|
||||
descriptionKey: 'keybindings.commands.cursorDocEnd'
|
||||
},
|
||||
[KeyBindingName.SelectDocStart]: {
|
||||
handler: selectDocStart,
|
||||
descriptionKey: 'keybindings.commands.selectDocStart'
|
||||
},
|
||||
[KeyBindingName.SelectDocEnd]: {
|
||||
handler: selectDocEnd,
|
||||
descriptionKey: 'keybindings.commands.selectDocEnd'
|
||||
},
|
||||
[KeyBindingName.SelectMatchingBracket]: {
|
||||
handler: selectMatchingBracket,
|
||||
descriptionKey: 'keybindings.commands.selectMatchingBracket'
|
||||
},
|
||||
[KeyBindingName.SplitLine]: {
|
||||
handler: splitLine,
|
||||
descriptionKey: 'keybindings.commands.splitLine'
|
||||
},
|
||||
[KeyBindingName.IndentLess]: {
|
||||
handler: indentLess,
|
||||
descriptionKey: 'keybindings.commands.indentLess'
|
||||
},
|
||||
[KeyBindingCommand.IndentMoreCommand]: {
|
||||
[KeyBindingName.IndentMore]: {
|
||||
handler: indentMore,
|
||||
descriptionKey: 'keybindings.commands.indentMore'
|
||||
},
|
||||
[KeyBindingCommand.IndentSelectionCommand]: {
|
||||
[KeyBindingName.IndentSelection]: {
|
||||
handler: indentSelection,
|
||||
descriptionKey: 'keybindings.commands.indentSelection'
|
||||
},
|
||||
[KeyBindingCommand.CursorMatchingBracketCommand]: {
|
||||
[KeyBindingName.CursorMatchingBracket]: {
|
||||
handler: cursorMatchingBracket,
|
||||
descriptionKey: 'keybindings.commands.cursorMatchingBracket'
|
||||
},
|
||||
[KeyBindingCommand.ToggleCommentCommand]: {
|
||||
[KeyBindingName.ToggleComment]: {
|
||||
handler: toggleComment,
|
||||
descriptionKey: 'keybindings.commands.toggleComment'
|
||||
},
|
||||
[KeyBindingCommand.ToggleBlockCommentCommand]: {
|
||||
[KeyBindingName.ToggleBlockComment]: {
|
||||
handler: toggleBlockComment,
|
||||
descriptionKey: 'keybindings.commands.toggleBlockComment'
|
||||
},
|
||||
[KeyBindingCommand.InsertNewlineAndIndentCommand]: {
|
||||
[KeyBindingName.InsertNewlineAndIndent]: {
|
||||
handler: insertNewlineAndIndent,
|
||||
descriptionKey: 'keybindings.commands.insertNewlineAndIndent'
|
||||
},
|
||||
[KeyBindingCommand.DeleteCharBackwardCommand]: {
|
||||
[KeyBindingName.DeleteCharBackward]: {
|
||||
handler: deleteCharBackward,
|
||||
descriptionKey: 'keybindings.commands.deleteCharBackward'
|
||||
},
|
||||
[KeyBindingCommand.DeleteCharForwardCommand]: {
|
||||
[KeyBindingName.DeleteCharForward]: {
|
||||
handler: deleteCharForward,
|
||||
descriptionKey: 'keybindings.commands.deleteCharForward'
|
||||
},
|
||||
[KeyBindingCommand.DeleteGroupBackwardCommand]: {
|
||||
[KeyBindingName.DeleteGroupBackward]: {
|
||||
handler: deleteGroupBackward,
|
||||
descriptionKey: 'keybindings.commands.deleteGroupBackward'
|
||||
},
|
||||
[KeyBindingCommand.DeleteGroupForwardCommand]: {
|
||||
[KeyBindingName.DeleteGroupForward]: {
|
||||
handler: deleteGroupForward,
|
||||
descriptionKey: 'keybindings.commands.deleteGroupForward'
|
||||
},
|
||||
} as const;
|
||||
|
||||
// Emacs 模式额外的基础导航命令
|
||||
[KeyBindingName.CursorCharLeft]: {
|
||||
handler: cursorCharLeft,
|
||||
descriptionKey: 'keybindings.commands.cursorCharLeft'
|
||||
},
|
||||
[KeyBindingName.CursorCharRight]: {
|
||||
handler: cursorCharRight,
|
||||
descriptionKey: 'keybindings.commands.cursorCharRight'
|
||||
},
|
||||
[KeyBindingName.CursorLineUp]: {
|
||||
handler: cursorLineUp,
|
||||
descriptionKey: 'keybindings.commands.cursorLineUp'
|
||||
},
|
||||
[KeyBindingName.CursorLineDown]: {
|
||||
handler: cursorLineDown,
|
||||
descriptionKey: 'keybindings.commands.cursorLineDown'
|
||||
},
|
||||
[KeyBindingName.CursorPageUp]: {
|
||||
handler: cursorPageUp,
|
||||
descriptionKey: 'keybindings.commands.cursorPageUp'
|
||||
},
|
||||
[KeyBindingName.CursorPageDown]: {
|
||||
handler: cursorPageDown,
|
||||
descriptionKey: 'keybindings.commands.cursorPageDown'
|
||||
},
|
||||
[KeyBindingName.SelectCharLeft]: {
|
||||
handler: selectCharLeft,
|
||||
descriptionKey: 'keybindings.commands.selectCharLeft'
|
||||
},
|
||||
[KeyBindingName.SelectCharRight]: {
|
||||
handler: selectCharRight,
|
||||
descriptionKey: 'keybindings.commands.selectCharRight'
|
||||
},
|
||||
[KeyBindingName.SelectLineUp]: {
|
||||
handler: selectLineUp,
|
||||
descriptionKey: 'keybindings.commands.selectLineUp'
|
||||
},
|
||||
[KeyBindingName.SelectLineDown]: {
|
||||
handler: selectLineDown,
|
||||
descriptionKey: 'keybindings.commands.selectLineDown'
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取命令处理函数
|
||||
* @param command 命令名称
|
||||
* @param key 命令标识符
|
||||
* @returns 对应的处理函数,如果不存在则返回 undefined
|
||||
*/
|
||||
export const getCommandHandler = (command: KeyBindingCommand) => {
|
||||
return commands[command]?.handler;
|
||||
export const getCommandHandler = (key: string) => {
|
||||
return commands[key]?.handler;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取命令描述
|
||||
* @param command 命令名称
|
||||
* @param key 命令标识符
|
||||
* @returns 对应的描述,如果不存在则返回 undefined
|
||||
*/
|
||||
export const getCommandDescription = (command: KeyBindingCommand) => {
|
||||
const descriptionKey = commands[command]?.descriptionKey;
|
||||
export const getCommandDescription = (key: string) => {
|
||||
const descriptionKey = commands[key]?.descriptionKey;
|
||||
return descriptionKey ? i18n.global.t(descriptionKey) : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 检查命令是否已注册
|
||||
* @param command 命令名称
|
||||
* @param key 命令标识符
|
||||
* @returns 是否已注册
|
||||
*/
|
||||
export const isCommandRegistered = (command: KeyBindingCommand): boolean => {
|
||||
return command in commands;
|
||||
export const isCommandRegistered = (key: string): boolean => {
|
||||
return key in commands;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取所有已注册的命令
|
||||
* @returns 已注册的命令列表
|
||||
*/
|
||||
export const getRegisteredCommands = (): KeyBindingCommand[] => {
|
||||
return Object.keys(commands) as KeyBindingCommand[];
|
||||
export const getRegisteredCommands = (): string[] => {
|
||||
return Object.keys(commands);
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Extension } from '@codemirror/state';
|
||||
import { useKeybindingStore } from '@/stores/keybindingStore';
|
||||
import { useExtensionStore } from '@/stores/extensionStore';
|
||||
import { Manager } from './manager';
|
||||
|
||||
/**
|
||||
@@ -8,22 +7,13 @@ import { Manager } from './manager';
|
||||
*/
|
||||
export const createDynamicKeymapExtension = async (): Promise<Extension> => {
|
||||
const keybindingStore = useKeybindingStore();
|
||||
const extensionStore = useExtensionStore();
|
||||
|
||||
// 确保快捷键配置已加载
|
||||
if (keybindingStore.keyBindings.length === 0) {
|
||||
await keybindingStore.loadKeyBindings();
|
||||
}
|
||||
|
||||
// 确保扩展配置已加载
|
||||
if (extensionStore.extensions.length === 0) {
|
||||
await extensionStore.loadExtensions();
|
||||
}
|
||||
|
||||
// 获取启用的扩展ID列表
|
||||
const enabledExtensionIds = extensionStore.enabledExtensions.map(ext => ext.id);
|
||||
|
||||
return Manager.createKeymapExtension(keybindingStore.keyBindings, enabledExtensionIds);
|
||||
return Manager.createKeymapExtension(keybindingStore.keyBindings);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -32,15 +22,9 @@ export const createDynamicKeymapExtension = async (): Promise<Extension> => {
|
||||
*/
|
||||
export const updateKeymapExtension = (view: any): void => {
|
||||
const keybindingStore = useKeybindingStore();
|
||||
const extensionStore = useExtensionStore();
|
||||
|
||||
// 获取启用的扩展ID列表
|
||||
const enabledExtensionIds = extensionStore.enabledExtensions.map(ext => ext.id);
|
||||
|
||||
Manager.updateKeymap(view, keybindingStore.keyBindings, enabledExtensionIds);
|
||||
Manager.updateKeymap(view, keybindingStore.keyBindings);
|
||||
};
|
||||
|
||||
// 导出相关模块
|
||||
export { Manager } from './manager';
|
||||
export { commands, getCommandHandler, getCommandDescription, isCommandRegistered, getRegisteredCommands } from './commands';
|
||||
export type { KeyBinding, CommandHandler, CommandDefinition, KeymapResult } from './types';
|
||||
@@ -1,7 +1,6 @@
|
||||
import {keymap} from '@codemirror/view';
|
||||
import {Extension, Compartment} from '@codemirror/state';
|
||||
import {KeyBinding as KeyBindingConfig, ExtensionID} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {KeyBinding, KeymapResult} from './types';
|
||||
import {KeyBinding, keymap} from '@codemirror/view';
|
||||
import {Compartment, Extension} from '@codemirror/state';
|
||||
import {KeyBinding as KeyBindingConfig} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
import {getCommandHandler, isCommandRegistered} from './commands';
|
||||
|
||||
/**
|
||||
@@ -14,10 +13,9 @@ export class Manager {
|
||||
/**
|
||||
* 将后端快捷键配置转换为CodeMirror快捷键绑定
|
||||
* @param keyBindings 后端快捷键配置列表
|
||||
* @param enabledExtensions 启用的扩展ID列表,如果不提供则使用所有启用的快捷键
|
||||
* @returns 转换结果
|
||||
*/
|
||||
static convertToKeyBindings(keyBindings: KeyBindingConfig[], enabledExtensions?: ExtensionID[]): KeymapResult {
|
||||
static convertToKeyBindings(keyBindings: KeyBindingConfig[]): KeyBinding[] {
|
||||
const result: KeyBinding[] = [];
|
||||
|
||||
for (const binding of keyBindings) {
|
||||
@@ -26,45 +24,40 @@ export class Manager {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 如果提供了扩展列表,则只处理启用扩展的快捷键
|
||||
if (enabledExtensions && !enabledExtensions.includes(binding.extension)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 检查命令是否已注册
|
||||
if (!isCommandRegistered(binding.command)) {
|
||||
if (!binding.name || !isCommandRegistered(binding.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 获取命令处理函数
|
||||
const handler = getCommandHandler(binding.command);
|
||||
const handler = getCommandHandler(binding.name);
|
||||
if (!handler) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 转换为CodeMirror快捷键格式
|
||||
const keyBinding: KeyBinding = {
|
||||
key: binding.key,
|
||||
key: binding.key || '',
|
||||
mac: binding.macos || undefined,
|
||||
win: binding.windows || undefined,
|
||||
linux: binding.linux || undefined,
|
||||
run: handler,
|
||||
preventDefault: true
|
||||
preventDefault: binding.preventDefault,
|
||||
scope: binding.scope || undefined
|
||||
};
|
||||
|
||||
result.push(keyBinding);
|
||||
}
|
||||
|
||||
return {keyBindings: result};
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建CodeMirror快捷键扩展
|
||||
* @param keyBindings 后端快捷键配置列表
|
||||
* @param enabledExtensions 启用的扩展ID列表
|
||||
* @returns CodeMirror扩展
|
||||
*/
|
||||
static createKeymapExtension(keyBindings: KeyBindingConfig[], enabledExtensions?: ExtensionID[]): Extension {
|
||||
const {keyBindings: cmKeyBindings} =
|
||||
this.convertToKeyBindings(keyBindings, enabledExtensions);
|
||||
|
||||
static createKeymapExtension(keyBindings: KeyBindingConfig[]): Extension {
|
||||
const cmKeyBindings = this.convertToKeyBindings(keyBindings);
|
||||
return this.compartment.of(keymap.of(cmKeyBindings));
|
||||
}
|
||||
|
||||
@@ -72,12 +65,9 @@ export class Manager {
|
||||
* 动态更新快捷键扩展
|
||||
* @param view 编辑器视图
|
||||
* @param keyBindings 后端快捷键配置列表
|
||||
* @param enabledExtensions 启用的扩展ID列表
|
||||
*/
|
||||
static updateKeymap(view: any, keyBindings: KeyBindingConfig[], enabledExtensions: ExtensionID[]): void {
|
||||
const {keyBindings: cmKeyBindings} =
|
||||
this.convertToKeyBindings(keyBindings, enabledExtensions);
|
||||
|
||||
static updateKeymap(view: any, keyBindings: KeyBindingConfig[]): void {
|
||||
const cmKeyBindings = this.convertToKeyBindings(keyBindings);
|
||||
view.dispatch({
|
||||
effects: this.compartment.reconfigure(keymap.of(cmKeyBindings))
|
||||
});
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import {Command} from '@codemirror/view';
|
||||
|
||||
/**
|
||||
* CodeMirror快捷键绑定格式
|
||||
*/
|
||||
export interface KeyBinding {
|
||||
key: string
|
||||
run: Command
|
||||
preventDefault?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 命令处理函数类型
|
||||
*/
|
||||
export type CommandHandler = Command
|
||||
|
||||
/**
|
||||
* 命令定义接口
|
||||
*/
|
||||
export interface CommandDefinition {
|
||||
handler: CommandHandler
|
||||
descriptionKey: string // 翻译键
|
||||
}
|
||||
|
||||
/**
|
||||
* 快捷键转换结果
|
||||
*/
|
||||
export interface KeymapResult {
|
||||
keyBindings: KeyBinding[]
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import {Manager} from './manager';
|
||||
import {ExtensionID} from '@/../bindings/voidraft/internal/models/models';
|
||||
import i18n from '@/i18n';
|
||||
import {ExtensionDefinition} from './types';
|
||||
import {Prec} from '@codemirror/state';
|
||||
@@ -15,6 +14,9 @@ import {foldGutter} from "@codemirror/language";
|
||||
import {highlightActiveLineGutter, highlightWhitespace, highlightTrailingWhitespace} from "@codemirror/view";
|
||||
import createEditorContextMenu from '../extensions/contextMenu';
|
||||
import {blockLineNumbers} from '../extensions/codeblock';
|
||||
import {createHttpClientExtension} from '../extensions/httpclient';
|
||||
import {createBlockImageExtension} from '../extensions/blockImage';
|
||||
import {ExtensionName} from '@/../bindings/voidraft/internal/models/models';
|
||||
|
||||
type ExtensionEntry = {
|
||||
definition: ExtensionDefinition
|
||||
@@ -22,35 +24,36 @@ type ExtensionEntry = {
|
||||
descriptionKey: string
|
||||
};
|
||||
|
||||
type RegisteredExtensionID = Exclude<ExtensionID, ExtensionID.$zero | ExtensionID.ExtensionEditor>;
|
||||
// 排除 $zero 的有效扩展 Key 类型
|
||||
type ValidExtensionName = Exclude<ExtensionName, ExtensionName.$zero>;
|
||||
|
||||
const defineExtension = (create: (config: any) => any, defaultConfig: Record<string, any> = {}): ExtensionDefinition => ({
|
||||
create,
|
||||
defaultConfig
|
||||
});
|
||||
|
||||
const EXTENSION_REGISTRY: Record<RegisteredExtensionID, ExtensionEntry> = {
|
||||
[ExtensionID.ExtensionRainbowBrackets]: {
|
||||
const EXTENSION_REGISTRY: Record<ValidExtensionName, ExtensionEntry> = {
|
||||
[ExtensionName.RainbowBrackets]: {
|
||||
definition: defineExtension(() => rainbowBrackets()),
|
||||
displayNameKey: 'extensions.rainbowBrackets.name',
|
||||
descriptionKey: 'extensions.rainbowBrackets.description'
|
||||
},
|
||||
[ExtensionID.ExtensionHyperlink]: {
|
||||
[ExtensionName.Hyperlink]: {
|
||||
definition: defineExtension(() => hyperLink),
|
||||
displayNameKey: 'extensions.hyperlink.name',
|
||||
descriptionKey: 'extensions.hyperlink.description'
|
||||
},
|
||||
[ExtensionID.ExtensionColorSelector]: {
|
||||
[ExtensionName.ColorSelector]: {
|
||||
definition: defineExtension(() => color),
|
||||
displayNameKey: 'extensions.colorSelector.name',
|
||||
descriptionKey: 'extensions.colorSelector.description'
|
||||
},
|
||||
[ExtensionID.ExtensionTranslator]: {
|
||||
[ExtensionName.Translator]: {
|
||||
definition: defineExtension(() => createTranslatorExtension()),
|
||||
displayNameKey: 'extensions.translator.name',
|
||||
descriptionKey: 'extensions.translator.description'
|
||||
},
|
||||
[ExtensionID.ExtensionMinimap]: {
|
||||
[ExtensionName.Minimap]: {
|
||||
definition: defineExtension((config: any) => minimap({
|
||||
displayText: config?.displayText ?? 'characters',
|
||||
showOverlay: config?.showOverlay ?? 'always',
|
||||
@@ -63,85 +66,95 @@ const EXTENSION_REGISTRY: Record<RegisteredExtensionID, ExtensionEntry> = {
|
||||
displayNameKey: 'extensions.minimap.name',
|
||||
descriptionKey: 'extensions.minimap.description'
|
||||
},
|
||||
[ExtensionID.ExtensionSearch]: {
|
||||
[ExtensionName.Search]: {
|
||||
definition: defineExtension(() => vscodeSearch),
|
||||
displayNameKey: 'extensions.search.name',
|
||||
descriptionKey: 'extensions.search.description'
|
||||
},
|
||||
[ExtensionID.ExtensionFold]: {
|
||||
[ExtensionName.Fold]: {
|
||||
definition: defineExtension(() => Prec.low(foldGutter())),
|
||||
displayNameKey: 'extensions.fold.name',
|
||||
descriptionKey: 'extensions.fold.description'
|
||||
},
|
||||
[ExtensionID.ExtensionMarkdown]: {
|
||||
[ExtensionName.Markdown]: {
|
||||
definition: defineExtension(() => markdownExtensions),
|
||||
displayNameKey: 'extensions.markdown.name',
|
||||
descriptionKey: 'extensions.markdown.description'
|
||||
},
|
||||
[ExtensionID.ExtensionLineNumbers]: {
|
||||
[ExtensionName.LineNumbers]: {
|
||||
definition: defineExtension(() => Prec.high([blockLineNumbers, highlightActiveLineGutter()])),
|
||||
displayNameKey: 'extensions.lineNumbers.name',
|
||||
descriptionKey: 'extensions.lineNumbers.description'
|
||||
},
|
||||
[ExtensionID.ExtensionContextMenu]: {
|
||||
[ExtensionName.ContextMenu]: {
|
||||
definition: defineExtension(() => createEditorContextMenu()),
|
||||
displayNameKey: 'extensions.contextMenu.name',
|
||||
descriptionKey: 'extensions.contextMenu.description'
|
||||
},
|
||||
[ExtensionID.ExtensionHighlightWhitespace]: {
|
||||
[ExtensionName.HighlightWhitespace]: {
|
||||
definition: defineExtension(() => highlightWhitespace()),
|
||||
displayNameKey: 'extensions.highlightWhitespace.name',
|
||||
descriptionKey: 'extensions.highlightWhitespace.description'
|
||||
},
|
||||
[ExtensionID.ExtensionHighlightTrailingWhitespace]: {
|
||||
[ExtensionName.HighlightTrailingWhitespace]: {
|
||||
definition: defineExtension(() => highlightTrailingWhitespace()),
|
||||
displayNameKey: 'extensions.highlightTrailingWhitespace.name',
|
||||
descriptionKey: 'extensions.highlightTrailingWhitespace.description'
|
||||
},
|
||||
[ExtensionName.HttpClient]: {
|
||||
definition: defineExtension(() => createHttpClientExtension()),
|
||||
displayNameKey: 'extensions.httpClient.name',
|
||||
descriptionKey: 'extensions.httpClient.description'
|
||||
},
|
||||
[ExtensionName.BlockImage]: {
|
||||
definition: defineExtension(() => createBlockImageExtension()),
|
||||
displayNameKey: 'extensions.blockImage.name',
|
||||
descriptionKey: 'extensions.blockImage.description'
|
||||
}
|
||||
} as const;
|
||||
};
|
||||
|
||||
const isRegisteredExtension = (id: ExtensionID): id is RegisteredExtensionID =>
|
||||
Object.prototype.hasOwnProperty.call(EXTENSION_REGISTRY, id);
|
||||
const isRegisteredExtension = (key: string): key is ValidExtensionName =>
|
||||
Object.prototype.hasOwnProperty.call(EXTENSION_REGISTRY, key);
|
||||
|
||||
const getRegistryEntry = (id: ExtensionID): ExtensionEntry | undefined => {
|
||||
if (!isRegisteredExtension(id)) {
|
||||
const getRegistryEntry = (key: string): ExtensionEntry | undefined => {
|
||||
if (!isRegisteredExtension(key)) {
|
||||
return undefined;
|
||||
}
|
||||
return EXTENSION_REGISTRY[id];
|
||||
return EXTENSION_REGISTRY[key];
|
||||
};
|
||||
|
||||
export function registerAllExtensions(manager: Manager): void {
|
||||
(Object.entries(EXTENSION_REGISTRY) as [RegisteredExtensionID, ExtensionEntry][]).forEach(([id, entry]) => {
|
||||
(Object.entries(EXTENSION_REGISTRY) as [ValidExtensionName, ExtensionEntry][]).forEach(([id, entry]) => {
|
||||
manager.registerExtension(id, entry.definition);
|
||||
});
|
||||
}
|
||||
|
||||
export function getExtensionDisplayName(id: ExtensionID): string {
|
||||
const entry = getRegistryEntry(id);
|
||||
return entry?.displayNameKey ? i18n.global.t(entry.displayNameKey) : id;
|
||||
export function getExtensionDisplayName(key: string): string {
|
||||
const entry = getRegistryEntry(key);
|
||||
return entry?.displayNameKey ? i18n.global.t(entry.displayNameKey) : key;
|
||||
}
|
||||
|
||||
export function getExtensionDescription(id: ExtensionID): string {
|
||||
const entry = getRegistryEntry(id);
|
||||
export function getExtensionDescription(key: string): string {
|
||||
const entry = getRegistryEntry(key);
|
||||
return entry?.descriptionKey ? i18n.global.t(entry.descriptionKey) : '';
|
||||
}
|
||||
|
||||
function getExtensionDefinition(id: ExtensionID): ExtensionDefinition | undefined {
|
||||
return getRegistryEntry(id)?.definition;
|
||||
function getExtensionDefinition(key: string): ExtensionDefinition | undefined {
|
||||
return getRegistryEntry(key)?.definition;
|
||||
}
|
||||
|
||||
export function getExtensionDefaultConfig(id: ExtensionID): any {
|
||||
const definition = getExtensionDefinition(id);
|
||||
export function getExtensionDefaultConfig(key: string): any {
|
||||
const definition = getExtensionDefinition(key);
|
||||
if (!definition) return {};
|
||||
return cloneConfig(definition.defaultConfig);
|
||||
}
|
||||
|
||||
export function hasExtensionConfig(id: ExtensionID): boolean {
|
||||
return Object.keys(getExtensionDefaultConfig(id)).length > 0;
|
||||
export function hasExtensionConfig(key: string): boolean {
|
||||
return Object.keys(getExtensionDefaultConfig(key)).length > 0;
|
||||
}
|
||||
|
||||
export function getAllExtensionIds(): ExtensionID[] {
|
||||
return Object.keys(EXTENSION_REGISTRY) as RegisteredExtensionID[];
|
||||
export function getExtensionsMap(): string[] {
|
||||
return Object.keys(EXTENSION_REGISTRY);
|
||||
}
|
||||
|
||||
const cloneConfig = (config: any) => {
|
||||
|
||||
@@ -12,9 +12,8 @@ const extensionManager = new Manager();
|
||||
/**
|
||||
* 异步创建动态扩展
|
||||
* 确保扩展配置已加载
|
||||
* @param _documentId 可选的文档ID,用于提前初始化视图
|
||||
*/
|
||||
export const createDynamicExtensions = async (_documentId?: number): Promise<Extension[]> => {
|
||||
export const createDynamicExtensions = async (): Promise<Extension[]> => {
|
||||
const extensionStore = useExtensionStore();
|
||||
|
||||
// 注册所有扩展工厂
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {Compartment, Extension} from '@codemirror/state';
|
||||
import {EditorView} from '@codemirror/view';
|
||||
import {Extension as ExtensionConfig, ExtensionID} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {Extension as ExtensionConfig} from '@/../bindings/voidraft/internal/models/ent/models';
|
||||
import {ExtensionDefinition, ExtensionState} from './types';
|
||||
|
||||
/**
|
||||
@@ -8,11 +8,11 @@ import {ExtensionDefinition, ExtensionState} from './types';
|
||||
* 负责注册、初始化与同步所有动态扩展
|
||||
*/
|
||||
export class Manager {
|
||||
private extensionStates = new Map<ExtensionID, ExtensionState>();
|
||||
private extensionStates = new Map<string, ExtensionState>();
|
||||
private views = new Map<number, EditorView>();
|
||||
|
||||
registerExtension(id: ExtensionID, definition: ExtensionDefinition): void {
|
||||
const existingState = this.extensionStates.get(id);
|
||||
registerExtension(name: string, definition: ExtensionDefinition): void {
|
||||
const existingState = this.extensionStates.get(name);
|
||||
if (existingState) {
|
||||
existingState.definition = definition;
|
||||
if (existingState.config === undefined) {
|
||||
@@ -21,8 +21,8 @@ export class Manager {
|
||||
} else {
|
||||
const compartment = new Compartment();
|
||||
const defaultConfig = this.cloneConfig(definition.defaultConfig ?? {});
|
||||
this.extensionStates.set(id, {
|
||||
id,
|
||||
this.extensionStates.set(name, {
|
||||
name,
|
||||
definition,
|
||||
config: defaultConfig,
|
||||
enabled: false,
|
||||
@@ -34,10 +34,11 @@ export class Manager {
|
||||
|
||||
initExtensions(extensionConfigs: ExtensionConfig[]): void {
|
||||
for (const config of extensionConfigs) {
|
||||
const state = this.extensionStates.get(config.id);
|
||||
if (!config.name) continue;
|
||||
const state = this.extensionStates.get(config.name);
|
||||
if (!state) continue;
|
||||
const resolvedConfig = this.cloneConfig(config.config ?? state.definition.defaultConfig ?? {});
|
||||
this.commitExtensionState(state, config.enabled, resolvedConfig);
|
||||
this.commitExtensionState(state, config.enabled ?? false, resolvedConfig);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +55,7 @@ export class Manager {
|
||||
this.applyAllExtensionsToView(view);
|
||||
}
|
||||
|
||||
updateExtension(id: ExtensionID, enabled: boolean, config?: any): void {
|
||||
updateExtension(id: string, enabled: boolean, config?: any): void {
|
||||
const state = this.extensionStates.get(id);
|
||||
if (!state) return;
|
||||
|
||||
@@ -87,13 +88,13 @@ export class Manager {
|
||||
state.enabled = enabled;
|
||||
state.config = config;
|
||||
state.extension = runtimeExtension;
|
||||
this.applyExtensionToAllViews(state.id);
|
||||
this.applyExtensionToAllViews(state.name);
|
||||
} catch (error) {
|
||||
console.error(`Failed to update extension ${state.id}:`, error);
|
||||
console.error(`Failed to update extension ${state.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
private applyExtensionToAllViews(id: ExtensionID): void {
|
||||
private applyExtensionToAllViews(id: string): void {
|
||||
const state = this.extensionStates.get(id);
|
||||
if (!state) return;
|
||||
|
||||
|
||||
@@ -1 +1,23 @@
|
||||
import {Compartment, Extension} from '@codemirror/state';
|
||||
import {Compartment, Extension} from '@codemirror/state';
|
||||
|
||||
/**
|
||||
* 扩展定义
|
||||
* 标准化 create 方法和默认配置
|
||||
*/
|
||||
export interface ExtensionDefinition {
|
||||
create(config: any): Extension
|
||||
defaultConfig: Record<string, any>
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展运行时状态
|
||||
*/
|
||||
export interface ExtensionState {
|
||||
name: string
|
||||
definition: ExtensionDefinition
|
||||
config: any
|
||||
enabled: boolean
|
||||
compartment: Compartment
|
||||
extension: Extension
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type {ThemeColors} from './types';
|
||||
import {ThemeType} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {Type as ThemeType} from '@/../bindings/voidraft/internal/models/ent/theme/models';
|
||||
import {defaultDarkColors} from './dark/default-dark';
|
||||
import {defaultLightColors} from './light/default-light';
|
||||
import {config as draculaColors} from './dark/dracula';
|
||||
@@ -24,20 +24,20 @@ export interface ThemePreset {
|
||||
export const FALLBACK_THEME_NAME = defaultDarkColors.themeName;
|
||||
|
||||
export const themePresetList: ThemePreset[] = [
|
||||
{name: defaultDarkColors.themeName, type: ThemeType.ThemeTypeDark, colors: defaultDarkColors},
|
||||
{name: draculaColors.themeName, type: ThemeType.ThemeTypeDark, colors: draculaColors},
|
||||
{name: auraColors.themeName, type: ThemeType.ThemeTypeDark, colors: auraColors},
|
||||
{name: githubDarkColors.themeName, type: ThemeType.ThemeTypeDark, colors: githubDarkColors},
|
||||
{name: materialDarkColors.themeName, type: ThemeType.ThemeTypeDark, colors: materialDarkColors},
|
||||
{name: oneDarkColors.themeName, type: ThemeType.ThemeTypeDark, colors: oneDarkColors},
|
||||
{name: solarizedDarkColors.themeName, type: ThemeType.ThemeTypeDark, colors: solarizedDarkColors},
|
||||
{name: tokyoNightColors.themeName, type: ThemeType.ThemeTypeDark, colors: tokyoNightColors},
|
||||
{name: tokyoNightStormColors.themeName, type: ThemeType.ThemeTypeDark, colors: tokyoNightStormColors},
|
||||
{name: defaultLightColors.themeName, type: ThemeType.ThemeTypeLight, colors: defaultLightColors},
|
||||
{name: githubLightColors.themeName, type: ThemeType.ThemeTypeLight, colors: githubLightColors},
|
||||
{name: materialLightColors.themeName, type: ThemeType.ThemeTypeLight, colors: materialLightColors},
|
||||
{name: solarizedLightColors.themeName, type: ThemeType.ThemeTypeLight, colors: solarizedLightColors},
|
||||
{name: tokyoNightDayColors.themeName, type: ThemeType.ThemeTypeLight, colors: tokyoNightDayColors},
|
||||
{name: defaultDarkColors.themeName, type: ThemeType.TypeDark, colors: defaultDarkColors},
|
||||
{name: draculaColors.themeName, type: ThemeType.TypeDark, colors: draculaColors},
|
||||
{name: auraColors.themeName, type: ThemeType.TypeDark, colors: auraColors},
|
||||
{name: githubDarkColors.themeName, type: ThemeType.TypeDark, colors: githubDarkColors},
|
||||
{name: materialDarkColors.themeName, type: ThemeType.TypeDark, colors: materialDarkColors},
|
||||
{name: oneDarkColors.themeName, type: ThemeType.TypeDark, colors: oneDarkColors},
|
||||
{name: solarizedDarkColors.themeName, type: ThemeType.TypeDark, colors: solarizedDarkColors},
|
||||
{name: tokyoNightColors.themeName, type: ThemeType.TypeDark, colors: tokyoNightColors},
|
||||
{name: tokyoNightStormColors.themeName, type: ThemeType.TypeDark, colors: tokyoNightStormColors},
|
||||
{name: defaultLightColors.themeName, type: ThemeType.TypeLight, colors: defaultLightColors},
|
||||
{name: githubLightColors.themeName, type: ThemeType.TypeLight, colors: githubLightColors},
|
||||
{name: materialLightColors.themeName, type: ThemeType.TypeLight, colors: materialLightColors},
|
||||
{name: solarizedLightColors.themeName, type: ThemeType.TypeLight, colors: solarizedLightColors},
|
||||
{name: tokyoNightDayColors.themeName, type: ThemeType.TypeLight, colors: tokyoNightDayColors},
|
||||
];
|
||||
|
||||
export const themePresetMap: Record<string, ThemePreset> = themePresetList.reduce(
|
||||
|
||||
@@ -7,7 +7,7 @@ import SettingSection from '../components/SettingSection.vue';
|
||||
import SettingItem from '../components/SettingItem.vue';
|
||||
import { SystemThemeType, LanguageType } from '@/../bindings/voidraft/internal/models/models';
|
||||
import { createDebounce } from '@/common/utils/debounce';
|
||||
import { createTimerManager } from '@/common/utils/timerUtils';
|
||||
import { useConfirm } from '@/composables/useConfirm';
|
||||
import PickColors from 'vue-pick-colors';
|
||||
import type { ThemeColors } from '@/views/editor/theme/types';
|
||||
|
||||
@@ -21,31 +21,22 @@ const { debouncedFn: debouncedUpdateColor } = createDebounce(
|
||||
{ delay: 100 }
|
||||
);
|
||||
|
||||
const { debouncedFn: debouncedResetTheme } = createDebounce(
|
||||
async () => {
|
||||
const success = await themeStore.resetCurrentTheme();
|
||||
|
||||
if (success) {
|
||||
// 重新加载临时颜色
|
||||
syncTempColors();
|
||||
hasUnsavedChanges.value = false;
|
||||
}
|
||||
},
|
||||
{ delay: 300 }
|
||||
);
|
||||
|
||||
// 创建定时器管理器
|
||||
const resetTimer = createTimerManager();
|
||||
|
||||
// 临时颜色状态(用于编辑)
|
||||
const tempColors = ref<ThemeColors | null>(null);
|
||||
|
||||
// 标记是否有未保存的更改
|
||||
const hasUnsavedChanges = ref(false);
|
||||
|
||||
// 重置按钮状态
|
||||
const resetButtonState = ref({
|
||||
confirming: false
|
||||
// 重置主题确认
|
||||
const { isConfirming: isResetConfirming, requestConfirm: requestResetConfirm } = useConfirm({
|
||||
timeout: 3000,
|
||||
onConfirm: async () => {
|
||||
const success = await themeStore.resetCurrentTheme();
|
||||
if (success) {
|
||||
syncTempColors();
|
||||
hasUnsavedChanges.value = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 当前选中的主题名称
|
||||
@@ -125,23 +116,6 @@ const toggleSearch = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 处理重置按钮点击
|
||||
const handleResetClick = () => {
|
||||
if (resetButtonState.value.confirming) {
|
||||
|
||||
debouncedResetTheme();
|
||||
|
||||
resetButtonState.value.confirming = false;
|
||||
resetTimer.clear();
|
||||
} else {
|
||||
resetButtonState.value.confirming = true;
|
||||
// 设置3秒后自动恢复
|
||||
resetTimer.set(() => {
|
||||
resetButtonState.value.confirming = false;
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
// 更新本地颜色配置
|
||||
const updateLocalColor = (colorKey: string, value: string) => {
|
||||
if (!tempColors.value) return;
|
||||
@@ -295,10 +269,10 @@ const handlePickerClose = () => {
|
||||
</button>
|
||||
<button
|
||||
v-if="!hasUnsavedChanges"
|
||||
:class="['reset-button', resetButtonState.confirming ? 'reset-button-confirming' : '']"
|
||||
@click="handleResetClick"
|
||||
:class="['reset-button', isResetConfirming('theme') ? 'reset-button-confirming' : '']"
|
||||
@click="requestResetConfirm('theme')"
|
||||
>
|
||||
{{ resetButtonState.confirming ? t('settings.confirmReset') : t('settings.resetToDefault') }}
|
||||
{{ isResetConfirming('theme') ? t('settings.confirmReset') : t('settings.resetToDefault') }}
|
||||
</button>
|
||||
<template v-else>
|
||||
<button class="apply-button" @click="applyChanges">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import {useConfigStore} from '@/stores/configStore';
|
||||
import {useBackupStore} from '@/stores/backupStore';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {computed} from 'vue';
|
||||
import {computed, ref, watch, onUnmounted} from 'vue';
|
||||
import SettingSection from '../components/SettingSection.vue';
|
||||
import SettingItem from '../components/SettingItem.vue';
|
||||
import ToggleSwitch from '../components/ToggleSwitch.vue';
|
||||
@@ -13,6 +13,37 @@ const {t} = useI18n();
|
||||
const configStore = useConfigStore();
|
||||
const backupStore = useBackupStore();
|
||||
|
||||
// 消息显示状态
|
||||
const message = ref<string | null>(null);
|
||||
const isError = ref(false);
|
||||
let messageTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const clearMessage = () => {
|
||||
if (messageTimer) {
|
||||
clearTimeout(messageTimer);
|
||||
messageTimer = null;
|
||||
}
|
||||
message.value = null;
|
||||
};
|
||||
|
||||
// 监听同步完成,显示消息并自动消失
|
||||
watch(() => backupStore.isSyncing, (syncing, wasSyncing) => {
|
||||
if (wasSyncing && !syncing) {
|
||||
clearMessage();
|
||||
if (backupStore.error) {
|
||||
message.value = backupStore.error;
|
||||
isError.value = true;
|
||||
messageTimer = setTimeout(clearMessage, 5000);
|
||||
} else {
|
||||
message.value = 'Sync successful';
|
||||
isError.value = false;
|
||||
messageTimer = setTimeout(clearMessage, 3000);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(clearMessage);
|
||||
|
||||
const authMethodOptions = computed(() => [
|
||||
{value: AuthMethod.Token, label: t('settings.backup.authMethods.token')},
|
||||
{value: AuthMethod.SSHKey, label: t('settings.backup.authMethods.sshKey')},
|
||||
@@ -172,18 +203,18 @@ const selectSshKeyFile = async () => {
|
||||
<!-- 备份操作 -->
|
||||
<SettingSection :title="t('settings.backup.backupOperations')">
|
||||
<SettingItem
|
||||
:title="t('settings.backup.pushToRemote')"
|
||||
:description="backupStore.message || undefined"
|
||||
:descriptionType="backupStore.message ? (backupStore.isError ? 'error' : 'success') : 'default'"
|
||||
:title="t('settings.backup.syncToRemote')"
|
||||
:description="message || undefined"
|
||||
:descriptionType="message ? (isError ? 'error' : 'success') : 'default'"
|
||||
>
|
||||
<button
|
||||
class="push-button"
|
||||
@click="backupStore.pushToRemote"
|
||||
:disabled="!configStore.config.backup.enabled || !configStore.config.backup.repo_url || backupStore.isPushing"
|
||||
:class="{ 'backing-up': backupStore.isPushing }"
|
||||
class="sync-button"
|
||||
@click="backupStore.sync"
|
||||
:disabled="!configStore.config.backup.enabled || !configStore.config.backup.repo_url || backupStore.isSyncing"
|
||||
:class="{ 'syncing': backupStore.isSyncing }"
|
||||
>
|
||||
<span v-if="backupStore.isPushing" class="loading-spinner"></span>
|
||||
{{ backupStore.isPushing ? t('settings.backup.pushing') : t('settings.backup.actions.push') }}
|
||||
<span v-if="backupStore.isSyncing" class="loading-spinner"></span>
|
||||
{{ backupStore.isSyncing ? t('settings.backup.syncing') : t('settings.backup.actions.sync') }}
|
||||
</button>
|
||||
</SettingItem>
|
||||
</SettingSection>
|
||||
@@ -257,7 +288,7 @@ const selectSshKeyFile = async () => {
|
||||
}
|
||||
|
||||
// 按钮样式
|
||||
.push-button {
|
||||
.sync-button {
|
||||
padding: 8px 16px;
|
||||
background-color: var(--settings-input-bg);
|
||||
border: 1px solid var(--settings-input-border);
|
||||
@@ -294,7 +325,7 @@ const selectSshKeyFile = async () => {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
&.backing-up {
|
||||
&.syncing {
|
||||
background-color: #2196f3;
|
||||
border-color: #2196f3;
|
||||
color: white;
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import {computed, ref} from 'vue';
|
||||
import {computed, onMounted, ref} from 'vue';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {useEditorStore} from '@/stores/editorStore';
|
||||
import {useExtensionStore} from '@/stores/extensionStore';
|
||||
import {ExtensionService} from '@/../bindings/voidraft/internal/services';
|
||||
import {ExtensionID} from '@/../bindings/voidraft/internal/models/models';
|
||||
import {
|
||||
getAllExtensionIds,
|
||||
getExtensionDefaultConfig,
|
||||
getExtensionDescription,
|
||||
getExtensionDisplayName,
|
||||
getExtensionDisplayName, getExtensionsMap,
|
||||
hasExtensionConfig
|
||||
} from '@/views/editor/manager/extensions';
|
||||
import SettingSection from '../components/SettingSection.vue';
|
||||
@@ -20,28 +18,33 @@ const {t} = useI18n();
|
||||
const editorStore = useEditorStore();
|
||||
const extensionStore = useExtensionStore();
|
||||
|
||||
// 页面初始化时加载扩展数据
|
||||
onMounted(async () => {
|
||||
await extensionStore.loadExtensions();
|
||||
});
|
||||
|
||||
// 展开状态管理
|
||||
const expandedExtensions = ref<Set<ExtensionID>>(new Set());
|
||||
const expandedExtensions = ref<Set<number>>(new Set());
|
||||
|
||||
// 获取所有可用的扩展
|
||||
const availableExtensions = computed(() => {
|
||||
return getAllExtensionIds().map(id => {
|
||||
const extension = extensionStore.extensions.find(ext => ext.id === id);
|
||||
return getExtensionsMap().map(name => {
|
||||
const extension = extensionStore.extensions.find(ext => ext.name === name);
|
||||
return {
|
||||
id,
|
||||
displayName: getExtensionDisplayName(id),
|
||||
description: getExtensionDescription(id),
|
||||
id: extension?.id ?? 0,
|
||||
name: name,
|
||||
displayName: getExtensionDisplayName(name),
|
||||
description: getExtensionDescription(name),
|
||||
enabled: extension?.enabled || false,
|
||||
isDefault: extension?.isDefault || false,
|
||||
hasConfig: hasExtensionConfig(id),
|
||||
hasConfig: hasExtensionConfig(name),
|
||||
config: extension?.config || {},
|
||||
defaultConfig: getExtensionDefaultConfig(id)
|
||||
defaultConfig: getExtensionDefaultConfig(name)
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
// 切换展开状态
|
||||
const toggleExpanded = (extensionId: ExtensionID) => {
|
||||
const toggleExpanded = (extensionId: number) => {
|
||||
if (expandedExtensions.value.has(extensionId)) {
|
||||
expandedExtensions.value.delete(extensionId);
|
||||
} else {
|
||||
@@ -50,7 +53,7 @@ const toggleExpanded = (extensionId: ExtensionID) => {
|
||||
};
|
||||
|
||||
// 更新扩展状态
|
||||
const updateExtension = async (extensionId: ExtensionID, enabled: boolean) => {
|
||||
const updateExtension = async (extensionId: number, enabled: boolean) => {
|
||||
try {
|
||||
await editorStore.updateExtension(extensionId, enabled);
|
||||
} catch (error) {
|
||||
@@ -59,21 +62,21 @@ const updateExtension = async (extensionId: ExtensionID, enabled: boolean) => {
|
||||
};
|
||||
|
||||
// 更新扩展配置
|
||||
const updateExtensionConfig = async (extensionId: ExtensionID, configKey: string, value: any) => {
|
||||
const updateExtensionConfig = async (extensionId: number, configKey: string, value: any) => {
|
||||
try {
|
||||
// 获取当前扩展状态
|
||||
const extension = extensionStore.extensions.find(ext => ext.id === extensionId);
|
||||
if (!extension) return;
|
||||
|
||||
// 更新配置
|
||||
const updatedConfig = {...extension.config};
|
||||
const updatedConfig = {...(extension.config || {})};
|
||||
if (value === undefined) {
|
||||
delete updatedConfig[configKey];
|
||||
} else {
|
||||
updatedConfig[configKey] = value;
|
||||
}
|
||||
// 使用editorStore的updateExtension方法更新,确保应用到所有编辑器实例
|
||||
await editorStore.updateExtension(extensionId, extension.enabled, updatedConfig);
|
||||
await editorStore.updateExtension(extensionId, extension.enabled ?? false, updatedConfig);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to update extension config:', error);
|
||||
@@ -81,10 +84,10 @@ const updateExtensionConfig = async (extensionId: ExtensionID, configKey: string
|
||||
};
|
||||
|
||||
// 重置扩展到默认配置
|
||||
const resetExtension = async (extensionId: ExtensionID) => {
|
||||
const resetExtension = async (extensionId: number) => {
|
||||
try {
|
||||
// 重置到默认配置
|
||||
await ExtensionService.ResetExtensionToDefault(extensionId);
|
||||
await ExtensionService.ResetExtensionConfig(extensionId);
|
||||
|
||||
// 重新加载扩展状态以获取最新配置
|
||||
await extensionStore.loadExtensions();
|
||||
@@ -93,7 +96,7 @@ const resetExtension = async (extensionId: ExtensionID) => {
|
||||
const extension = extensionStore.extensions.find(ext => ext.id === extensionId);
|
||||
if (extension) {
|
||||
// 通过editorStore更新,确保所有视图都能同步
|
||||
await editorStore.updateExtension(extensionId, extension.enabled, extension.config);
|
||||
await editorStore.updateExtension(extensionId, extension.enabled ?? false, extension.config);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to reset extension:', error);
|
||||
@@ -127,7 +130,7 @@ const formatConfigValue = (value: any): string => {
|
||||
|
||||
|
||||
const handleConfigInput = async (
|
||||
extensionId: ExtensionID,
|
||||
extensionId: number,
|
||||
configKey: string,
|
||||
defaultValue: any,
|
||||
event: Event
|
||||
@@ -160,7 +163,7 @@ const handleConfigInput = async (
|
||||
<SettingSection :title="t('settings.extensions')">
|
||||
<div
|
||||
v-for="extension in availableExtensions"
|
||||
:key="extension.id"
|
||||
:key="extension.name"
|
||||
class="extension-item"
|
||||
>
|
||||
<!-- 扩展主项 -->
|
||||
@@ -238,10 +241,6 @@ const handleConfigInput = async (
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.settings-page {
|
||||
//max-width: 1000px;
|
||||
}
|
||||
|
||||
.extension-item {
|
||||
border-bottom: 1px solid var(--settings-input-border);
|
||||
|
||||
@@ -296,36 +295,38 @@ const handleConfigInput = async (
|
||||
|
||||
.extension-config {
|
||||
background-color: var(--settings-input-bg);
|
||||
border-left: 3px solid var(--settings-accent);
|
||||
margin: 8px 0 16px 0;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
border-left: 2px solid var(--settings-accent);
|
||||
margin: 4px 0 12px 0;
|
||||
padding: 8px 10px;
|
||||
border-radius: 2px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.config-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.config-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--settings-text);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.reset-button {
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
padding: 3px 8px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--settings-input-border);
|
||||
border-radius: 4px;
|
||||
background-color: var(--settings-input-bg);
|
||||
border-radius: 2px;
|
||||
background-color: transparent;
|
||||
color: var(--settings-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
transition: all 0.15s ease;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
@@ -337,8 +338,7 @@ const handleConfigInput = async (
|
||||
|
||||
.config-table-wrapper {
|
||||
border: 1px solid var(--settings-input-border);
|
||||
border-radius: 6px;
|
||||
margin-top: 8px;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
background-color: var(--settings-panel, var(--settings-input-bg));
|
||||
}
|
||||
@@ -346,7 +346,7 @@ const handleConfigInput = async (
|
||||
.config-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.config-table tr + tr {
|
||||
@@ -355,38 +355,41 @@ const handleConfigInput = async (
|
||||
|
||||
.config-table th,
|
||||
.config-table td {
|
||||
padding: 10px 12px;
|
||||
padding: 5px 8px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.config-table-key {
|
||||
width: 36%;
|
||||
width: 30%;
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
color: var(--settings-text-secondary);
|
||||
border-right: 1px solid var(--settings-input-border);
|
||||
background-color: var(--settings-input-bg);
|
||||
background-color: rgba(0, 0, 0, 0.05);
|
||||
font-family: ui-monospace, SFMono-Regular, "SF Mono", Consolas, monospace;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.config-table-value {
|
||||
padding: 6px;
|
||||
padding: 3px 4px;
|
||||
}
|
||||
|
||||
.config-value-input {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
padding: 4px 6px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
border-radius: 2px;
|
||||
background: transparent;
|
||||
color: var(--settings-text);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
font-size: 11px;
|
||||
font-family: ui-monospace, SFMono-Regular, "SF Mono", Consolas, monospace;
|
||||
line-height: 1.3;
|
||||
box-sizing: border-box;
|
||||
transition: border-color 0.2s ease, background-color 0.2s ease;
|
||||
transition: border-color 0.15s ease, background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.config-value-input:hover {
|
||||
border-color: var(--settings-hover-border, var(--settings-input-border));
|
||||
border-color: var(--settings-input-border);
|
||||
background-color: var(--settings-hover);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,181 +2,127 @@
|
||||
import {useConfigStore} from '@/stores/configStore';
|
||||
import {useTabStore} from '@/stores/tabStore';
|
||||
import {useI18n} from 'vue-i18n';
|
||||
import {computed, onUnmounted, ref} from 'vue';
|
||||
import {computed, ref, onMounted} from 'vue';
|
||||
import SettingSection from '../components/SettingSection.vue';
|
||||
import SettingItem from '../components/SettingItem.vue';
|
||||
import ToggleSwitch from '../components/ToggleSwitch.vue';
|
||||
import {
|
||||
DialogService,
|
||||
MigrationProgress,
|
||||
MigrationService,
|
||||
MigrationStatus
|
||||
} from '@/../bindings/voidraft/internal/services';
|
||||
import {DialogService, HotkeyService, MigrationService} from '@/../bindings/voidraft/internal/services';
|
||||
import {useSystemStore} from "@/stores/systemStore";
|
||||
import {useConfirm, usePolling} from '@/composables';
|
||||
|
||||
const {t} = useI18n();
|
||||
const configStore = useConfigStore();
|
||||
const {
|
||||
config: {general},
|
||||
resetConfig,
|
||||
setAlwaysOnTop,
|
||||
setDataPath,
|
||||
setEnableGlobalHotkey,
|
||||
setEnableLoadingAnimation,
|
||||
setEnableSystemTray,
|
||||
setEnableTabs,
|
||||
setEnableWindowSnap,
|
||||
setGlobalHotkey,
|
||||
setStartAtLogin
|
||||
} = useConfigStore();
|
||||
const systemStore = useSystemStore();
|
||||
const tabStore = useTabStore();
|
||||
// 迁移进度状态
|
||||
const migrationProgress = ref<MigrationProgress>(new MigrationProgress({
|
||||
status: MigrationStatus.MigrationStatusCompleted,
|
||||
progress: 0
|
||||
}));
|
||||
|
||||
// 轮询相关
|
||||
let pollingTimer: number | null = null;
|
||||
const isPolling = ref(false);
|
||||
|
||||
// 进度条显示控制
|
||||
const showProgress = ref(false);
|
||||
const progressError = ref('');
|
||||
let hideProgressTimer: any = null;
|
||||
const showBar = ref(false);
|
||||
const manualError = ref(''); // 用于捕获 MigrateDirectory 抛出的错误
|
||||
let hideTimer = 0;
|
||||
|
||||
// 开始轮询迁移进度
|
||||
const startPolling = () => {
|
||||
if (isPolling.value) return;
|
||||
|
||||
isPolling.value = true;
|
||||
showProgress.value = true;
|
||||
progressError.value = '';
|
||||
|
||||
// 立即重置迁移进度状态,避免从之前的失败状态渐变
|
||||
migrationProgress.value = new MigrationProgress({
|
||||
status: MigrationStatus.MigrationStatusMigrating,
|
||||
progress: 0
|
||||
});
|
||||
|
||||
pollingTimer = window.setInterval(async () => {
|
||||
try {
|
||||
const progress = await MigrationService.GetProgress();
|
||||
migrationProgress.value = progress;
|
||||
|
||||
const {status, error} = progress;
|
||||
const isCompleted = [MigrationStatus.MigrationStatusCompleted, MigrationStatus.MigrationStatusFailed].includes(status);
|
||||
|
||||
if (isCompleted) {
|
||||
stopPolling();
|
||||
|
||||
// 设置错误信息(如果是失败状态)
|
||||
progressError.value = (status === MigrationStatus.MigrationStatusFailed) ? (error || 'Migration failed') : '';
|
||||
|
||||
const delay = status === MigrationStatus.MigrationStatusCompleted ? 3000 : 5000;
|
||||
hideProgressTimer = setTimeout(hideProgress, delay);
|
||||
// 轮询迁移进度
|
||||
const {data: progress, error: pollError, isActive: migrating, start, stop, reset} = usePolling(
|
||||
() => MigrationService.GetProgress(),
|
||||
{
|
||||
interval: 300,
|
||||
shouldStop: ({progress, error}) => !!error || progress >= 100,
|
||||
onStop: () => {
|
||||
const hasError = pollError.value || progress.value?.error;
|
||||
hideTimer = window.setTimeout(hideAll, hasError ? 5000 : 3000);
|
||||
}
|
||||
} catch (_error) {
|
||||
stopPolling();
|
||||
|
||||
// 使用常量简化错误处理
|
||||
const errorMsg = 'Failed to get migration progress';
|
||||
Object.assign(migrationProgress.value, {
|
||||
status: MigrationStatus.MigrationStatusFailed,
|
||||
progress: 0,
|
||||
error: errorMsg
|
||||
});
|
||||
progressError.value = errorMsg;
|
||||
|
||||
hideProgressTimer = setTimeout(hideProgress, 5000);
|
||||
}
|
||||
}, 200);
|
||||
};
|
||||
|
||||
// 停止轮询
|
||||
const stopPolling = () => {
|
||||
if (pollingTimer) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
isPolling.value = false;
|
||||
};
|
||||
|
||||
// 隐藏进度条
|
||||
const hideProgress = () => {
|
||||
showProgress.value = false;
|
||||
progressError.value = '';
|
||||
|
||||
// 重置迁移状态,避免下次显示时状态不正确
|
||||
migrationProgress.value = new MigrationProgress({
|
||||
status: MigrationStatus.MigrationStatusCompleted,
|
||||
progress: 0
|
||||
});
|
||||
|
||||
if (hideProgressTimer) {
|
||||
clearTimeout(hideProgressTimer);
|
||||
hideProgressTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
// 简化的迁移状态管理
|
||||
const isMigrating = computed(() => migrationProgress.value.status === MigrationStatus.MigrationStatusMigrating);
|
||||
|
||||
// 进度条样式 - 使用 Map 简化条件判断
|
||||
const statusClassMap = new Map([
|
||||
[MigrationStatus.MigrationStatusMigrating, 'migrating'],
|
||||
[MigrationStatus.MigrationStatusCompleted, 'success'],
|
||||
[MigrationStatus.MigrationStatusFailed, 'error']
|
||||
]);
|
||||
|
||||
const progressBarClass = computed(() =>
|
||||
showProgress.value ? statusClassMap.get(migrationProgress.value.status) ?? '' : ''
|
||||
);
|
||||
|
||||
const progressBarWidth = computed(() => {
|
||||
if (!showProgress.value) return '0%';
|
||||
return isMigrating.value ? `${migrationProgress.value.progress}%` : '100%';
|
||||
// 派生状态
|
||||
const migrationError = computed(() => manualError.value || pollError.value || progress.value?.error || '');
|
||||
const currentProgress = computed(() => progress.value?.progress ?? 0);
|
||||
|
||||
const barClass = computed(() => {
|
||||
if (!showBar.value) return '';
|
||||
return migrationError.value ? 'error' : currentProgress.value >= 100 ? 'success' : 'migrating';
|
||||
});
|
||||
|
||||
// 重置确认状态
|
||||
const resetConfirmState = ref<'idle' | 'confirming'>('idle');
|
||||
let resetConfirmTimer: any = null;
|
||||
const barWidth = computed(() => {
|
||||
if (!showBar.value) return '0%';
|
||||
return (migrationError.value || currentProgress.value >= 100) ? '100%' : `${currentProgress.value}%`;
|
||||
});
|
||||
|
||||
// 可选键列表
|
||||
const keyOptions = [
|
||||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
||||
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'
|
||||
];
|
||||
// 隐藏进度条并清除所有状态
|
||||
const hideAll = () => {
|
||||
clearTimeout(hideTimer);
|
||||
hideTimer = 0;
|
||||
showBar.value = false;
|
||||
manualError.value = '';
|
||||
reset(); // 清除轮询状态
|
||||
};
|
||||
|
||||
// 重置设置确认
|
||||
const {isConfirming: isResetConfirming, requestConfirm: requestResetConfirm} = useConfirm({
|
||||
timeout: 3000,
|
||||
onConfirm: async () => {
|
||||
await resetConfig();
|
||||
}
|
||||
});
|
||||
|
||||
// 可选键列表 - 从后端获取系统支持的快捷键
|
||||
const keyOptions = ref<string[]>([]);
|
||||
|
||||
// 初始化时从后端获取支持的键列表
|
||||
onMounted(async () => {
|
||||
keyOptions.value = await HotkeyService.GetSupportedKeys();
|
||||
});
|
||||
|
||||
// 计算属性 - 启用全局热键
|
||||
const enableGlobalHotkey = computed({
|
||||
get: () => configStore.config.general.enableGlobalHotkey,
|
||||
set: (value: boolean) => configStore.setEnableGlobalHotkey(value)
|
||||
get: () => general.enableGlobalHotkey,
|
||||
set: (value: boolean) => setEnableGlobalHotkey(value)
|
||||
});
|
||||
|
||||
// 计算属性 - 窗口始终置顶
|
||||
const alwaysOnTop = computed({
|
||||
get: () => configStore.config.general.alwaysOnTop,
|
||||
get: () => general.alwaysOnTop,
|
||||
set: async (value: boolean) => {
|
||||
// 先更新配置
|
||||
await configStore.setAlwaysOnTop(value);
|
||||
await setAlwaysOnTop(value);
|
||||
await systemStore.setWindowOnTop(value);
|
||||
}
|
||||
});
|
||||
|
||||
// 计算属性 - 启用系统托盘
|
||||
const enableSystemTray = computed({
|
||||
get: () => configStore.config.general.enableSystemTray,
|
||||
set: (value: boolean) => configStore.setEnableSystemTray(value)
|
||||
get: () => general.enableSystemTray,
|
||||
set: (value: boolean) => setEnableSystemTray(value)
|
||||
});
|
||||
|
||||
// 计算属性 - 启用窗口吸附
|
||||
const enableWindowSnap = computed({
|
||||
get: () => configStore.config.general.enableWindowSnap,
|
||||
set: (value: boolean) => configStore.setEnableWindowSnap(value)
|
||||
get: () => general.enableWindowSnap,
|
||||
set: (value: boolean) => setEnableWindowSnap(value)
|
||||
});
|
||||
|
||||
// 计算属性 - 启用加载动画
|
||||
const enableLoadingAnimation = computed({
|
||||
get: () => configStore.config.general.enableLoadingAnimation,
|
||||
set: (value: boolean) => configStore.setEnableLoadingAnimation(value)
|
||||
get: () => general.enableLoadingAnimation,
|
||||
set: (value: boolean) => setEnableLoadingAnimation(value)
|
||||
});
|
||||
|
||||
// 计算属性 - 启用标签页
|
||||
const enableTabs = computed({
|
||||
get: () => configStore.config.general.enableTabs,
|
||||
get: () => general.enableTabs,
|
||||
set: async (value: boolean) => {
|
||||
await configStore.setEnableTabs(value);
|
||||
await setEnableTabs(value);
|
||||
if (value) {
|
||||
// 开启tabs功能时,初始化当前文档到标签页
|
||||
tabStore.initializeTab();
|
||||
@@ -189,62 +135,41 @@ const enableTabs = computed({
|
||||
|
||||
// 计算属性 - 开机启动
|
||||
const startAtLogin = computed({
|
||||
get: () => configStore.config.general.startAtLogin,
|
||||
set: (value: boolean) => configStore.setStartAtLogin(value)
|
||||
get: () => general.startAtLogin,
|
||||
set: (value: boolean) => setStartAtLogin(value)
|
||||
});
|
||||
|
||||
// 修饰键配置 - 只读计算属性
|
||||
const modifierKeys = computed(() => ({
|
||||
ctrl: configStore.config.general.globalHotkey.ctrl,
|
||||
shift: configStore.config.general.globalHotkey.shift,
|
||||
alt: configStore.config.general.globalHotkey.alt,
|
||||
win: configStore.config.general.globalHotkey.win
|
||||
ctrl: general.globalHotkey.ctrl,
|
||||
shift: general.globalHotkey.shift,
|
||||
alt: general.globalHotkey.alt,
|
||||
win: general.globalHotkey.win
|
||||
}));
|
||||
|
||||
// 主键配置 - 只读计算属性
|
||||
const selectedKey = computed(() => configStore.config.general.globalHotkey.key);
|
||||
// 主键配置
|
||||
const selectedKey = computed(() => general.globalHotkey.key);
|
||||
|
||||
// 切换修饰键
|
||||
const toggleModifier = (key: 'ctrl' | 'shift' | 'alt' | 'win') => {
|
||||
const currentHotkey = configStore.config.general.globalHotkey;
|
||||
const currentHotkey = general.globalHotkey;
|
||||
const newHotkey = {...currentHotkey, [key]: !currentHotkey[key]};
|
||||
configStore.setGlobalHotkey(newHotkey);
|
||||
setGlobalHotkey(newHotkey);
|
||||
};
|
||||
|
||||
// 更新选择的键
|
||||
const updateSelectedKey = (event: Event) => {
|
||||
const select = event.target as HTMLSelectElement;
|
||||
const newHotkey = {...configStore.config.general.globalHotkey, key: select.value};
|
||||
configStore.setGlobalHotkey(newHotkey);
|
||||
const newHotkey = {...general.globalHotkey, key: select.value};
|
||||
setGlobalHotkey(newHotkey);
|
||||
};
|
||||
|
||||
// 重置设置
|
||||
const resetSettings = () => {
|
||||
if (resetConfirmState.value === 'idle') {
|
||||
// 第一次点击,进入确认状态
|
||||
resetConfirmState.value = 'confirming';
|
||||
// 3秒后自动返回idle状态
|
||||
resetConfirmTimer = setTimeout(() => {
|
||||
resetConfirmState.value = 'idle';
|
||||
}, 3000);
|
||||
} else if (resetConfirmState.value === 'confirming') {
|
||||
// 第二次点击,执行重置
|
||||
clearTimeout(resetConfirmTimer);
|
||||
resetConfirmState.value = 'idle';
|
||||
confirmReset();
|
||||
}
|
||||
};
|
||||
|
||||
// 确认重置
|
||||
const confirmReset = async () => {
|
||||
await configStore.resetConfig();
|
||||
};
|
||||
|
||||
// 计算热键预览文本 - 使用现代语法简化
|
||||
// 计算热键预览文本
|
||||
const hotkeyPreview = computed(() => {
|
||||
if (!enableGlobalHotkey.value) return '';
|
||||
|
||||
const {ctrl, shift, alt, win, key} = configStore.config.general.globalHotkey;
|
||||
const {ctrl, shift, alt, win, key} = general.globalHotkey;
|
||||
const modifiers = [
|
||||
ctrl && 'Ctrl',
|
||||
shift && 'Shift',
|
||||
@@ -257,58 +182,34 @@ const hotkeyPreview = computed(() => {
|
||||
});
|
||||
|
||||
// 数据路径配置
|
||||
const currentDataPath = computed(() => configStore.config.general.dataPath);
|
||||
const currentDataPath = computed(() => general.dataPath);
|
||||
|
||||
// 选择数据存储目录
|
||||
const selectDataDirectory = async () => {
|
||||
if (isMigrating.value) return;
|
||||
|
||||
if (migrating.value) return;
|
||||
|
||||
const selectedPath = await DialogService.SelectDirectory();
|
||||
if (!selectedPath?.trim() || selectedPath === currentDataPath.value) return;
|
||||
|
||||
// 检查用户是否取消了选择或路径为空
|
||||
if (!selectedPath || !selectedPath.trim() || selectedPath === currentDataPath.value) {
|
||||
return;
|
||||
}
|
||||
const oldPath = currentDataPath.value;
|
||||
const newPath = selectedPath.trim();
|
||||
const [oldPath, newPath] = [currentDataPath.value, selectedPath.trim()];
|
||||
|
||||
// 清除之前的进度状态
|
||||
hideProgress();
|
||||
// 清除之前的状态并开始轮询
|
||||
hideAll();
|
||||
showBar.value = true;
|
||||
manualError.value = '';
|
||||
start();
|
||||
|
||||
// 开始轮询迁移进度
|
||||
startPolling();
|
||||
|
||||
// 开始迁移
|
||||
try {
|
||||
await MigrationService.MigrateDirectory(oldPath, newPath);
|
||||
await configStore.setDataPath(newPath);
|
||||
} catch (error) {
|
||||
stopPolling();
|
||||
|
||||
// 使用解构和默认值简化错误处理
|
||||
const errorMsg = error?.toString() || 'Migration failed';
|
||||
showProgress.value = true;
|
||||
|
||||
Object.assign(migrationProgress.value, {
|
||||
status: MigrationStatus.MigrationStatusFailed,
|
||||
progress: 0,
|
||||
error: errorMsg
|
||||
});
|
||||
progressError.value = errorMsg;
|
||||
|
||||
hideProgressTimer = setTimeout(hideProgress, 5000);
|
||||
await setDataPath(newPath);
|
||||
} catch (e) {
|
||||
stop();
|
||||
// 设置手动捕获的错误(当轮询还没获取到错误时)
|
||||
manualError.value = String(e).replace(/^Error:\s*/i, '') || 'Migration failed';
|
||||
showBar.value = true;
|
||||
hideTimer = window.setTimeout(hideAll, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
// 清理定时器
|
||||
onUnmounted(() => {
|
||||
stopPolling();
|
||||
hideProgress();
|
||||
if (resetConfirmTimer) {
|
||||
clearTimeout(resetConfirmTimer);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -394,24 +295,15 @@ onUnmounted(() => {
|
||||
class="path-display-input"
|
||||
@click="selectDataDirectory"
|
||||
:title="t('settings.clickToSelectPath')"
|
||||
:disabled="isMigrating"
|
||||
:disabled="migrating"
|
||||
/>
|
||||
<!-- 简洁的进度条 -->
|
||||
<div
|
||||
class="progress-bar"
|
||||
:class="[
|
||||
{ 'active': showProgress },
|
||||
progressBarClass
|
||||
]"
|
||||
:style="{ width: progressBarWidth }"
|
||||
></div>
|
||||
<!-- 进度条 -->
|
||||
<div class="progress-bar" :class="[{'active': showBar}, barClass]" :style="{width: barWidth}"/>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<Transition name="error-fade">
|
||||
<div v-if="progressError" class="progress-error">
|
||||
{{ progressError }}
|
||||
</div>
|
||||
<div v-if="migrationError" class="progress-error">{{ migrationError }}</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</div>
|
||||
@@ -421,15 +313,10 @@ onUnmounted(() => {
|
||||
<SettingItem :title="t('settings.resetAllSettings')">
|
||||
<button
|
||||
class="reset-button"
|
||||
:class="{ 'confirming': resetConfirmState === 'confirming' }"
|
||||
@click="resetSettings"
|
||||
:class="{ 'confirming': isResetConfirming('reset') }"
|
||||
@click="requestResetConfirm('reset')"
|
||||
>
|
||||
<template v-if="resetConfirmState === 'idle'">
|
||||
{{ t('settings.reset') }}
|
||||
</template>
|
||||
<template v-else-if="resetConfirmState === 'confirming'">
|
||||
{{ t('settings.confirmReset') }}
|
||||
</template>
|
||||
{{ isResetConfirming('reset') ? t('settings.confirmReset') : t('settings.reset') }}
|
||||
</button>
|
||||
</SettingItem>
|
||||
</SettingSection>
|
||||
@@ -439,10 +326,6 @@ onUnmounted(() => {
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.settings-page {
|
||||
//max-width: 800px;
|
||||
}
|
||||
|
||||
.hotkey-selector {
|
||||
padding: 15px 0 5px 20px;
|
||||
transition: all 0.3s ease;
|
||||
@@ -656,11 +539,8 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.progress-error {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: #ef4444;
|
||||
padding: 0 2px;
|
||||
line-height: 1.4;
|
||||
opacity: 1;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
@@ -1,228 +1,315 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { onMounted, computed } from 'vue';
|
||||
import { onMounted, computed, ref, onUnmounted, watch } from 'vue';
|
||||
import SettingSection from '../components/SettingSection.vue';
|
||||
import SettingItem from '../components/SettingItem.vue';
|
||||
import { useKeybindingStore } from '@/stores/keybindingStore';
|
||||
import { useExtensionStore } from '@/stores/extensionStore';
|
||||
import { useSystemStore } from '@/stores/systemStore';
|
||||
import { useConfigStore } from '@/stores/configStore';
|
||||
import { useEditorStore } from '@/stores/editorStore';
|
||||
import { getCommandDescription } from '@/views/editor/keymap/commands';
|
||||
import {KeyBindingCommand} from "@/../bindings/voidraft/internal/models";
|
||||
import { KeyBindingType } from '@/../bindings/voidraft/internal/models/models';
|
||||
import { KeyBindingService } from '@/../bindings/voidraft/internal/services';
|
||||
import { useConfirm } from '@/composables/useConfirm';
|
||||
|
||||
const { t } = useI18n();
|
||||
const keybindingStore = useKeybindingStore();
|
||||
const extensionStore = useExtensionStore();
|
||||
const systemStore = useSystemStore();
|
||||
const configStore = useConfigStore();
|
||||
const editorStore = useEditorStore();
|
||||
|
||||
interface EditingState {
|
||||
id: number;
|
||||
name: string;
|
||||
originalKey: string;
|
||||
}
|
||||
|
||||
const editingBinding = ref<EditingState | null>(null);
|
||||
const capturedKey = ref('');
|
||||
const capturedKeyDisplay = ref<string[]>([]);
|
||||
const isConflict = ref(false);
|
||||
|
||||
const isEditing = computed(() => !!editingBinding.value);
|
||||
|
||||
// 加载数据
|
||||
onMounted(async () => {
|
||||
await keybindingStore.loadKeyBindings();
|
||||
await extensionStore.loadExtensions();
|
||||
});
|
||||
|
||||
// 从store中获取快捷键数据并转换为显示格式
|
||||
const keyBindings = computed(() => {
|
||||
// 只显示启用扩展的快捷键
|
||||
const enabledExtensionIds = new Set(extensionStore.enabledExtensionIds);
|
||||
const keymapModeOptions = [
|
||||
{ label: t('keybindings.modes.standard'), value: KeyBindingType.Standard },
|
||||
{ label: t('keybindings.modes.emacs'), value: KeyBindingType.Emacs }
|
||||
];
|
||||
|
||||
return keybindingStore.keyBindings
|
||||
.filter(kb => kb.enabled && enabledExtensionIds.has(kb.extension))
|
||||
.map(kb => ({
|
||||
id: kb.command,
|
||||
keys: parseKeyBinding(kb.key, kb.command),
|
||||
category: kb.extension,
|
||||
description: getCommandDescription(kb.command) || kb.command
|
||||
}));
|
||||
const updateKeymapMode = async (mode: KeyBindingType) => {
|
||||
await configStore.setKeymapMode(mode);
|
||||
await keybindingStore.loadKeyBindings();
|
||||
await editorStore.applyKeymapSettings();
|
||||
};
|
||||
|
||||
// 重置快捷键确认
|
||||
const { isConfirming: isResetConfirming, requestConfirm: requestResetConfirm } = useConfirm({
|
||||
timeout: 3000,
|
||||
onConfirm: async () => {
|
||||
await KeyBindingService.ResetKeyBindings();
|
||||
await keybindingStore.loadKeyBindings();
|
||||
await editorStore.applyKeymapSettings();
|
||||
}
|
||||
});
|
||||
|
||||
// 解析快捷键字符串为显示数组
|
||||
const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
if (!keyStr) return [];
|
||||
const keyBindings = computed(() =>
|
||||
keybindingStore.keyBindings.map(kb => ({
|
||||
id: kb.id,
|
||||
name: kb.name,
|
||||
command: getDisplayKeybinding(kb),
|
||||
rawKey: getRawKey(kb),
|
||||
extension: kb.extension || '',
|
||||
description: getCommandDescription(kb.name) || kb.name || ''
|
||||
}))
|
||||
);
|
||||
|
||||
// 特殊处理重做快捷键的操作系统差异
|
||||
if (command === KeyBindingCommand.HistoryRedoCommand && keyStr === 'Mod-Shift-z') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '⇧', 'Z']; // macOS: Cmd+Shift+Z
|
||||
} else {
|
||||
return ['Ctrl', 'Y']; // Windows/Linux: Ctrl+Y
|
||||
}
|
||||
const getRawKey = (kb: any): string => {
|
||||
const platformKey = systemStore.isMacOS ? kb.macos
|
||||
: systemStore.isWindows ? kb.windows
|
||||
: systemStore.isLinux ? kb.linux
|
||||
: kb.key;
|
||||
|
||||
return platformKey || kb.key || '';
|
||||
};
|
||||
|
||||
const getDisplayKeybinding = (kb: any): string[] => {
|
||||
const keyStr = getRawKey(kb);
|
||||
return keyStr ? parseKeyString(keyStr) : [];
|
||||
};
|
||||
|
||||
const parseKeyString = (keyStr: string): string[] => {
|
||||
const symbolMap: Record<string, string> = {
|
||||
'Mod': systemStore.isMacOS ? '⌘' : 'Ctrl',
|
||||
'Cmd': '⌘',
|
||||
...(systemStore.isMacOS ? {
|
||||
'Alt': '⌥',
|
||||
'Shift': '⇧',
|
||||
'Ctrl': '⌃'
|
||||
} : {}),
|
||||
'ArrowUp': '↑',
|
||||
'ArrowDown': '↓',
|
||||
'ArrowLeft': '←',
|
||||
'ArrowRight': '→'
|
||||
};
|
||||
|
||||
return keyStr
|
||||
.split(/[-+]/)
|
||||
.map(part => symbolMap[part] ?? part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
|
||||
// 键盘事件捕获
|
||||
const SPECIAL_KEYS: Record<string, string> = {
|
||||
' ': 'Space',
|
||||
'ArrowUp': 'ArrowUp',
|
||||
'ArrowDown': 'ArrowDown',
|
||||
'ArrowLeft': 'ArrowLeft',
|
||||
'ArrowRight': 'ArrowRight',
|
||||
'Enter': 'Enter',
|
||||
'Tab': 'Tab',
|
||||
'Backspace': 'Backspace',
|
||||
'Delete': 'Delete',
|
||||
'Home': 'Home',
|
||||
'End': 'End',
|
||||
'PageUp': 'PageUp',
|
||||
'PageDown': 'PageDown',
|
||||
};
|
||||
|
||||
const MODIFIER_KEYS = ['Control', 'Alt', 'Shift', 'Meta'];
|
||||
const MAX_KEY_PARTS = 3; // 最多3个键
|
||||
|
||||
const captureKeyBinding = (event: KeyboardEvent): string | null => {
|
||||
// 忽略单独的修饰键
|
||||
if (MODIFIER_KEYS.includes(event.key)) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
|
||||
// 添加修饰键
|
||||
if (event.ctrlKey || event.metaKey) parts.push('Mod');
|
||||
if (event.altKey) parts.push('Alt');
|
||||
if (event.shiftKey) parts.push('Shift');
|
||||
|
||||
// 获取主键
|
||||
const mainKey = SPECIAL_KEYS[event.key] ??
|
||||
(event.key.length === 1 ? event.key.toLowerCase() : event.key);
|
||||
|
||||
if (mainKey) parts.push(mainKey);
|
||||
|
||||
// 限制最多3个键
|
||||
if (parts.length > MAX_KEY_PARTS) return null;
|
||||
|
||||
return parts.join('-');
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
window.removeEventListener('keydown', handleKeyCapture, true);
|
||||
editingBinding.value = null;
|
||||
capturedKey.value = '';
|
||||
capturedKeyDisplay.value = [];
|
||||
isConflict.value = false;
|
||||
};
|
||||
|
||||
const handleKeyCapture = (event: KeyboardEvent) => {
|
||||
if (!isEditing.value) return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
// ESC 取消编辑
|
||||
if (event.key === 'Escape') {
|
||||
cancelEdit();
|
||||
return;
|
||||
}
|
||||
|
||||
// 特殊处理重做选择快捷键的操作系统差异
|
||||
if (command === KeyBindingCommand.HistoryRedoSelectionCommand && keyStr === 'Mod-Shift-u') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '⇧', 'U']; // macOS: Cmd+Shift+U
|
||||
} else {
|
||||
return ['Alt', 'U']; // Windows/Linux: Alt+U
|
||||
}
|
||||
const key = captureKeyBinding(event);
|
||||
if (key) {
|
||||
capturedKey.value = key;
|
||||
capturedKeyDisplay.value = parseKeyString(key);
|
||||
isConflict.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const startEditBinding = (binding: any) => {
|
||||
editingBinding.value = {
|
||||
id: binding.id,
|
||||
name: binding.name,
|
||||
originalKey: binding.rawKey
|
||||
};
|
||||
capturedKey.value = '';
|
||||
capturedKeyDisplay.value = [];
|
||||
isConflict.value = false;
|
||||
|
||||
// 手动添加键盘监听
|
||||
window.addEventListener('keydown', handleKeyCapture, true);
|
||||
};
|
||||
|
||||
const checkConflict = (newKey: string): boolean =>
|
||||
keyBindings.value.some(kb =>
|
||||
kb.rawKey === newKey && kb.name !== editingBinding.value?.name
|
||||
);
|
||||
|
||||
const confirmKeybinding = async () => {
|
||||
if (!editingBinding.value || !capturedKey.value) return;
|
||||
|
||||
// 检查冲突
|
||||
if (checkConflict(capturedKey.value)) {
|
||||
isConflict.value = true;
|
||||
setTimeout(cancelEdit, 600);
|
||||
return;
|
||||
}
|
||||
|
||||
// 特殊处理代码折叠快捷键的操作系统差异
|
||||
if (command === KeyBindingCommand.FoldCodeCommand && keyStr === 'Ctrl-Shift-[') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '⌥', '[']; // macOS: Cmd+Alt+[
|
||||
} else {
|
||||
return ['Ctrl', 'Shift', '[']; // Windows/Linux: Ctrl+Shift+[
|
||||
}
|
||||
try {
|
||||
await keybindingStore.updateKeyBinding(
|
||||
editingBinding.value.id,
|
||||
capturedKey.value
|
||||
);
|
||||
await editorStore.applyKeymapSettings();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
cancelEdit();
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.UnfoldCodeCommand && keyStr === 'Ctrl-Shift-]') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '⌥', ']']; // macOS: Cmd+Alt+]
|
||||
} else {
|
||||
return ['Ctrl', 'Shift', ']']; // Windows/Linux: Ctrl+Shift+]
|
||||
}
|
||||
}
|
||||
|
||||
// 特殊处理编辑快捷键的操作系统差异
|
||||
if (command === KeyBindingCommand.CursorSyntaxLeftCommand && keyStr === 'Alt-ArrowLeft') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['Ctrl', '←']; // macOS: Ctrl+ArrowLeft
|
||||
} else {
|
||||
return ['Alt', '←']; // Windows/Linux: Alt+ArrowLeft
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.CursorSyntaxRightCommand && keyStr === 'Alt-ArrowRight') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['Ctrl', '→']; // macOS: Ctrl+ArrowRight
|
||||
} else {
|
||||
return ['Alt', '→']; // Windows/Linux: Alt+ArrowRight
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.InsertBlankLineCommand && keyStr === 'Ctrl-Enter') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', 'Enter']; // macOS: Cmd+Enter
|
||||
} else {
|
||||
return ['Ctrl', 'Enter']; // Windows/Linux: Ctrl+Enter
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.SelectLineCommand && keyStr === 'Alt-l') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['Ctrl', 'L']; // macOS: Ctrl+l
|
||||
} else {
|
||||
return ['Alt', 'L']; // Windows/Linux: Alt+l
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.SelectParentSyntaxCommand && keyStr === 'Ctrl-i') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', 'I']; // macOS: Cmd+i
|
||||
} else {
|
||||
return ['Ctrl', 'I']; // Windows/Linux: Ctrl+i
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.IndentLessCommand && keyStr === 'Ctrl-[') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '[']; // macOS: Cmd+[
|
||||
} else {
|
||||
return ['Ctrl', '[']; // Windows/Linux: Ctrl+[
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.IndentMoreCommand && keyStr === 'Ctrl-]') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', ']']; // macOS: Cmd+]
|
||||
} else {
|
||||
return ['Ctrl', ']']; // Windows/Linux: Ctrl+]
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.IndentSelectionCommand && keyStr === 'Ctrl-Alt-\\') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '⌥', '\\']; // macOS: Cmd+Alt+\
|
||||
} else {
|
||||
return ['Ctrl', 'Alt', '\\']; // Windows/Linux: Ctrl+Alt+\
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.CursorMatchingBracketCommand && keyStr === 'Shift-Ctrl-\\') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⇧', '⌘', '\\']; // macOS: Shift+Cmd+\
|
||||
} else {
|
||||
return ['Shift', 'Ctrl', '\\']; // Windows/Linux: Shift+Ctrl+\
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.ToggleCommentCommand && keyStr === 'Ctrl-/') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', '/']; // macOS: Cmd+/
|
||||
} else {
|
||||
return ['Ctrl', '/']; // Windows/Linux: Ctrl+/
|
||||
}
|
||||
}
|
||||
|
||||
// 特殊处理删除快捷键的操作系统差异
|
||||
if (command === KeyBindingCommand.DeleteGroupBackwardCommand && keyStr === 'Ctrl-Backspace') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', 'Backspace']; // macOS: Cmd+Backspace
|
||||
} else {
|
||||
return ['Ctrl', 'Backspace']; // Windows/Linux: Ctrl+Backspace
|
||||
}
|
||||
}
|
||||
|
||||
if (command === KeyBindingCommand.DeleteGroupForwardCommand && keyStr === 'Ctrl-Delete') {
|
||||
if (systemStore.isMacOS) {
|
||||
return ['⌘', 'Delete']; // macOS: Cmd+Delete
|
||||
} else {
|
||||
return ['Ctrl', 'Delete']; // Windows/Linux: Ctrl+Delete
|
||||
}
|
||||
}
|
||||
|
||||
// 处理常见的快捷键格式
|
||||
const parts = keyStr.split(/[-+]/);
|
||||
return parts.map(part => {
|
||||
// 根据操作系统将 Mod 替换为相应的键
|
||||
if (part === 'Mod') {
|
||||
if (systemStore.isMacOS) {
|
||||
return '⌘'; // macOS 使用 Command 键符号
|
||||
} else {
|
||||
return 'Ctrl'; // Windows/Linux 使用 Ctrl
|
||||
}
|
||||
}
|
||||
|
||||
// 处理其他键名的操作系统差异
|
||||
if (part === 'Alt' && systemStore.isMacOS) {
|
||||
return '⌥'; // macOS 使用 Option 键符号
|
||||
}
|
||||
|
||||
if (part === 'Shift') {
|
||||
return systemStore.isMacOS ? '⇧' : 'Shift'; // macOS 使用符号
|
||||
}
|
||||
|
||||
// 首字母大写
|
||||
return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();
|
||||
}).filter(part => part.length > 0);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="settings-page">
|
||||
<!-- 快捷键模式设置 -->
|
||||
<SettingSection :title="t('keybindings.keymapMode')">
|
||||
<SettingItem
|
||||
:title="t('keybindings.keymapMode')">
|
||||
<select
|
||||
:value="configStore.config.editing.keymapMode"
|
||||
@change="updateKeymapMode(($event.target as HTMLSelectElement).value as KeyBindingType)"
|
||||
class="select-input"
|
||||
>
|
||||
<option
|
||||
v-for="option in keymapModeOptions"
|
||||
:key="option.value"
|
||||
:value="option.value"
|
||||
>
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
</SettingItem>
|
||||
</SettingSection>
|
||||
|
||||
<!-- 快捷键列表 -->
|
||||
<SettingSection :title="t('settings.keyBindings')">
|
||||
<template #title-right>
|
||||
<button
|
||||
:class="['reset-button', isResetConfirming('keybindings') ? 'reset-button-confirming' : '']"
|
||||
@click="requestResetConfirm('keybindings')"
|
||||
>
|
||||
{{ isResetConfirming('keybindings') ? t('keybindings.confirmReset') : t('keybindings.resetToDefault') }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<div class="key-bindings-container">
|
||||
<div class="key-bindings-header">
|
||||
<div class="keybinding-col">{{ t('keybindings.headers.shortcut') }}</div>
|
||||
<div class="category-col">{{ t('keybindings.headers.category') }}</div>
|
||||
<div class="extension-col">{{ t('keybindings.headers.extension') }}</div>
|
||||
<div class="description-col">{{ t('keybindings.headers.description') }}</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="binding in keyBindings"
|
||||
:key="binding.id"
|
||||
:key="binding.name"
|
||||
class="key-binding-row"
|
||||
>
|
||||
<div class="keybinding-col">
|
||||
<span
|
||||
v-for="(key, index) in binding.keys"
|
||||
:key="index"
|
||||
class="key-badge"
|
||||
>
|
||||
{{ key }}
|
||||
</span>
|
||||
<!-- 快捷键列 -->
|
||||
<div
|
||||
class="keybinding-col"
|
||||
:class="{ 'editing': editingBinding?.name === binding.name }"
|
||||
@click.stop="editingBinding?.name !== binding.name && startEditBinding(binding)"
|
||||
>
|
||||
<!-- 编辑模式 -->
|
||||
<template v-if="editingBinding?.name === binding.name">
|
||||
<template v-if="!capturedKey">
|
||||
<span class="key-badge waiting">waiting...</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span
|
||||
v-for="(key, index) in capturedKeyDisplay"
|
||||
:key="index"
|
||||
class="key-badge captured"
|
||||
:class="{ 'conflict': isConflict }"
|
||||
>
|
||||
{{ key }}
|
||||
</span>
|
||||
</template>
|
||||
<button
|
||||
@click.stop="confirmKeybinding"
|
||||
class="btn-mini btn-confirm"
|
||||
:disabled="!capturedKey"
|
||||
title="Ok"
|
||||
>✓</button>
|
||||
<button
|
||||
@click.stop="cancelEdit"
|
||||
class="btn-mini btn-cancel"
|
||||
title="Cancel"
|
||||
>✕</button>
|
||||
</template>
|
||||
|
||||
<!-- 显示模式 -->
|
||||
<template v-else>
|
||||
<span
|
||||
v-for="(key, index) in binding.command"
|
||||
:key="index"
|
||||
class="key-badge"
|
||||
>
|
||||
{{ key }}
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
<div class="category-col">{{ binding.category }}</div>
|
||||
|
||||
<div class="extension-col">{{ binding.extension }}</div>
|
||||
<div class="description-col">{{ binding.description }}</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -231,16 +318,68 @@ const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.settings-page {
|
||||
//max-width: 800px;
|
||||
.select-input {
|
||||
min-width: 140px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--settings-input-border);
|
||||
border-radius: 4px;
|
||||
background-color: var(--settings-input-bg);
|
||||
color: var(--settings-text);
|
||||
font-size: 12px;
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23666666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 6px center;
|
||||
background-size: 14px;
|
||||
padding-right: 26px;
|
||||
transition: border-color 0.2s ease;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: #4a9eff;
|
||||
}
|
||||
|
||||
option {
|
||||
background-color: var(--settings-card-bg);
|
||||
color: var(--settings-text);
|
||||
}
|
||||
}
|
||||
|
||||
.reset-button {
|
||||
padding: 6px 12px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--settings-input-border);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
background-color: var(--settings-button-bg);
|
||||
color: var(--settings-button-text);
|
||||
|
||||
&:hover {
|
||||
border-color: #4a9eff;
|
||||
background-color: var(--settings-button-hover-bg);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
&.reset-button-confirming {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
border-color: #c0392b;
|
||||
|
||||
&:hover {
|
||||
background-color: #c0392b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.key-bindings-container {
|
||||
padding: 10px 16px;
|
||||
|
||||
.key-bindings-header {
|
||||
display: flex;
|
||||
padding: 0 0 10px 0;
|
||||
padding: 0 0 8px 0;
|
||||
border-bottom: 1px solid var(--settings-border);
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
@@ -249,7 +388,7 @@ const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
|
||||
.key-binding-row {
|
||||
display: flex;
|
||||
padding: 14px 0;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid var(--settings-border);
|
||||
align-items: center;
|
||||
transition: background-color 0.2s ease;
|
||||
@@ -262,9 +401,20 @@ const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
.keybinding-col {
|
||||
width: 150px;
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
gap: 4px;
|
||||
padding: 0 10px 0 0;
|
||||
color: var(--settings-text);
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover:not(.editing) .key-badge {
|
||||
border-color: #4a9eff;
|
||||
}
|
||||
|
||||
&.editing {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.key-badge {
|
||||
background-color: var(--settings-input-bg);
|
||||
@@ -273,10 +423,75 @@ const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
font-size: 11px;
|
||||
border: 1px solid var(--settings-input-border);
|
||||
color: var(--settings-text);
|
||||
transition: border-color 0.2s ease;
|
||||
white-space: nowrap;
|
||||
|
||||
&.waiting {
|
||||
border: none;
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
color: #4a9eff;
|
||||
font-style: italic;
|
||||
animation: colorPulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
&.captured {
|
||||
background-color: #4a9eff;
|
||||
color: white;
|
||||
border-color: #4a9eff;
|
||||
|
||||
&.conflict {
|
||||
background-color: #dc3545;
|
||||
border-color: #dc3545;
|
||||
animation: shake 0.6s ease-in-out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.category-col {
|
||||
.btn-mini {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
min-width: 16px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
cursor: pointer;
|
||||
font-size: 10px;
|
||||
transition: opacity 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
margin-left: auto;
|
||||
|
||||
&.btn-confirm {
|
||||
background-color: #28a745;
|
||||
color: white;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background-color: var(--settings-input-border);
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
&.btn-cancel {
|
||||
background-color: #dc3545;
|
||||
color: white;
|
||||
margin-left: 2px;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.extension-col {
|
||||
width: 80px;
|
||||
padding: 0 10px 0 0;
|
||||
font-size: 13px;
|
||||
@@ -291,6 +506,29 @@ const parseKeyBinding = (keyStr: string, command?: string): string[] => {
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes colorPulse {
|
||||
0%, 100% {
|
||||
color: #4a9eff;
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
color: #2080ff;
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
0%, 100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
10%, 30%, 50%, 70%, 90% {
|
||||
transform: translateX(-4px);
|
||||
}
|
||||
20%, 40%, 60%, 80% {
|
||||
transform: translateX(4px);
|
||||
}
|
||||
}
|
||||
|
||||
.coming-soon-placeholder {
|
||||
padding: 20px;
|
||||
background-color: var(--settings-card-bg);
|
||||
|
||||
59
go.mod
59
go.mod
@@ -3,22 +3,25 @@ module voidraft
|
||||
go 1.25
|
||||
|
||||
require (
|
||||
github.com/creativeprojects/go-selfupdate v1.5.1
|
||||
github.com/go-git/go-git/v5 v5.16.3
|
||||
entgo.io/ent v0.14.5
|
||||
github.com/creativeprojects/go-selfupdate v1.5.2
|
||||
github.com/go-git/go-git/v5 v5.16.4
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/knadh/koanf/parsers/json v1.0.0
|
||||
github.com/knadh/koanf/providers/file v1.2.0
|
||||
github.com/knadh/koanf/providers/file v1.2.1
|
||||
github.com/knadh/koanf/providers/structs v1.0.0
|
||||
github.com/knadh/koanf/v2 v2.3.0
|
||||
github.com/mattn/go-sqlite3 v1.14.32
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.41
|
||||
golang.org/x/net v0.47.0
|
||||
golang.org/x/sys v0.38.0
|
||||
golang.org/x/text v0.31.0
|
||||
modernc.org/sqlite v1.40.1
|
||||
resty.dev/v3 v3.0.0-beta.3
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.51
|
||||
golang.org/x/net v0.48.0
|
||||
golang.org/x/sys v0.39.0
|
||||
golang.org/x/text v0.32.0
|
||||
resty.dev/v3 v3.0.0-beta.5
|
||||
)
|
||||
|
||||
require (
|
||||
ariga.io/atlas v0.38.0 // indirect
|
||||
code.gitea.io/sdk/gitea v0.22.1 // indirect
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
|
||||
@@ -27,29 +30,33 @@ require (
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/go-crypto v1.3.0 // indirect
|
||||
github.com/adrg/xdg v0.5.3 // indirect
|
||||
github.com/agext/levenshtein v1.2.3 // indirect
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
|
||||
github.com/bep/debounce v1.2.1 // indirect
|
||||
github.com/cloudflare/circl v1.6.1 // indirect
|
||||
github.com/bmatcuk/doublestar v1.3.4 // indirect
|
||||
github.com/cloudflare/circl v1.6.2 // indirect
|
||||
github.com/cyphar/filepath-securejoin v0.6.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/davidmz/go-pageant v1.0.2 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/ebitengine/purego v0.9.1 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/fatih/structs v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.7.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-openapi/inflect v0.21.5 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.1 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
|
||||
github.com/google/go-github/v30 v30.1.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/go-github/v74 v74.0.0 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
|
||||
github.com/hashicorp/go-version v1.7.0 // indirect
|
||||
github.com/hashicorp/go-version v1.8.0 // indirect
|
||||
github.com/hashicorp/hcl/v2 v2.24.0 // indirect
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
||||
github.com/kevinburke/ssh_config v1.4.0 // indirect
|
||||
@@ -61,13 +68,11 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pjbgf/sha1cd v0.5.0 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/samber/lo v1.52.0 // indirect
|
||||
github.com/sergi/go-diff v1.4.0 // indirect
|
||||
@@ -75,17 +80,19 @@ require (
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
github.com/wailsapp/go-webview2 v1.0.23 // indirect
|
||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||
github.com/xanzy/go-gitlab v0.115.0 // indirect
|
||||
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
github.com/zclconf/go-cty v1.17.0 // indirect
|
||||
github.com/zclconf/go-cty-yaml v1.2.0 // indirect
|
||||
gitlab.com/gitlab-org/api/client-go v1.10.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
||||
golang.org/x/image v0.33.0 // indirect
|
||||
golang.org/x/oauth2 v0.33.0 // indirect
|
||||
golang.org/x/image v0.34.0 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/oauth2 v0.34.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.67.0 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
155
go.sum
155
go.sum
@@ -1,11 +1,17 @@
|
||||
ariga.io/atlas v0.38.0 h1:MwbtwVtDWJFq+ECyeTAz2ArvewDnpeiw/t/sgNdDsdo=
|
||||
ariga.io/atlas v0.38.0/go.mod h1:D7XMK6ei3GvfDqvzk+2VId78j77LdqHrqPOWamn51/s=
|
||||
code.gitea.io/sdk/gitea v0.22.1 h1:7K05KjRORyTcTYULQ/AwvlVS6pawLcWyXZcTr7gHFyA=
|
||||
code.gitea.io/sdk/gitea v0.22.1/go.mod h1:yyF5+GhljqvA30sRDreoyHILruNiy4ASufugzYg0VHM=
|
||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||
entgo.io/ent v0.14.5 h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=
|
||||
entgo.io/ent v0.14.5/go.mod h1:zTzLmWtPvGpmSwtkaayM2cm5m819NdM7z7tYPq3vN0U=
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
|
||||
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
|
||||
github.com/42wim/httpsig v1.2.3 h1:xb0YyWhkYj57SPtfSttIobJUPJZB9as1nsfo7KWVcEs=
|
||||
github.com/42wim/httpsig v1.2.3/go.mod h1:nZq9OlYKDrUBhptd77IHx4/sZZD+IxTBADvAPI9G/EM=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
|
||||
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
|
||||
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
|
||||
@@ -15,16 +21,22 @@ github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBi
|
||||
github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=
|
||||
github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78=
|
||||
github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ=
|
||||
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
|
||||
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
|
||||
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||
github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
|
||||
github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
|
||||
github.com/creativeprojects/go-selfupdate v1.5.1 h1:fuyEGFFfqcC8SxDGolcEPYPLXGQ9Mcrc5uRyRG2Mqnk=
|
||||
github.com/creativeprojects/go-selfupdate v1.5.1/go.mod h1:2uY75rP8z/D/PBuDn6mlBnzu+ysEmwOJfcgF8np0JIM=
|
||||
github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
|
||||
github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
|
||||
github.com/cloudflare/circl v1.6.2 h1:hL7VBpHHKzrV5WTfHCaBsgx/HGbBYlgrwvNXEVDYYsQ=
|
||||
github.com/cloudflare/circl v1.6.2/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
||||
github.com/creativeprojects/go-selfupdate v1.5.2 h1:3KR3JLrq70oplb9yZzbmJ89qRP78D1AN/9u+l3k0LJ4=
|
||||
github.com/creativeprojects/go-selfupdate v1.5.2/go.mod h1:BCOuwIl1dRRCmPNRPH0amULeZqayhKyY2mH/h4va7Dk=
|
||||
github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE=
|
||||
github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -32,8 +44,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
|
||||
github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=
|
||||
github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
|
||||
@@ -52,31 +62,31 @@ github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
|
||||
github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=
|
||||
github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
|
||||
github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
|
||||
github.com/go-git/go-billy/v5 v5.7.0 h1:83lBUJhGWhYp0ngzCMSgllhUSuoHP1iEWYjsPl9nwqM=
|
||||
github.com/go-git/go-billy/v5 v5.7.0/go.mod h1:/1IUejTKH8xipsAcdfcSAlUlo2J7lkYV8GTKxAT/L3E=
|
||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=
|
||||
github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=
|
||||
github.com/go-git/go-git/v5 v5.16.3 h1:Z8BtvxZ09bYm/yYNgPKCzgWtaRqDTgIKRgIRHBfU6Z8=
|
||||
github.com/go-git/go-git/v5 v5.16.3/go.mod h1:4Ge4alE/5gPs30F2H1esi2gPd69R0C39lolkucHBOp8=
|
||||
github.com/go-git/go-git/v5 v5.16.4 h1:7ajIEZHZJULcyJebDLo99bGgS0jRrOxzZG4uCk2Yb2Y=
|
||||
github.com/go-git/go-git/v5 v5.16.4/go.mod h1:4Ge4alE/5gPs30F2H1esi2gPd69R0C39lolkucHBOp8=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/go-openapi/inflect v0.21.5 h1:M2RCq6PPS3YbIaL7CXosGL3BbzAcmfBAT0nC3YfesZA=
|
||||
github.com/go-openapi/inflect v0.21.5/go.mod h1:GypUyi6bU880NYurWaEH2CmH84zFDNd+EhhmzroHmB4=
|
||||
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
|
||||
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.2.0 h1:3WexO+U+yg9T70v9FdHr9kCxYlazaAXUhx2VMkbfax8=
|
||||
github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/godbus/dbus/v5 v5.2.1 h1:I4wwMdWSkmI57ewd+elNGwLRf2/dtSaFz1DujfWYvOk=
|
||||
github.com/godbus/dbus/v5 v5.2.1/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/go-github/v30 v30.1.0 h1:VLDx+UolQICEOKu2m4uAoMti1SxuEBAl7RSEG16L+Oo=
|
||||
github.com/google/go-github/v30 v30.1.0/go.mod h1:n8jBpHl45a/rlBUtRJMOG4GhNADUQFEufcolZ95JfU8=
|
||||
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
|
||||
github.com/google/go-github/v74 v74.0.0 h1:yZcddTUn8DPbj11GxnMrNiAnXH14gNs559AsUpNpPgM=
|
||||
github.com/google/go-github/v74 v74.0.0/go.mod h1:ubn/YdyftV80VPSI26nSJvaEsTOnsjrxG3o9kJhcyak=
|
||||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
|
||||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
@@ -85,10 +95,10 @@ github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB1
|
||||
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
|
||||
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
|
||||
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=
|
||||
github.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE=
|
||||
github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM=
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
|
||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
|
||||
@@ -101,8 +111,8 @@ github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpb
|
||||
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
|
||||
github.com/knadh/koanf/parsers/json v1.0.0 h1:1pVR1JhMwbqSg5ICzU+surJmeBbdT4bQm7jjgnA+f8o=
|
||||
github.com/knadh/koanf/parsers/json v1.0.0/go.mod h1:zb5WtibRdpxSoSJfXysqGbVxvbszdlroWDHGdDkkEYU=
|
||||
github.com/knadh/koanf/providers/file v1.2.0 h1:hrUJ6Y9YOA49aNu/RSYzOTFlqzXSCpmYIDXI7OJU6+U=
|
||||
github.com/knadh/koanf/providers/file v1.2.0/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=
|
||||
github.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP3AESOJYp9wM=
|
||||
github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=
|
||||
github.com/knadh/koanf/providers/structs v1.0.0 h1:DznjB7NQykhqCar2LvNug3MuxEQsZ5KvfgMbio+23u4=
|
||||
github.com/knadh/koanf/providers/structs v1.0.0/go.mod h1:kjo5TFtgpaZORlpoJqcbeLowM2cINodv8kX+oFAeQ1w=
|
||||
github.com/knadh/koanf/v2 v2.3.0 h1:Qg076dDRFHvqnKG97ZEsi9TAg2/nFTa9hCdcSa1lvlM=
|
||||
@@ -127,12 +137,14 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
|
||||
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
|
||||
github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
|
||||
github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=
|
||||
@@ -143,8 +155,6 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
@@ -168,36 +178,40 @@ github.com/wailsapp/go-webview2 v1.0.23 h1:jmv8qhz1lHibCc79bMM/a/FqOnnzOGEisLav+
|
||||
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
||||
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
||||
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.41 h1:DYcC1/vtO862sxnoyCOMfLLypbzpFWI257fR6zDYY+Y=
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.41/go.mod h1:7i8tSuA74q97zZ5qEJlcVZdnO+IR7LT2KU8UpzYMPsw=
|
||||
github.com/xanzy/go-gitlab v0.115.0 h1:6DmtItNcVe+At/liXSgfE/DZNZrGfalQmBRmOcJjOn8=
|
||||
github.com/xanzy/go-gitlab v0.115.0/go.mod h1:5XCDtM7AM6WMKmfDdOiEpyRWUqui2iS9ILfvCZ2gJ5M=
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.51 h1:n8KT0H4lvtWld9tMIiHVX4nrR0wEMT2zy5hM/R6luMU=
|
||||
github.com/wailsapp/wails/v3 v3.0.0-alpha.51/go.mod h1:yaz8baG0+YzoiN8J6osn0wKiEi0iUux0ZU5NsZFu6OQ=
|
||||
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
|
||||
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
|
||||
github.com/zclconf/go-cty v1.17.0 h1:seZvECve6XX4tmnvRzWtJNHdscMtYEx5R7bnnVyd/d0=
|
||||
github.com/zclconf/go-cty v1.17.0/go.mod h1:wqFzcImaLTI6A5HfsRwB0nj5n0MRZFwmey8YoFPPs3U=
|
||||
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=
|
||||
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=
|
||||
github.com/zclconf/go-cty-yaml v1.2.0 h1:GDyL4+e/Qe/S0B7YaecMLbVvAR/Mp21CXMOSiCTOi1M=
|
||||
github.com/zclconf/go-cty-yaml v1.2.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
|
||||
gitlab.com/gitlab-org/api/client-go v1.10.0 h1:VlB9gXQdG6w643lH53VduUHVnCWQG5Ty86VbXnyi70A=
|
||||
gitlab.com/gitlab-org/api/client-go v1.10.0/go.mod h1:U3QKvjbT1J1FrgLsA7w/XlhoBIendUqB4o3/Ht3UhEQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=
|
||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=
|
||||
golang.org/x/image v0.33.0 h1:LXRZRnv1+zGd5XBUVRFmYEphyyKJjQjCRiOuAP3sZfQ=
|
||||
golang.org/x/image v0.33.0/go.mod h1:DD3OsTYT9chzuzTQt+zMcOlBHgfoKQb1gry8p76Y1sc=
|
||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/image v0.34.0 h1:33gCkyw9hmwbZJeZkct8XyR11yH889EQt/QH4VmXMn8=
|
||||
golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo=
|
||||
golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
|
||||
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -209,23 +223,22 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
|
||||
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
@@ -238,33 +251,5 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
|
||||
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
|
||||
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
|
||||
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.67.0 h1:QzL4IrKab2OFmxA3/vRYl0tLXrIamwrhD6CKD4WBVjQ=
|
||||
modernc.org/libc v1.67.0/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.40.1 h1:VfuXcxcUWWKRBuP8+BR9L7VnmusMgBNNnBYGEe9w/iY=
|
||||
modernc.org/sqlite v1.40.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
resty.dev/v3 v3.0.0-beta.3 h1:3kEwzEgCnnS6Ob4Emlk94t+I/gClyoah7SnNi67lt+E=
|
||||
resty.dev/v3 v3.0.0-beta.3/go.mod h1:OgkqiPvTDtOuV4MGZuUDhwOpkY8enjOsjjMzeOHefy4=
|
||||
resty.dev/v3 v3.0.0-beta.5 h1:NV1xbqOLzSq7XMTs1t/HLPvu7xrxoXzF90SR4OO6faQ=
|
||||
resty.dev/v3 v3.0.0-beta.5/go.mod h1:NTOerrC/4T7/FE6tXIZGIysXXBdgNqwMZuKtxpea9NM=
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package services
|
||||
package helper
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
const pathSeparator = '.'
|
||||
|
||||
// ObserverCallback 观察者回调函数
|
||||
type ObserverCallback func(oldValue, newValue interface{})
|
||||
|
||||
@@ -49,6 +51,8 @@ func NewConfigObserver(logger *log.LogService) *ConfigObserver {
|
||||
}
|
||||
|
||||
// Watch 注册配置变更监听器
|
||||
// 支持前缀监听:注册 "generate" 可以监听 "generate.xxx"、"generate.yyy" 等所有子路径的变化
|
||||
// 返回取消函数,调用后停止监听
|
||||
func (co *ConfigObserver) Watch(path string, callback ObserverCallback) CancelFunc {
|
||||
// 生成唯一ID
|
||||
id := fmt.Sprintf("obs_%d", co.nextObserverID.Add(1))
|
||||
@@ -103,36 +107,91 @@ func (co *ConfigObserver) removeObserver(path, id string) {
|
||||
}
|
||||
}
|
||||
|
||||
// Notify 通知指定路径的所有观察者
|
||||
// Notify 通知指定路径及其所有父路径的观察者
|
||||
// 支持前缀监听:当 "generate.xxx" 变化时,同时通知监听 "generate" 的观察者
|
||||
// 通知顺序:精确匹配 -> 父路径(从近到远)
|
||||
func (co *ConfigObserver) Notify(path string, oldValue, newValue interface{}) {
|
||||
// 获取该路径的所有观察者(拷贝以避免并发问题)
|
||||
co.observerMu.RLock()
|
||||
observers := co.observers[path]
|
||||
if len(observers) == 0 {
|
||||
co.observerMu.RUnlock()
|
||||
callbacks := co.collectCallbacks(path)
|
||||
co.observerMu.RUnlock()
|
||||
|
||||
if len(callbacks) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 拷贝观察者列表
|
||||
callbacks := make([]ObserverCallback, len(observers))
|
||||
for i, obs := range observers {
|
||||
callbacks[i] = obs.callback
|
||||
}
|
||||
co.observerMu.RUnlock()
|
||||
|
||||
// 在独立 goroutine 中执行回调
|
||||
// 执行所有回调
|
||||
for _, callback := range callbacks {
|
||||
co.executeCallback(callback, oldValue, newValue)
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyAll 通知所有匹配前缀的观察者
|
||||
// collectCallbacks 收集指定路径及其所有父路径的观察者回调
|
||||
// 调用者必须持有读锁
|
||||
func (co *ConfigObserver) collectCallbacks(path string) []ObserverCallback {
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var callbacks []ObserverCallback
|
||||
|
||||
// 1. 收集精确匹配的观察者
|
||||
if observers := co.observers[path]; len(observers) > 0 {
|
||||
callbacks = make([]ObserverCallback, 0, len(observers)*2)
|
||||
for _, obs := range observers {
|
||||
callbacks = append(callbacks, obs.callback)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 收集父路径的观察者(从后向前遍历,避免 strings.Split 的内存分配)
|
||||
for i := len(path) - 1; i >= 0; i-- {
|
||||
if path[i] == pathSeparator {
|
||||
parentPath := path[:i]
|
||||
if observers := co.observers[parentPath]; len(observers) > 0 {
|
||||
if callbacks == nil {
|
||||
callbacks = make([]ObserverCallback, 0, len(observers))
|
||||
}
|
||||
for _, obs := range observers {
|
||||
callbacks = append(callbacks, obs.callback)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return callbacks
|
||||
}
|
||||
|
||||
// NotifyAll 批量通知所有匹配路径的观察者
|
||||
func (co *ConfigObserver) NotifyAll(changes map[string]struct {
|
||||
OldValue interface{}
|
||||
NewValue interface{}
|
||||
}) {
|
||||
if len(changes) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
type callbackTask struct {
|
||||
callback ObserverCallback
|
||||
oldValue interface{}
|
||||
newValue interface{}
|
||||
}
|
||||
|
||||
// 只获取一次读锁,收集所有回调
|
||||
co.observerMu.RLock()
|
||||
var tasks []callbackTask
|
||||
for path, change := range changes {
|
||||
co.Notify(path, change.OldValue, change.NewValue)
|
||||
for _, cb := range co.collectCallbacks(path) {
|
||||
tasks = append(tasks, callbackTask{
|
||||
callback: cb,
|
||||
oldValue: change.OldValue,
|
||||
newValue: change.NewValue,
|
||||
})
|
||||
}
|
||||
}
|
||||
co.observerMu.RUnlock()
|
||||
|
||||
// 执行所有回调
|
||||
for _, task := range tasks {
|
||||
co.executeCallback(task.callback, task.oldValue, task.newValue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package models
|
||||
|
||||
// Git备份相关类型定义
|
||||
type (
|
||||
// AuthMethod 定义Git认证方式
|
||||
AuthMethod string
|
||||
)
|
||||
|
||||
const (
|
||||
// 认证方式
|
||||
Token AuthMethod = "token"
|
||||
SSHKey AuthMethod = "ssh_key"
|
||||
UserPass AuthMethod = "user_pass"
|
||||
)
|
||||
|
||||
// GitBackupConfig Git备份配置
|
||||
type GitBackupConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
AuthMethod AuthMethod `json:"auth_method"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
SSHKeyPath string `json:"ssh_key_path,omitempty"`
|
||||
SSHKeyPass string `json:"ssh_key_passphrase,omitempty"`
|
||||
BackupInterval int `json:"backup_interval"` // 分钟
|
||||
AutoBackup bool `json:"auto_backup"`
|
||||
}
|
||||
@@ -103,6 +103,9 @@ type EditingConfig struct {
|
||||
TabSize int `json:"tabSize"` // Tab大小
|
||||
TabType TabType `json:"tabType"` // Tab类型(空格或Tab)
|
||||
|
||||
// 快捷键模式
|
||||
KeymapMode KeyBindingType `json:"keymapMode"` // 快捷键模式(standard 或 emacs)
|
||||
|
||||
// 保存选项
|
||||
AutoSaveDelay int `json:"autoSaveDelay"` // 自动保存延迟(毫秒)
|
||||
}
|
||||
@@ -126,6 +129,33 @@ type UpdatesConfig struct {
|
||||
Gitea GiteaConfig `json:"gitea"` // Gitea配置
|
||||
}
|
||||
|
||||
// Git备份相关类型定义
|
||||
type (
|
||||
// AuthMethod 定义Git认证方式
|
||||
AuthMethod string
|
||||
)
|
||||
|
||||
const (
|
||||
// 认证方式
|
||||
Token AuthMethod = "token"
|
||||
SSHKey AuthMethod = "ssh_key"
|
||||
UserPass AuthMethod = "user_pass"
|
||||
)
|
||||
|
||||
// GitBackupConfig Git备份配置
|
||||
type GitBackupConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
AuthMethod AuthMethod `json:"auth_method"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
SSHKeyPath string `json:"ssh_key_path,omitempty"`
|
||||
SSHKeyPass string `json:"ssh_key_passphrase,omitempty"`
|
||||
BackupInterval int `json:"backup_interval"` // 分钟
|
||||
AutoBackup bool `json:"auto_backup"`
|
||||
}
|
||||
|
||||
// AppConfig 应用配置 - 按照前端设置页面分类组织
|
||||
type AppConfig struct {
|
||||
General GeneralConfig `json:"general"` // 通用设置
|
||||
@@ -176,12 +206,14 @@ func NewDefaultAppConfig() *AppConfig {
|
||||
EnableTabIndent: true,
|
||||
TabSize: 4,
|
||||
TabType: TabTypeTab,
|
||||
// 快捷键模式
|
||||
KeymapMode: Standard, // 默认使用标准模式
|
||||
// 保存选项
|
||||
AutoSaveDelay: 2000,
|
||||
},
|
||||
Appearance: AppearanceConfig{
|
||||
Language: LangEnUS,
|
||||
SystemTheme: SystemThemeAuto,
|
||||
SystemTheme: SystemThemeDark,
|
||||
CurrentTheme: "default-dark", // 默认使用 default-dark 主题
|
||||
},
|
||||
Updates: UpdatesConfig{
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Document represents a document in the system
|
||||
type Document struct {
|
||||
ID int64 `json:"id" db:"id"`
|
||||
Title string `json:"title" db:"title"`
|
||||
Content string `json:"content" db:"content"`
|
||||
CreatedAt string `json:"createdAt" db:"created_at"`
|
||||
UpdatedAt string `json:"updatedAt" db:"updated_at"`
|
||||
IsDeleted bool `json:"is_deleted" db:"is_deleted"`
|
||||
IsLocked bool `json:"is_locked" db:"is_locked"` // 锁定标志,锁定的文档无法被删除
|
||||
}
|
||||
|
||||
// NewDocument 创建新文档
|
||||
func NewDocument(title, content string) *Document {
|
||||
now := time.Now()
|
||||
return &Document{
|
||||
Title: title,
|
||||
Content: content,
|
||||
CreatedAt: now.String(),
|
||||
UpdatedAt: now.String(),
|
||||
IsDeleted: false,
|
||||
IsLocked: false, // 默认不锁定
|
||||
}
|
||||
}
|
||||
|
||||
// NewDefaultDocument 创建默认文档
|
||||
func NewDefaultDocument() *Document {
|
||||
return NewDocument("default", "\n∞∞∞text-a\n")
|
||||
}
|
||||
804
internal/models/ent/client.go
Normal file
804
internal/models/ent/client.go
Normal file
@@ -0,0 +1,804 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
|
||||
"voidraft/internal/models/ent/migrate"
|
||||
|
||||
"voidraft/internal/models/ent/document"
|
||||
"voidraft/internal/models/ent/extension"
|
||||
"voidraft/internal/models/ent/keybinding"
|
||||
"voidraft/internal/models/ent/theme"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
|
||||
stdsql "database/sql"
|
||||
)
|
||||
|
||||
// Client is the client that holds all ent builders.
|
||||
type Client struct {
|
||||
config
|
||||
// Schema is the client for creating, migrating and dropping schema.
|
||||
Schema *migrate.Schema
|
||||
// Document is the client for interacting with the Document builders.
|
||||
Document *DocumentClient
|
||||
// Extension is the client for interacting with the Extension builders.
|
||||
Extension *ExtensionClient
|
||||
// KeyBinding is the client for interacting with the KeyBinding builders.
|
||||
KeyBinding *KeyBindingClient
|
||||
// Theme is the client for interacting with the Theme builders.
|
||||
Theme *ThemeClient
|
||||
}
|
||||
|
||||
// NewClient creates a new client configured with the given options.
|
||||
func NewClient(opts ...Option) *Client {
|
||||
client := &Client{config: newConfig(opts...)}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *Client) init() {
|
||||
c.Schema = migrate.NewSchema(c.driver)
|
||||
c.Document = NewDocumentClient(c.config)
|
||||
c.Extension = NewExtensionClient(c.config)
|
||||
c.KeyBinding = NewKeyBindingClient(c.config)
|
||||
c.Theme = NewThemeClient(c.config)
|
||||
}
|
||||
|
||||
type (
|
||||
// config is the configuration for the client and its builder.
|
||||
config struct {
|
||||
// driver used for executing database requests.
|
||||
driver dialect.Driver
|
||||
// debug enable a debug logging.
|
||||
debug bool
|
||||
// log used for logging on debug mode.
|
||||
log func(...any)
|
||||
// hooks to execute on mutations.
|
||||
hooks *hooks
|
||||
// interceptors to execute on queries.
|
||||
inters *inters
|
||||
}
|
||||
// Option function to configure the client.
|
||||
Option func(*config)
|
||||
)
|
||||
|
||||
// newConfig creates a new config for the client.
|
||||
func newConfig(opts ...Option) config {
|
||||
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
|
||||
cfg.options(opts...)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// options applies the options on the config object.
|
||||
func (c *config) options(opts ...Option) {
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
if c.debug {
|
||||
c.driver = dialect.Debug(c.driver, c.log)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug enables debug logging on the ent.Driver.
|
||||
func Debug() Option {
|
||||
return func(c *config) {
|
||||
c.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// Log sets the logging function for debug mode.
|
||||
func Log(fn func(...any)) Option {
|
||||
return func(c *config) {
|
||||
c.log = fn
|
||||
}
|
||||
}
|
||||
|
||||
// Driver configures the client driver.
|
||||
func Driver(driver dialect.Driver) Option {
|
||||
return func(c *config) {
|
||||
c.driver = driver
|
||||
}
|
||||
}
|
||||
|
||||
// Open opens a database/sql.DB specified by the driver name and
|
||||
// the data source name, and returns a new client attached to it.
|
||||
// Optional parameters can be added for configuring the client.
|
||||
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
|
||||
switch driverName {
|
||||
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
|
||||
drv, err := sql.Open(driverName, dataSourceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewClient(append(options, Driver(drv))...), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported driver: %q", driverName)
|
||||
}
|
||||
}
|
||||
|
||||
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
|
||||
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
|
||||
|
||||
// Tx returns a new transactional client. The provided context
|
||||
// is used until the transaction is committed or rolled back.
|
||||
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, ErrTxStarted
|
||||
}
|
||||
tx, err := newTx(ctx, c.driver)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = tx
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
Document: NewDocumentClient(cfg),
|
||||
Extension: NewExtensionClient(cfg),
|
||||
KeyBinding: NewKeyBindingClient(cfg),
|
||||
Theme: NewThemeClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BeginTx returns a transactional client with specified options.
|
||||
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
|
||||
if _, ok := c.driver.(*txDriver); ok {
|
||||
return nil, errors.New("ent: cannot start a transaction within a transaction")
|
||||
}
|
||||
tx, err := c.driver.(interface {
|
||||
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
|
||||
}).BeginTx(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = &txDriver{tx: tx, drv: c.driver}
|
||||
return &Tx{
|
||||
ctx: ctx,
|
||||
config: cfg,
|
||||
Document: NewDocumentClient(cfg),
|
||||
Extension: NewExtensionClient(cfg),
|
||||
KeyBinding: NewKeyBindingClient(cfg),
|
||||
Theme: NewThemeClient(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
|
||||
//
|
||||
// client.Debug().
|
||||
// Document.
|
||||
// Query().
|
||||
// Count(ctx)
|
||||
func (c *Client) Debug() *Client {
|
||||
if c.debug {
|
||||
return c
|
||||
}
|
||||
cfg := c.config
|
||||
cfg.driver = dialect.Debug(c.driver, c.log)
|
||||
client := &Client{config: cfg}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Close closes the database connection and prevents new queries from starting.
|
||||
func (c *Client) Close() error {
|
||||
return c.driver.Close()
|
||||
}
|
||||
|
||||
// Use adds the mutation hooks to all the entity clients.
|
||||
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
|
||||
func (c *Client) Use(hooks ...Hook) {
|
||||
c.Document.Use(hooks...)
|
||||
c.Extension.Use(hooks...)
|
||||
c.KeyBinding.Use(hooks...)
|
||||
c.Theme.Use(hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds the query interceptors to all the entity clients.
|
||||
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
|
||||
func (c *Client) Intercept(interceptors ...Interceptor) {
|
||||
c.Document.Intercept(interceptors...)
|
||||
c.Extension.Intercept(interceptors...)
|
||||
c.KeyBinding.Intercept(interceptors...)
|
||||
c.Theme.Intercept(interceptors...)
|
||||
}
|
||||
|
||||
// Mutate implements the ent.Mutator interface.
|
||||
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
|
||||
switch m := m.(type) {
|
||||
case *DocumentMutation:
|
||||
return c.Document.mutate(ctx, m)
|
||||
case *ExtensionMutation:
|
||||
return c.Extension.mutate(ctx, m)
|
||||
case *KeyBindingMutation:
|
||||
return c.KeyBinding.mutate(ctx, m)
|
||||
case *ThemeMutation:
|
||||
return c.Theme.mutate(ctx, m)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
|
||||
}
|
||||
}
|
||||
|
||||
// DocumentClient is a client for the Document schema.
|
||||
type DocumentClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewDocumentClient returns a client for the Document from the given config.
|
||||
func NewDocumentClient(c config) *DocumentClient {
|
||||
return &DocumentClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `document.Hooks(f(g(h())))`.
|
||||
func (c *DocumentClient) Use(hooks ...Hook) {
|
||||
c.hooks.Document = append(c.hooks.Document, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `document.Intercept(f(g(h())))`.
|
||||
func (c *DocumentClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.Document = append(c.inters.Document, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a Document entity.
|
||||
func (c *DocumentClient) Create() *DocumentCreate {
|
||||
mutation := newDocumentMutation(c.config, OpCreate)
|
||||
return &DocumentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of Document entities.
|
||||
func (c *DocumentClient) CreateBulk(builders ...*DocumentCreate) *DocumentCreateBulk {
|
||||
return &DocumentCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *DocumentClient) MapCreateBulk(slice any, setFunc func(*DocumentCreate, int)) *DocumentCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &DocumentCreateBulk{err: fmt.Errorf("calling to DocumentClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*DocumentCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &DocumentCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Document.
|
||||
func (c *DocumentClient) Update() *DocumentUpdate {
|
||||
mutation := newDocumentMutation(c.config, OpUpdate)
|
||||
return &DocumentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *DocumentClient) UpdateOne(_m *Document) *DocumentUpdateOne {
|
||||
mutation := newDocumentMutation(c.config, OpUpdateOne, withDocument(_m))
|
||||
return &DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *DocumentClient) UpdateOneID(id int) *DocumentUpdateOne {
|
||||
mutation := newDocumentMutation(c.config, OpUpdateOne, withDocumentID(id))
|
||||
return &DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Document.
|
||||
func (c *DocumentClient) Delete() *DocumentDelete {
|
||||
mutation := newDocumentMutation(c.config, OpDelete)
|
||||
return &DocumentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *DocumentClient) DeleteOne(_m *Document) *DocumentDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *DocumentClient) DeleteOneID(id int) *DocumentDeleteOne {
|
||||
builder := c.Delete().Where(document.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &DocumentDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for Document.
|
||||
func (c *DocumentClient) Query() *DocumentQuery {
|
||||
return &DocumentQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeDocument},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a Document entity by its id.
|
||||
func (c *DocumentClient) Get(ctx context.Context, id int) (*Document, error) {
|
||||
return c.Query().Where(document.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *DocumentClient) GetX(ctx context.Context, id int) *Document {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *DocumentClient) Hooks() []Hook {
|
||||
hooks := c.hooks.Document
|
||||
return append(hooks[:len(hooks):len(hooks)], document.Hooks[:]...)
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *DocumentClient) Interceptors() []Interceptor {
|
||||
inters := c.inters.Document
|
||||
return append(inters[:len(inters):len(inters)], document.Interceptors[:]...)
|
||||
}
|
||||
|
||||
func (c *DocumentClient) mutate(ctx context.Context, m *DocumentMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&DocumentCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&DocumentUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&DocumentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&DocumentDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown Document mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// ExtensionClient is a client for the Extension schema.
|
||||
type ExtensionClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewExtensionClient returns a client for the Extension from the given config.
|
||||
func NewExtensionClient(c config) *ExtensionClient {
|
||||
return &ExtensionClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `extension.Hooks(f(g(h())))`.
|
||||
func (c *ExtensionClient) Use(hooks ...Hook) {
|
||||
c.hooks.Extension = append(c.hooks.Extension, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `extension.Intercept(f(g(h())))`.
|
||||
func (c *ExtensionClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.Extension = append(c.inters.Extension, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a Extension entity.
|
||||
func (c *ExtensionClient) Create() *ExtensionCreate {
|
||||
mutation := newExtensionMutation(c.config, OpCreate)
|
||||
return &ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of Extension entities.
|
||||
func (c *ExtensionClient) CreateBulk(builders ...*ExtensionCreate) *ExtensionCreateBulk {
|
||||
return &ExtensionCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *ExtensionClient) MapCreateBulk(slice any, setFunc func(*ExtensionCreate, int)) *ExtensionCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &ExtensionCreateBulk{err: fmt.Errorf("calling to ExtensionClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*ExtensionCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &ExtensionCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Extension.
|
||||
func (c *ExtensionClient) Update() *ExtensionUpdate {
|
||||
mutation := newExtensionMutation(c.config, OpUpdate)
|
||||
return &ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *ExtensionClient) UpdateOne(_m *Extension) *ExtensionUpdateOne {
|
||||
mutation := newExtensionMutation(c.config, OpUpdateOne, withExtension(_m))
|
||||
return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *ExtensionClient) UpdateOneID(id int) *ExtensionUpdateOne {
|
||||
mutation := newExtensionMutation(c.config, OpUpdateOne, withExtensionID(id))
|
||||
return &ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Extension.
|
||||
func (c *ExtensionClient) Delete() *ExtensionDelete {
|
||||
mutation := newExtensionMutation(c.config, OpDelete)
|
||||
return &ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *ExtensionClient) DeleteOne(_m *Extension) *ExtensionDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *ExtensionClient) DeleteOneID(id int) *ExtensionDeleteOne {
|
||||
builder := c.Delete().Where(extension.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &ExtensionDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for Extension.
|
||||
func (c *ExtensionClient) Query() *ExtensionQuery {
|
||||
return &ExtensionQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeExtension},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a Extension entity by its id.
|
||||
func (c *ExtensionClient) Get(ctx context.Context, id int) (*Extension, error) {
|
||||
return c.Query().Where(extension.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *ExtensionClient) GetX(ctx context.Context, id int) *Extension {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *ExtensionClient) Hooks() []Hook {
|
||||
hooks := c.hooks.Extension
|
||||
return append(hooks[:len(hooks):len(hooks)], extension.Hooks[:]...)
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *ExtensionClient) Interceptors() []Interceptor {
|
||||
inters := c.inters.Extension
|
||||
return append(inters[:len(inters):len(inters)], extension.Interceptors[:]...)
|
||||
}
|
||||
|
||||
func (c *ExtensionClient) mutate(ctx context.Context, m *ExtensionMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&ExtensionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&ExtensionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&ExtensionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&ExtensionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown Extension mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// KeyBindingClient is a client for the KeyBinding schema.
|
||||
type KeyBindingClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewKeyBindingClient returns a client for the KeyBinding from the given config.
|
||||
func NewKeyBindingClient(c config) *KeyBindingClient {
|
||||
return &KeyBindingClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `keybinding.Hooks(f(g(h())))`.
|
||||
func (c *KeyBindingClient) Use(hooks ...Hook) {
|
||||
c.hooks.KeyBinding = append(c.hooks.KeyBinding, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `keybinding.Intercept(f(g(h())))`.
|
||||
func (c *KeyBindingClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.KeyBinding = append(c.inters.KeyBinding, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a KeyBinding entity.
|
||||
func (c *KeyBindingClient) Create() *KeyBindingCreate {
|
||||
mutation := newKeyBindingMutation(c.config, OpCreate)
|
||||
return &KeyBindingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of KeyBinding entities.
|
||||
func (c *KeyBindingClient) CreateBulk(builders ...*KeyBindingCreate) *KeyBindingCreateBulk {
|
||||
return &KeyBindingCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *KeyBindingClient) MapCreateBulk(slice any, setFunc func(*KeyBindingCreate, int)) *KeyBindingCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &KeyBindingCreateBulk{err: fmt.Errorf("calling to KeyBindingClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*KeyBindingCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &KeyBindingCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for KeyBinding.
|
||||
func (c *KeyBindingClient) Update() *KeyBindingUpdate {
|
||||
mutation := newKeyBindingMutation(c.config, OpUpdate)
|
||||
return &KeyBindingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *KeyBindingClient) UpdateOne(_m *KeyBinding) *KeyBindingUpdateOne {
|
||||
mutation := newKeyBindingMutation(c.config, OpUpdateOne, withKeyBinding(_m))
|
||||
return &KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *KeyBindingClient) UpdateOneID(id int) *KeyBindingUpdateOne {
|
||||
mutation := newKeyBindingMutation(c.config, OpUpdateOne, withKeyBindingID(id))
|
||||
return &KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for KeyBinding.
|
||||
func (c *KeyBindingClient) Delete() *KeyBindingDelete {
|
||||
mutation := newKeyBindingMutation(c.config, OpDelete)
|
||||
return &KeyBindingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *KeyBindingClient) DeleteOne(_m *KeyBinding) *KeyBindingDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *KeyBindingClient) DeleteOneID(id int) *KeyBindingDeleteOne {
|
||||
builder := c.Delete().Where(keybinding.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &KeyBindingDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for KeyBinding.
|
||||
func (c *KeyBindingClient) Query() *KeyBindingQuery {
|
||||
return &KeyBindingQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeKeyBinding},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a KeyBinding entity by its id.
|
||||
func (c *KeyBindingClient) Get(ctx context.Context, id int) (*KeyBinding, error) {
|
||||
return c.Query().Where(keybinding.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *KeyBindingClient) GetX(ctx context.Context, id int) *KeyBinding {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *KeyBindingClient) Hooks() []Hook {
|
||||
hooks := c.hooks.KeyBinding
|
||||
return append(hooks[:len(hooks):len(hooks)], keybinding.Hooks[:]...)
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *KeyBindingClient) Interceptors() []Interceptor {
|
||||
inters := c.inters.KeyBinding
|
||||
return append(inters[:len(inters):len(inters)], keybinding.Interceptors[:]...)
|
||||
}
|
||||
|
||||
func (c *KeyBindingClient) mutate(ctx context.Context, m *KeyBindingMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&KeyBindingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&KeyBindingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&KeyBindingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&KeyBindingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown KeyBinding mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// ThemeClient is a client for the Theme schema.
|
||||
type ThemeClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewThemeClient returns a client for the Theme from the given config.
|
||||
func NewThemeClient(c config) *ThemeClient {
|
||||
return &ThemeClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `theme.Hooks(f(g(h())))`.
|
||||
func (c *ThemeClient) Use(hooks ...Hook) {
|
||||
c.hooks.Theme = append(c.hooks.Theme, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `theme.Intercept(f(g(h())))`.
|
||||
func (c *ThemeClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.Theme = append(c.inters.Theme, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a Theme entity.
|
||||
func (c *ThemeClient) Create() *ThemeCreate {
|
||||
mutation := newThemeMutation(c.config, OpCreate)
|
||||
return &ThemeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of Theme entities.
|
||||
func (c *ThemeClient) CreateBulk(builders ...*ThemeCreate) *ThemeCreateBulk {
|
||||
return &ThemeCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *ThemeClient) MapCreateBulk(slice any, setFunc func(*ThemeCreate, int)) *ThemeCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &ThemeCreateBulk{err: fmt.Errorf("calling to ThemeClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*ThemeCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &ThemeCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for Theme.
|
||||
func (c *ThemeClient) Update() *ThemeUpdate {
|
||||
mutation := newThemeMutation(c.config, OpUpdate)
|
||||
return &ThemeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *ThemeClient) UpdateOne(_m *Theme) *ThemeUpdateOne {
|
||||
mutation := newThemeMutation(c.config, OpUpdateOne, withTheme(_m))
|
||||
return &ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *ThemeClient) UpdateOneID(id int) *ThemeUpdateOne {
|
||||
mutation := newThemeMutation(c.config, OpUpdateOne, withThemeID(id))
|
||||
return &ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for Theme.
|
||||
func (c *ThemeClient) Delete() *ThemeDelete {
|
||||
mutation := newThemeMutation(c.config, OpDelete)
|
||||
return &ThemeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *ThemeClient) DeleteOne(_m *Theme) *ThemeDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *ThemeClient) DeleteOneID(id int) *ThemeDeleteOne {
|
||||
builder := c.Delete().Where(theme.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &ThemeDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for Theme.
|
||||
func (c *ThemeClient) Query() *ThemeQuery {
|
||||
return &ThemeQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeTheme},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a Theme entity by its id.
|
||||
func (c *ThemeClient) Get(ctx context.Context, id int) (*Theme, error) {
|
||||
return c.Query().Where(theme.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *ThemeClient) GetX(ctx context.Context, id int) *Theme {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *ThemeClient) Hooks() []Hook {
|
||||
hooks := c.hooks.Theme
|
||||
return append(hooks[:len(hooks):len(hooks)], theme.Hooks[:]...)
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *ThemeClient) Interceptors() []Interceptor {
|
||||
inters := c.inters.Theme
|
||||
return append(inters[:len(inters):len(inters)], theme.Interceptors[:]...)
|
||||
}
|
||||
|
||||
func (c *ThemeClient) mutate(ctx context.Context, m *ThemeMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&ThemeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&ThemeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&ThemeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&ThemeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown Theme mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
Document, Extension, KeyBinding, Theme []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
Document, Extension, KeyBinding, Theme []ent.Interceptor
|
||||
}
|
||||
)
|
||||
|
||||
// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it.
|
||||
// See, database/sql#DB.ExecContext for more information.
|
||||
func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
|
||||
ex, ok := c.driver.(interface {
|
||||
ExecContext(context.Context, string, ...any) (stdsql.Result, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Driver.ExecContext is not supported")
|
||||
}
|
||||
return ex.ExecContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it.
|
||||
// See, database/sql#DB.QueryContext for more information.
|
||||
func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
|
||||
q, ok := c.driver.(interface {
|
||||
QueryContext(context.Context, string, ...any) (*stdsql.Rows, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Driver.QueryContext is not supported")
|
||||
}
|
||||
return q.QueryContext(ctx, query, args...)
|
||||
}
|
||||
174
internal/models/ent/document.go
Normal file
174
internal/models/ent/document.go
Normal file
@@ -0,0 +1,174 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"voidraft/internal/models/ent/document"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// Document is the model entity for the Document schema.
|
||||
type Document struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// UUID for cross-device sync (UUIDv7)
|
||||
UUID string `json:"uuid"`
|
||||
// creation time
|
||||
CreatedAt string `json:"created_at"`
|
||||
// update time
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
// deleted at
|
||||
DeletedAt *string `json:"deleted_at,omitempty"`
|
||||
// document title
|
||||
Title string `json:"title"`
|
||||
// document content
|
||||
Content string `json:"content"`
|
||||
// document locked status
|
||||
Locked bool `json:"locked"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Document) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case document.FieldLocked:
|
||||
values[i] = new(sql.NullBool)
|
||||
case document.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case document.FieldUUID, document.FieldCreatedAt, document.FieldUpdatedAt, document.FieldDeletedAt, document.FieldTitle, document.FieldContent:
|
||||
values[i] = new(sql.NullString)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Document fields.
|
||||
func (_m *Document) assignValues(columns []string, values []any) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case document.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int(value.Int64)
|
||||
case document.FieldUUID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field uuid", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UUID = value.String
|
||||
}
|
||||
case document.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field created_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CreatedAt = value.String
|
||||
}
|
||||
case document.FieldUpdatedAt:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UpdatedAt = value.String
|
||||
}
|
||||
case document.FieldDeletedAt:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.DeletedAt = new(string)
|
||||
*_m.DeletedAt = value.String
|
||||
}
|
||||
case document.FieldTitle:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field title", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Title = value.String
|
||||
}
|
||||
case document.FieldContent:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field content", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Content = value.String
|
||||
}
|
||||
case document.FieldLocked:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field locked", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Locked = value.Bool
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Document.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Document) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Document.
|
||||
// Note that you need to call Document.Unwrap() before calling this method if this Document
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Document) Update() *DocumentUpdateOne {
|
||||
return NewDocumentClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Document entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *Document) Unwrap() *Document {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Document is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Document) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Document(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("uuid=")
|
||||
builder.WriteString(_m.UUID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("updated_at=")
|
||||
builder.WriteString(_m.UpdatedAt)
|
||||
builder.WriteString(", ")
|
||||
if v := _m.DeletedAt; v != nil {
|
||||
builder.WriteString("deleted_at=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("title=")
|
||||
builder.WriteString(_m.Title)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("content=")
|
||||
builder.WriteString(_m.Content)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("locked=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Locked))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Documents is a parsable slice of Document.
|
||||
type Documents []*Document
|
||||
118
internal/models/ent/document/document.go
Normal file
118
internal/models/ent/document/document.go
Normal file
@@ -0,0 +1,118 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package document
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the document type in the database.
|
||||
Label = "document"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldUUID holds the string denoting the uuid field in the database.
|
||||
FieldUUID = "uuid"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
|
||||
FieldUpdatedAt = "updated_at"
|
||||
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
|
||||
FieldDeletedAt = "deleted_at"
|
||||
// FieldTitle holds the string denoting the title field in the database.
|
||||
FieldTitle = "title"
|
||||
// FieldContent holds the string denoting the content field in the database.
|
||||
FieldContent = "content"
|
||||
// FieldLocked holds the string denoting the locked field in the database.
|
||||
FieldLocked = "locked"
|
||||
// Table holds the table name of the document in the database.
|
||||
Table = "documents"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for document fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldUUID,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
FieldDeletedAt,
|
||||
FieldTitle,
|
||||
FieldContent,
|
||||
FieldLocked,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Note that the variables below are initialized by the runtime
|
||||
// package on the initialization of the application. Therefore,
|
||||
// it should be imported in the main as follows:
|
||||
//
|
||||
// import _ "voidraft/internal/models/ent/runtime"
|
||||
var (
|
||||
Hooks [2]ent.Hook
|
||||
Interceptors [1]ent.Interceptor
|
||||
// DefaultUUID holds the default value on creation for the "uuid" field.
|
||||
DefaultUUID func() string
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() string
|
||||
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
|
||||
DefaultUpdatedAt func() string
|
||||
// TitleValidator is a validator for the "title" field. It is called by the builders before save.
|
||||
TitleValidator func(string) error
|
||||
// DefaultContent holds the default value on creation for the "content" field.
|
||||
DefaultContent string
|
||||
// DefaultLocked holds the default value on creation for the "locked" field.
|
||||
DefaultLocked bool
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Document queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUUID orders the results by the uuid field.
|
||||
func ByUUID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUUID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUpdatedAt orders the results by the updated_at field.
|
||||
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDeletedAt orders the results by the deleted_at field.
|
||||
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTitle orders the results by the title field.
|
||||
func ByTitle(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTitle, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByContent orders the results by the content field.
|
||||
func ByContent(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldContent, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByLocked orders the results by the locked field.
|
||||
func ByLocked(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldLocked, opts...).ToFunc()
|
||||
}
|
||||
524
internal/models/ent/document/where.go
Normal file
524
internal/models/ent/document/where.go
Normal file
@@ -0,0 +1,524 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package document
|
||||
|
||||
import (
|
||||
"voidraft/internal/models/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// UUID applies equality check predicate on the "uuid" field. It's identical to UUIDEQ.
|
||||
func UUID(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUUID, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
|
||||
func DeletedAt(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
|
||||
func Title(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// Content applies equality check predicate on the "content" field. It's identical to ContentEQ.
|
||||
func Content(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// Locked applies equality check predicate on the "locked" field. It's identical to LockedEQ.
|
||||
func Locked(v bool) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldLocked, v))
|
||||
}
|
||||
|
||||
// UUIDEQ applies the EQ predicate on the "uuid" field.
|
||||
func UUIDEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDNEQ applies the NEQ predicate on the "uuid" field.
|
||||
func UUIDNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDIn applies the In predicate on the "uuid" field.
|
||||
func UUIDIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldUUID, vs...))
|
||||
}
|
||||
|
||||
// UUIDNotIn applies the NotIn predicate on the "uuid" field.
|
||||
func UUIDNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldUUID, vs...))
|
||||
}
|
||||
|
||||
// UUIDGT applies the GT predicate on the "uuid" field.
|
||||
func UUIDGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDGTE applies the GTE predicate on the "uuid" field.
|
||||
func UUIDGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDLT applies the LT predicate on the "uuid" field.
|
||||
func UUIDLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDLTE applies the LTE predicate on the "uuid" field.
|
||||
func UUIDLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDContains applies the Contains predicate on the "uuid" field.
|
||||
func UUIDContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDHasPrefix applies the HasPrefix predicate on the "uuid" field.
|
||||
func UUIDHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDHasSuffix applies the HasSuffix predicate on the "uuid" field.
|
||||
func UUIDHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
|
||||
func UUIDEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldUUID, v))
|
||||
}
|
||||
|
||||
// UUIDContainsFold applies the ContainsFold predicate on the "uuid" field.
|
||||
func UUIDContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldUUID, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtContains applies the Contains predicate on the "created_at" field.
|
||||
func CreatedAtContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
|
||||
func CreatedAtHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
|
||||
func CreatedAtHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtEqualFold applies the EqualFold predicate on the "created_at" field.
|
||||
func CreatedAtEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtContainsFold applies the ContainsFold predicate on the "created_at" field.
|
||||
func CreatedAtContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
|
||||
func UpdatedAtContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
|
||||
func UpdatedAtHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
|
||||
func UpdatedAtHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEqualFold applies the EqualFold predicate on the "updated_at" field.
|
||||
func UpdatedAtEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtContainsFold applies the ContainsFold predicate on the "updated_at" field.
|
||||
func UpdatedAtContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
|
||||
func DeletedAtEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
|
||||
func DeletedAtNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtIn applies the In predicate on the "deleted_at" field.
|
||||
func DeletedAtIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldDeletedAt, vs...))
|
||||
}
|
||||
|
||||
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
|
||||
func DeletedAtNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldDeletedAt, vs...))
|
||||
}
|
||||
|
||||
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
|
||||
func DeletedAtGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
|
||||
func DeletedAtGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
|
||||
func DeletedAtLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
|
||||
func DeletedAtLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtContains applies the Contains predicate on the "deleted_at" field.
|
||||
func DeletedAtContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtHasPrefix applies the HasPrefix predicate on the "deleted_at" field.
|
||||
func DeletedAtHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtHasSuffix applies the HasSuffix predicate on the "deleted_at" field.
|
||||
func DeletedAtHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
|
||||
func DeletedAtIsNil() predicate.Document {
|
||||
return predicate.Document(sql.FieldIsNull(FieldDeletedAt))
|
||||
}
|
||||
|
||||
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
|
||||
func DeletedAtNotNil() predicate.Document {
|
||||
return predicate.Document(sql.FieldNotNull(FieldDeletedAt))
|
||||
}
|
||||
|
||||
// DeletedAtEqualFold applies the EqualFold predicate on the "deleted_at" field.
|
||||
func DeletedAtEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// DeletedAtContainsFold applies the ContainsFold predicate on the "deleted_at" field.
|
||||
func DeletedAtContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldDeletedAt, v))
|
||||
}
|
||||
|
||||
// TitleEQ applies the EQ predicate on the "title" field.
|
||||
func TitleEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleNEQ applies the NEQ predicate on the "title" field.
|
||||
func TitleNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleIn applies the In predicate on the "title" field.
|
||||
func TitleIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldTitle, vs...))
|
||||
}
|
||||
|
||||
// TitleNotIn applies the NotIn predicate on the "title" field.
|
||||
func TitleNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldTitle, vs...))
|
||||
}
|
||||
|
||||
// TitleGT applies the GT predicate on the "title" field.
|
||||
func TitleGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleGTE applies the GTE predicate on the "title" field.
|
||||
func TitleGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleLT applies the LT predicate on the "title" field.
|
||||
func TitleLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleLTE applies the LTE predicate on the "title" field.
|
||||
func TitleLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleContains applies the Contains predicate on the "title" field.
|
||||
func TitleContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
|
||||
func TitleHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
|
||||
func TitleHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleEqualFold applies the EqualFold predicate on the "title" field.
|
||||
func TitleEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldTitle, v))
|
||||
}
|
||||
|
||||
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
|
||||
func TitleContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldTitle, v))
|
||||
}
|
||||
|
||||
// ContentEQ applies the EQ predicate on the "content" field.
|
||||
func ContentEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentNEQ applies the NEQ predicate on the "content" field.
|
||||
func ContentNEQ(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentIn applies the In predicate on the "content" field.
|
||||
func ContentIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldIn(FieldContent, vs...))
|
||||
}
|
||||
|
||||
// ContentNotIn applies the NotIn predicate on the "content" field.
|
||||
func ContentNotIn(vs ...string) predicate.Document {
|
||||
return predicate.Document(sql.FieldNotIn(FieldContent, vs...))
|
||||
}
|
||||
|
||||
// ContentGT applies the GT predicate on the "content" field.
|
||||
func ContentGT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGT(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentGTE applies the GTE predicate on the "content" field.
|
||||
func ContentGTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldGTE(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentLT applies the LT predicate on the "content" field.
|
||||
func ContentLT(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLT(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentLTE applies the LTE predicate on the "content" field.
|
||||
func ContentLTE(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldLTE(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentContains applies the Contains predicate on the "content" field.
|
||||
func ContentContains(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContains(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentHasPrefix applies the HasPrefix predicate on the "content" field.
|
||||
func ContentHasPrefix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasPrefix(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentHasSuffix applies the HasSuffix predicate on the "content" field.
|
||||
func ContentHasSuffix(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldHasSuffix(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentIsNil applies the IsNil predicate on the "content" field.
|
||||
func ContentIsNil() predicate.Document {
|
||||
return predicate.Document(sql.FieldIsNull(FieldContent))
|
||||
}
|
||||
|
||||
// ContentNotNil applies the NotNil predicate on the "content" field.
|
||||
func ContentNotNil() predicate.Document {
|
||||
return predicate.Document(sql.FieldNotNull(FieldContent))
|
||||
}
|
||||
|
||||
// ContentEqualFold applies the EqualFold predicate on the "content" field.
|
||||
func ContentEqualFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldEqualFold(FieldContent, v))
|
||||
}
|
||||
|
||||
// ContentContainsFold applies the ContainsFold predicate on the "content" field.
|
||||
func ContentContainsFold(v string) predicate.Document {
|
||||
return predicate.Document(sql.FieldContainsFold(FieldContent, v))
|
||||
}
|
||||
|
||||
// LockedEQ applies the EQ predicate on the "locked" field.
|
||||
func LockedEQ(v bool) predicate.Document {
|
||||
return predicate.Document(sql.FieldEQ(FieldLocked, v))
|
||||
}
|
||||
|
||||
// LockedNEQ applies the NEQ predicate on the "locked" field.
|
||||
func LockedNEQ(v bool) predicate.Document {
|
||||
return predicate.Document(sql.FieldNEQ(FieldLocked, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.Document) predicate.Document {
|
||||
return predicate.Document(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Document) predicate.Document {
|
||||
return predicate.Document(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Document) predicate.Document {
|
||||
return predicate.Document(sql.NotPredicates(p))
|
||||
}
|
||||
346
internal/models/ent/document_create.go
Normal file
346
internal/models/ent/document_create.go
Normal file
@@ -0,0 +1,346 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"voidraft/internal/models/ent/document"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// DocumentCreate is the builder for creating a Document entity.
|
||||
type DocumentCreate struct {
|
||||
config
|
||||
mutation *DocumentMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetUUID sets the "uuid" field.
|
||||
func (_c *DocumentCreate) SetUUID(v string) *DocumentCreate {
|
||||
_c.mutation.SetUUID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableUUID sets the "uuid" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableUUID(v *string) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetUUID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *DocumentCreate) SetCreatedAt(v string) *DocumentCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableCreatedAt(v *string) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_c *DocumentCreate) SetUpdatedAt(v string) *DocumentCreate {
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableUpdatedAt(v *string) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetUpdatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetDeletedAt sets the "deleted_at" field.
|
||||
func (_c *DocumentCreate) SetDeletedAt(v string) *DocumentCreate {
|
||||
_c.mutation.SetDeletedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableDeletedAt(v *string) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetDeletedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTitle sets the "title" field.
|
||||
func (_c *DocumentCreate) SetTitle(v string) *DocumentCreate {
|
||||
_c.mutation.SetTitle(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetContent sets the "content" field.
|
||||
func (_c *DocumentCreate) SetContent(v string) *DocumentCreate {
|
||||
_c.mutation.SetContent(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableContent sets the "content" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableContent(v *string) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetContent(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetLocked sets the "locked" field.
|
||||
func (_c *DocumentCreate) SetLocked(v bool) *DocumentCreate {
|
||||
_c.mutation.SetLocked(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableLocked sets the "locked" field if the given value is not nil.
|
||||
func (_c *DocumentCreate) SetNillableLocked(v *bool) *DocumentCreate {
|
||||
if v != nil {
|
||||
_c.SetLocked(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// Mutation returns the DocumentMutation object of the builder.
|
||||
func (_c *DocumentCreate) Mutation() *DocumentMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Document in the database.
|
||||
func (_c *DocumentCreate) Save(ctx context.Context) (*Document, error) {
|
||||
if err := _c.defaults(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *DocumentCreate) SaveX(ctx context.Context) *Document {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *DocumentCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *DocumentCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *DocumentCreate) defaults() error {
|
||||
if _, ok := _c.mutation.UUID(); !ok {
|
||||
if document.DefaultUUID == nil {
|
||||
return fmt.Errorf("ent: uninitialized document.DefaultUUID (forgotten import ent/runtime?)")
|
||||
}
|
||||
v := document.DefaultUUID()
|
||||
_c.mutation.SetUUID(v)
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
if document.DefaultCreatedAt == nil {
|
||||
return fmt.Errorf("ent: uninitialized document.DefaultCreatedAt (forgotten import ent/runtime?)")
|
||||
}
|
||||
v := document.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
if document.DefaultUpdatedAt == nil {
|
||||
return fmt.Errorf("ent: uninitialized document.DefaultUpdatedAt (forgotten import ent/runtime?)")
|
||||
}
|
||||
v := document.DefaultUpdatedAt()
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
if _, ok := _c.mutation.Content(); !ok {
|
||||
v := document.DefaultContent
|
||||
_c.mutation.SetContent(v)
|
||||
}
|
||||
if _, ok := _c.mutation.Locked(); !ok {
|
||||
v := document.DefaultLocked
|
||||
_c.mutation.SetLocked(v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *DocumentCreate) check() error {
|
||||
if _, ok := _c.mutation.UUID(); !ok {
|
||||
return &ValidationError{Name: "uuid", err: errors.New(`ent: missing required field "Document.uuid"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Document.created_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Document.updated_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.Title(); !ok {
|
||||
return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Document.title"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Title(); ok {
|
||||
if err := document.TitleValidator(v); err != nil {
|
||||
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Locked(); !ok {
|
||||
return &ValidationError{Name: "locked", err: errors.New(`ent: missing required field "Document.locked"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *DocumentCreate) sqlSave(ctx context.Context) (*Document, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Document{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(document.Table, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
|
||||
)
|
||||
if value, ok := _c.mutation.UUID(); ok {
|
||||
_spec.SetField(document.FieldUUID, field.TypeString, value)
|
||||
_node.UUID = value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(document.FieldCreatedAt, field.TypeString, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.DeletedAt(); ok {
|
||||
_spec.SetField(document.FieldDeletedAt, field.TypeString, value)
|
||||
_node.DeletedAt = &value
|
||||
}
|
||||
if value, ok := _c.mutation.Title(); ok {
|
||||
_spec.SetField(document.FieldTitle, field.TypeString, value)
|
||||
_node.Title = value
|
||||
}
|
||||
if value, ok := _c.mutation.Content(); ok {
|
||||
_spec.SetField(document.FieldContent, field.TypeString, value)
|
||||
_node.Content = value
|
||||
}
|
||||
if value, ok := _c.mutation.Locked(); ok {
|
||||
_spec.SetField(document.FieldLocked, field.TypeBool, value)
|
||||
_node.Locked = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// DocumentCreateBulk is the builder for creating many Document entities in bulk.
|
||||
type DocumentCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*DocumentCreate
|
||||
}
|
||||
|
||||
// Save creates the Document entities in the database.
|
||||
func (_c *DocumentCreateBulk) Save(ctx context.Context) ([]*Document, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Document, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*DocumentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *DocumentCreateBulk) SaveX(ctx context.Context) []*Document {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *DocumentCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *DocumentCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/models/ent/document_delete.go
Normal file
88
internal/models/ent/document_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"voidraft/internal/models/ent/document"
|
||||
"voidraft/internal/models/ent/predicate"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// DocumentDelete is the builder for deleting a Document entity.
|
||||
type DocumentDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *DocumentMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the DocumentDelete builder.
|
||||
func (_d *DocumentDelete) Where(ps ...predicate.Document) *DocumentDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *DocumentDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *DocumentDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *DocumentDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(document.Table, sqlgraph.NewFieldSpec(document.FieldID, field.TypeInt))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// DocumentDeleteOne is the builder for deleting a single Document entity.
|
||||
type DocumentDeleteOne struct {
|
||||
_d *DocumentDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the DocumentDelete builder.
|
||||
func (_d *DocumentDeleteOne) Where(ps ...predicate.Document) *DocumentDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *DocumentDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{document.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *DocumentDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user