3 Commits

Author SHA1 Message Date
fa134d31d6 📝 Update README.md 2025-12-20 17:05:49 +08:00
d035dcd531 Merge branch 'master' into dev 2025-12-20 17:04:39 +08:00
7b746155f7 ♻️ Refactor keybinding service 2025-12-20 16:43:04 +08:00
61 changed files with 4527 additions and 1820 deletions

View File

@@ -159,8 +159,5 @@ Welcome to Fork, Star, and contribute code.
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub stars](https://img.shields.io/github/stars/landaiqing/voidraft.svg?style=social&label=Star)](https://github.com/yourusername/voidraft) [![GitHub stars](https://img.shields.io/github/stars/landaiqing/voidraft.svg?style=social&label=Star)](https://github.com/yourusername/voidraft)
[![GitHub forks](https://img.shields.io/github/forks/landaiqing/voidraft.svg?style=social&label=Fork)](https://github.com/yourusername/voidraft) [![GitHub forks](https://img.shields.io/github/forks/landaiqing/voidraft.svg?style=social&label=Fork)](https://github.com/yourusername/voidraft)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Flandaiqing%2Fvoidraft.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Flandaiqing%2Fvoidraft?ref=badge_shield)
*Made with ❤️ by landaiqing* *Made with ❤️ by landaiqing*
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Flandaiqing%2Fvoidraft.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Flandaiqing%2Fvoidraft?ref=badge_large)

View File

@@ -21,7 +21,7 @@ export class Document {
/** /**
* UUID for cross-device sync (UUIDv7) * UUID for cross-device sync (UUIDv7)
*/ */
"uuid": string | null; "uuid": string;
/** /**
* creation time * creation time
@@ -56,7 +56,7 @@ export class Document {
/** Creates a new Document instance. */ /** Creates a new Document instance. */
constructor($$source: Partial<Document> = {}) { constructor($$source: Partial<Document> = {}) {
if (!("uuid" in $$source)) { if (!("uuid" in $$source)) {
this["uuid"] = null; this["uuid"] = "";
} }
if (!("created_at" in $$source)) { if (!("created_at" in $$source)) {
this["created_at"] = ""; this["created_at"] = "";
@@ -98,7 +98,7 @@ export class Extension {
/** /**
* UUID for cross-device sync (UUIDv7) * UUID for cross-device sync (UUIDv7)
*/ */
"uuid": string | null; "uuid": string;
/** /**
* creation time * creation time
@@ -116,9 +116,9 @@ export class Extension {
"deleted_at"?: string | null; "deleted_at"?: string | null;
/** /**
* extension key * extension name
*/ */
"key": string; "name": string;
/** /**
* extension enabled or not * extension enabled or not
@@ -133,7 +133,7 @@ export class Extension {
/** Creates a new Extension instance. */ /** Creates a new Extension instance. */
constructor($$source: Partial<Extension> = {}) { constructor($$source: Partial<Extension> = {}) {
if (!("uuid" in $$source)) { if (!("uuid" in $$source)) {
this["uuid"] = null; this["uuid"] = "";
} }
if (!("created_at" in $$source)) { if (!("created_at" in $$source)) {
this["created_at"] = ""; this["created_at"] = "";
@@ -141,8 +141,8 @@ export class Extension {
if (!("updated_at" in $$source)) { if (!("updated_at" in $$source)) {
this["updated_at"] = ""; this["updated_at"] = "";
} }
if (!("key" in $$source)) { if (!("name" in $$source)) {
this["key"] = ""; this["name"] = "";
} }
if (!("enabled" in $$source)) { if (!("enabled" in $$source)) {
this["enabled"] = false; this["enabled"] = false;
@@ -179,7 +179,7 @@ export class KeyBinding {
/** /**
* UUID for cross-device sync (UUIDv7) * UUID for cross-device sync (UUIDv7)
*/ */
"uuid": string | null; "uuid": string;
/** /**
* creation time * creation time
@@ -197,29 +197,59 @@ export class KeyBinding {
"deleted_at"?: string | null; "deleted_at"?: string | null;
/** /**
* key binding key * command identifier
*/ */
"key": string; "name": string;
/** /**
* key binding command * keybinding type: standard or emacs
*/ */
"command": string; "type": string;
/** /**
* key binding extension * universal keybinding (cross-platform)
*/ */
"extension"?: string; "key"?: string;
/** /**
* key binding enabled * 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; "enabled": boolean;
/**
* prevent browser default behavior
*/
"preventDefault": boolean;
/**
* keybinding scope (default: editor)
*/
"scope"?: string;
/** Creates a new KeyBinding instance. */ /** Creates a new KeyBinding instance. */
constructor($$source: Partial<KeyBinding> = {}) { constructor($$source: Partial<KeyBinding> = {}) {
if (!("uuid" in $$source)) { if (!("uuid" in $$source)) {
this["uuid"] = null; this["uuid"] = "";
} }
if (!("created_at" in $$source)) { if (!("created_at" in $$source)) {
this["created_at"] = ""; this["created_at"] = "";
@@ -227,15 +257,21 @@ export class KeyBinding {
if (!("updated_at" in $$source)) { if (!("updated_at" in $$source)) {
this["updated_at"] = ""; this["updated_at"] = "";
} }
if (!("key" in $$source)) { if (!("name" in $$source)) {
this["key"] = ""; this["name"] = "";
} }
if (!("command" in $$source)) { if (!("type" in $$source)) {
this["command"] = ""; this["type"] = "";
}
if (!("extension" in $$source)) {
this["extension"] = "";
} }
if (!("enabled" in $$source)) { if (!("enabled" in $$source)) {
this["enabled"] = false; this["enabled"] = false;
} }
if (!("preventDefault" in $$source)) {
this["preventDefault"] = false;
}
Object.assign(this, $$source); Object.assign(this, $$source);
} }
@@ -261,7 +297,7 @@ export class Theme {
/** /**
* UUID for cross-device sync (UUIDv7) * UUID for cross-device sync (UUIDv7)
*/ */
"uuid": string | null; "uuid": string;
/** /**
* creation time * creation time
@@ -279,9 +315,9 @@ export class Theme {
"deleted_at"?: string | null; "deleted_at"?: string | null;
/** /**
* theme key * theme name
*/ */
"key": string; "name": string;
/** /**
* theme type * theme type
@@ -296,7 +332,7 @@ export class Theme {
/** Creates a new Theme instance. */ /** Creates a new Theme instance. */
constructor($$source: Partial<Theme> = {}) { constructor($$source: Partial<Theme> = {}) {
if (!("uuid" in $$source)) { if (!("uuid" in $$source)) {
this["uuid"] = null; this["uuid"] = "";
} }
if (!("created_at" in $$source)) { if (!("created_at" in $$source)) {
this["created_at"] = ""; this["created_at"] = "";
@@ -304,8 +340,8 @@ export class Theme {
if (!("updated_at" in $$source)) { if (!("updated_at" in $$source)) {
this["updated_at"] = ""; this["updated_at"] = "";
} }
if (!("key" in $$source)) { if (!("name" in $$source)) {
this["key"] = ""; this["name"] = "";
} }
if (!("type" in $$source)) { if (!("type" in $$source)) {
this["type"] = ("" as theme$0.Type); this["type"] = ("" as theme$0.Type);

View File

@@ -234,6 +234,12 @@ export class EditingConfig {
*/ */
"tabType": TabType; "tabType": TabType;
/**
* 快捷键模式
* 快捷键模式standard 或 emacs
*/
"keymapMode": KeyBindingType;
/** /**
* 保存选项 * 保存选项
* 自动保存延迟(毫秒) * 自动保存延迟(毫秒)
@@ -263,6 +269,9 @@ export class EditingConfig {
if (!("tabType" in $$source)) { if (!("tabType" in $$source)) {
this["tabType"] = ("" as TabType); this["tabType"] = ("" as TabType);
} }
if (!("keymapMode" in $$source)) {
this["keymapMode"] = ("" as KeyBindingType);
}
if (!("autoSaveDelay" in $$source)) { if (!("autoSaveDelay" in $$source)) {
this["autoSaveDelay"] = 0; this["autoSaveDelay"] = 0;
} }
@@ -283,14 +292,14 @@ export class EditingConfig {
* Extension 扩展配置 * Extension 扩展配置
*/ */
export class Extension { export class Extension {
"key": ExtensionKey; "key": ExtensionName;
"enabled": boolean; "enabled": boolean;
"config": ExtensionConfig; "config": ExtensionConfig;
/** Creates a new Extension instance. */ /** Creates a new Extension instance. */
constructor($$source: Partial<Extension> = {}) { constructor($$source: Partial<Extension> = {}) {
if (!("key" in $$source)) { if (!("key" in $$source)) {
this["key"] = ("" as ExtensionKey); this["key"] = ("" as ExtensionName);
} }
if (!("enabled" in $$source)) { if (!("enabled" in $$source)) {
this["enabled"] = false; this["enabled"] = false;
@@ -321,79 +330,78 @@ export class Extension {
export type ExtensionConfig = { [_: string]: any }; export type ExtensionConfig = { [_: string]: any };
/** /**
* ExtensionKey 扩展标识符 * ExtensionName 扩展标识符
*/ */
export enum ExtensionKey { export enum ExtensionName {
/** /**
* The Go zero value for the underlying type of the enum. * The Go zero value for the underlying type of the enum.
*/ */
$zero = "", $zero = "",
/** /**
* 编辑增强扩展
* 彩虹括号 * 彩虹括号
*/ */
ExtensionRainbowBrackets = "rainbowBrackets", RainbowBrackets = "rainbowBrackets",
/** /**
* 超链接 * 超链接
*/ */
ExtensionHyperlink = "hyperlink", Hyperlink = "hyperlink",
/** /**
* 颜色选择器 * 颜色选择器
*/ */
ExtensionColorSelector = "colorSelector", ColorSelector = "colorSelector",
/** /**
* 代码折叠 * 代码折叠
*/ */
ExtensionFold = "fold", Fold = "fold",
/** /**
* 划词翻译 * 划词翻译
*/ */
ExtensionTranslator = "translator", Translator = "translator",
/** /**
* Markdown渲染 * Markdown渲染
*/ */
ExtensionMarkdown = "markdown", Markdown = "markdown",
/** /**
* 显示空白字符 * 显示空白字符
*/ */
ExtensionHighlightWhitespace = "highlightWhitespace", HighlightWhitespace = "highlightWhitespace",
/** /**
* 高亮行尾空白 * 高亮行尾空白
*/ */
ExtensionHighlightTrailingWhitespace = "highlightTrailingWhitespace", HighlightTrailingWhitespace = "highlightTrailingWhitespace",
/** /**
* 小地图 * 小地图
*/ */
ExtensionMinimap = "minimap", Minimap = "minimap",
/** /**
* 行号显示 * 行号显示
*/ */
ExtensionLineNumbers = "lineNumbers", LineNumbers = "lineNumbers",
/** /**
* 上下文菜单 * 上下文菜单
*/ */
ExtensionContextMenu = "contextMenu", ContextMenu = "contextMenu",
/** /**
* 搜索功能 * 搜索功能
*/ */
ExtensionSearch = "search", Search = "search",
/** /**
* HTTP 客户端 * HTTP 客户端
*/ */
ExtensionHttpClient = "httpClient", HttpClient = "httpClient",
}; };
/** /**
@@ -684,25 +692,73 @@ export class HotkeyCombo {
* KeyBinding 单个快捷键绑定 * KeyBinding 单个快捷键绑定
*/ */
export class KeyBinding { export class KeyBinding {
"key": KeyBindingKey; /**
"command": string; * 命令唯一标识符
"extension": ExtensionKey; */
"name": KeyBindingName;
/**
* 快捷键类型standard 或 "emacs"
*/
"type": KeyBindingType;
/**
* 通用快捷键(跨平台)
*/
"key"?: string;
/**
* macOS 专用快捷键
*/
"macos"?: string;
/**
* windows 专用快捷键
*/
"win"?: string;
/**
* Linux 专用快捷键
*/
"linux"?: string;
/**
* 所属扩展
*/
"extension": ExtensionName;
/**
* 是否启用
*/
"enabled": boolean; "enabled": boolean;
/**
* 阻止浏览器默认行为
*/
"preventDefault": boolean;
/**
* 作用域(默认 "editor"
*/
"scope"?: string;
/** Creates a new KeyBinding instance. */ /** Creates a new KeyBinding instance. */
constructor($$source: Partial<KeyBinding> = {}) { constructor($$source: Partial<KeyBinding> = {}) {
if (!("key" in $$source)) { if (!("name" in $$source)) {
this["key"] = ("" as KeyBindingKey); this["name"] = ("" as KeyBindingName);
} }
if (!("command" in $$source)) { if (!("type" in $$source)) {
this["command"] = ""; this["type"] = ("" as KeyBindingType);
} }
if (!("extension" in $$source)) { if (!("extension" in $$source)) {
this["extension"] = ("" as ExtensionKey); this["extension"] = ("" as ExtensionName);
} }
if (!("enabled" in $$source)) { if (!("enabled" in $$source)) {
this["enabled"] = false; this["enabled"] = false;
} }
if (!("preventDefault" in $$source)) {
this["preventDefault"] = false;
}
Object.assign(this, $$source); Object.assign(this, $$source);
} }
@@ -717,9 +773,9 @@ export class KeyBinding {
} }
/** /**
* KeyBindingKey 快捷键命令 * KeyBindingName 快捷键命令标识符
*/ */
export enum KeyBindingKey { export enum KeyBindingName {
/** /**
* The Go zero value for the underlying type of the enum. * The Go zero value for the underlying type of the enum.
*/ */
@@ -728,247 +784,409 @@ export enum KeyBindingKey {
/** /**
* 显示搜索 * 显示搜索
*/ */
ShowSearchKeyBindingKey = "showSearch", ShowSearch = "showSearch",
/** /**
* 隐藏搜索 * 隐藏搜索
*/ */
HideSearchKeyBindingKey = "hideSearch", HideSearch = "hideSearch",
/** /**
* 块内选择全部 * 块内选择全部
*/ */
BlockSelectAllKeyBindingKey = "blockSelectAll", BlockSelectAll = "blockSelectAll",
/** /**
* 在当前块后添加新块 * 在当前块后添加新块
*/ */
BlockAddAfterCurrentKeyBindingKey = "blockAddAfterCurrent", BlockAddAfterCurrent = "blockAddAfterCurrent",
/** /**
* 在最后添加新块 * 在最后添加新块
*/ */
BlockAddAfterLastKeyBindingKey = "blockAddAfterLast", BlockAddAfterLast = "blockAddAfterLast",
/** /**
* 在当前块前添加新块 * 在当前块前添加新块
*/ */
BlockAddBeforeCurrentKeyBindingKey = "blockAddBeforeCurrent", BlockAddBeforeCurrent = "blockAddBeforeCurrent",
/** /**
* 跳转到上一个块 * 跳转到上一个块
*/ */
BlockGotoPreviousKeyBindingKey = "blockGotoPrevious", BlockGotoPrevious = "blockGotoPrevious",
/** /**
* 跳转到下一个块 * 跳转到下一个块
*/ */
BlockGotoNextKeyBindingKey = "blockGotoNext", BlockGotoNext = "blockGotoNext",
/** /**
* 选择上一个块 * 选择上一个块
*/ */
BlockSelectPreviousKeyBindingKey = "blockSelectPrevious", BlockSelectPrevious = "blockSelectPrevious",
/** /**
* 选择下一个块 * 选择下一个块
*/ */
BlockSelectNextKeyBindingKey = "blockSelectNext", BlockSelectNext = "blockSelectNext",
/** /**
* 删除当前块 * 删除当前块
*/ */
BlockDeleteKeyBindingKey = "blockDelete", BlockDelete = "blockDelete",
/** /**
* 向上移动当前块 * 向上移动当前块
*/ */
BlockMoveUpKeyBindingKey = "blockMoveUp", BlockMoveUp = "blockMoveUp",
/** /**
* 向下移动当前块 * 向下移动当前块
*/ */
BlockMoveDownKeyBindingKey = "blockMoveDown", BlockMoveDown = "blockMoveDown",
/** /**
* 删除行 * 删除行
*/ */
BlockDeleteLineKeyBindingKey = "blockDeleteLine", BlockDeleteLine = "blockDeleteLine",
/** /**
* 向上移动行 * 向上移动行
*/ */
BlockMoveLineUpKeyBindingKey = "blockMoveLineUp", BlockMoveLineUp = "blockMoveLineUp",
/** /**
* 向下移动行 * 向下移动行
*/ */
BlockMoveLineDownKeyBindingKey = "blockMoveLineDown", BlockMoveLineDown = "blockMoveLineDown",
/** /**
* 字符转置 * 字符转置
*/ */
BlockTransposeCharsKeyBindingKey = "blockTransposeChars", BlockTransposeChars = "blockTransposeChars",
/** /**
* 格式化代码块 * 格式化代码块
*/ */
BlockFormatKeyBindingKey = "blockFormat", BlockFormat = "blockFormat",
/** /**
* 复制 * 复制
*/ */
BlockCopyKeyBindingKey = "blockCopy", BlockCopy = "blockCopy",
/** /**
* 剪切 * 剪切
*/ */
BlockCutKeyBindingKey = "blockCut", BlockCut = "blockCut",
/** /**
* 粘贴 * 粘贴
*/ */
BlockPasteKeyBindingKey = "blockPaste", BlockPaste = "blockPaste",
/** /**
* 折叠代码 * 折叠代码
*/ */
FoldCodeKeyBindingKey = "foldCode", FoldCode = "foldCode",
/** /**
* 展开代码 * 展开代码
*/ */
UnfoldCodeKeyBindingKey = "unfoldCode", UnfoldCode = "unfoldCode",
/** /**
* 折叠全部 * 折叠全部
*/ */
FoldAllKeyBindingKey = "foldAll", FoldAll = "foldAll",
/** /**
* 展开全部 * 展开全部
*/ */
UnfoldAllKeyBindingKey = "unfoldAll", UnfoldAll = "unfoldAll",
/** /**
* 光标按语法左移 * 光标按语法左移
*/ */
CursorSyntaxLeftKeyBindingKey = "cursorSyntaxLeft", CursorSyntaxLeft = "cursorSyntaxLeft",
/** /**
* 光标按语法右移 * 光标按语法右移
*/ */
CursorSyntaxRightKeyBindingKey = "cursorSyntaxRight", CursorSyntaxRight = "cursorSyntaxRight",
/** /**
* 按语法选择左侧 * 按语法选择左侧
*/ */
SelectSyntaxLeftKeyBindingKey = "selectSyntaxLeft", SelectSyntaxLeft = "selectSyntaxLeft",
/** /**
* 按语法选择右侧 * 按语法选择右侧
*/ */
SelectSyntaxRightKeyBindingKey = "selectSyntaxRight", SelectSyntaxRight = "selectSyntaxRight",
/** /**
* 向上复制行 * 向上复制行
*/ */
CopyLineUpKeyBindingKey = "copyLineUp", CopyLineUp = "copyLineUp",
/** /**
* 向下复制行 * 向下复制行
*/ */
CopyLineDownKeyBindingKey = "copyLineDown", CopyLineDown = "copyLineDown",
/** /**
* 插入空行 * 插入空行
*/ */
InsertBlankLineKeyBindingKey = "insertBlankLine", InsertBlankLine = "insertBlankLine",
/** /**
* 选择行 * 选择行
*/ */
SelectLineKeyBindingKey = "selectLine", SelectLine = "selectLine",
/** /**
* 选择父级语法 * 选择父级语法
*/ */
SelectParentSyntaxKeyBindingKey = "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",
/** /**
* 减少缩进 * 减少缩进
*/ */
IndentLessKeyBindingKey = "indentLess", IndentLess = "indentLess",
/** /**
* 增加缩进 * 增加缩进
*/ */
IndentMoreKeyBindingKey = "indentMore", IndentMore = "indentMore",
/** /**
* 缩进选择 * 缩进选择
*/ */
IndentSelectionKeyBindingKey = "indentSelection", IndentSelection = "indentSelection",
/** /**
* 光标到匹配括号 * 光标到匹配括号
*/ */
CursorMatchingBracketKeyBindingKey = "cursorMatchingBracket", CursorMatchingBracket = "cursorMatchingBracket",
/** /**
* 切换注释 * 切换注释
*/ */
ToggleCommentKeyBindingKey = "toggleComment", ToggleComment = "toggleComment",
/** /**
* 切换块注释 * 切换块注释
*/ */
ToggleBlockCommentKeyBindingKey = "toggleBlockComment", ToggleBlockComment = "toggleBlockComment",
/** /**
* 插入新行并缩进 * 插入新行并缩进
*/ */
InsertNewlineAndIndentKeyBindingKey = "insertNewlineAndIndent", InsertNewlineAndIndent = "insertNewlineAndIndent",
/** /**
* 向后删除字符 * 向后删除字符
*/ */
DeleteCharBackwardKeyBindingKey = "deleteCharBackward", DeleteCharBackward = "deleteCharBackward",
/** /**
* 向前删除字符 * 向前删除字符
*/ */
DeleteCharForwardKeyBindingKey = "deleteCharForward", DeleteCharForward = "deleteCharForward",
/** /**
* 向后删除组 * 向后删除组
*/ */
DeleteGroupBackwardKeyBindingKey = "deleteGroupBackward", DeleteGroupBackward = "deleteGroupBackward",
/** /**
* 向前删除组 * 向前删除组
*/ */
DeleteGroupForwardKeyBindingKey = "deleteGroupForward", DeleteGroupForward = "deleteGroupForward",
/** /**
* 撤销 * 撤销
*/ */
HistoryUndoKeyBindingKey = "historyUndo", HistoryUndo = "historyUndo",
/** /**
* 重做 * 重做
*/ */
HistoryRedoKeyBindingKey = "historyRedo", HistoryRedo = "historyRedo",
/** /**
* 撤销选择 * 撤销选择
*/ */
HistoryUndoSelectionKeyBindingKey = "historyUndoSelection", HistoryUndoSelection = "historyUndoSelection",
/** /**
* 重做选择 * 重做选择
*/ */
HistoryRedoSelectionKeyBindingKey = "historyRedoSelection", HistoryRedoSelection = "historyRedoSelection",
};
export enum KeyBindingType {
/**
* The Go zero value for the underlying type of the enum.
*/
$zero = "",
/**
* standard 标准快捷键
*/
Standard = "standard",
/**
* emacs 快捷键
*/
Emacs = "emacs",
}; };
/** /**

View File

@@ -20,35 +20,11 @@ import * as models$0 from "../models/models.js";
// @ts-ignore: Unused imports // @ts-ignore: Unused imports
import * as ent$0 from "../models/ent/models.js"; import * as ent$0 from "../models/ent/models.js";
/**
* GetAllExtensions 获取所有扩展
*/
export function GetAllExtensions(): Promise<(ent$0.Extension | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(3094292124) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType2($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/** /**
* GetDefaultExtensions 获取默认扩展配置(用于前端绑定生成) * GetDefaultExtensions 获取默认扩展配置(用于前端绑定生成)
*/ */
export function GetDefaultExtensions(): Promise<models$0.Extension[]> & { cancel(): void } { export function GetDefaultExtensions(): Promise<models$0.Extension[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(4036328166) as any; let $resultPromise = $Call.ByID(4036328166) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType4($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* GetExtensionByKey 根据Key获取扩展
*/
export function GetExtensionByKey(key: string): Promise<ent$0.Extension | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(2551065776, key) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType1($result); return $$createType1($result);
}) as any; }) as any;
@@ -56,11 +32,47 @@ export function GetExtensionByKey(key: string): Promise<ent$0.Extension | null>
return $typingPromise; return $typingPromise;
} }
/**
* GetExtensionByID 根据ID获取扩展
*/
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 重置单个扩展到默认状态 * ResetExtensionConfig 重置单个扩展到默认状态
*/ */
export function ResetExtensionConfig(key: string): Promise<void> & { cancel(): void } { export function ResetExtensionConfig(id: number): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(3990780299, key) as any; let $resultPromise = $Call.ByID(3990780299, id) as any;
return $resultPromise; return $resultPromise;
} }
@@ -83,22 +95,23 @@ export function SyncExtensions(): Promise<void> & { cancel(): void } {
/** /**
* UpdateExtensionConfig 更新扩展配置 * UpdateExtensionConfig 更新扩展配置
*/ */
export function UpdateExtensionConfig(key: string, config: { [_: string]: any }): Promise<void> & { cancel(): void } { export function UpdateExtensionConfig(id: number, config: { [_: string]: any }): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(3184142503, key, config) as any; let $resultPromise = $Call.ByID(3184142503, id, config) as any;
return $resultPromise; return $resultPromise;
} }
/** /**
* UpdateExtensionEnabled 更新扩展启用状态 * UpdateExtensionEnabled 更新扩展启用状态
*/ */
export function UpdateExtensionEnabled(key: string, enabled: boolean): Promise<void> & { cancel(): void } { export function UpdateExtensionEnabled(id: number, enabled: boolean): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(1067300094, key, enabled) as any; let $resultPromise = $Call.ByID(1067300094, id, enabled) as any;
return $resultPromise; return $resultPromise;
} }
// Private type creation functions // Private type creation functions
const $$createType0 = ent$0.Extension.createFrom; const $$createType0 = models$0.Extension.createFrom;
const $$createType1 = $Create.Nullable($$createType0); const $$createType1 = $Create.Array($$createType0);
const $$createType2 = $Create.Array($$createType1); const $$createType2 = ent$0.Extension.createFrom;
const $$createType3 = models$0.Extension.createFrom; const $$createType3 = $Create.Nullable($$createType2);
const $$createType4 = $Create.Array($$createType3); const $$createType4 = $Create.Map($Create.Any, $Create.Any);
const $$createType5 = $Create.Array($$createType3);

View File

@@ -21,22 +21,34 @@ import * as models$0 from "../models/models.js";
import * as ent$0 from "../models/ent/models.js"; import * as ent$0 from "../models/ent/models.js";
/** /**
* GetAllKeyBindings 获取所有快捷键 * GetDefaultKeyBindings 获取默认快捷键配置
*/ */
export function GetAllKeyBindings(): Promise<(ent$0.KeyBinding | null)[]> & { cancel(): void } { export function GetDefaultKeyBindings(): Promise<models$0.KeyBinding[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(1633502882) as any; let $resultPromise = $Call.ByID(3843471588) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType2($result); return $$createType1($result);
}) as any; }) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise); $typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise; return $typingPromise;
} }
/** /**
* GetDefaultKeyBindings 获取默认快捷键配置 * GetKeyBindingByID 根据ID获取快捷键
*/ */
export function GetDefaultKeyBindings(): Promise<models$0.KeyBinding[]> & { cancel(): void } { export function GetKeyBindingByID(id: number): Promise<ent$0.KeyBinding | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(3843471588) as any; 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) => { let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType4($result); return $$createType4($result);
}) as any; }) as any;
@@ -45,15 +57,11 @@ export function GetDefaultKeyBindings(): Promise<models$0.KeyBinding[]> & { canc
} }
/** /**
* GetKeyBindingByKey 根据Key获取快捷键 * ResetKeyBindings 重置所有快捷键到默认值
*/ */
export function GetKeyBindingByKey(key: string): Promise<ent$0.KeyBinding | null> & { cancel(): void } { export function ResetKeyBindings(): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(852938650, key) as any; let $resultPromise = $Call.ByID(4251626010) as any;
let $typingPromise = $resultPromise.then(($result: any) => { return $resultPromise;
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
} }
/** /**
@@ -73,24 +81,24 @@ export function SyncKeyBindings(): Promise<void> & { cancel(): void } {
} }
/** /**
* UpdateKeyBindingCommand 更新快捷键命令 * UpdateKeyBindingEnabled 更新快捷键启用状态
*/ */
export function UpdateKeyBindingCommand(key: string, command: string): Promise<void> & { cancel(): void } { export function UpdateKeyBindingEnabled(id: number, enabled: boolean): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(1293670628, key, command) as any; let $resultPromise = $Call.ByID(843626124, id, enabled) as any;
return $resultPromise; return $resultPromise;
} }
/** /**
* UpdateKeyBindingEnabled 更新快捷键启用状态 * UpdateKeyBindingKeys 更新快捷键绑定(根据操作系统自动判断更新哪个字段)
*/ */
export function UpdateKeyBindingEnabled(key: string, enabled: boolean): Promise<void> & { cancel(): void } { export function UpdateKeyBindingKeys(id: number, key: string): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(843626124, key, enabled) as any; let $resultPromise = $Call.ByID(3432755175, id, key) as any;
return $resultPromise; return $resultPromise;
} }
// Private type creation functions // Private type creation functions
const $$createType0 = ent$0.KeyBinding.createFrom; const $$createType0 = models$0.KeyBinding.createFrom;
const $$createType1 = $Create.Nullable($$createType0); const $$createType1 = $Create.Array($$createType0);
const $$createType2 = $Create.Array($$createType1); const $$createType2 = ent$0.KeyBinding.createFrom;
const $$createType3 = models$0.KeyBinding.createFrom; const $$createType3 = $Create.Nullable($$createType2);
const $$createType4 = $Create.Array($$createType3); const $$createType4 = $Create.Array($$createType3);

View File

@@ -18,10 +18,10 @@ import * as application$0 from "../../../github.com/wailsapp/wails/v3/pkg/applic
import * as ent$0 from "../models/ent/models.js"; import * as ent$0 from "../models/ent/models.js";
/** /**
* GetThemeByKey 根据Key获取主题 * GetThemeByName 根据Key获取主题
*/ */
export function GetThemeByKey(key: string): Promise<ent$0.Theme | null> & { cancel(): void } { export function GetThemeByName(name: string): Promise<ent$0.Theme | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(808794256, key) as any; let $resultPromise = $Call.ByID(1938954770, name) as any;
let $typingPromise = $resultPromise.then(($result: any) => { let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType1($result); return $$createType1($result);
}) as any; }) as any;

View File

@@ -1,6 +1,7 @@
import { import {
AppConfig, AppConfig,
AuthMethod, AuthMethod,
KeyBindingType,
LanguageType, LanguageType,
SystemThemeType, SystemThemeType,
TabType, TabType,
@@ -31,6 +32,7 @@ export const CONFIG_KEY_MAP = {
enableTabIndent: 'editing.enableTabIndent', enableTabIndent: 'editing.enableTabIndent',
tabSize: 'editing.tabSize', tabSize: 'editing.tabSize',
tabType: 'editing.tabType', tabType: 'editing.tabType',
keymapMode: 'editing.keymapMode',
autoSaveDelay: 'editing.autoSaveDelay', autoSaveDelay: 'editing.autoSaveDelay',
// appearance // appearance
language: 'appearance.language', language: 'appearance.language',
@@ -95,11 +97,12 @@ export const DEFAULT_CONFIG: AppConfig = {
enableTabIndent: true, enableTabIndent: true,
tabSize: CONFIG_LIMITS.tabSize.default, tabSize: CONFIG_LIMITS.tabSize.default,
tabType: CONFIG_LIMITS.tabType.default, tabType: CONFIG_LIMITS.tabType.default,
keymapMode: KeyBindingType.Standard,
autoSaveDelay: 5000 autoSaveDelay: 5000
}, },
appearance: { appearance: {
language: LanguageType.LangZhCN, language: LanguageType.LangZhCN,
systemTheme: SystemThemeType.SystemThemeAuto, systemTheme: SystemThemeType.SystemThemeDark,
currentTheme: 'default-dark' currentTheme: 'default-dark'
}, },
updates: { updates: {

View File

@@ -44,11 +44,18 @@ export default {
auto: 'Follow System' auto: 'Follow System'
}, },
keybindings: { keybindings: {
keymapMode: 'Keymap Mode',
modes: {
standard: 'Standard Mode',
emacs: 'Emacs Mode'
},
headers: { headers: {
shortcut: 'Shortcut', shortcut: 'Shortcut',
extension: 'Extension', extension: 'Extension',
description: 'Description' description: 'Description'
}, },
resetToDefault: 'Reset to Default',
confirmReset: 'Confirm Reset?',
commands: { commands: {
showSearch: 'Show search panel', showSearch: 'Show search panel',
hideSearch: 'Hide search panel', hideSearch: 'Hide search panel',
@@ -93,6 +100,25 @@ export default {
insertBlankLine: 'Insert blank line', insertBlankLine: 'Insert blank line',
selectLine: 'Select line', selectLine: 'Select line',
selectParentSyntax: 'Select parent syntax', 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', indentLess: 'Indent less',
indentMore: 'Indent more', indentMore: 'Indent more',
indentSelection: 'Indent selection', indentSelection: 'Indent selection',
@@ -104,6 +130,18 @@ export default {
deleteCharForward: 'Delete character forward', deleteCharForward: 'Delete character forward',
deleteGroupBackward: 'Delete group backward', deleteGroupBackward: 'Delete group backward',
deleteGroupForward: 'Delete group forward', 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: { tabs: {

View File

@@ -44,11 +44,18 @@ export default {
auto: '跟随系统' auto: '跟随系统'
}, },
keybindings: { keybindings: {
keymapMode: '快捷键模式',
modes: {
standard: '标准模式',
emacs: 'Emacs 模式'
},
headers: { headers: {
shortcut: '快捷键', shortcut: '快捷键',
extension: '扩展', extension: '扩展',
description: '描述' description: '描述'
}, },
resetToDefault: '重置为默认',
confirmReset: '确认重置?',
commands: { commands: {
showSearch: '显示搜索面板', showSearch: '显示搜索面板',
hideSearch: '隐藏搜索面板', hideSearch: '隐藏搜索面板',
@@ -93,6 +100,25 @@ export default {
insertBlankLine: '插入空行', insertBlankLine: '插入空行',
selectLine: '选择行', selectLine: '选择行',
selectParentSyntax: '选择父级语法', selectParentSyntax: '选择父级语法',
simplifySelection: '简化选择',
addCursorAbove: '在上方添加光标',
addCursorBelow: '在下方添加光标',
cursorGroupLeft: '光标按单词左移',
cursorGroupRight: '光标按单词右移',
selectGroupLeft: '按单词选择左侧',
selectGroupRight: '按单词选择右侧',
deleteToLineEnd: '删除到行尾',
deleteToLineStart: '删除到行首',
cursorLineStart: '移动到行首',
cursorLineEnd: '移动到行尾',
selectLineStart: '选择到行首',
selectLineEnd: '选择到行尾',
cursorDocStart: '跳转到文档开头',
cursorDocEnd: '跳转到文档结尾',
selectDocStart: '选择到文档开头',
selectDocEnd: '选择到文档结尾',
selectMatchingBracket: '选择到匹配括号',
splitLine: '分割行',
indentLess: '减少缩进', indentLess: '减少缩进',
indentMore: '增加缩进', indentMore: '增加缩进',
indentSelection: '缩进选择', indentSelection: '缩进选择',
@@ -104,6 +130,18 @@ export default {
deleteCharForward: '向前删除字符', deleteCharForward: '向前删除字符',
deleteGroupBackward: '向后删除组', deleteGroupBackward: '向后删除组',
deleteGroupForward: '向前删除组', deleteGroupForward: '向前删除组',
// Emacs 模式额外的基础导航命令
cursorCharLeft: '光标左移一个字符',
cursorCharRight: '光标右移一个字符',
cursorLineUp: '光标上移一行',
cursorLineDown: '光标下移一行',
cursorPageUp: '向上翻页',
cursorPageDown: '向下翻页',
selectCharLeft: '选择左移一个字符',
selectCharRight: '选择右移一个字符',
selectLineUp: '选择上移一行',
selectLineDown: '选择下移一行',
} }
}, },
tabs: { tabs: {

View File

@@ -275,6 +275,9 @@ export const useConfigStore = defineStore('config', () => {
// 标签页配置相关方法 // 标签页配置相关方法
setEnableTabs: (value: boolean) => updateConfig('enableTabs', value), setEnableTabs: (value: boolean) => updateConfig('enableTabs', value),
// 快捷键模式配置相关方法
setKeymapMode: (value: any) => updateConfig('keymapMode', value),
// 更新配置相关方法 // 更新配置相关方法
setAutoUpdate: (value: boolean) => updateConfig('autoUpdate', value), setAutoUpdate: (value: boolean) => updateConfig('autoUpdate', value),

View File

@@ -204,8 +204,8 @@ export const useDocumentStore = defineStore('document', () => {
await openDocument(currentDocumentId.value); await openDocument(currentDocumentId.value);
} else { } else {
// 否则打开第一个文档 // 否则打开第一个文档
if (documents.value[0].id) { if (documentList.value[0].id) {
await openDocument(documents.value[0].id); await openDocument(documentList.value[0].id);
} }
} }
} catch (error) { } catch (error) {

View File

@@ -29,6 +29,7 @@ import {generateContentHash} from "@/common/utils/hashUtils";
import {createTimerManager, type TimerManager} from '@/common/utils/timerUtils'; import {createTimerManager, type TimerManager} from '@/common/utils/timerUtils';
import {EDITOR_CONFIG} from '@/common/constant/editor'; import {EDITOR_CONFIG} from '@/common/constant/editor';
import {createDebounce} from '@/common/utils/debounce'; import {createDebounce} from '@/common/utils/debounce';
import {useKeybindingStore} from "@/stores/keybindingStore";
export interface DocumentStats { export interface DocumentStats {
lines: number; lines: number;
@@ -602,28 +603,30 @@ export const useEditorStore = defineStore('editor', () => {
}; };
// 更新扩展 // 更新扩展
const updateExtension = async (key: string, enabled: boolean, config?: any) => { const updateExtension = async (id: number, enabled: boolean, config?: any) => {
// 更新启用状态 // 更新启用状态
await ExtensionService.UpdateExtensionEnabled(key, enabled); await ExtensionService.UpdateExtensionEnabled(id, enabled);
// 如果需要更新配置 // 如果需要更新配置
if (config !== undefined) { if (config !== undefined) {
await ExtensionService.UpdateExtensionConfig(key, config); await ExtensionService.UpdateExtensionConfig(id, config);
} }
// 重新加载扩展配置
await extensionStore.loadExtensions();
// 获取更新后的扩展名称
const extension = extensionStore.extensions.find(ext => ext.id === id);
if (!extension) return;
// 更新前端编辑器扩展 - 应用于所有实例 // 更新前端编辑器扩展 - 应用于所有实例
const manager = getExtensionManager(); const manager = getExtensionManager();
if (manager) { if (manager) {
// 直接更新前端扩展至所有视图 // 直接更新前端扩展至所有视图
manager.updateExtension(key, enabled, config); manager.updateExtension(extension.name, enabled, config);
}
// 重新加载扩展配置
await extensionStore.loadExtensions();
if (manager) {
manager.initExtensions(extensionStore.extensions);
} }
await useKeybindingStore().loadKeyBindings();
await applyKeymapSettings(); await applyKeymapSettings();
}; };

View File

@@ -7,22 +7,12 @@ export const useExtensionStore = defineStore('extension', () => {
// 扩展配置数据 // 扩展配置数据
const extensions = ref<Extension[]>([]); const extensions = ref<Extension[]>([]);
// 获取启用的扩展
const enabledExtensions = computed(() =>
extensions.value.filter(ext => ext.enabled)
);
// 获取启用的扩展ID列表 (key)
const enabledExtensionIds = computed(() =>
enabledExtensions.value.map(ext => ext.key).filter((k): k is string => k !== undefined)
);
/** /**
* 从后端加载扩展配置 * 从后端加载扩展配置
*/ */
const loadExtensions = async (): Promise<void> => { const loadExtensions = async (): Promise<void> => {
try { try {
const result = await ExtensionService.GetAllExtensions(); const result = await ExtensionService.GetExtensions();
extensions.value = result.filter((ext): ext is Extension => ext !== null); extensions.value = result.filter((ext): ext is Extension => ext !== null);
} catch (err) { } catch (err) {
console.error('[ExtensionStore] Failed to load extensions:', err); console.error('[ExtensionStore] Failed to load extensions:', err);
@@ -32,17 +22,19 @@ export const useExtensionStore = defineStore('extension', () => {
/** /**
* 获取扩展配置 * 获取扩展配置
*/ */
const getExtensionConfig = (key: string): any => { const getExtensionConfig = async (id: number): Promise<any> => {
const extension = extensions.value.find(ext => ext.key === key); try {
return extension?.config ?? {}; const config = await ExtensionService.GetExtensionConfig(id);
return config ?? {};
} catch (err) {
console.error('[ExtensionStore] Failed to get extension config:', err);
return {};
}
}; };
return { return {
// 状态 // 状态
extensions, extensions,
enabledExtensions,
enabledExtensionIds,
// 方法 // 方法
loadExtensions, loadExtensions,
getExtensionConfig, getExtensionConfig,

View File

@@ -1,86 +1,38 @@
import {defineStore} from 'pinia'; import {defineStore} from 'pinia';
import {computed, ref} from 'vue'; import {computed, ref} from 'vue';
import {KeyBinding} from '@/../bindings/voidraft/internal/models/ent/models'; import {KeyBinding} from '@/../bindings/voidraft/internal/models/ent/models';
import {GetAllKeyBindings} from '@/../bindings/voidraft/internal/services/keybindingservice'; import {KeyBindingService} from '@/../bindings/voidraft/internal/services';
import {KeyBindingType} from '@/../bindings/voidraft/internal/models/models';
import {useConfigStore} from './configStore';
export const useKeybindingStore = defineStore('keybinding', () => { export const useKeybindingStore = defineStore('keybinding', () => {
const configStore = useConfigStore();
// 快捷键配置数据 // 快捷键配置数据
const keyBindings = ref<KeyBinding[]>([]); const keyBindings = ref<KeyBinding[]>([]);
// 获取启用的快捷键
const enabledKeyBindings = computed(() =>
keyBindings.value.filter(kb => kb.enabled)
);
// 按扩展分组的快捷键
const keyBindingsByExtension = computed(() => {
const groups = new Map<string, KeyBinding[]>();
for (const binding of keyBindings.value) {
const ext = binding.extension || '';
if (!groups.has(ext)) {
groups.set(ext, []);
}
groups.get(ext)!.push(binding);
}
return groups;
});
// 获取指定扩展的快捷键
const getKeyBindingsByExtension = computed(() =>
(extension: string) =>
keyBindings.value.filter(kb => kb.extension === extension)
);
// 按命令获取快捷键
const getKeyBindingByCommand = computed(() =>
(command: string) =>
keyBindings.value.find(kb => kb.command === command)
);
/** /**
* 从后端加载快捷键配置 * 从后端加载快捷键配置(根据当前配置的模式)
*/ */
const loadKeyBindings = async (): Promise<void> => { const loadKeyBindings = async (): Promise<void> => {
const result = 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); keyBindings.value = result.filter((kb): kb is KeyBinding => kb !== null);
}; };
/** /**
* 检查是否存在指定命令的快捷键 * 更新快捷键绑定
*/ */
const hasCommand = (command: string): boolean => { const updateKeyBinding = async (id: number, key: string): Promise<void> => {
return keyBindings.value.some(kb => kb.command === command && kb.enabled); await KeyBindingService.UpdateKeyBindingKeys(id, key);
await loadKeyBindings();
}; };
/**
* 获取扩展相关的所有扩展ID
*/
const getAllExtensionIds = computed(() => {
const extensionIds = new Set<string>();
for (const binding of keyBindings.value) {
if (binding.extension) {
extensionIds.add(binding.extension);
}
}
return Array.from(extensionIds);
});
return { return {
// 状态 // 状态
keyBindings, keyBindings,
enabledKeyBindings,
keyBindingsByExtension,
getAllExtensionIds,
// 计算属性
getKeyBindingByCommand,
getKeyBindingsByExtension,
// 方法 // 方法
loadKeyBindings, loadKeyBindings,
hasCommand, updateKeyBinding,
}; };
}); });

View File

@@ -8,45 +8,19 @@ import {useEditorStore} from './editorStore';
import type {ThemeColors} from '@/views/editor/theme/types'; import type {ThemeColors} from '@/views/editor/theme/types';
import {cloneThemeColors, FALLBACK_THEME_NAME, themePresetList, themePresetMap} from '@/views/editor/theme/presets'; import {cloneThemeColors, FALLBACK_THEME_NAME, themePresetList, themePresetMap} from '@/views/editor/theme/presets';
type ThemeColorConfig = { [_: string]: any }; // 类型定义
type ThemeOption = { name: string; type: ThemeType }; type ThemeOption = {name: string; type: ThemeType};
const resolveThemeName = (name?: string) => // 解析主题名称,确保返回有效的主题
const resolveThemeName = (name?: string): string =>
name && themePresetMap[name] ? name : FALLBACK_THEME_NAME; name && themePresetMap[name] ? name : FALLBACK_THEME_NAME;
// 根据主题类型创建主题选项列表
const createThemeOptions = (type: ThemeType): ThemeOption[] => const createThemeOptions = (type: ThemeType): ThemeOption[] =>
themePresetList themePresetList
.filter(preset => preset.type === type) .filter(preset => preset.type === type)
.map(preset => ({name: preset.name, type: preset.type})); .map(preset => ({name: preset.name, type: preset.type}));
const darkThemeOptions = createThemeOptions(ThemeType.TypeDark);
const lightThemeOptions = createThemeOptions(ThemeType.TypeLight);
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.GetThemeByKey(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);
};
export const useThemeStore = defineStore('theme', () => { export const useThemeStore = defineStore('theme', () => {
const configStore = useConfigStore(); const configStore = useConfigStore();
const currentColors = ref<ThemeColors | null>(null); const currentColors = ref<ThemeColors | null>(null);
@@ -62,10 +36,12 @@ export const useThemeStore = defineStore('theme', () => {
window.matchMedia('(prefers-color-scheme: dark)').matches) window.matchMedia('(prefers-color-scheme: dark)').matches)
); );
// 根据当前模式动态计算可用主题列表
const availableThemes = computed<ThemeOption[]>(() => const availableThemes = computed<ThemeOption[]>(() =>
isDarkMode.value ? darkThemeOptions : lightThemeOptions createThemeOptions(isDarkMode.value ? ThemeType.TypeDark : ThemeType.TypeLight)
); );
// 应用主题到 DOM
const applyThemeToDOM = (theme: SystemThemeType) => { const applyThemeToDOM = (theme: SystemThemeType) => {
const themeMap = { const themeMap = {
[SystemThemeType.SystemThemeAuto]: 'auto', [SystemThemeType.SystemThemeAuto]: 'auto',
@@ -75,6 +51,31 @@ export const useThemeStore = defineStore('theme', () => {
document.documentElement.setAttribute('data-theme', themeMap[theme]); document.documentElement.setAttribute('data-theme', themeMap[theme]);
}; };
// 获取预设主题颜色
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 = cloneThemeColors(theme.colors as ThemeColors);
colors.themeName = safeName;
return colors;
}
} catch (error) {
console.error('Failed to load theme override:', error);
}
return getPresetColors(safeName);
};
// 加载主题颜色
const loadThemeColors = async (themeName?: string) => { const loadThemeColors = async (themeName?: string) => {
const targetName = resolveThemeName( const targetName = resolveThemeName(
themeName || configStore.config?.appearance?.currentTheme themeName || configStore.config?.appearance?.currentTheme
@@ -82,17 +83,21 @@ export const useThemeStore = defineStore('theme', () => {
currentColors.value = await fetchThemeColors(targetName); currentColors.value = await fetchThemeColors(targetName);
}; };
// 初始化主题
const initTheme = async () => { const initTheme = async () => {
applyThemeToDOM(currentTheme.value); applyThemeToDOM(currentTheme.value);
await loadThemeColors(); await loadThemeColors();
refreshEditorTheme();
}; };
// 设置系统主题
const setTheme = async (theme: SystemThemeType) => { const setTheme = async (theme: SystemThemeType) => {
await configStore.setSystemTheme(theme); await configStore.setSystemTheme(theme);
applyThemeToDOM(theme); applyThemeToDOM(theme);
refreshEditorTheme(); refreshEditorTheme();
}; };
// 切换到指定主题
const switchToTheme = async (themeName: string) => { const switchToTheme = async (themeName: string) => {
if (!themePresetMap[themeName]) { if (!themePresetMap[themeName]) {
console.error('Theme not found:', themeName); console.error('Theme not found:', themeName);
@@ -105,11 +110,13 @@ export const useThemeStore = defineStore('theme', () => {
return true; return true;
}; };
// 更新当前主题颜色
const updateCurrentColors = (colors: Partial<ThemeColors>) => { const updateCurrentColors = (colors: Partial<ThemeColors>) => {
if (!currentColors.value) return; if (!currentColors.value) return;
Object.assign(currentColors.value, colors); Object.assign(currentColors.value, colors);
}; };
// 保存当前主题
const saveCurrentTheme = async () => { const saveCurrentTheme = async () => {
if (!currentColors.value) { if (!currentColors.value) {
throw new Error('No theme selected'); throw new Error('No theme selected');
@@ -118,13 +125,14 @@ export const useThemeStore = defineStore('theme', () => {
const themeName = resolveThemeName(currentColors.value.themeName); const themeName = resolveThemeName(currentColors.value.themeName);
currentColors.value.themeName = themeName; currentColors.value.themeName = themeName;
await ThemeService.UpdateTheme(themeName, currentColors.value as ThemeColorConfig); await ThemeService.UpdateTheme(themeName, currentColors.value);
await loadThemeColors(themeName); await loadThemeColors(themeName);
refreshEditorTheme(); refreshEditorTheme();
return true; return true;
}; };
// 重置当前主题到默认值
const resetCurrentTheme = async () => { const resetCurrentTheme = async () => {
if (!currentColors.value) { if (!currentColors.value) {
throw new Error('No theme selected'); throw new Error('No theme selected');
@@ -138,6 +146,7 @@ export const useThemeStore = defineStore('theme', () => {
return true; return true;
}; };
// 刷新编辑器主题
const refreshEditorTheme = () => { const refreshEditorTheme = () => {
applyThemeToDOM(currentTheme.value); applyThemeToDOM(currentTheme.value);
const editorStore = useEditorStore(); const editorStore = useEditorStore();

View File

@@ -1,140 +1,136 @@
import { EditorView } from '@codemirror/view'; import {EditorView} from '@codemirror/view';
import { Extension } from '@codemirror/state'; import {Extension} from '@codemirror/state';
import { copyCommand, cutCommand, pasteCommand } from '../codeblock/copyPaste'; import {copyCommand, cutCommand, pasteCommand} from '../codeblock/copyPaste';
import { KeyBindingKey } from '@/../bindings/voidraft/internal/models/models'; import {KeyBindingName} from '@/../bindings/voidraft/internal/models/models';
import { useKeybindingStore } from '@/stores/keybindingStore'; import {useKeybindingStore} from '@/stores/keybindingStore';
import { undo, redo } from '@codemirror/commands'; import {redo, undo} from '@codemirror/commands';
import i18n from '@/i18n'; import i18n from '@/i18n';
import { useSystemStore } from '@/stores/systemStore'; import {useSystemStore} from '@/stores/systemStore';
import { showContextMenu } from './manager'; import {showContextMenu} from './manager';
import { import type {MenuSchemaNode} from './menuSchema';
buildRegisteredMenu, import {buildRegisteredMenu, createMenuContext, registerMenuNodes} from './menuSchema';
createMenuContext,
registerMenuNodes
} from './menuSchema';
import type { MenuSchemaNode } from './menuSchema';
function t(key: string): string { function t(key: string): string {
return i18n.global.t(key); return i18n.global.t(key);
} }
function formatKeyBinding(keyBinding: string): string { function formatKeyBinding(keyBinding: string): string {
const systemStore = useSystemStore(); const systemStore = useSystemStore();
const isMac = systemStore.isMacOS; const isMac = systemStore.isMacOS;
return keyBinding return keyBinding
.replace("Mod", isMac ? "Cmd" : "Ctrl") .replace("Mod", isMac ? "Cmd" : "Ctrl")
.replace("Alt", isMac ? "Option" : "Alt") .replace("Alt", isMac ? "Option" : "Alt")
.replace(/-/g, " + "); .replace(/-/g, " + ");
} }
const shortcutCache = new Map<KeyBindingKey, string>(); const shortcutCache = new Map<KeyBindingName, string>();
function getShortcutText(keyBindingKey?: KeyBindingKey): string { function getShortcutText(keyBindingKey?: KeyBindingName): string {
if (keyBindingKey === undefined) { if (keyBindingKey === undefined) {
return ""; 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?.command) {
const formatted = formatKeyBinding(binding.command);
shortcutCache.set(keyBindingKey, formatted);
return formatted;
} }
} catch (error) {
console.warn("An error occurred while getting the shortcut:", error);
}
shortcutCache.set(keyBindingKey, ""); const cached = shortcutCache.get(keyBindingKey);
return ""; 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 "";
} }
function builtinMenuNodes(): MenuSchemaNode[] { function builtinMenuNodes(): MenuSchemaNode[] {
return [ return [
{ {
id: "copy", id: "copy",
labelKey: "keybindings.commands.blockCopy", labelKey: "keybindings.commands.blockCopy",
command: copyCommand, command: copyCommand,
keyBindingKey: KeyBindingKey.BlockCopyKeyBindingKey, keyBindingName: KeyBindingName.BlockCopy,
enabled: (context) => context.hasSelection enabled: (context) => context.hasSelection
}, },
{ {
id: "cut", id: "cut",
labelKey: "keybindings.commands.blockCut", labelKey: "keybindings.commands.blockCut",
command: cutCommand, command: cutCommand,
keyBindingKey: KeyBindingKey.BlockCutKeyBindingKey, keyBindingName: KeyBindingName.BlockCut,
visible: (context) => context.isEditable, visible: (context) => context.isEditable,
enabled: (context) => context.hasSelection && context.isEditable enabled: (context) => context.hasSelection && context.isEditable
}, },
{ {
id: "paste", id: "paste",
labelKey: "keybindings.commands.blockPaste", labelKey: "keybindings.commands.blockPaste",
command: pasteCommand, command: pasteCommand,
keyBindingKey: KeyBindingKey.BlockPasteKeyBindingKey, keyBindingName: KeyBindingName.BlockPaste,
visible: (context) => context.isEditable visible: (context) => context.isEditable
}, },
{ {
id: "undo", id: "undo",
labelKey: "keybindings.commands.historyUndo", labelKey: "keybindings.commands.historyUndo",
command: undo, command: undo,
keyBindingKey: KeyBindingKey.HistoryUndoKeyBindingKey, keyBindingName: KeyBindingName.HistoryUndo,
visible: (context) => context.isEditable visible: (context) => context.isEditable
}, },
{ {
id: "redo", id: "redo",
labelKey: "keybindings.commands.historyRedo", labelKey: "keybindings.commands.historyRedo",
command: redo, command: redo,
keyBindingKey: KeyBindingKey.HistoryRedoKeyBindingKey, keyBindingName: KeyBindingName.HistoryRedo,
visible: (context) => context.isEditable visible: (context) => context.isEditable
} }
]; ];
} }
let builtinMenuRegistered = false; let builtinMenuRegistered = false;
function ensureBuiltinMenuRegistered(): void { function ensureBuiltinMenuRegistered(): void {
if (builtinMenuRegistered) return; if (builtinMenuRegistered) return;
registerMenuNodes(builtinMenuNodes()); registerMenuNodes(builtinMenuNodes());
builtinMenuRegistered = true; builtinMenuRegistered = true;
} }
export function createEditorContextMenu(): Extension { export function createEditorContextMenu(): Extension {
ensureBuiltinMenuRegistered(); ensureBuiltinMenuRegistered();
return EditorView.domEventHandlers({ return EditorView.domEventHandlers({
contextmenu: (event, view) => { contextmenu: (event, view) => {
event.preventDefault(); event.preventDefault();
const context = createMenuContext(view, event as MouseEvent); const context = createMenuContext(view, event as MouseEvent);
const menuItems = buildRegisteredMenu(context, { const menuItems = buildRegisteredMenu(context, {
translate: t, translate: t,
formatShortcut: getShortcutText formatShortcut: getShortcutText
}); });
if (menuItems.length === 0) { if (menuItems.length === 0) {
return false; return false;
} }
showContextMenu(view, event.clientX, event.clientY, menuItems); showContextMenu(view, event.clientX, event.clientY, menuItems);
return true; return true;
} }
}); });
} }
export default createEditorContextMenu; export default createEditorContextMenu;

View File

@@ -1,6 +1,6 @@
import type { EditorView } from '@codemirror/view'; import type { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state'; import { EditorState } from '@codemirror/state';
import { KeyBindingKey } from '@/../bindings/voidraft/internal/models/models'; import { KeyBindingName } from '@/../bindings/voidraft/internal/models/models';
export interface MenuContext { export interface MenuContext {
view: EditorView; view: EditorView;
@@ -16,7 +16,7 @@ export type MenuSchemaNode =
type?: "action"; type?: "action";
labelKey: string; labelKey: string;
command?: (view: EditorView) => boolean; command?: (view: EditorView) => boolean;
keyBindingKey?: KeyBindingKey; keyBindingName?: KeyBindingName;
visible?: (context: MenuContext) => boolean; visible?: (context: MenuContext) => boolean;
enabled?: (context: MenuContext) => boolean; enabled?: (context: MenuContext) => boolean;
} }
@@ -37,7 +37,7 @@ export interface RenderMenuItem {
interface MenuBuildOptions { interface MenuBuildOptions {
translate: (key: string) => string; translate: (key: string) => string;
formatShortcut: (keyBindingKey?: KeyBindingKey) => string; formatShortcut: (keyBindingKey?: KeyBindingName) => string;
} }
const menuRegistry: MenuSchemaNode[] = []; const menuRegistry: MenuSchemaNode[] = [];
@@ -89,7 +89,7 @@ function convertNode(
} }
const disabled = node.enabled ? !node.enabled(context) : false; const disabled = node.enabled ? !node.enabled(context) : false;
const shortcut = options.formatShortcut(node.keyBindingKey); const shortcut = options.formatShortcut(node.keyBindingName);
return { return {
id: node.id, id: node.id,

View File

@@ -65,9 +65,15 @@ export function handleCodeBlock(
if (ctx.seen.has(nf)) return; if (ctx.seen.has(nf)) return;
ctx.seen.add(nf); ctx.seen.add(nf);
ranges.push([nf, nt]); 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 startLine = ctx.view.state.doc.lineAt(nf);
const endLine = ctx.view.state.doc.lineAt(nt); const endLine = ctx.view.state.doc.lineAt(nt);
// Add background decorations for each line
for (let num = startLine.number; num <= endLine.number; num++) { for (let num = startLine.number; num <= endLine.number; num++) {
const line = ctx.view.state.doc.line(num); const line = ctx.view.state.doc.line(num);
let deco = DECO_CODEBLOCK_LINE; let deco = DECO_CODEBLOCK_LINE;
@@ -76,14 +82,14 @@ export function handleCodeBlock(
else if (num === endLine.number) deco = DECO_CODEBLOCK_END; else if (num === endLine.number) deco = DECO_CODEBLOCK_END;
ctx.items.push({ from: line.from, to: line.from, deco }); ctx.items.push({ from: line.from, to: line.from, deco });
} }
if (!inCursor) {
const codeInfo = node.getChild('CodeInfo'); // Add language info widget and hide code marks
const codeMarks = node.getChildren('CodeMark'); const codeInfo = node.getChild('CodeInfo');
const language = codeInfo ? ctx.view.state.doc.sliceString(codeInfo.from, codeInfo.to).trim() : null; const codeMarks = node.getChildren('CodeMark');
ctx.items.push({ from: startLine.to, to: startLine.to, deco: Decoration.widget({ widget: new CodeBlockInfoWidget(nf, nt, language), side: 1 }), priority: 1 }); const language = codeInfo ? ctx.view.state.doc.sliceString(codeInfo.from, codeInfo.to).trim() : null;
if (codeInfo) ctx.items.push({ from: codeInfo.from, to: codeInfo.to, deco: invisibleDecoration }); ctx.items.push({ from: startLine.to, to: startLine.to, deco: Decoration.widget({ widget: new CodeBlockInfoWidget(nf, nt, language), side: 1 }), priority: 1 });
for (const mark of codeMarks) ctx.items.push({ from: mark.from, to: mark.to, deco: invisibleDecoration }); 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 });
} }
/** /**

View File

@@ -18,8 +18,22 @@ import {moveLineDown, moveLineUp} from '../extensions/codeblock/moveLines';
import {transposeChars} from '../extensions/codeblock'; import {transposeChars} from '../extensions/codeblock';
import {copyCommand, cutCommand, pasteCommand} from '../extensions/codeblock/copyPaste'; import {copyCommand, cutCommand, pasteCommand} from '../extensions/codeblock/copyPaste';
import { import {
addCursorAbove,
addCursorBelow,
copyLineDown, copyLineDown,
copyLineUp, copyLineUp,
cursorCharLeft,
cursorCharRight,
cursorLineDown,
cursorLineUp,
cursorPageDown,
cursorPageUp,
cursorDocEnd,
cursorDocStart,
cursorGroupLeft,
cursorGroupRight,
cursorLineEnd,
cursorLineStart,
cursorMatchingBracket, cursorMatchingBracket,
cursorSyntaxLeft, cursorSyntaxLeft,
cursorSyntaxRight, cursorSyntaxRight,
@@ -27,6 +41,8 @@ import {
deleteCharForward, deleteCharForward,
deleteGroupBackward, deleteGroupBackward,
deleteGroupForward, deleteGroupForward,
deleteToLineEnd,
deleteToLineStart,
indentLess, indentLess,
indentMore, indentMore,
indentSelection, indentSelection,
@@ -34,10 +50,23 @@ import {
insertNewlineAndIndent, insertNewlineAndIndent,
redo, redo,
redoSelection, redoSelection,
selectCharLeft,
selectCharRight,
selectLineDown,
selectLineUp,
selectDocEnd,
selectDocStart,
selectGroupLeft,
selectGroupRight,
selectLine, selectLine,
selectLineEnd,
selectLineStart,
selectMatchingBracket,
selectParentSyntax, selectParentSyntax,
selectSyntaxLeft, selectSyntaxLeft,
selectSyntaxRight, selectSyntaxRight,
simplifySelection,
splitLine,
toggleBlockComment, toggleBlockComment,
toggleComment, toggleComment,
undo, undo,
@@ -45,9 +74,8 @@ import {
} from '@codemirror/commands'; } from '@codemirror/commands';
import {foldAll, foldCode, unfoldAll, unfoldCode} from '@codemirror/language'; import {foldAll, foldCode, unfoldAll, unfoldCode} from '@codemirror/language';
import i18n from '@/i18n'; import i18n from '@/i18n';
import {KeyBindingKey} from '@/../bindings/voidraft/internal/models/models'; import {KeyBindingName} from '@/../bindings/voidraft/internal/models/models';
// 默认代码块扩展选项
const defaultBlockExtensionOptions = { const defaultBlockExtensionOptions = {
defaultBlockToken: 'text', defaultBlockToken: 'text',
defaultBlockAutoDetect: true, defaultBlockAutoDetect: true,
@@ -58,202 +86,320 @@ const defaultBlockExtensionOptions = {
* 将后端定义的key字段映射到具体的前端方法和翻译键 * 将后端定义的key字段映射到具体的前端方法和翻译键
*/ */
export const commands: Record<string, { handler: any; descriptionKey: string }> = { export const commands: Record<string, { handler: any; descriptionKey: string }> = {
[KeyBindingKey.ShowSearchKeyBindingKey]: { [KeyBindingName.ShowSearch]: {
handler: openSearchPanel, handler: openSearchPanel,
descriptionKey: 'keybindings.commands.showSearch' descriptionKey: 'keybindings.commands.showSearch'
}, },
[KeyBindingKey.HideSearchKeyBindingKey]: { [KeyBindingName.HideSearch]: {
handler: closeSearchPanel, handler: closeSearchPanel,
descriptionKey: 'keybindings.commands.hideSearch' descriptionKey: 'keybindings.commands.hideSearch'
}, },
[KeyBindingKey.BlockSelectAllKeyBindingKey]: { [KeyBindingName.BlockSelectAll]: {
handler: selectAll, handler: selectAll,
descriptionKey: 'keybindings.commands.blockSelectAll' descriptionKey: 'keybindings.commands.blockSelectAll'
}, },
[KeyBindingKey.BlockAddAfterCurrentKeyBindingKey]: { [KeyBindingName.BlockAddAfterCurrent]: {
handler: addNewBlockAfterCurrent(defaultBlockExtensionOptions), handler: addNewBlockAfterCurrent(defaultBlockExtensionOptions),
descriptionKey: 'keybindings.commands.blockAddAfterCurrent' descriptionKey: 'keybindings.commands.blockAddAfterCurrent'
}, },
[KeyBindingKey.BlockAddAfterLastKeyBindingKey]: { [KeyBindingName.BlockAddAfterLast]: {
handler: addNewBlockAfterLast(defaultBlockExtensionOptions), handler: addNewBlockAfterLast(defaultBlockExtensionOptions),
descriptionKey: 'keybindings.commands.blockAddAfterLast' descriptionKey: 'keybindings.commands.blockAddAfterLast'
}, },
[KeyBindingKey.BlockAddBeforeCurrentKeyBindingKey]: { [KeyBindingName.BlockAddBeforeCurrent]: {
handler: addNewBlockBeforeCurrent(defaultBlockExtensionOptions), handler: addNewBlockBeforeCurrent(defaultBlockExtensionOptions),
descriptionKey: 'keybindings.commands.blockAddBeforeCurrent' descriptionKey: 'keybindings.commands.blockAddBeforeCurrent'
}, },
[KeyBindingKey.BlockGotoPreviousKeyBindingKey]: { [KeyBindingName.BlockGotoPrevious]: {
handler: gotoPreviousBlock, handler: gotoPreviousBlock,
descriptionKey: 'keybindings.commands.blockGotoPrevious' descriptionKey: 'keybindings.commands.blockGotoPrevious'
}, },
[KeyBindingKey.BlockGotoNextKeyBindingKey]: { [KeyBindingName.BlockGotoNext]: {
handler: gotoNextBlock, handler: gotoNextBlock,
descriptionKey: 'keybindings.commands.blockGotoNext' descriptionKey: 'keybindings.commands.blockGotoNext'
}, },
[KeyBindingKey.BlockSelectPreviousKeyBindingKey]: { [KeyBindingName.BlockSelectPrevious]: {
handler: selectPreviousBlock, handler: selectPreviousBlock,
descriptionKey: 'keybindings.commands.blockSelectPrevious' descriptionKey: 'keybindings.commands.blockSelectPrevious'
}, },
[KeyBindingKey.BlockSelectNextKeyBindingKey]: { [KeyBindingName.BlockSelectNext]: {
handler: selectNextBlock, handler: selectNextBlock,
descriptionKey: 'keybindings.commands.blockSelectNext' descriptionKey: 'keybindings.commands.blockSelectNext'
}, },
[KeyBindingKey.BlockDeleteKeyBindingKey]: { [KeyBindingName.BlockDelete]: {
handler: deleteBlock(defaultBlockExtensionOptions), handler: deleteBlock(defaultBlockExtensionOptions),
descriptionKey: 'keybindings.commands.blockDelete' descriptionKey: 'keybindings.commands.blockDelete'
}, },
[KeyBindingKey.BlockMoveUpKeyBindingKey]: { [KeyBindingName.BlockMoveUp]: {
handler: moveCurrentBlockUp, handler: moveCurrentBlockUp,
descriptionKey: 'keybindings.commands.blockMoveUp' descriptionKey: 'keybindings.commands.blockMoveUp'
}, },
[KeyBindingKey.BlockMoveDownKeyBindingKey]: { [KeyBindingName.BlockMoveDown]: {
handler: moveCurrentBlockDown, handler: moveCurrentBlockDown,
descriptionKey: 'keybindings.commands.blockMoveDown' descriptionKey: 'keybindings.commands.blockMoveDown'
}, },
[KeyBindingKey.BlockDeleteLineKeyBindingKey]: { [KeyBindingName.BlockDeleteLine]: {
handler: deleteLineCommand, handler: deleteLineCommand,
descriptionKey: 'keybindings.commands.blockDeleteLine' descriptionKey: 'keybindings.commands.blockDeleteLine'
}, },
[KeyBindingKey.BlockMoveLineUpKeyBindingKey]: { [KeyBindingName.BlockMoveLineUp]: {
handler: moveLineUp, handler: moveLineUp,
descriptionKey: 'keybindings.commands.blockMoveLineUp' descriptionKey: 'keybindings.commands.blockMoveLineUp'
}, },
[KeyBindingKey.BlockMoveLineDownKeyBindingKey]: { [KeyBindingName.BlockMoveLineDown]: {
handler: moveLineDown, handler: moveLineDown,
descriptionKey: 'keybindings.commands.blockMoveLineDown' descriptionKey: 'keybindings.commands.blockMoveLineDown'
}, },
[KeyBindingKey.BlockTransposeCharsKeyBindingKey]: { [KeyBindingName.BlockTransposeChars]: {
handler: transposeChars, handler: transposeChars,
descriptionKey: 'keybindings.commands.blockTransposeChars' descriptionKey: 'keybindings.commands.blockTransposeChars'
}, },
[KeyBindingKey.BlockFormatKeyBindingKey]: { [KeyBindingName.BlockFormat]: {
handler: formatCurrentBlock, handler: formatCurrentBlock,
descriptionKey: 'keybindings.commands.blockFormat' descriptionKey: 'keybindings.commands.blockFormat'
}, },
[KeyBindingKey.BlockCopyKeyBindingKey]: { [KeyBindingName.BlockCopy]: {
handler: copyCommand, handler: copyCommand,
descriptionKey: 'keybindings.commands.blockCopy' descriptionKey: 'keybindings.commands.blockCopy'
}, },
[KeyBindingKey.BlockCutKeyBindingKey]: { [KeyBindingName.BlockCut]: {
handler: cutCommand, handler: cutCommand,
descriptionKey: 'keybindings.commands.blockCut' descriptionKey: 'keybindings.commands.blockCut'
}, },
[KeyBindingKey.BlockPasteKeyBindingKey]: { [KeyBindingName.BlockPaste]: {
handler: pasteCommand, handler: pasteCommand,
descriptionKey: 'keybindings.commands.blockPaste' descriptionKey: 'keybindings.commands.blockPaste'
}, },
[KeyBindingKey.HistoryUndoKeyBindingKey]: { [KeyBindingName.HistoryUndo]: {
handler: undo, handler: undo,
descriptionKey: 'keybindings.commands.historyUndo' descriptionKey: 'keybindings.commands.historyUndo'
}, },
[KeyBindingKey.HistoryRedoKeyBindingKey]: { [KeyBindingName.HistoryRedo]: {
handler: redo, handler: redo,
descriptionKey: 'keybindings.commands.historyRedo' descriptionKey: 'keybindings.commands.historyRedo'
}, },
[KeyBindingKey.HistoryUndoSelectionKeyBindingKey]: { [KeyBindingName.HistoryUndoSelection]: {
handler: undoSelection, handler: undoSelection,
descriptionKey: 'keybindings.commands.historyUndoSelection' descriptionKey: 'keybindings.commands.historyUndoSelection'
}, },
[KeyBindingKey.HistoryRedoSelectionKeyBindingKey]: { [KeyBindingName.HistoryRedoSelection]: {
handler: redoSelection, handler: redoSelection,
descriptionKey: 'keybindings.commands.historyRedoSelection' descriptionKey: 'keybindings.commands.historyRedoSelection'
}, },
[KeyBindingKey.FoldCodeKeyBindingKey]: { [KeyBindingName.FoldCode]: {
handler: foldCode, handler: foldCode,
descriptionKey: 'keybindings.commands.foldCode' descriptionKey: 'keybindings.commands.foldCode'
}, },
[KeyBindingKey.UnfoldCodeKeyBindingKey]: { [KeyBindingName.UnfoldCode]: {
handler: unfoldCode, handler: unfoldCode,
descriptionKey: 'keybindings.commands.unfoldCode' descriptionKey: 'keybindings.commands.unfoldCode'
}, },
[KeyBindingKey.FoldAllKeyBindingKey]: { [KeyBindingName.FoldAll]: {
handler: foldAll, handler: foldAll,
descriptionKey: 'keybindings.commands.foldAll' descriptionKey: 'keybindings.commands.foldAll'
}, },
[KeyBindingKey.UnfoldAllKeyBindingKey]: { [KeyBindingName.UnfoldAll]: {
handler: unfoldAll, handler: unfoldAll,
descriptionKey: 'keybindings.commands.unfoldAll' descriptionKey: 'keybindings.commands.unfoldAll'
}, },
[KeyBindingKey.CursorSyntaxLeftKeyBindingKey]: { [KeyBindingName.CursorSyntaxLeft]: {
handler: cursorSyntaxLeft, handler: cursorSyntaxLeft,
descriptionKey: 'keybindings.commands.cursorSyntaxLeft' descriptionKey: 'keybindings.commands.cursorSyntaxLeft'
}, },
[KeyBindingKey.CursorSyntaxRightKeyBindingKey]: { [KeyBindingName.CursorSyntaxRight]: {
handler: cursorSyntaxRight, handler: cursorSyntaxRight,
descriptionKey: 'keybindings.commands.cursorSyntaxRight' descriptionKey: 'keybindings.commands.cursorSyntaxRight'
}, },
[KeyBindingKey.SelectSyntaxLeftKeyBindingKey]: { [KeyBindingName.SelectSyntaxLeft]: {
handler: selectSyntaxLeft, handler: selectSyntaxLeft,
descriptionKey: 'keybindings.commands.selectSyntaxLeft' descriptionKey: 'keybindings.commands.selectSyntaxLeft'
}, },
[KeyBindingKey.SelectSyntaxRightKeyBindingKey]: { [KeyBindingName.SelectSyntaxRight]: {
handler: selectSyntaxRight, handler: selectSyntaxRight,
descriptionKey: 'keybindings.commands.selectSyntaxRight' descriptionKey: 'keybindings.commands.selectSyntaxRight'
}, },
[KeyBindingKey.CopyLineUpKeyBindingKey]: { [KeyBindingName.CopyLineUp]: {
handler: copyLineUp, handler: copyLineUp,
descriptionKey: 'keybindings.commands.copyLineUp' descriptionKey: 'keybindings.commands.copyLineUp'
}, },
[KeyBindingKey.CopyLineDownKeyBindingKey]: { [KeyBindingName.CopyLineDown]: {
handler: copyLineDown, handler: copyLineDown,
descriptionKey: 'keybindings.commands.copyLineDown' descriptionKey: 'keybindings.commands.copyLineDown'
}, },
[KeyBindingKey.InsertBlankLineKeyBindingKey]: { [KeyBindingName.InsertBlankLine]: {
handler: insertBlankLine, handler: insertBlankLine,
descriptionKey: 'keybindings.commands.insertBlankLine' descriptionKey: 'keybindings.commands.insertBlankLine'
}, },
[KeyBindingKey.SelectLineKeyBindingKey]: { [KeyBindingName.SelectLine]: {
handler: selectLine, handler: selectLine,
descriptionKey: 'keybindings.commands.selectLine' descriptionKey: 'keybindings.commands.selectLine'
}, },
[KeyBindingKey.SelectParentSyntaxKeyBindingKey]: { [KeyBindingName.SelectParentSyntax]: {
handler: selectParentSyntax, handler: selectParentSyntax,
descriptionKey: 'keybindings.commands.selectParentSyntax' descriptionKey: 'keybindings.commands.selectParentSyntax'
}, },
[KeyBindingKey.IndentLessKeyBindingKey]: { [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, handler: indentLess,
descriptionKey: 'keybindings.commands.indentLess' descriptionKey: 'keybindings.commands.indentLess'
}, },
[KeyBindingKey.IndentMoreKeyBindingKey]: { [KeyBindingName.IndentMore]: {
handler: indentMore, handler: indentMore,
descriptionKey: 'keybindings.commands.indentMore' descriptionKey: 'keybindings.commands.indentMore'
}, },
[KeyBindingKey.IndentSelectionKeyBindingKey]: { [KeyBindingName.IndentSelection]: {
handler: indentSelection, handler: indentSelection,
descriptionKey: 'keybindings.commands.indentSelection' descriptionKey: 'keybindings.commands.indentSelection'
}, },
[KeyBindingKey.CursorMatchingBracketKeyBindingKey]: { [KeyBindingName.CursorMatchingBracket]: {
handler: cursorMatchingBracket, handler: cursorMatchingBracket,
descriptionKey: 'keybindings.commands.cursorMatchingBracket' descriptionKey: 'keybindings.commands.cursorMatchingBracket'
}, },
[KeyBindingKey.ToggleCommentKeyBindingKey]: { [KeyBindingName.ToggleComment]: {
handler: toggleComment, handler: toggleComment,
descriptionKey: 'keybindings.commands.toggleComment' descriptionKey: 'keybindings.commands.toggleComment'
}, },
[KeyBindingKey.ToggleBlockCommentKeyBindingKey]: { [KeyBindingName.ToggleBlockComment]: {
handler: toggleBlockComment, handler: toggleBlockComment,
descriptionKey: 'keybindings.commands.toggleBlockComment' descriptionKey: 'keybindings.commands.toggleBlockComment'
}, },
[KeyBindingKey.InsertNewlineAndIndentKeyBindingKey]: { [KeyBindingName.InsertNewlineAndIndent]: {
handler: insertNewlineAndIndent, handler: insertNewlineAndIndent,
descriptionKey: 'keybindings.commands.insertNewlineAndIndent' descriptionKey: 'keybindings.commands.insertNewlineAndIndent'
}, },
[KeyBindingKey.DeleteCharBackwardKeyBindingKey]: { [KeyBindingName.DeleteCharBackward]: {
handler: deleteCharBackward, handler: deleteCharBackward,
descriptionKey: 'keybindings.commands.deleteCharBackward' descriptionKey: 'keybindings.commands.deleteCharBackward'
}, },
[KeyBindingKey.DeleteCharForwardKeyBindingKey]: { [KeyBindingName.DeleteCharForward]: {
handler: deleteCharForward, handler: deleteCharForward,
descriptionKey: 'keybindings.commands.deleteCharForward' descriptionKey: 'keybindings.commands.deleteCharForward'
}, },
[KeyBindingKey.DeleteGroupBackwardKeyBindingKey]: { [KeyBindingName.DeleteGroupBackward]: {
handler: deleteGroupBackward, handler: deleteGroupBackward,
descriptionKey: 'keybindings.commands.deleteGroupBackward' descriptionKey: 'keybindings.commands.deleteGroupBackward'
}, },
[KeyBindingKey.DeleteGroupForwardKeyBindingKey]: { [KeyBindingName.DeleteGroupForward]: {
handler: deleteGroupForward, handler: deleteGroupForward,
descriptionKey: 'keybindings.commands.deleteGroupForward' descriptionKey: 'keybindings.commands.deleteGroupForward'
}, },
// 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'
},
}; };
/** /**

View File

@@ -27,5 +27,4 @@ export const updateKeymapExtension = (view: any): void => {
// 导出相关模块 // 导出相关模块
export { Manager } from './manager'; export { Manager } from './manager';
export { commands, getCommandHandler, getCommandDescription, isCommandRegistered, getRegisteredCommands } from './commands'; export { commands, getCommandHandler, getCommandDescription, isCommandRegistered, getRegisteredCommands } from './commands';
export type { KeyBinding, CommandHandler, CommandDefinition, KeymapResult } from './types';

View File

@@ -1,7 +1,6 @@
import {keymap} from '@codemirror/view'; import {KeyBinding, keymap} from '@codemirror/view';
import {Extension, Compartment} from '@codemirror/state'; import {Compartment, Extension} from '@codemirror/state';
import {KeyBinding as KeyBindingConfig} from '@/../bindings/voidraft/internal/models/ent/models'; import {KeyBinding as KeyBindingConfig} from '@/../bindings/voidraft/internal/models/ent/models';
import {KeyBinding, KeymapResult} from './types';
import {getCommandHandler, isCommandRegistered} from './commands'; import {getCommandHandler, isCommandRegistered} from './commands';
/** /**
@@ -10,13 +9,13 @@ import {getCommandHandler, isCommandRegistered} from './commands';
*/ */
export class Manager { export class Manager {
private static compartment = new Compartment(); private static compartment = new Compartment();
/** /**
* 将后端快捷键配置转换为CodeMirror快捷键绑定 * 将后端快捷键配置转换为CodeMirror快捷键绑定
* @param keyBindings 后端快捷键配置列表 * @param keyBindings 后端快捷键配置列表
* @returns 转换结果 * @returns 转换结果
*/ */
static convertToKeyBindings(keyBindings: KeyBindingConfig[]): KeymapResult { static convertToKeyBindings(keyBindings: KeyBindingConfig[]): KeyBinding[] {
const result: KeyBinding[] = []; const result: KeyBinding[] = [];
for (const binding of keyBindings) { for (const binding of keyBindings) {
@@ -25,29 +24,31 @@ export class Manager {
continue; continue;
} }
// 检查命令是否已注册(使用 key 字段作为命令标识符) // 检查命令是否已注册
if (!binding.key || !isCommandRegistered(binding.key)) { if (!binding.name || !isCommandRegistered(binding.name)) {
continue; continue;
} }
// 获取命令处理函数 // 获取命令处理函数
const handler = getCommandHandler(binding.key); const handler = getCommandHandler(binding.name);
if (!handler) { if (!handler) {
continue; continue;
} }
// 转换为CodeMirror快捷键格式
// binding.command 是快捷键组合 (如 "Mod-f")binding.key 是命令标识符
const keyBinding: KeyBinding = { const keyBinding: KeyBinding = {
key: binding.command || '', key: binding.key || '',
mac: binding.macos || undefined,
win: binding.windows || undefined,
linux: binding.linux || undefined,
run: handler, run: handler,
preventDefault: true preventDefault: binding.preventDefault,
scope: binding.scope || undefined
}; };
result.push(keyBinding); result.push(keyBinding);
} }
return {keyBindings: result}; return result;
} }
/** /**
@@ -56,7 +57,7 @@ export class Manager {
* @returns CodeMirror扩展 * @returns CodeMirror扩展
*/ */
static createKeymapExtension(keyBindings: KeyBindingConfig[]): Extension { static createKeymapExtension(keyBindings: KeyBindingConfig[]): Extension {
const {keyBindings: cmKeyBindings} = this.convertToKeyBindings(keyBindings); const cmKeyBindings = this.convertToKeyBindings(keyBindings);
return this.compartment.of(keymap.of(cmKeyBindings)); return this.compartment.of(keymap.of(cmKeyBindings));
} }
@@ -66,7 +67,7 @@ export class Manager {
* @param keyBindings 后端快捷键配置列表 * @param keyBindings 后端快捷键配置列表
*/ */
static updateKeymap(view: any, keyBindings: KeyBindingConfig[]): void { static updateKeymap(view: any, keyBindings: KeyBindingConfig[]): void {
const {keyBindings: cmKeyBindings} = this.convertToKeyBindings(keyBindings); const cmKeyBindings = this.convertToKeyBindings(keyBindings);
view.dispatch({ view.dispatch({
effects: this.compartment.reconfigure(keymap.of(cmKeyBindings)) effects: this.compartment.reconfigure(keymap.of(cmKeyBindings))
}); });

View File

@@ -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[]
}

View File

@@ -15,7 +15,7 @@ import {highlightActiveLineGutter, highlightWhitespace, highlightTrailingWhitesp
import createEditorContextMenu from '../extensions/contextMenu'; import createEditorContextMenu from '../extensions/contextMenu';
import {blockLineNumbers} from '../extensions/codeblock'; import {blockLineNumbers} from '../extensions/codeblock';
import {createHttpClientExtension} from '../extensions/httpclient'; import {createHttpClientExtension} from '../extensions/httpclient';
import {ExtensionKey} from '@/../bindings/voidraft/internal/models/models'; import {ExtensionName} from '@/../bindings/voidraft/internal/models/models';
type ExtensionEntry = { type ExtensionEntry = {
definition: ExtensionDefinition definition: ExtensionDefinition
@@ -24,35 +24,35 @@ type ExtensionEntry = {
}; };
// 排除 $zero 的有效扩展 Key 类型 // 排除 $zero 的有效扩展 Key 类型
type ValidExtensionKey = Exclude<ExtensionKey, ExtensionKey.$zero>; type ValidExtensionName = Exclude<ExtensionName, ExtensionName.$zero>;
const defineExtension = (create: (config: any) => any, defaultConfig: Record<string, any> = {}): ExtensionDefinition => ({ const defineExtension = (create: (config: any) => any, defaultConfig: Record<string, any> = {}): ExtensionDefinition => ({
create, create,
defaultConfig defaultConfig
}); });
const EXTENSION_REGISTRY: Record<ValidExtensionKey, ExtensionEntry> = { const EXTENSION_REGISTRY: Record<ValidExtensionName, ExtensionEntry> = {
[ExtensionKey.ExtensionRainbowBrackets]: { [ExtensionName.RainbowBrackets]: {
definition: defineExtension(() => rainbowBrackets()), definition: defineExtension(() => rainbowBrackets()),
displayNameKey: 'extensions.rainbowBrackets.name', displayNameKey: 'extensions.rainbowBrackets.name',
descriptionKey: 'extensions.rainbowBrackets.description' descriptionKey: 'extensions.rainbowBrackets.description'
}, },
[ExtensionKey.ExtensionHyperlink]: { [ExtensionName.Hyperlink]: {
definition: defineExtension(() => hyperLink), definition: defineExtension(() => hyperLink),
displayNameKey: 'extensions.hyperlink.name', displayNameKey: 'extensions.hyperlink.name',
descriptionKey: 'extensions.hyperlink.description' descriptionKey: 'extensions.hyperlink.description'
}, },
[ExtensionKey.ExtensionColorSelector]: { [ExtensionName.ColorSelector]: {
definition: defineExtension(() => color), definition: defineExtension(() => color),
displayNameKey: 'extensions.colorSelector.name', displayNameKey: 'extensions.colorSelector.name',
descriptionKey: 'extensions.colorSelector.description' descriptionKey: 'extensions.colorSelector.description'
}, },
[ExtensionKey.ExtensionTranslator]: { [ExtensionName.Translator]: {
definition: defineExtension(() => createTranslatorExtension()), definition: defineExtension(() => createTranslatorExtension()),
displayNameKey: 'extensions.translator.name', displayNameKey: 'extensions.translator.name',
descriptionKey: 'extensions.translator.description' descriptionKey: 'extensions.translator.description'
}, },
[ExtensionKey.ExtensionMinimap]: { [ExtensionName.Minimap]: {
definition: defineExtension((config: any) => minimap({ definition: defineExtension((config: any) => minimap({
displayText: config?.displayText ?? 'characters', displayText: config?.displayText ?? 'characters',
showOverlay: config?.showOverlay ?? 'always', showOverlay: config?.showOverlay ?? 'always',
@@ -65,49 +65,49 @@ const EXTENSION_REGISTRY: Record<ValidExtensionKey, ExtensionEntry> = {
displayNameKey: 'extensions.minimap.name', displayNameKey: 'extensions.minimap.name',
descriptionKey: 'extensions.minimap.description' descriptionKey: 'extensions.minimap.description'
}, },
[ExtensionKey.ExtensionSearch]: { [ExtensionName.Search]: {
definition: defineExtension(() => vscodeSearch), definition: defineExtension(() => vscodeSearch),
displayNameKey: 'extensions.search.name', displayNameKey: 'extensions.search.name',
descriptionKey: 'extensions.search.description' descriptionKey: 'extensions.search.description'
}, },
[ExtensionKey.ExtensionFold]: { [ExtensionName.Fold]: {
definition: defineExtension(() => Prec.low(foldGutter())), definition: defineExtension(() => Prec.low(foldGutter())),
displayNameKey: 'extensions.fold.name', displayNameKey: 'extensions.fold.name',
descriptionKey: 'extensions.fold.description' descriptionKey: 'extensions.fold.description'
}, },
[ExtensionKey.ExtensionMarkdown]: { [ExtensionName.Markdown]: {
definition: defineExtension(() => markdownExtensions), definition: defineExtension(() => markdownExtensions),
displayNameKey: 'extensions.markdown.name', displayNameKey: 'extensions.markdown.name',
descriptionKey: 'extensions.markdown.description' descriptionKey: 'extensions.markdown.description'
}, },
[ExtensionKey.ExtensionLineNumbers]: { [ExtensionName.LineNumbers]: {
definition: defineExtension(() => Prec.high([blockLineNumbers, highlightActiveLineGutter()])), definition: defineExtension(() => Prec.high([blockLineNumbers, highlightActiveLineGutter()])),
displayNameKey: 'extensions.lineNumbers.name', displayNameKey: 'extensions.lineNumbers.name',
descriptionKey: 'extensions.lineNumbers.description' descriptionKey: 'extensions.lineNumbers.description'
}, },
[ExtensionKey.ExtensionContextMenu]: { [ExtensionName.ContextMenu]: {
definition: defineExtension(() => createEditorContextMenu()), definition: defineExtension(() => createEditorContextMenu()),
displayNameKey: 'extensions.contextMenu.name', displayNameKey: 'extensions.contextMenu.name',
descriptionKey: 'extensions.contextMenu.description' descriptionKey: 'extensions.contextMenu.description'
}, },
[ExtensionKey.ExtensionHighlightWhitespace]: { [ExtensionName.HighlightWhitespace]: {
definition: defineExtension(() => highlightWhitespace()), definition: defineExtension(() => highlightWhitespace()),
displayNameKey: 'extensions.highlightWhitespace.name', displayNameKey: 'extensions.highlightWhitespace.name',
descriptionKey: 'extensions.highlightWhitespace.description' descriptionKey: 'extensions.highlightWhitespace.description'
}, },
[ExtensionKey.ExtensionHighlightTrailingWhitespace]: { [ExtensionName.HighlightTrailingWhitespace]: {
definition: defineExtension(() => highlightTrailingWhitespace()), definition: defineExtension(() => highlightTrailingWhitespace()),
displayNameKey: 'extensions.highlightTrailingWhitespace.name', displayNameKey: 'extensions.highlightTrailingWhitespace.name',
descriptionKey: 'extensions.highlightTrailingWhitespace.description' descriptionKey: 'extensions.highlightTrailingWhitespace.description'
}, },
[ExtensionKey.ExtensionHttpClient]: { [ExtensionName.HttpClient]: {
definition: defineExtension(() => createHttpClientExtension()), definition: defineExtension(() => createHttpClientExtension()),
displayNameKey: 'extensions.httpClient.name', displayNameKey: 'extensions.httpClient.name',
descriptionKey: 'extensions.httpClient.description' descriptionKey: 'extensions.httpClient.description'
} }
}; };
const isRegisteredExtension = (key: string): key is ValidExtensionKey => const isRegisteredExtension = (key: string): key is ValidExtensionName =>
Object.prototype.hasOwnProperty.call(EXTENSION_REGISTRY, key); Object.prototype.hasOwnProperty.call(EXTENSION_REGISTRY, key);
const getRegistryEntry = (key: string): ExtensionEntry | undefined => { const getRegistryEntry = (key: string): ExtensionEntry | undefined => {
@@ -118,7 +118,7 @@ const getRegistryEntry = (key: string): ExtensionEntry | undefined => {
}; };
export function registerAllExtensions(manager: Manager): void { export function registerAllExtensions(manager: Manager): void {
(Object.entries(EXTENSION_REGISTRY) as [ValidExtensionKey, ExtensionEntry][]).forEach(([id, entry]) => { (Object.entries(EXTENSION_REGISTRY) as [ValidExtensionName, ExtensionEntry][]).forEach(([id, entry]) => {
manager.registerExtension(id, entry.definition); manager.registerExtension(id, entry.definition);
}); });
} }
@@ -147,7 +147,7 @@ export function hasExtensionConfig(key: string): boolean {
return Object.keys(getExtensionDefaultConfig(key)).length > 0; return Object.keys(getExtensionDefaultConfig(key)).length > 0;
} }
export function getAllExtensionIds(): string[] { export function getExtensionsMap(): string[] {
return Object.keys(EXTENSION_REGISTRY); return Object.keys(EXTENSION_REGISTRY);
} }

View File

@@ -11,8 +11,8 @@ export class Manager {
private extensionStates = new Map<string, ExtensionState>(); private extensionStates = new Map<string, ExtensionState>();
private views = new Map<number, EditorView>(); private views = new Map<number, EditorView>();
registerExtension(id: string, definition: ExtensionDefinition): void { registerExtension(name: string, definition: ExtensionDefinition): void {
const existingState = this.extensionStates.get(id); const existingState = this.extensionStates.get(name);
if (existingState) { if (existingState) {
existingState.definition = definition; existingState.definition = definition;
if (existingState.config === undefined) { if (existingState.config === undefined) {
@@ -21,8 +21,8 @@ export class Manager {
} else { } else {
const compartment = new Compartment(); const compartment = new Compartment();
const defaultConfig = this.cloneConfig(definition.defaultConfig ?? {}); const defaultConfig = this.cloneConfig(definition.defaultConfig ?? {});
this.extensionStates.set(id, { this.extensionStates.set(name, {
id, name,
definition, definition,
config: defaultConfig, config: defaultConfig,
enabled: false, enabled: false,
@@ -34,8 +34,8 @@ export class Manager {
initExtensions(extensionConfigs: ExtensionConfig[]): void { initExtensions(extensionConfigs: ExtensionConfig[]): void {
for (const config of extensionConfigs) { for (const config of extensionConfigs) {
if (!config.key) continue; if (!config.name) continue;
const state = this.extensionStates.get(config.key); const state = this.extensionStates.get(config.name);
if (!state) continue; if (!state) continue;
const resolvedConfig = this.cloneConfig(config.config ?? state.definition.defaultConfig ?? {}); const resolvedConfig = this.cloneConfig(config.config ?? state.definition.defaultConfig ?? {});
this.commitExtensionState(state, config.enabled ?? false, resolvedConfig); this.commitExtensionState(state, config.enabled ?? false, resolvedConfig);
@@ -88,9 +88,9 @@ export class Manager {
state.enabled = enabled; state.enabled = enabled;
state.config = config; state.config = config;
state.extension = runtimeExtension; state.extension = runtimeExtension;
this.applyExtensionToAllViews(state.id); this.applyExtensionToAllViews(state.name);
} catch (error) { } catch (error) {
console.error(`Failed to update extension ${state.id}:`, error); console.error(`Failed to update extension ${state.name}:`, error);
} }
} }

View File

@@ -13,7 +13,7 @@ export interface ExtensionDefinition {
* 扩展运行时状态 * 扩展运行时状态
*/ */
export interface ExtensionState { export interface ExtensionState {
id: string // 扩展 key name: string
definition: ExtensionDefinition definition: ExtensionDefinition
config: any config: any
enabled: boolean enabled: boolean

View File

@@ -1,14 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import {computed, ref} from 'vue'; import {computed, onMounted, ref} from 'vue';
import {useI18n} from 'vue-i18n'; import {useI18n} from 'vue-i18n';
import {useEditorStore} from '@/stores/editorStore'; import {useEditorStore} from '@/stores/editorStore';
import {useExtensionStore} from '@/stores/extensionStore'; import {useExtensionStore} from '@/stores/extensionStore';
import {ExtensionService} from '@/../bindings/voidraft/internal/services'; import {ExtensionService} from '@/../bindings/voidraft/internal/services';
import { import {
getAllExtensionIds,
getExtensionDefaultConfig, getExtensionDefaultConfig,
getExtensionDescription, getExtensionDescription,
getExtensionDisplayName, getExtensionDisplayName, getExtensionsMap,
hasExtensionConfig hasExtensionConfig
} from '@/views/editor/manager/extensions'; } from '@/views/editor/manager/extensions';
import SettingSection from '../components/SettingSection.vue'; import SettingSection from '../components/SettingSection.vue';
@@ -19,48 +18,54 @@ const {t} = useI18n();
const editorStore = useEditorStore(); const editorStore = useEditorStore();
const extensionStore = useExtensionStore(); const extensionStore = useExtensionStore();
// 页面初始化时加载扩展数据
onMounted(async () => {
await extensionStore.loadExtensions();
});
// 展开状态管理 // 展开状态管理
const expandedExtensions = ref<Set<string>>(new Set()); const expandedExtensions = ref<Set<number>>(new Set());
// 获取所有可用的扩展 // 获取所有可用的扩展
const availableExtensions = computed(() => { const availableExtensions = computed(() => {
return getAllExtensionIds().map(key => { return getExtensionsMap().map(name => {
const extension = extensionStore.extensions.find(ext => ext.key === key); const extension = extensionStore.extensions.find(ext => ext.name === name);
return { return {
id: key, id: extension?.id ?? 0,
displayName: getExtensionDisplayName(key), name: name,
description: getExtensionDescription(key), displayName: getExtensionDisplayName(name),
description: getExtensionDescription(name),
enabled: extension?.enabled || false, enabled: extension?.enabled || false,
hasConfig: hasExtensionConfig(key), hasConfig: hasExtensionConfig(name),
config: extension?.config || {}, config: extension?.config || {},
defaultConfig: getExtensionDefaultConfig(key) defaultConfig: getExtensionDefaultConfig(name)
}; };
}); });
}); });
// 切换展开状态 // 切换展开状态
const toggleExpanded = (extensionKey: string) => { const toggleExpanded = (extensionId: number) => {
if (expandedExtensions.value.has(extensionKey)) { if (expandedExtensions.value.has(extensionId)) {
expandedExtensions.value.delete(extensionKey); expandedExtensions.value.delete(extensionId);
} else { } else {
expandedExtensions.value.add(extensionKey); expandedExtensions.value.add(extensionId);
} }
}; };
// 更新扩展状态 // 更新扩展状态
const updateExtension = async (extensionKey: string, enabled: boolean) => { const updateExtension = async (extensionId: number, enabled: boolean) => {
try { try {
await editorStore.updateExtension(extensionKey, enabled); await editorStore.updateExtension(extensionId, enabled);
} catch (error) { } catch (error) {
console.error('Failed to update extension:', error); console.error('Failed to update extension:', error);
} }
}; };
// 更新扩展配置 // 更新扩展配置
const updateExtensionConfig = async (extensionKey: string, configKey: string, value: any) => { const updateExtensionConfig = async (extensionId: number, configKey: string, value: any) => {
try { try {
// 获取当前扩展状态 // 获取当前扩展状态
const extension = extensionStore.extensions.find(ext => ext.key === extensionKey); const extension = extensionStore.extensions.find(ext => ext.id === extensionId);
if (!extension) return; if (!extension) return;
// 更新配置 // 更新配置
@@ -71,7 +76,7 @@ const updateExtensionConfig = async (extensionKey: string, configKey: string, va
updatedConfig[configKey] = value; updatedConfig[configKey] = value;
} }
// 使用editorStore的updateExtension方法更新确保应用到所有编辑器实例 // 使用editorStore的updateExtension方法更新确保应用到所有编辑器实例
await editorStore.updateExtension(extensionKey, extension.enabled ?? false, updatedConfig); await editorStore.updateExtension(extensionId, extension.enabled ?? false, updatedConfig);
} catch (error) { } catch (error) {
console.error('Failed to update extension config:', error); console.error('Failed to update extension config:', error);
@@ -79,19 +84,19 @@ const updateExtensionConfig = async (extensionKey: string, configKey: string, va
}; };
// 重置扩展到默认配置 // 重置扩展到默认配置
const resetExtension = async (extensionKey: string) => { const resetExtension = async (extensionId: number) => {
try { try {
// 重置到默认配置 // 重置到默认配置
await ExtensionService.ResetExtensionConfig(extensionKey); await ExtensionService.ResetExtensionConfig(extensionId);
// 重新加载扩展状态以获取最新配置 // 重新加载扩展状态以获取最新配置
await extensionStore.loadExtensions(); await extensionStore.loadExtensions();
// 获取重置后的状态,立即应用到所有编辑器视图 // 获取重置后的状态,立即应用到所有编辑器视图
const extension = extensionStore.extensions.find(ext => ext.key === extensionKey); const extension = extensionStore.extensions.find(ext => ext.id === extensionId);
if (extension) { if (extension) {
// 通过editorStore更新确保所有视图都能同步 // 通过editorStore更新确保所有视图都能同步
await editorStore.updateExtension(extensionKey, extension.enabled ?? false, extension.config); await editorStore.updateExtension(extensionId, extension.enabled ?? false, extension.config);
} }
} catch (error) { } catch (error) {
console.error('Failed to reset extension:', error); console.error('Failed to reset extension:', error);
@@ -125,7 +130,7 @@ const formatConfigValue = (value: any): string => {
const handleConfigInput = async ( const handleConfigInput = async (
extensionKey: string, extensionId: number,
configKey: string, configKey: string,
defaultValue: any, defaultValue: any,
event: Event event: Event
@@ -135,15 +140,15 @@ const handleConfigInput = async (
const rawValue = target.value; const rawValue = target.value;
const trimmedValue = rawValue.trim(); const trimmedValue = rawValue.trim();
if (!trimmedValue.length) { if (!trimmedValue.length) {
await updateExtensionConfig(extensionKey, configKey, undefined); await updateExtensionConfig(extensionId, configKey, undefined);
return; return;
} }
try { try {
const parsedValue = JSON.parse(trimmedValue); const parsedValue = JSON.parse(trimmedValue);
await updateExtensionConfig(extensionKey, configKey, parsedValue); await updateExtensionConfig(extensionId, configKey, parsedValue);
} catch (_error) { } catch (_error) {
const extension = extensionStore.extensions.find(ext => ext.key === extensionKey); const extension = extensionStore.extensions.find(ext => ext.id === extensionId);
const fallbackValue = getConfigValue(extension?.config, configKey, defaultValue); const fallbackValue = getConfigValue(extension?.config, configKey, defaultValue);
target.value = formatConfigValue(fallbackValue); target.value = formatConfigValue(fallbackValue);
@@ -158,7 +163,7 @@ const handleConfigInput = async (
<SettingSection :title="t('settings.extensions')"> <SettingSection :title="t('settings.extensions')">
<div <div
v-for="extension in availableExtensions" v-for="extension in availableExtensions"
:key="extension.id" :key="extension.name"
class="extension-item" class="extension-item"
> >
<!-- 扩展主项 --> <!-- 扩展主项 -->

View File

@@ -1,200 +1,256 @@
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; 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 SettingSection from '../components/SettingSection.vue';
import SettingItem from '../components/SettingItem.vue';
import { useKeybindingStore } from '@/stores/keybindingStore'; import { useKeybindingStore } from '@/stores/keybindingStore';
import { useSystemStore } from '@/stores/systemStore'; import { useSystemStore } from '@/stores/systemStore';
import { useConfigStore } from '@/stores/configStore';
import { useEditorStore } from '@/stores/editorStore';
import { getCommandDescription } from '@/views/editor/keymap/commands'; import { getCommandDescription } from '@/views/editor/keymap/commands';
import { KeyBindingKey } from '@/../bindings/voidraft/internal/models/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 { t } = useI18n();
const keybindingStore = useKeybindingStore(); const keybindingStore = useKeybindingStore();
const systemStore = useSystemStore(); 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 () => { onMounted(async () => {
await keybindingStore.loadKeyBindings(); await keybindingStore.loadKeyBindings();
}); });
// 从store中获取快捷键数据并转换为显示格式 const keymapModeOptions = [
const keyBindings = computed(() => { { label: t('keybindings.modes.standard'), value: KeyBindingType.Standard },
return keybindingStore.keyBindings { label: t('keybindings.modes.emacs'), value: KeyBindingType.Emacs }
.filter(kb => kb.enabled) ];
.map(kb => ({
key: kb.key, const updateKeymapMode = async (mode: KeyBindingType) => {
command: parseKeyBinding(kb.command || '', kb.key), await configStore.setKeymapMode(mode);
extension: kb.extension || '', await keybindingStore.loadKeyBindings();
description: kb.key ? (getCommandDescription(kb.key) || kb.key) : '' await editorStore.applyKeymapSettings();
})); };
// 重置快捷键确认
const { isConfirming: isResetConfirming, requestConfirm: requestResetConfirm } = useConfirm({
timeout: 3000,
onConfirm: async () => {
await KeyBindingService.ResetKeyBindings();
await keybindingStore.loadKeyBindings();
await editorStore.applyKeymapSettings();
}
}); });
// 解析快捷键字符串为显示数组 const keyBindings = computed(() =>
const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => { keybindingStore.keyBindings.map(kb => ({
if (!keyStr) return []; id: kb.id,
name: kb.name,
command: getDisplayKeybinding(kb),
rawKey: getRawKey(kb),
extension: kb.extension || '',
description: getCommandDescription(kb.name) || kb.name || ''
}))
);
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 || '';
if (keyBindingKey === KeyBindingKey.HistoryRedoKeyBindingKey && keyStr === 'Mod-Shift-z') { };
if (systemStore.isMacOS) {
return ['⌘', '⇧', 'Z']; // macOS: Cmd+Shift+Z const getDisplayKeybinding = (kb: any): string[] => {
} else { const keyStr = getRawKey(kb);
return ['Ctrl', 'Y']; // Windows/Linux: Ctrl+Y 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;
} }
// 特殊处理重做选择快捷键的操作系统差异 const key = captureKeyBinding(event);
if (keyBindingKey === KeyBindingKey.HistoryRedoSelectionKeyBindingKey && keyStr === 'Mod-Shift-u') { if (key) {
if (systemStore.isMacOS) { capturedKey.value = key;
return ['⌘', '⇧', 'U']; // macOS: Cmd+Shift+U capturedKeyDisplay.value = parseKeyString(key);
} else { isConflict.value = false;
return ['Alt', 'U']; // Windows/Linux: Alt+U }
} };
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;
} }
// 特殊处理代码折叠快捷键的操作系统差异 try {
if (keyBindingKey === KeyBindingKey.FoldCodeKeyBindingKey && keyStr === 'Ctrl-Shift-[') { await keybindingStore.updateKeyBinding(
if (systemStore.isMacOS) { editingBinding.value.id,
return ['⌘', '⌥', '[']; // macOS: Cmd+Alt+[ capturedKey.value
} else { );
return ['Ctrl', 'Shift', '[']; // Windows/Linux: Ctrl+Shift+[ await editorStore.applyKeymapSettings();
} } catch (error) {
console.error(error);
} finally {
cancelEdit();
} }
if (keyBindingKey === KeyBindingKey.UnfoldCodeKeyBindingKey && keyStr === 'Ctrl-Shift-]') {
if (systemStore.isMacOS) {
return ['⌘', '⌥', ']']; // macOS: Cmd+Alt+]
} else {
return ['Ctrl', 'Shift', ']']; // Windows/Linux: Ctrl+Shift+]
}
}
// 特殊处理编辑快捷键的操作系统差异
if (keyBindingKey === KeyBindingKey.CursorSyntaxLeftKeyBindingKey && keyStr === 'Alt-ArrowLeft') {
if (systemStore.isMacOS) {
return ['Ctrl', '←']; // macOS: Ctrl+ArrowLeft
} else {
return ['Alt', '←']; // Windows/Linux: Alt+ArrowLeft
}
}
if (keyBindingKey === KeyBindingKey.CursorSyntaxRightKeyBindingKey && keyStr === 'Alt-ArrowRight') {
if (systemStore.isMacOS) {
return ['Ctrl', '→']; // macOS: Ctrl+ArrowRight
} else {
return ['Alt', '→']; // Windows/Linux: Alt+ArrowRight
}
}
if (keyBindingKey === KeyBindingKey.InsertBlankLineKeyBindingKey && keyStr === 'Ctrl-Enter') {
if (systemStore.isMacOS) {
return ['⌘', 'Enter']; // macOS: Cmd+Enter
} else {
return ['Ctrl', 'Enter']; // Windows/Linux: Ctrl+Enter
}
}
if (keyBindingKey === KeyBindingKey.SelectLineKeyBindingKey && keyStr === 'Alt-l') {
if (systemStore.isMacOS) {
return ['Ctrl', 'L']; // macOS: Ctrl+l
} else {
return ['Alt', 'L']; // Windows/Linux: Alt+l
}
}
if (keyBindingKey === KeyBindingKey.SelectParentSyntaxKeyBindingKey && keyStr === 'Ctrl-i') {
if (systemStore.isMacOS) {
return ['⌘', 'I']; // macOS: Cmd+i
} else {
return ['Ctrl', 'I']; // Windows/Linux: Ctrl+i
}
}
if (keyBindingKey === KeyBindingKey.IndentLessKeyBindingKey && keyStr === 'Ctrl-[') {
if (systemStore.isMacOS) {
return ['⌘', '[']; // macOS: Cmd+[
} else {
return ['Ctrl', '[']; // Windows/Linux: Ctrl+[
}
}
if (keyBindingKey === KeyBindingKey.IndentMoreKeyBindingKey && keyStr === 'Ctrl-]') {
if (systemStore.isMacOS) {
return ['⌘', ']']; // macOS: Cmd+]
} else {
return ['Ctrl', ']']; // Windows/Linux: Ctrl+]
}
}
if (keyBindingKey === KeyBindingKey.IndentSelectionKeyBindingKey && keyStr === 'Ctrl-Alt-\\') {
if (systemStore.isMacOS) {
return ['⌘', '⌥', '\\']; // macOS: Cmd+Alt+\
} else {
return ['Ctrl', 'Alt', '\\']; // Windows/Linux: Ctrl+Alt+\
}
}
if (keyBindingKey === KeyBindingKey.CursorMatchingBracketKeyBindingKey && keyStr === 'Shift-Ctrl-\\') {
if (systemStore.isMacOS) {
return ['⇧', '⌘', '\\']; // macOS: Shift+Cmd+\
} else {
return ['Shift', 'Ctrl', '\\']; // Windows/Linux: Shift+Ctrl+\
}
}
if (keyBindingKey === KeyBindingKey.ToggleCommentKeyBindingKey && keyStr === 'Ctrl-/') {
if (systemStore.isMacOS) {
return ['⌘', '/']; // macOS: Cmd+/
} else {
return ['Ctrl', '/']; // Windows/Linux: Ctrl+/
}
}
// 特殊处理删除快捷键的操作系统差异
if (keyBindingKey === KeyBindingKey.DeleteGroupBackwardKeyBindingKey && keyStr === 'Ctrl-Backspace') {
if (systemStore.isMacOS) {
return ['⌘', 'Backspace']; // macOS: Cmd+Backspace
} else {
return ['Ctrl', 'Backspace']; // Windows/Linux: Ctrl+Backspace
}
}
if (keyBindingKey === KeyBindingKey.DeleteGroupForwardKeyBindingKey && 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> </script>
<template> <template>
<div class="settings-page"> <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')"> <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-container">
<div class="key-bindings-header"> <div class="key-bindings-header">
<div class="keybinding-col">{{ t('keybindings.headers.shortcut') }}</div> <div class="keybinding-col">{{ t('keybindings.headers.shortcut') }}</div>
@@ -204,18 +260,55 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => {
<div <div
v-for="binding in keyBindings" v-for="binding in keyBindings"
:key="binding.key" :key="binding.name"
class="key-binding-row" class="key-binding-row"
> >
<div class="keybinding-col"> <!-- 快捷键列 -->
<span <div
v-for="(key, index) in binding.command" class="keybinding-col"
:key="index" :class="{ 'editing': editingBinding?.name === binding.name }"
class="key-badge" @click.stop="editingBinding?.name !== binding.name && startEditBinding(binding)"
> >
{{ key }} <!-- 编辑模式 -->
</span> <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>
<div class="extension-col">{{ binding.extension }}</div> <div class="extension-col">{{ binding.extension }}</div>
<div class="description-col">{{ binding.description }}</div> <div class="description-col">{{ binding.description }}</div>
</div> </div>
@@ -225,16 +318,68 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => {
</template> </template>
<style scoped lang="scss"> <style scoped lang="scss">
.settings-page { .select-input {
//max-width: 800px; 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 { .key-bindings-container {
padding: 10px 16px;
.key-bindings-header { .key-bindings-header {
display: flex; display: flex;
padding: 0 0 10px 0; padding: 0 0 8px 0;
border-bottom: 1px solid var(--settings-border); border-bottom: 1px solid var(--settings-border);
color: var(--text-muted); color: var(--text-muted);
font-size: 12px; font-size: 12px;
@@ -243,7 +388,7 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => {
.key-binding-row { .key-binding-row {
display: flex; display: flex;
padding: 14px 0; padding: 10px 0;
border-bottom: 1px solid var(--settings-border); border-bottom: 1px solid var(--settings-border);
align-items: center; align-items: center;
transition: background-color 0.2s ease; transition: background-color 0.2s ease;
@@ -256,9 +401,20 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => {
.keybinding-col { .keybinding-col {
width: 150px; width: 150px;
display: flex; display: flex;
gap: 5px; gap: 4px;
padding: 0 10px 0 0; padding: 0 10px 0 0;
color: var(--settings-text); 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 { .key-badge {
background-color: var(--settings-input-bg); background-color: var(--settings-input-bg);
@@ -267,6 +423,71 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: string): string[] => {
font-size: 11px; font-size: 11px;
border: 1px solid var(--settings-input-border); border: 1px solid var(--settings-input-border);
color: var(--settings-text); 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;
}
}
}
}
.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;
}
} }
} }
@@ -285,6 +506,29 @@ const parseKeyBinding = (keyStr: string, keyBindingKey?: 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 { .coming-soon-placeholder {
padding: 20px; padding: 20px;
background-color: var(--settings-card-bg); background-color: var(--settings-card-bg);

View File

@@ -103,6 +103,9 @@ type EditingConfig struct {
TabSize int `json:"tabSize"` // Tab大小 TabSize int `json:"tabSize"` // Tab大小
TabType TabType `json:"tabType"` // Tab类型空格或Tab TabType TabType `json:"tabType"` // Tab类型空格或Tab
// 快捷键模式
KeymapMode KeyBindingType `json:"keymapMode"` // 快捷键模式standard 或 emacs
// 保存选项 // 保存选项
AutoSaveDelay int `json:"autoSaveDelay"` // 自动保存延迟(毫秒) AutoSaveDelay int `json:"autoSaveDelay"` // 自动保存延迟(毫秒)
} }
@@ -203,6 +206,8 @@ func NewDefaultAppConfig() *AppConfig {
EnableTabIndent: true, EnableTabIndent: true,
TabSize: 4, TabSize: 4,
TabType: TabTypeTab, TabType: TabTypeTab,
// 快捷键模式
KeymapMode: Standard, // 默认使用标准模式
// 保存选项 // 保存选项
AutoSaveDelay: 2000, AutoSaveDelay: 2000,
}, },

View File

@@ -17,7 +17,7 @@ type Document struct {
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID int `json:"id,omitempty"`
// UUID for cross-device sync (UUIDv7) // UUID for cross-device sync (UUIDv7)
UUID *string `json:"uuid"` UUID string `json:"uuid"`
// creation time // creation time
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
// update time // update time
@@ -69,8 +69,7 @@ func (_m *Document) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i]) return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value.Valid { } else if value.Valid {
_m.UUID = new(string) _m.UUID = value.String
*_m.UUID = value.String
} }
case document.FieldCreatedAt: case document.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -145,10 +144,8 @@ func (_m *Document) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("Document(") builder.WriteString("Document(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
if v := _m.UUID; v != nil { builder.WriteString("uuid=")
builder.WriteString("uuid=") builder.WriteString(_m.UUID)
builder.WriteString(*v)
}
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("created_at=") builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt) builder.WriteString(_m.CreatedAt)

View File

@@ -143,16 +143,6 @@ func UUIDHasSuffix(v string) predicate.Document {
return predicate.Document(sql.FieldHasSuffix(FieldUUID, v)) return predicate.Document(sql.FieldHasSuffix(FieldUUID, v))
} }
// UUIDIsNil applies the IsNil predicate on the "uuid" field.
func UUIDIsNil() predicate.Document {
return predicate.Document(sql.FieldIsNull(FieldUUID))
}
// UUIDNotNil applies the NotNil predicate on the "uuid" field.
func UUIDNotNil() predicate.Document {
return predicate.Document(sql.FieldNotNull(FieldUUID))
}
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field. // UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
func UUIDEqualFold(v string) predicate.Document { func UUIDEqualFold(v string) predicate.Document {
return predicate.Document(sql.FieldEqualFold(FieldUUID, v)) return predicate.Document(sql.FieldEqualFold(FieldUUID, v))

View File

@@ -180,6 +180,9 @@ func (_c *DocumentCreate) defaults() error {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_c *DocumentCreate) check() error { 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 { if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Document.created_at"`)} return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Document.created_at"`)}
} }
@@ -225,7 +228,7 @@ func (_c *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
) )
if value, ok := _c.mutation.UUID(); ok { if value, ok := _c.mutation.UUID(); ok {
_spec.SetField(document.FieldUUID, field.TypeString, value) _spec.SetField(document.FieldUUID, field.TypeString, value)
_node.UUID = &value _node.UUID = value
} }
if value, ok := _c.mutation.CreatedAt(); ok { if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(document.FieldCreatedAt, field.TypeString, value) _spec.SetField(document.FieldCreatedAt, field.TypeString, value)

View File

@@ -170,9 +170,6 @@ func (_u *DocumentUpdate) sqlSave(ctx context.Context) (_node int, err error) {
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(document.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value) _spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
} }
@@ -388,9 +385,6 @@ func (_u *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(document.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(document.FieldUpdatedAt, field.TypeString, value) _spec.SetField(document.FieldUpdatedAt, field.TypeString, value)
} }

View File

@@ -52,7 +52,7 @@ var schemaGraph = func() *sqlgraph.Schema {
extension.FieldCreatedAt: {Type: field.TypeString, Column: extension.FieldCreatedAt}, extension.FieldCreatedAt: {Type: field.TypeString, Column: extension.FieldCreatedAt},
extension.FieldUpdatedAt: {Type: field.TypeString, Column: extension.FieldUpdatedAt}, extension.FieldUpdatedAt: {Type: field.TypeString, Column: extension.FieldUpdatedAt},
extension.FieldDeletedAt: {Type: field.TypeString, Column: extension.FieldDeletedAt}, extension.FieldDeletedAt: {Type: field.TypeString, Column: extension.FieldDeletedAt},
extension.FieldKey: {Type: field.TypeString, Column: extension.FieldKey}, extension.FieldName: {Type: field.TypeString, Column: extension.FieldName},
extension.FieldEnabled: {Type: field.TypeBool, Column: extension.FieldEnabled}, extension.FieldEnabled: {Type: field.TypeBool, Column: extension.FieldEnabled},
extension.FieldConfig: {Type: field.TypeJSON, Column: extension.FieldConfig}, extension.FieldConfig: {Type: field.TypeJSON, Column: extension.FieldConfig},
}, },
@@ -68,14 +68,20 @@ var schemaGraph = func() *sqlgraph.Schema {
}, },
Type: "KeyBinding", Type: "KeyBinding",
Fields: map[string]*sqlgraph.FieldSpec{ Fields: map[string]*sqlgraph.FieldSpec{
keybinding.FieldUUID: {Type: field.TypeString, Column: keybinding.FieldUUID}, keybinding.FieldUUID: {Type: field.TypeString, Column: keybinding.FieldUUID},
keybinding.FieldCreatedAt: {Type: field.TypeString, Column: keybinding.FieldCreatedAt}, keybinding.FieldCreatedAt: {Type: field.TypeString, Column: keybinding.FieldCreatedAt},
keybinding.FieldUpdatedAt: {Type: field.TypeString, Column: keybinding.FieldUpdatedAt}, keybinding.FieldUpdatedAt: {Type: field.TypeString, Column: keybinding.FieldUpdatedAt},
keybinding.FieldDeletedAt: {Type: field.TypeString, Column: keybinding.FieldDeletedAt}, keybinding.FieldDeletedAt: {Type: field.TypeString, Column: keybinding.FieldDeletedAt},
keybinding.FieldKey: {Type: field.TypeString, Column: keybinding.FieldKey}, keybinding.FieldName: {Type: field.TypeString, Column: keybinding.FieldName},
keybinding.FieldCommand: {Type: field.TypeString, Column: keybinding.FieldCommand}, keybinding.FieldType: {Type: field.TypeString, Column: keybinding.FieldType},
keybinding.FieldExtension: {Type: field.TypeString, Column: keybinding.FieldExtension}, keybinding.FieldKey: {Type: field.TypeString, Column: keybinding.FieldKey},
keybinding.FieldEnabled: {Type: field.TypeBool, Column: keybinding.FieldEnabled}, keybinding.FieldMacos: {Type: field.TypeString, Column: keybinding.FieldMacos},
keybinding.FieldWindows: {Type: field.TypeString, Column: keybinding.FieldWindows},
keybinding.FieldLinux: {Type: field.TypeString, Column: keybinding.FieldLinux},
keybinding.FieldExtension: {Type: field.TypeString, Column: keybinding.FieldExtension},
keybinding.FieldEnabled: {Type: field.TypeBool, Column: keybinding.FieldEnabled},
keybinding.FieldPreventDefault: {Type: field.TypeBool, Column: keybinding.FieldPreventDefault},
keybinding.FieldScope: {Type: field.TypeString, Column: keybinding.FieldScope},
}, },
} }
graph.Nodes[3] = &sqlgraph.Node{ graph.Nodes[3] = &sqlgraph.Node{
@@ -93,7 +99,7 @@ var schemaGraph = func() *sqlgraph.Schema {
theme.FieldCreatedAt: {Type: field.TypeString, Column: theme.FieldCreatedAt}, theme.FieldCreatedAt: {Type: field.TypeString, Column: theme.FieldCreatedAt},
theme.FieldUpdatedAt: {Type: field.TypeString, Column: theme.FieldUpdatedAt}, theme.FieldUpdatedAt: {Type: field.TypeString, Column: theme.FieldUpdatedAt},
theme.FieldDeletedAt: {Type: field.TypeString, Column: theme.FieldDeletedAt}, theme.FieldDeletedAt: {Type: field.TypeString, Column: theme.FieldDeletedAt},
theme.FieldKey: {Type: field.TypeString, Column: theme.FieldKey}, theme.FieldName: {Type: field.TypeString, Column: theme.FieldName},
theme.FieldType: {Type: field.TypeEnum, Column: theme.FieldType}, theme.FieldType: {Type: field.TypeEnum, Column: theme.FieldType},
theme.FieldColors: {Type: field.TypeJSON, Column: theme.FieldColors}, theme.FieldColors: {Type: field.TypeJSON, Column: theme.FieldColors},
}, },
@@ -242,9 +248,9 @@ func (f *ExtensionFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(extension.FieldDeletedAt)) f.Where(p.Field(extension.FieldDeletedAt))
} }
// WhereKey applies the entql string predicate on the key field. // WhereName applies the entql string predicate on the name field.
func (f *ExtensionFilter) WhereKey(p entql.StringP) { func (f *ExtensionFilter) WhereName(p entql.StringP) {
f.Where(p.Field(extension.FieldKey)) f.Where(p.Field(extension.FieldName))
} }
// WhereEnabled applies the entql bool predicate on the enabled field. // WhereEnabled applies the entql bool predicate on the enabled field.
@@ -317,14 +323,34 @@ func (f *KeyBindingFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(keybinding.FieldDeletedAt)) f.Where(p.Field(keybinding.FieldDeletedAt))
} }
// WhereName applies the entql string predicate on the name field.
func (f *KeyBindingFilter) WhereName(p entql.StringP) {
f.Where(p.Field(keybinding.FieldName))
}
// WhereType applies the entql string predicate on the type field.
func (f *KeyBindingFilter) WhereType(p entql.StringP) {
f.Where(p.Field(keybinding.FieldType))
}
// WhereKey applies the entql string predicate on the key field. // WhereKey applies the entql string predicate on the key field.
func (f *KeyBindingFilter) WhereKey(p entql.StringP) { func (f *KeyBindingFilter) WhereKey(p entql.StringP) {
f.Where(p.Field(keybinding.FieldKey)) f.Where(p.Field(keybinding.FieldKey))
} }
// WhereCommand applies the entql string predicate on the command field. // WhereMacos applies the entql string predicate on the macos field.
func (f *KeyBindingFilter) WhereCommand(p entql.StringP) { func (f *KeyBindingFilter) WhereMacos(p entql.StringP) {
f.Where(p.Field(keybinding.FieldCommand)) f.Where(p.Field(keybinding.FieldMacos))
}
// WhereWindows applies the entql string predicate on the windows field.
func (f *KeyBindingFilter) WhereWindows(p entql.StringP) {
f.Where(p.Field(keybinding.FieldWindows))
}
// WhereLinux applies the entql string predicate on the linux field.
func (f *KeyBindingFilter) WhereLinux(p entql.StringP) {
f.Where(p.Field(keybinding.FieldLinux))
} }
// WhereExtension applies the entql string predicate on the extension field. // WhereExtension applies the entql string predicate on the extension field.
@@ -337,6 +363,16 @@ func (f *KeyBindingFilter) WhereEnabled(p entql.BoolP) {
f.Where(p.Field(keybinding.FieldEnabled)) f.Where(p.Field(keybinding.FieldEnabled))
} }
// WherePreventDefault applies the entql bool predicate on the prevent_default field.
func (f *KeyBindingFilter) WherePreventDefault(p entql.BoolP) {
f.Where(p.Field(keybinding.FieldPreventDefault))
}
// WhereScope applies the entql string predicate on the scope field.
func (f *KeyBindingFilter) WhereScope(p entql.StringP) {
f.Where(p.Field(keybinding.FieldScope))
}
// addPredicate implements the predicateAdder interface. // addPredicate implements the predicateAdder interface.
func (_q *ThemeQuery) addPredicate(pred func(s *sql.Selector)) { func (_q *ThemeQuery) addPredicate(pred func(s *sql.Selector)) {
_q.predicates = append(_q.predicates, pred) _q.predicates = append(_q.predicates, pred)
@@ -397,9 +433,9 @@ func (f *ThemeFilter) WhereDeletedAt(p entql.StringP) {
f.Where(p.Field(theme.FieldDeletedAt)) f.Where(p.Field(theme.FieldDeletedAt))
} }
// WhereKey applies the entql string predicate on the key field. // WhereName applies the entql string predicate on the name field.
func (f *ThemeFilter) WhereKey(p entql.StringP) { func (f *ThemeFilter) WhereName(p entql.StringP) {
f.Where(p.Field(theme.FieldKey)) f.Where(p.Field(theme.FieldName))
} }
// WhereType applies the entql string predicate on the type field. // WhereType applies the entql string predicate on the type field.

View File

@@ -18,15 +18,15 @@ type Extension struct {
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID int `json:"id,omitempty"`
// UUID for cross-device sync (UUIDv7) // UUID for cross-device sync (UUIDv7)
UUID *string `json:"uuid"` UUID string `json:"uuid"`
// creation time // creation time
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
// update time // update time
UpdatedAt string `json:"updated_at"` UpdatedAt string `json:"updated_at"`
// deleted at // deleted at
DeletedAt *string `json:"deleted_at,omitempty"` DeletedAt *string `json:"deleted_at,omitempty"`
// extension key // extension name
Key string `json:"key"` Name string `json:"name"`
// extension enabled or not // extension enabled or not
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
// extension config // extension config
@@ -45,7 +45,7 @@ func (*Extension) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool) values[i] = new(sql.NullBool)
case extension.FieldID: case extension.FieldID:
values[i] = new(sql.NullInt64) values[i] = new(sql.NullInt64)
case extension.FieldUUID, extension.FieldCreatedAt, extension.FieldUpdatedAt, extension.FieldDeletedAt, extension.FieldKey: case extension.FieldUUID, extension.FieldCreatedAt, extension.FieldUpdatedAt, extension.FieldDeletedAt, extension.FieldName:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
default: default:
values[i] = new(sql.UnknownType) values[i] = new(sql.UnknownType)
@@ -72,8 +72,7 @@ func (_m *Extension) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i]) return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value.Valid { } else if value.Valid {
_m.UUID = new(string) _m.UUID = value.String
*_m.UUID = value.String
} }
case extension.FieldCreatedAt: case extension.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -94,11 +93,11 @@ func (_m *Extension) assignValues(columns []string, values []any) error {
_m.DeletedAt = new(string) _m.DeletedAt = new(string)
*_m.DeletedAt = value.String *_m.DeletedAt = value.String
} }
case extension.FieldKey: case extension.FieldName:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i]) return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid { } else if value.Valid {
_m.Key = value.String _m.Name = value.String
} }
case extension.FieldEnabled: case extension.FieldEnabled:
if value, ok := values[i].(*sql.NullBool); !ok { if value, ok := values[i].(*sql.NullBool); !ok {
@@ -150,10 +149,8 @@ func (_m *Extension) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("Extension(") builder.WriteString("Extension(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
if v := _m.UUID; v != nil { builder.WriteString("uuid=")
builder.WriteString("uuid=") builder.WriteString(_m.UUID)
builder.WriteString(*v)
}
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("created_at=") builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt) builder.WriteString(_m.CreatedAt)
@@ -166,8 +163,8 @@ func (_m *Extension) String() string {
builder.WriteString(*v) builder.WriteString(*v)
} }
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("key=") builder.WriteString("name=")
builder.WriteString(_m.Key) builder.WriteString(_m.Name)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("enabled=") builder.WriteString("enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.Enabled)) builder.WriteString(fmt.Sprintf("%v", _m.Enabled))

View File

@@ -20,8 +20,8 @@ const (
FieldUpdatedAt = "updated_at" FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database. // FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at" FieldDeletedAt = "deleted_at"
// FieldKey holds the string denoting the key field in the database. // FieldName holds the string denoting the name field in the database.
FieldKey = "key" FieldName = "name"
// FieldEnabled holds the string denoting the enabled field in the database. // FieldEnabled holds the string denoting the enabled field in the database.
FieldEnabled = "enabled" FieldEnabled = "enabled"
// FieldConfig holds the string denoting the config field in the database. // FieldConfig holds the string denoting the config field in the database.
@@ -37,7 +37,7 @@ var Columns = []string{
FieldCreatedAt, FieldCreatedAt,
FieldUpdatedAt, FieldUpdatedAt,
FieldDeletedAt, FieldDeletedAt,
FieldKey, FieldName,
FieldEnabled, FieldEnabled,
FieldConfig, FieldConfig,
} }
@@ -66,8 +66,8 @@ var (
DefaultCreatedAt func() string DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field. // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string DefaultUpdatedAt func() string
// KeyValidator is a validator for the "key" field. It is called by the builders before save. // NameValidator is a validator for the "name" field. It is called by the builders before save.
KeyValidator func(string) error NameValidator func(string) error
// DefaultEnabled holds the default value on creation for the "enabled" field. // DefaultEnabled holds the default value on creation for the "enabled" field.
DefaultEnabled bool DefaultEnabled bool
) )
@@ -100,9 +100,9 @@ func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
} }
// ByKey orders the results by the key field. // ByName orders the results by the name field.
func ByKey(opts ...sql.OrderTermOption) OrderOption { func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc() return sql.OrderByField(FieldName, opts...).ToFunc()
} }
// ByEnabled orders the results by the enabled field. // ByEnabled orders the results by the enabled field.

View File

@@ -73,9 +73,9 @@ func DeletedAt(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldDeletedAt, v)) return predicate.Extension(sql.FieldEQ(FieldDeletedAt, v))
} }
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. // Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Key(v string) predicate.Extension { func Name(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldKey, v)) return predicate.Extension(sql.FieldEQ(FieldName, v))
} }
// Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ. // Enabled applies equality check predicate on the "enabled" field. It's identical to EnabledEQ.
@@ -138,16 +138,6 @@ func UUIDHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldUUID, v)) return predicate.Extension(sql.FieldHasSuffix(FieldUUID, v))
} }
// UUIDIsNil applies the IsNil predicate on the "uuid" field.
func UUIDIsNil() predicate.Extension {
return predicate.Extension(sql.FieldIsNull(FieldUUID))
}
// UUIDNotNil applies the NotNil predicate on the "uuid" field.
func UUIDNotNil() predicate.Extension {
return predicate.Extension(sql.FieldNotNull(FieldUUID))
}
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field. // UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
func UUIDEqualFold(v string) predicate.Extension { func UUIDEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldUUID, v)) return predicate.Extension(sql.FieldEqualFold(FieldUUID, v))
@@ -363,69 +353,69 @@ func DeletedAtContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldDeletedAt, v)) return predicate.Extension(sql.FieldContainsFold(FieldDeletedAt, v))
} }
// KeyEQ applies the EQ predicate on the "key" field. // NameEQ applies the EQ predicate on the "name" field.
func KeyEQ(v string) predicate.Extension { func NameEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldEQ(FieldKey, v)) return predicate.Extension(sql.FieldEQ(FieldName, v))
} }
// KeyNEQ applies the NEQ predicate on the "key" field. // NameNEQ applies the NEQ predicate on the "name" field.
func KeyNEQ(v string) predicate.Extension { func NameNEQ(v string) predicate.Extension {
return predicate.Extension(sql.FieldNEQ(FieldKey, v)) return predicate.Extension(sql.FieldNEQ(FieldName, v))
} }
// KeyIn applies the In predicate on the "key" field. // NameIn applies the In predicate on the "name" field.
func KeyIn(vs ...string) predicate.Extension { func NameIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldIn(FieldKey, vs...)) return predicate.Extension(sql.FieldIn(FieldName, vs...))
} }
// KeyNotIn applies the NotIn predicate on the "key" field. // NameNotIn applies the NotIn predicate on the "name" field.
func KeyNotIn(vs ...string) predicate.Extension { func NameNotIn(vs ...string) predicate.Extension {
return predicate.Extension(sql.FieldNotIn(FieldKey, vs...)) return predicate.Extension(sql.FieldNotIn(FieldName, vs...))
} }
// KeyGT applies the GT predicate on the "key" field. // NameGT applies the GT predicate on the "name" field.
func KeyGT(v string) predicate.Extension { func NameGT(v string) predicate.Extension {
return predicate.Extension(sql.FieldGT(FieldKey, v)) return predicate.Extension(sql.FieldGT(FieldName, v))
} }
// KeyGTE applies the GTE predicate on the "key" field. // NameGTE applies the GTE predicate on the "name" field.
func KeyGTE(v string) predicate.Extension { func NameGTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldGTE(FieldKey, v)) return predicate.Extension(sql.FieldGTE(FieldName, v))
} }
// KeyLT applies the LT predicate on the "key" field. // NameLT applies the LT predicate on the "name" field.
func KeyLT(v string) predicate.Extension { func NameLT(v string) predicate.Extension {
return predicate.Extension(sql.FieldLT(FieldKey, v)) return predicate.Extension(sql.FieldLT(FieldName, v))
} }
// KeyLTE applies the LTE predicate on the "key" field. // NameLTE applies the LTE predicate on the "name" field.
func KeyLTE(v string) predicate.Extension { func NameLTE(v string) predicate.Extension {
return predicate.Extension(sql.FieldLTE(FieldKey, v)) return predicate.Extension(sql.FieldLTE(FieldName, v))
} }
// KeyContains applies the Contains predicate on the "key" field. // NameContains applies the Contains predicate on the "name" field.
func KeyContains(v string) predicate.Extension { func NameContains(v string) predicate.Extension {
return predicate.Extension(sql.FieldContains(FieldKey, v)) return predicate.Extension(sql.FieldContains(FieldName, v))
} }
// KeyHasPrefix applies the HasPrefix predicate on the "key" field. // NameHasPrefix applies the HasPrefix predicate on the "name" field.
func KeyHasPrefix(v string) predicate.Extension { func NameHasPrefix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasPrefix(FieldKey, v)) return predicate.Extension(sql.FieldHasPrefix(FieldName, v))
} }
// KeyHasSuffix applies the HasSuffix predicate on the "key" field. // NameHasSuffix applies the HasSuffix predicate on the "name" field.
func KeyHasSuffix(v string) predicate.Extension { func NameHasSuffix(v string) predicate.Extension {
return predicate.Extension(sql.FieldHasSuffix(FieldKey, v)) return predicate.Extension(sql.FieldHasSuffix(FieldName, v))
} }
// KeyEqualFold applies the EqualFold predicate on the "key" field. // NameEqualFold applies the EqualFold predicate on the "name" field.
func KeyEqualFold(v string) predicate.Extension { func NameEqualFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldEqualFold(FieldKey, v)) return predicate.Extension(sql.FieldEqualFold(FieldName, v))
} }
// KeyContainsFold applies the ContainsFold predicate on the "key" field. // NameContainsFold applies the ContainsFold predicate on the "name" field.
func KeyContainsFold(v string) predicate.Extension { func NameContainsFold(v string) predicate.Extension {
return predicate.Extension(sql.FieldContainsFold(FieldKey, v)) return predicate.Extension(sql.FieldContainsFold(FieldName, v))
} }
// EnabledEQ applies the EQ predicate on the "enabled" field. // EnabledEQ applies the EQ predicate on the "enabled" field.

View File

@@ -75,9 +75,9 @@ func (_c *ExtensionCreate) SetNillableDeletedAt(v *string) *ExtensionCreate {
return _c return _c
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_c *ExtensionCreate) SetKey(v string) *ExtensionCreate { func (_c *ExtensionCreate) SetName(v string) *ExtensionCreate {
_c.mutation.SetKey(v) _c.mutation.SetName(v)
return _c return _c
} }
@@ -168,18 +168,21 @@ func (_c *ExtensionCreate) defaults() error {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_c *ExtensionCreate) check() error { func (_c *ExtensionCreate) check() error {
if _, ok := _c.mutation.UUID(); !ok {
return &ValidationError{Name: "uuid", err: errors.New(`ent: missing required field "Extension.uuid"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok { if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Extension.created_at"`)} return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Extension.created_at"`)}
} }
if _, ok := _c.mutation.UpdatedAt(); !ok { if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Extension.updated_at"`)} return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Extension.updated_at"`)}
} }
if _, ok := _c.mutation.Key(); !ok { if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Extension.key"`)} return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Extension.name"`)}
} }
if v, ok := _c.mutation.Key(); ok { if v, ok := _c.mutation.Name(); ok {
if err := extension.KeyValidator(v); err != nil { if err := extension.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Extension.name": %w`, err)}
} }
} }
if _, ok := _c.mutation.Enabled(); !ok { if _, ok := _c.mutation.Enabled(); !ok {
@@ -213,7 +216,7 @@ func (_c *ExtensionCreate) createSpec() (*Extension, *sqlgraph.CreateSpec) {
) )
if value, ok := _c.mutation.UUID(); ok { if value, ok := _c.mutation.UUID(); ok {
_spec.SetField(extension.FieldUUID, field.TypeString, value) _spec.SetField(extension.FieldUUID, field.TypeString, value)
_node.UUID = &value _node.UUID = value
} }
if value, ok := _c.mutation.CreatedAt(); ok { if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(extension.FieldCreatedAt, field.TypeString, value) _spec.SetField(extension.FieldCreatedAt, field.TypeString, value)
@@ -227,9 +230,9 @@ func (_c *ExtensionCreate) createSpec() (*Extension, *sqlgraph.CreateSpec) {
_spec.SetField(extension.FieldDeletedAt, field.TypeString, value) _spec.SetField(extension.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value _node.DeletedAt = &value
} }
if value, ok := _c.mutation.Key(); ok { if value, ok := _c.mutation.Name(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value) _spec.SetField(extension.FieldName, field.TypeString, value)
_node.Key = value _node.Name = value
} }
if value, ok := _c.mutation.Enabled(); ok { if value, ok := _c.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value) _spec.SetField(extension.FieldEnabled, field.TypeBool, value)

View File

@@ -62,16 +62,16 @@ func (_u *ExtensionUpdate) ClearDeletedAt() *ExtensionUpdate {
return _u return _u
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_u *ExtensionUpdate) SetKey(v string) *ExtensionUpdate { func (_u *ExtensionUpdate) SetName(v string) *ExtensionUpdate {
_u.mutation.SetKey(v) _u.mutation.SetName(v)
return _u return _u
} }
// SetNillableKey sets the "key" field if the given value is not nil. // SetNillableName sets the "name" field if the given value is not nil.
func (_u *ExtensionUpdate) SetNillableKey(v *string) *ExtensionUpdate { func (_u *ExtensionUpdate) SetNillableName(v *string) *ExtensionUpdate {
if v != nil { if v != nil {
_u.SetKey(*v) _u.SetName(*v)
} }
return _u return _u
} }
@@ -136,9 +136,9 @@ func (_u *ExtensionUpdate) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *ExtensionUpdate) check() error { func (_u *ExtensionUpdate) check() error {
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Name(); ok {
if err := extension.KeyValidator(v); err != nil { if err := extension.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Extension.name": %w`, err)}
} }
} }
return nil return nil
@@ -162,9 +162,6 @@ func (_u *ExtensionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(extension.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(extension.FieldUpdatedAt, field.TypeString, value) _spec.SetField(extension.FieldUpdatedAt, field.TypeString, value)
} }
@@ -174,8 +171,8 @@ func (_u *ExtensionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(extension.FieldDeletedAt, field.TypeString) _spec.ClearField(extension.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value) _spec.SetField(extension.FieldName, field.TypeString, value)
} }
if value, ok := _u.mutation.Enabled(); ok { if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value) _spec.SetField(extension.FieldEnabled, field.TypeBool, value)
@@ -242,16 +239,16 @@ func (_u *ExtensionUpdateOne) ClearDeletedAt() *ExtensionUpdateOne {
return _u return _u
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_u *ExtensionUpdateOne) SetKey(v string) *ExtensionUpdateOne { func (_u *ExtensionUpdateOne) SetName(v string) *ExtensionUpdateOne {
_u.mutation.SetKey(v) _u.mutation.SetName(v)
return _u return _u
} }
// SetNillableKey sets the "key" field if the given value is not nil. // SetNillableName sets the "name" field if the given value is not nil.
func (_u *ExtensionUpdateOne) SetNillableKey(v *string) *ExtensionUpdateOne { func (_u *ExtensionUpdateOne) SetNillableName(v *string) *ExtensionUpdateOne {
if v != nil { if v != nil {
_u.SetKey(*v) _u.SetName(*v)
} }
return _u return _u
} }
@@ -329,9 +326,9 @@ func (_u *ExtensionUpdateOne) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *ExtensionUpdateOne) check() error { func (_u *ExtensionUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Name(); ok {
if err := extension.KeyValidator(v); err != nil { if err := extension.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Extension.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Extension.name": %w`, err)}
} }
} }
return nil return nil
@@ -372,9 +369,6 @@ func (_u *ExtensionUpdateOne) sqlSave(ctx context.Context) (_node *Extension, er
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(extension.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(extension.FieldUpdatedAt, field.TypeString, value) _spec.SetField(extension.FieldUpdatedAt, field.TypeString, value)
} }
@@ -384,8 +378,8 @@ func (_u *ExtensionUpdateOne) sqlSave(ctx context.Context) (_node *Extension, er
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(extension.FieldDeletedAt, field.TypeString) _spec.ClearField(extension.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(extension.FieldKey, field.TypeString, value) _spec.SetField(extension.FieldName, field.TypeString, value)
} }
if value, ok := _u.mutation.Enabled(); ok { if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(extension.FieldEnabled, field.TypeBool, value) _spec.SetField(extension.FieldEnabled, field.TypeBool, value)

View File

@@ -17,21 +17,33 @@ type KeyBinding struct {
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID int `json:"id,omitempty"`
// UUID for cross-device sync (UUIDv7) // UUID for cross-device sync (UUIDv7)
UUID *string `json:"uuid"` UUID string `json:"uuid"`
// creation time // creation time
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
// update time // update time
UpdatedAt string `json:"updated_at"` UpdatedAt string `json:"updated_at"`
// deleted at // deleted at
DeletedAt *string `json:"deleted_at,omitempty"` DeletedAt *string `json:"deleted_at,omitempty"`
// key binding key // command identifier
Key string `json:"key"` Name string `json:"name"`
// key binding command // keybinding type: standard or emacs
Command string `json:"command"` Type string `json:"type"`
// key binding extension // universal keybinding (cross-platform)
Extension string `json:"extension,omitempty"` Key string `json:"key,omitempty"`
// key binding enabled // macOS specific keybinding
Enabled bool `json:"enabled"` Macos string `json:"macos,omitempty"`
// Windows specific keybinding
Windows string `json:"windows,omitempty"`
// Linux specific keybinding
Linux string `json:"linux,omitempty"`
// extension name (functional category)
Extension string `json:"extension"`
// whether this keybinding is enabled
Enabled bool `json:"enabled"`
// prevent browser default behavior
PreventDefault bool `json:"preventDefault"`
// keybinding scope (default: editor)
Scope string `json:"scope,omitempty"`
selectValues sql.SelectValues selectValues sql.SelectValues
} }
@@ -40,11 +52,11 @@ func (*KeyBinding) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns)) values := make([]any, len(columns))
for i := range columns { for i := range columns {
switch columns[i] { switch columns[i] {
case keybinding.FieldEnabled: case keybinding.FieldEnabled, keybinding.FieldPreventDefault:
values[i] = new(sql.NullBool) values[i] = new(sql.NullBool)
case keybinding.FieldID: case keybinding.FieldID:
values[i] = new(sql.NullInt64) values[i] = new(sql.NullInt64)
case keybinding.FieldUUID, keybinding.FieldCreatedAt, keybinding.FieldUpdatedAt, keybinding.FieldDeletedAt, keybinding.FieldKey, keybinding.FieldCommand, keybinding.FieldExtension: case keybinding.FieldUUID, keybinding.FieldCreatedAt, keybinding.FieldUpdatedAt, keybinding.FieldDeletedAt, keybinding.FieldName, keybinding.FieldType, keybinding.FieldKey, keybinding.FieldMacos, keybinding.FieldWindows, keybinding.FieldLinux, keybinding.FieldExtension, keybinding.FieldScope:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
default: default:
values[i] = new(sql.UnknownType) values[i] = new(sql.UnknownType)
@@ -71,8 +83,7 @@ func (_m *KeyBinding) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i]) return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value.Valid { } else if value.Valid {
_m.UUID = new(string) _m.UUID = value.String
*_m.UUID = value.String
} }
case keybinding.FieldCreatedAt: case keybinding.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -93,17 +104,41 @@ func (_m *KeyBinding) assignValues(columns []string, values []any) error {
_m.DeletedAt = new(string) _m.DeletedAt = new(string)
*_m.DeletedAt = value.String *_m.DeletedAt = value.String
} }
case keybinding.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case keybinding.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_m.Type = value.String
}
case keybinding.FieldKey: case keybinding.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i]) return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid { } else if value.Valid {
_m.Key = value.String _m.Key = value.String
} }
case keybinding.FieldCommand: case keybinding.FieldMacos:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field command", values[i]) return fmt.Errorf("unexpected type %T for field macos", values[i])
} else if value.Valid { } else if value.Valid {
_m.Command = value.String _m.Macos = value.String
}
case keybinding.FieldWindows:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field windows", values[i])
} else if value.Valid {
_m.Windows = value.String
}
case keybinding.FieldLinux:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field linux", values[i])
} else if value.Valid {
_m.Linux = value.String
} }
case keybinding.FieldExtension: case keybinding.FieldExtension:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -117,6 +152,18 @@ func (_m *KeyBinding) assignValues(columns []string, values []any) error {
} else if value.Valid { } else if value.Valid {
_m.Enabled = value.Bool _m.Enabled = value.Bool
} }
case keybinding.FieldPreventDefault:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field prevent_default", values[i])
} else if value.Valid {
_m.PreventDefault = value.Bool
}
case keybinding.FieldScope:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field scope", values[i])
} else if value.Valid {
_m.Scope = value.String
}
default: default:
_m.selectValues.Set(columns[i], values[i]) _m.selectValues.Set(columns[i], values[i])
} }
@@ -153,10 +200,8 @@ func (_m *KeyBinding) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("KeyBinding(") builder.WriteString("KeyBinding(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
if v := _m.UUID; v != nil { builder.WriteString("uuid=")
builder.WriteString("uuid=") builder.WriteString(_m.UUID)
builder.WriteString(*v)
}
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("created_at=") builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt) builder.WriteString(_m.CreatedAt)
@@ -169,17 +214,35 @@ func (_m *KeyBinding) String() string {
builder.WriteString(*v) builder.WriteString(*v)
} }
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(_m.Type)
builder.WriteString(", ")
builder.WriteString("key=") builder.WriteString("key=")
builder.WriteString(_m.Key) builder.WriteString(_m.Key)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("command=") builder.WriteString("macos=")
builder.WriteString(_m.Command) builder.WriteString(_m.Macos)
builder.WriteString(", ")
builder.WriteString("windows=")
builder.WriteString(_m.Windows)
builder.WriteString(", ")
builder.WriteString("linux=")
builder.WriteString(_m.Linux)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("extension=") builder.WriteString("extension=")
builder.WriteString(_m.Extension) builder.WriteString(_m.Extension)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("enabled=") builder.WriteString("enabled=")
builder.WriteString(fmt.Sprintf("%v", _m.Enabled)) builder.WriteString(fmt.Sprintf("%v", _m.Enabled))
builder.WriteString(", ")
builder.WriteString("prevent_default=")
builder.WriteString(fmt.Sprintf("%v", _m.PreventDefault))
builder.WriteString(", ")
builder.WriteString("scope=")
builder.WriteString(_m.Scope)
builder.WriteByte(')') builder.WriteByte(')')
return builder.String() return builder.String()
} }

View File

@@ -20,14 +20,26 @@ const (
FieldUpdatedAt = "updated_at" FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database. // FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at" FieldDeletedAt = "deleted_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldKey holds the string denoting the key field in the database. // FieldKey holds the string denoting the key field in the database.
FieldKey = "key" FieldKey = "key"
// FieldCommand holds the string denoting the command field in the database. // FieldMacos holds the string denoting the macos field in the database.
FieldCommand = "command" FieldMacos = "macos"
// FieldWindows holds the string denoting the windows field in the database.
FieldWindows = "windows"
// FieldLinux holds the string denoting the linux field in the database.
FieldLinux = "linux"
// FieldExtension holds the string denoting the extension field in the database. // FieldExtension holds the string denoting the extension field in the database.
FieldExtension = "extension" FieldExtension = "extension"
// FieldEnabled holds the string denoting the enabled field in the database. // FieldEnabled holds the string denoting the enabled field in the database.
FieldEnabled = "enabled" FieldEnabled = "enabled"
// FieldPreventDefault holds the string denoting the prevent_default field in the database.
FieldPreventDefault = "prevent_default"
// FieldScope holds the string denoting the scope field in the database.
FieldScope = "scope"
// Table holds the table name of the keybinding in the database. // Table holds the table name of the keybinding in the database.
Table = "key_bindings" Table = "key_bindings"
) )
@@ -39,10 +51,16 @@ var Columns = []string{
FieldCreatedAt, FieldCreatedAt,
FieldUpdatedAt, FieldUpdatedAt,
FieldDeletedAt, FieldDeletedAt,
FieldName,
FieldType,
FieldKey, FieldKey,
FieldCommand, FieldMacos,
FieldWindows,
FieldLinux,
FieldExtension, FieldExtension,
FieldEnabled, FieldEnabled,
FieldPreventDefault,
FieldScope,
} }
// ValidColumn reports if the column name is valid (part of the table columns). // ValidColumn reports if the column name is valid (part of the table columns).
@@ -69,14 +87,30 @@ var (
DefaultCreatedAt func() string DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field. // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string DefaultUpdatedAt func() string
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultType holds the default value on creation for the "type" field.
DefaultType string
// TypeValidator is a validator for the "type" field. It is called by the builders before save.
TypeValidator func(string) error
// KeyValidator is a validator for the "key" field. It is called by the builders before save. // KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error KeyValidator func(string) error
// CommandValidator is a validator for the "command" field. It is called by the builders before save. // MacosValidator is a validator for the "macos" field. It is called by the builders before save.
CommandValidator func(string) error MacosValidator func(string) error
// WindowsValidator is a validator for the "windows" field. It is called by the builders before save.
WindowsValidator func(string) error
// LinuxValidator is a validator for the "linux" field. It is called by the builders before save.
LinuxValidator func(string) error
// ExtensionValidator is a validator for the "extension" field. It is called by the builders before save. // ExtensionValidator is a validator for the "extension" field. It is called by the builders before save.
ExtensionValidator func(string) error ExtensionValidator func(string) error
// DefaultEnabled holds the default value on creation for the "enabled" field. // DefaultEnabled holds the default value on creation for the "enabled" field.
DefaultEnabled bool DefaultEnabled bool
// DefaultPreventDefault holds the default value on creation for the "prevent_default" field.
DefaultPreventDefault bool
// DefaultScope holds the default value on creation for the "scope" field.
DefaultScope string
// ScopeValidator is a validator for the "scope" field. It is called by the builders before save.
ScopeValidator func(string) error
) )
// OrderOption defines the ordering options for the KeyBinding queries. // OrderOption defines the ordering options for the KeyBinding queries.
@@ -107,14 +141,34 @@ func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
} }
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByType orders the results by the type field.
func ByType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldType, opts...).ToFunc()
}
// ByKey orders the results by the key field. // ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption { func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc() return sql.OrderByField(FieldKey, opts...).ToFunc()
} }
// ByCommand orders the results by the command field. // ByMacos orders the results by the macos field.
func ByCommand(opts ...sql.OrderTermOption) OrderOption { func ByMacos(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCommand, opts...).ToFunc() return sql.OrderByField(FieldMacos, opts...).ToFunc()
}
// ByWindows orders the results by the windows field.
func ByWindows(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldWindows, opts...).ToFunc()
}
// ByLinux orders the results by the linux field.
func ByLinux(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLinux, opts...).ToFunc()
} }
// ByExtension orders the results by the extension field. // ByExtension orders the results by the extension field.
@@ -126,3 +180,13 @@ func ByExtension(opts ...sql.OrderTermOption) OrderOption {
func ByEnabled(opts ...sql.OrderTermOption) OrderOption { func ByEnabled(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEnabled, opts...).ToFunc() return sql.OrderByField(FieldEnabled, opts...).ToFunc()
} }
// ByPreventDefault orders the results by the prevent_default field.
func ByPreventDefault(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPreventDefault, opts...).ToFunc()
}
// ByScope orders the results by the scope field.
func ByScope(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldScope, opts...).ToFunc()
}

View File

@@ -73,14 +73,34 @@ func DeletedAt(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldDeletedAt, v)) return predicate.KeyBinding(sql.FieldEQ(FieldDeletedAt, v))
} }
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldName, v))
}
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
func Type(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldType, v))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. // Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.KeyBinding { func Key(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldKey, v)) return predicate.KeyBinding(sql.FieldEQ(FieldKey, v))
} }
// Command applies equality check predicate on the "command" field. It's identical to CommandEQ. // Macos applies equality check predicate on the "macos" field. It's identical to MacosEQ.
func Command(v string) predicate.KeyBinding { func Macos(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCommand, v)) return predicate.KeyBinding(sql.FieldEQ(FieldMacos, v))
}
// Windows applies equality check predicate on the "windows" field. It's identical to WindowsEQ.
func Windows(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldWindows, v))
}
// Linux applies equality check predicate on the "linux" field. It's identical to LinuxEQ.
func Linux(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldLinux, v))
} }
// Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ. // Extension applies equality check predicate on the "extension" field. It's identical to ExtensionEQ.
@@ -93,6 +113,16 @@ func Enabled(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldEnabled, v)) return predicate.KeyBinding(sql.FieldEQ(FieldEnabled, v))
} }
// PreventDefault applies equality check predicate on the "prevent_default" field. It's identical to PreventDefaultEQ.
func PreventDefault(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldPreventDefault, v))
}
// Scope applies equality check predicate on the "scope" field. It's identical to ScopeEQ.
func Scope(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldScope, v))
}
// UUIDEQ applies the EQ predicate on the "uuid" field. // UUIDEQ applies the EQ predicate on the "uuid" field.
func UUIDEQ(v string) predicate.KeyBinding { func UUIDEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldUUID, v)) return predicate.KeyBinding(sql.FieldEQ(FieldUUID, v))
@@ -148,16 +178,6 @@ func UUIDHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldUUID, v)) return predicate.KeyBinding(sql.FieldHasSuffix(FieldUUID, v))
} }
// UUIDIsNil applies the IsNil predicate on the "uuid" field.
func UUIDIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldUUID))
}
// UUIDNotNil applies the NotNil predicate on the "uuid" field.
func UUIDNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldUUID))
}
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field. // UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
func UUIDEqualFold(v string) predicate.KeyBinding { func UUIDEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldUUID, v)) return predicate.KeyBinding(sql.FieldEqualFold(FieldUUID, v))
@@ -373,6 +393,136 @@ func DeletedAtContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldDeletedAt, v)) return predicate.KeyBinding(sql.FieldContainsFold(FieldDeletedAt, v))
} }
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldName, v))
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldType, v))
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldType, v))
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldType, vs...))
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldType, vs...))
}
// TypeGT applies the GT predicate on the "type" field.
func TypeGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldType, v))
}
// TypeGTE applies the GTE predicate on the "type" field.
func TypeGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldType, v))
}
// TypeLT applies the LT predicate on the "type" field.
func TypeLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldType, v))
}
// TypeLTE applies the LTE predicate on the "type" field.
func TypeLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldType, v))
}
// TypeContains applies the Contains predicate on the "type" field.
func TypeContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldType, v))
}
// TypeHasPrefix applies the HasPrefix predicate on the "type" field.
func TypeHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldType, v))
}
// TypeHasSuffix applies the HasSuffix predicate on the "type" field.
func TypeHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldType, v))
}
// TypeEqualFold applies the EqualFold predicate on the "type" field.
func TypeEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldType, v))
}
// TypeContainsFold applies the ContainsFold predicate on the "type" field.
func TypeContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldType, v))
}
// KeyEQ applies the EQ predicate on the "key" field. // KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.KeyBinding { func KeyEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldKey, v)) return predicate.KeyBinding(sql.FieldEQ(FieldKey, v))
@@ -428,6 +578,16 @@ func KeyHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldKey, v)) return predicate.KeyBinding(sql.FieldHasSuffix(FieldKey, v))
} }
// KeyIsNil applies the IsNil predicate on the "key" field.
func KeyIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldKey))
}
// KeyNotNil applies the NotNil predicate on the "key" field.
func KeyNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldKey))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field. // KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.KeyBinding { func KeyEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldKey, v)) return predicate.KeyBinding(sql.FieldEqualFold(FieldKey, v))
@@ -438,69 +598,229 @@ func KeyContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldKey, v)) return predicate.KeyBinding(sql.FieldContainsFold(FieldKey, v))
} }
// CommandEQ applies the EQ predicate on the "command" field. // MacosEQ applies the EQ predicate on the "macos" field.
func CommandEQ(v string) predicate.KeyBinding { func MacosEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldCommand, v)) return predicate.KeyBinding(sql.FieldEQ(FieldMacos, v))
} }
// CommandNEQ applies the NEQ predicate on the "command" field. // MacosNEQ applies the NEQ predicate on the "macos" field.
func CommandNEQ(v string) predicate.KeyBinding { func MacosNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldCommand, v)) return predicate.KeyBinding(sql.FieldNEQ(FieldMacos, v))
} }
// CommandIn applies the In predicate on the "command" field. // MacosIn applies the In predicate on the "macos" field.
func CommandIn(vs ...string) predicate.KeyBinding { func MacosIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldCommand, vs...)) return predicate.KeyBinding(sql.FieldIn(FieldMacos, vs...))
} }
// CommandNotIn applies the NotIn predicate on the "command" field. // MacosNotIn applies the NotIn predicate on the "macos" field.
func CommandNotIn(vs ...string) predicate.KeyBinding { func MacosNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldCommand, vs...)) return predicate.KeyBinding(sql.FieldNotIn(FieldMacos, vs...))
} }
// CommandGT applies the GT predicate on the "command" field. // MacosGT applies the GT predicate on the "macos" field.
func CommandGT(v string) predicate.KeyBinding { func MacosGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldCommand, v)) return predicate.KeyBinding(sql.FieldGT(FieldMacos, v))
} }
// CommandGTE applies the GTE predicate on the "command" field. // MacosGTE applies the GTE predicate on the "macos" field.
func CommandGTE(v string) predicate.KeyBinding { func MacosGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldCommand, v)) return predicate.KeyBinding(sql.FieldGTE(FieldMacos, v))
} }
// CommandLT applies the LT predicate on the "command" field. // MacosLT applies the LT predicate on the "macos" field.
func CommandLT(v string) predicate.KeyBinding { func MacosLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldCommand, v)) return predicate.KeyBinding(sql.FieldLT(FieldMacos, v))
} }
// CommandLTE applies the LTE predicate on the "command" field. // MacosLTE applies the LTE predicate on the "macos" field.
func CommandLTE(v string) predicate.KeyBinding { func MacosLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldCommand, v)) return predicate.KeyBinding(sql.FieldLTE(FieldMacos, v))
} }
// CommandContains applies the Contains predicate on the "command" field. // MacosContains applies the Contains predicate on the "macos" field.
func CommandContains(v string) predicate.KeyBinding { func MacosContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldCommand, v)) return predicate.KeyBinding(sql.FieldContains(FieldMacos, v))
} }
// CommandHasPrefix applies the HasPrefix predicate on the "command" field. // MacosHasPrefix applies the HasPrefix predicate on the "macos" field.
func CommandHasPrefix(v string) predicate.KeyBinding { func MacosHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldCommand, v)) return predicate.KeyBinding(sql.FieldHasPrefix(FieldMacos, v))
} }
// CommandHasSuffix applies the HasSuffix predicate on the "command" field. // MacosHasSuffix applies the HasSuffix predicate on the "macos" field.
func CommandHasSuffix(v string) predicate.KeyBinding { func MacosHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldCommand, v)) return predicate.KeyBinding(sql.FieldHasSuffix(FieldMacos, v))
} }
// CommandEqualFold applies the EqualFold predicate on the "command" field. // MacosIsNil applies the IsNil predicate on the "macos" field.
func CommandEqualFold(v string) predicate.KeyBinding { func MacosIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldCommand, v)) return predicate.KeyBinding(sql.FieldIsNull(FieldMacos))
} }
// CommandContainsFold applies the ContainsFold predicate on the "command" field. // MacosNotNil applies the NotNil predicate on the "macos" field.
func CommandContainsFold(v string) predicate.KeyBinding { func MacosNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldCommand, v)) return predicate.KeyBinding(sql.FieldNotNull(FieldMacos))
}
// MacosEqualFold applies the EqualFold predicate on the "macos" field.
func MacosEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldMacos, v))
}
// MacosContainsFold applies the ContainsFold predicate on the "macos" field.
func MacosContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldMacos, v))
}
// WindowsEQ applies the EQ predicate on the "windows" field.
func WindowsEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldWindows, v))
}
// WindowsNEQ applies the NEQ predicate on the "windows" field.
func WindowsNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldWindows, v))
}
// WindowsIn applies the In predicate on the "windows" field.
func WindowsIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldWindows, vs...))
}
// WindowsNotIn applies the NotIn predicate on the "windows" field.
func WindowsNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldWindows, vs...))
}
// WindowsGT applies the GT predicate on the "windows" field.
func WindowsGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldWindows, v))
}
// WindowsGTE applies the GTE predicate on the "windows" field.
func WindowsGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldWindows, v))
}
// WindowsLT applies the LT predicate on the "windows" field.
func WindowsLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldWindows, v))
}
// WindowsLTE applies the LTE predicate on the "windows" field.
func WindowsLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldWindows, v))
}
// WindowsContains applies the Contains predicate on the "windows" field.
func WindowsContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldWindows, v))
}
// WindowsHasPrefix applies the HasPrefix predicate on the "windows" field.
func WindowsHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldWindows, v))
}
// WindowsHasSuffix applies the HasSuffix predicate on the "windows" field.
func WindowsHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldWindows, v))
}
// WindowsIsNil applies the IsNil predicate on the "windows" field.
func WindowsIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldWindows))
}
// WindowsNotNil applies the NotNil predicate on the "windows" field.
func WindowsNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldWindows))
}
// WindowsEqualFold applies the EqualFold predicate on the "windows" field.
func WindowsEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldWindows, v))
}
// WindowsContainsFold applies the ContainsFold predicate on the "windows" field.
func WindowsContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldWindows, v))
}
// LinuxEQ applies the EQ predicate on the "linux" field.
func LinuxEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldLinux, v))
}
// LinuxNEQ applies the NEQ predicate on the "linux" field.
func LinuxNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldLinux, v))
}
// LinuxIn applies the In predicate on the "linux" field.
func LinuxIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldLinux, vs...))
}
// LinuxNotIn applies the NotIn predicate on the "linux" field.
func LinuxNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldLinux, vs...))
}
// LinuxGT applies the GT predicate on the "linux" field.
func LinuxGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldLinux, v))
}
// LinuxGTE applies the GTE predicate on the "linux" field.
func LinuxGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldLinux, v))
}
// LinuxLT applies the LT predicate on the "linux" field.
func LinuxLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldLinux, v))
}
// LinuxLTE applies the LTE predicate on the "linux" field.
func LinuxLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldLinux, v))
}
// LinuxContains applies the Contains predicate on the "linux" field.
func LinuxContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldLinux, v))
}
// LinuxHasPrefix applies the HasPrefix predicate on the "linux" field.
func LinuxHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldLinux, v))
}
// LinuxHasSuffix applies the HasSuffix predicate on the "linux" field.
func LinuxHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldLinux, v))
}
// LinuxIsNil applies the IsNil predicate on the "linux" field.
func LinuxIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldLinux))
}
// LinuxNotNil applies the NotNil predicate on the "linux" field.
func LinuxNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldLinux))
}
// LinuxEqualFold applies the EqualFold predicate on the "linux" field.
func LinuxEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldLinux, v))
}
// LinuxContainsFold applies the ContainsFold predicate on the "linux" field.
func LinuxContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldLinux, v))
} }
// ExtensionEQ applies the EQ predicate on the "extension" field. // ExtensionEQ applies the EQ predicate on the "extension" field.
@@ -558,16 +878,6 @@ func ExtensionHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldExtension, v)) return predicate.KeyBinding(sql.FieldHasSuffix(FieldExtension, v))
} }
// ExtensionIsNil applies the IsNil predicate on the "extension" field.
func ExtensionIsNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIsNull(FieldExtension))
}
// ExtensionNotNil applies the NotNil predicate on the "extension" field.
func ExtensionNotNil() predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotNull(FieldExtension))
}
// ExtensionEqualFold applies the EqualFold predicate on the "extension" field. // ExtensionEqualFold applies the EqualFold predicate on the "extension" field.
func ExtensionEqualFold(v string) predicate.KeyBinding { func ExtensionEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldExtension, v)) return predicate.KeyBinding(sql.FieldEqualFold(FieldExtension, v))
@@ -588,6 +898,81 @@ func EnabledNEQ(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldEnabled, v)) return predicate.KeyBinding(sql.FieldNEQ(FieldEnabled, v))
} }
// PreventDefaultEQ applies the EQ predicate on the "prevent_default" field.
func PreventDefaultEQ(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldPreventDefault, v))
}
// PreventDefaultNEQ applies the NEQ predicate on the "prevent_default" field.
func PreventDefaultNEQ(v bool) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldPreventDefault, v))
}
// ScopeEQ applies the EQ predicate on the "scope" field.
func ScopeEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEQ(FieldScope, v))
}
// ScopeNEQ applies the NEQ predicate on the "scope" field.
func ScopeNEQ(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNEQ(FieldScope, v))
}
// ScopeIn applies the In predicate on the "scope" field.
func ScopeIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldIn(FieldScope, vs...))
}
// ScopeNotIn applies the NotIn predicate on the "scope" field.
func ScopeNotIn(vs ...string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldNotIn(FieldScope, vs...))
}
// ScopeGT applies the GT predicate on the "scope" field.
func ScopeGT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGT(FieldScope, v))
}
// ScopeGTE applies the GTE predicate on the "scope" field.
func ScopeGTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldGTE(FieldScope, v))
}
// ScopeLT applies the LT predicate on the "scope" field.
func ScopeLT(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLT(FieldScope, v))
}
// ScopeLTE applies the LTE predicate on the "scope" field.
func ScopeLTE(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldLTE(FieldScope, v))
}
// ScopeContains applies the Contains predicate on the "scope" field.
func ScopeContains(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContains(FieldScope, v))
}
// ScopeHasPrefix applies the HasPrefix predicate on the "scope" field.
func ScopeHasPrefix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasPrefix(FieldScope, v))
}
// ScopeHasSuffix applies the HasSuffix predicate on the "scope" field.
func ScopeHasSuffix(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldHasSuffix(FieldScope, v))
}
// ScopeEqualFold applies the EqualFold predicate on the "scope" field.
func ScopeEqualFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldEqualFold(FieldScope, v))
}
// ScopeContainsFold applies the ContainsFold predicate on the "scope" field.
func ScopeContainsFold(v string) predicate.KeyBinding {
return predicate.KeyBinding(sql.FieldContainsFold(FieldScope, v))
}
// And groups predicates with the AND operator between them. // And groups predicates with the AND operator between them.
func And(predicates ...predicate.KeyBinding) predicate.KeyBinding { func And(predicates ...predicate.KeyBinding) predicate.KeyBinding {
return predicate.KeyBinding(sql.AndPredicates(predicates...)) return predicate.KeyBinding(sql.AndPredicates(predicates...))

View File

@@ -75,15 +75,79 @@ func (_c *KeyBindingCreate) SetNillableDeletedAt(v *string) *KeyBindingCreate {
return _c return _c
} }
// SetName sets the "name" field.
func (_c *KeyBindingCreate) SetName(v string) *KeyBindingCreate {
_c.mutation.SetName(v)
return _c
}
// SetType sets the "type" field.
func (_c *KeyBindingCreate) SetType(v string) *KeyBindingCreate {
_c.mutation.SetType(v)
return _c
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableType(v *string) *KeyBindingCreate {
if v != nil {
_c.SetType(*v)
}
return _c
}
// SetKey sets the "key" field. // SetKey sets the "key" field.
func (_c *KeyBindingCreate) SetKey(v string) *KeyBindingCreate { func (_c *KeyBindingCreate) SetKey(v string) *KeyBindingCreate {
_c.mutation.SetKey(v) _c.mutation.SetKey(v)
return _c return _c
} }
// SetCommand sets the "command" field. // SetNillableKey sets the "key" field if the given value is not nil.
func (_c *KeyBindingCreate) SetCommand(v string) *KeyBindingCreate { func (_c *KeyBindingCreate) SetNillableKey(v *string) *KeyBindingCreate {
_c.mutation.SetCommand(v) if v != nil {
_c.SetKey(*v)
}
return _c
}
// SetMacos sets the "macos" field.
func (_c *KeyBindingCreate) SetMacos(v string) *KeyBindingCreate {
_c.mutation.SetMacos(v)
return _c
}
// SetNillableMacos sets the "macos" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableMacos(v *string) *KeyBindingCreate {
if v != nil {
_c.SetMacos(*v)
}
return _c
}
// SetWindows sets the "windows" field.
func (_c *KeyBindingCreate) SetWindows(v string) *KeyBindingCreate {
_c.mutation.SetWindows(v)
return _c
}
// SetNillableWindows sets the "windows" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableWindows(v *string) *KeyBindingCreate {
if v != nil {
_c.SetWindows(*v)
}
return _c
}
// SetLinux sets the "linux" field.
func (_c *KeyBindingCreate) SetLinux(v string) *KeyBindingCreate {
_c.mutation.SetLinux(v)
return _c
}
// SetNillableLinux sets the "linux" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableLinux(v *string) *KeyBindingCreate {
if v != nil {
_c.SetLinux(*v)
}
return _c return _c
} }
@@ -93,14 +157,6 @@ func (_c *KeyBindingCreate) SetExtension(v string) *KeyBindingCreate {
return _c return _c
} }
// SetNillableExtension sets the "extension" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableExtension(v *string) *KeyBindingCreate {
if v != nil {
_c.SetExtension(*v)
}
return _c
}
// SetEnabled sets the "enabled" field. // SetEnabled sets the "enabled" field.
func (_c *KeyBindingCreate) SetEnabled(v bool) *KeyBindingCreate { func (_c *KeyBindingCreate) SetEnabled(v bool) *KeyBindingCreate {
_c.mutation.SetEnabled(v) _c.mutation.SetEnabled(v)
@@ -115,6 +171,34 @@ func (_c *KeyBindingCreate) SetNillableEnabled(v *bool) *KeyBindingCreate {
return _c return _c
} }
// SetPreventDefault sets the "prevent_default" field.
func (_c *KeyBindingCreate) SetPreventDefault(v bool) *KeyBindingCreate {
_c.mutation.SetPreventDefault(v)
return _c
}
// SetNillablePreventDefault sets the "prevent_default" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillablePreventDefault(v *bool) *KeyBindingCreate {
if v != nil {
_c.SetPreventDefault(*v)
}
return _c
}
// SetScope sets the "scope" field.
func (_c *KeyBindingCreate) SetScope(v string) *KeyBindingCreate {
_c.mutation.SetScope(v)
return _c
}
// SetNillableScope sets the "scope" field if the given value is not nil.
func (_c *KeyBindingCreate) SetNillableScope(v *string) *KeyBindingCreate {
if v != nil {
_c.SetScope(*v)
}
return _c
}
// Mutation returns the KeyBindingMutation object of the builder. // Mutation returns the KeyBindingMutation object of the builder.
func (_c *KeyBindingCreate) Mutation() *KeyBindingMutation { func (_c *KeyBindingCreate) Mutation() *KeyBindingMutation {
return _c.mutation return _c.mutation
@@ -173,37 +257,75 @@ func (_c *KeyBindingCreate) defaults() error {
v := keybinding.DefaultUpdatedAt() v := keybinding.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v) _c.mutation.SetUpdatedAt(v)
} }
if _, ok := _c.mutation.GetType(); !ok {
v := keybinding.DefaultType
_c.mutation.SetType(v)
}
if _, ok := _c.mutation.Enabled(); !ok { if _, ok := _c.mutation.Enabled(); !ok {
v := keybinding.DefaultEnabled v := keybinding.DefaultEnabled
_c.mutation.SetEnabled(v) _c.mutation.SetEnabled(v)
} }
if _, ok := _c.mutation.PreventDefault(); !ok {
v := keybinding.DefaultPreventDefault
_c.mutation.SetPreventDefault(v)
}
if _, ok := _c.mutation.Scope(); !ok {
v := keybinding.DefaultScope
_c.mutation.SetScope(v)
}
return nil return nil
} }
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_c *KeyBindingCreate) check() error { func (_c *KeyBindingCreate) check() error {
if _, ok := _c.mutation.UUID(); !ok {
return &ValidationError{Name: "uuid", err: errors.New(`ent: missing required field "KeyBinding.uuid"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok { if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "KeyBinding.created_at"`)} return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "KeyBinding.created_at"`)}
} }
if _, ok := _c.mutation.UpdatedAt(); !ok { if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "KeyBinding.updated_at"`)} return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "KeyBinding.updated_at"`)}
} }
if _, ok := _c.mutation.Key(); !ok { if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "KeyBinding.key"`)} return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "KeyBinding.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := keybinding.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.name": %w`, err)}
}
}
if _, ok := _c.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "KeyBinding.type"`)}
}
if v, ok := _c.mutation.GetType(); ok {
if err := keybinding.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.type": %w`, err)}
}
} }
if v, ok := _c.mutation.Key(); ok { if v, ok := _c.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil { if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)} return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
} }
} }
if _, ok := _c.mutation.Command(); !ok { if v, ok := _c.mutation.Macos(); ok {
return &ValidationError{Name: "command", err: errors.New(`ent: missing required field "KeyBinding.command"`)} if err := keybinding.MacosValidator(v); err != nil {
} return &ValidationError{Name: "macos", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.macos": %w`, err)}
if v, ok := _c.mutation.Command(); ok {
if err := keybinding.CommandValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)}
} }
} }
if v, ok := _c.mutation.Windows(); ok {
if err := keybinding.WindowsValidator(v); err != nil {
return &ValidationError{Name: "windows", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.windows": %w`, err)}
}
}
if v, ok := _c.mutation.Linux(); ok {
if err := keybinding.LinuxValidator(v); err != nil {
return &ValidationError{Name: "linux", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.linux": %w`, err)}
}
}
if _, ok := _c.mutation.Extension(); !ok {
return &ValidationError{Name: "extension", err: errors.New(`ent: missing required field "KeyBinding.extension"`)}
}
if v, ok := _c.mutation.Extension(); ok { if v, ok := _c.mutation.Extension(); ok {
if err := keybinding.ExtensionValidator(v); err != nil { if err := keybinding.ExtensionValidator(v); err != nil {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)} return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
@@ -212,6 +334,17 @@ func (_c *KeyBindingCreate) check() error {
if _, ok := _c.mutation.Enabled(); !ok { if _, ok := _c.mutation.Enabled(); !ok {
return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "KeyBinding.enabled"`)} return &ValidationError{Name: "enabled", err: errors.New(`ent: missing required field "KeyBinding.enabled"`)}
} }
if _, ok := _c.mutation.PreventDefault(); !ok {
return &ValidationError{Name: "prevent_default", err: errors.New(`ent: missing required field "KeyBinding.prevent_default"`)}
}
if _, ok := _c.mutation.Scope(); !ok {
return &ValidationError{Name: "scope", err: errors.New(`ent: missing required field "KeyBinding.scope"`)}
}
if v, ok := _c.mutation.Scope(); ok {
if err := keybinding.ScopeValidator(v); err != nil {
return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.scope": %w`, err)}
}
}
return nil return nil
} }
@@ -240,7 +373,7 @@ func (_c *KeyBindingCreate) createSpec() (*KeyBinding, *sqlgraph.CreateSpec) {
) )
if value, ok := _c.mutation.UUID(); ok { if value, ok := _c.mutation.UUID(); ok {
_spec.SetField(keybinding.FieldUUID, field.TypeString, value) _spec.SetField(keybinding.FieldUUID, field.TypeString, value)
_node.UUID = &value _node.UUID = value
} }
if value, ok := _c.mutation.CreatedAt(); ok { if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(keybinding.FieldCreatedAt, field.TypeString, value) _spec.SetField(keybinding.FieldCreatedAt, field.TypeString, value)
@@ -254,13 +387,29 @@ func (_c *KeyBindingCreate) createSpec() (*KeyBinding, *sqlgraph.CreateSpec) {
_spec.SetField(keybinding.FieldDeletedAt, field.TypeString, value) _spec.SetField(keybinding.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value _node.DeletedAt = &value
} }
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(keybinding.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.GetType(); ok {
_spec.SetField(keybinding.FieldType, field.TypeString, value)
_node.Type = value
}
if value, ok := _c.mutation.Key(); ok { if value, ok := _c.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value) _spec.SetField(keybinding.FieldKey, field.TypeString, value)
_node.Key = value _node.Key = value
} }
if value, ok := _c.mutation.Command(); ok { if value, ok := _c.mutation.Macos(); ok {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value) _spec.SetField(keybinding.FieldMacos, field.TypeString, value)
_node.Command = value _node.Macos = value
}
if value, ok := _c.mutation.Windows(); ok {
_spec.SetField(keybinding.FieldWindows, field.TypeString, value)
_node.Windows = value
}
if value, ok := _c.mutation.Linux(); ok {
_spec.SetField(keybinding.FieldLinux, field.TypeString, value)
_node.Linux = value
} }
if value, ok := _c.mutation.Extension(); ok { if value, ok := _c.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value) _spec.SetField(keybinding.FieldExtension, field.TypeString, value)
@@ -270,6 +419,14 @@ func (_c *KeyBindingCreate) createSpec() (*KeyBinding, *sqlgraph.CreateSpec) {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value) _spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
_node.Enabled = value _node.Enabled = value
} }
if value, ok := _c.mutation.PreventDefault(); ok {
_spec.SetField(keybinding.FieldPreventDefault, field.TypeBool, value)
_node.PreventDefault = value
}
if value, ok := _c.mutation.Scope(); ok {
_spec.SetField(keybinding.FieldScope, field.TypeString, value)
_node.Scope = value
}
return _node, _spec return _node, _spec
} }

View File

@@ -62,6 +62,34 @@ func (_u *KeyBindingUpdate) ClearDeletedAt() *KeyBindingUpdate {
return _u return _u
} }
// SetName sets the "name" field.
func (_u *KeyBindingUpdate) SetName(v string) *KeyBindingUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableName(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *KeyBindingUpdate) SetType(v string) *KeyBindingUpdate {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableType(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetKey sets the "key" field. // SetKey sets the "key" field.
func (_u *KeyBindingUpdate) SetKey(v string) *KeyBindingUpdate { func (_u *KeyBindingUpdate) SetKey(v string) *KeyBindingUpdate {
_u.mutation.SetKey(v) _u.mutation.SetKey(v)
@@ -76,20 +104,72 @@ func (_u *KeyBindingUpdate) SetNillableKey(v *string) *KeyBindingUpdate {
return _u return _u
} }
// SetCommand sets the "command" field. // ClearKey clears the value of the "key" field.
func (_u *KeyBindingUpdate) SetCommand(v string) *KeyBindingUpdate { func (_u *KeyBindingUpdate) ClearKey() *KeyBindingUpdate {
_u.mutation.SetCommand(v) _u.mutation.ClearKey()
return _u return _u
} }
// SetNillableCommand sets the "command" field if the given value is not nil. // SetMacos sets the "macos" field.
func (_u *KeyBindingUpdate) SetNillableCommand(v *string) *KeyBindingUpdate { func (_u *KeyBindingUpdate) SetMacos(v string) *KeyBindingUpdate {
_u.mutation.SetMacos(v)
return _u
}
// SetNillableMacos sets the "macos" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableMacos(v *string) *KeyBindingUpdate {
if v != nil { if v != nil {
_u.SetCommand(*v) _u.SetMacos(*v)
} }
return _u return _u
} }
// ClearMacos clears the value of the "macos" field.
func (_u *KeyBindingUpdate) ClearMacos() *KeyBindingUpdate {
_u.mutation.ClearMacos()
return _u
}
// SetWindows sets the "windows" field.
func (_u *KeyBindingUpdate) SetWindows(v string) *KeyBindingUpdate {
_u.mutation.SetWindows(v)
return _u
}
// SetNillableWindows sets the "windows" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableWindows(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetWindows(*v)
}
return _u
}
// ClearWindows clears the value of the "windows" field.
func (_u *KeyBindingUpdate) ClearWindows() *KeyBindingUpdate {
_u.mutation.ClearWindows()
return _u
}
// SetLinux sets the "linux" field.
func (_u *KeyBindingUpdate) SetLinux(v string) *KeyBindingUpdate {
_u.mutation.SetLinux(v)
return _u
}
// SetNillableLinux sets the "linux" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableLinux(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetLinux(*v)
}
return _u
}
// ClearLinux clears the value of the "linux" field.
func (_u *KeyBindingUpdate) ClearLinux() *KeyBindingUpdate {
_u.mutation.ClearLinux()
return _u
}
// SetExtension sets the "extension" field. // SetExtension sets the "extension" field.
func (_u *KeyBindingUpdate) SetExtension(v string) *KeyBindingUpdate { func (_u *KeyBindingUpdate) SetExtension(v string) *KeyBindingUpdate {
_u.mutation.SetExtension(v) _u.mutation.SetExtension(v)
@@ -104,12 +184,6 @@ func (_u *KeyBindingUpdate) SetNillableExtension(v *string) *KeyBindingUpdate {
return _u return _u
} }
// ClearExtension clears the value of the "extension" field.
func (_u *KeyBindingUpdate) ClearExtension() *KeyBindingUpdate {
_u.mutation.ClearExtension()
return _u
}
// SetEnabled sets the "enabled" field. // SetEnabled sets the "enabled" field.
func (_u *KeyBindingUpdate) SetEnabled(v bool) *KeyBindingUpdate { func (_u *KeyBindingUpdate) SetEnabled(v bool) *KeyBindingUpdate {
_u.mutation.SetEnabled(v) _u.mutation.SetEnabled(v)
@@ -124,6 +198,34 @@ func (_u *KeyBindingUpdate) SetNillableEnabled(v *bool) *KeyBindingUpdate {
return _u return _u
} }
// SetPreventDefault sets the "prevent_default" field.
func (_u *KeyBindingUpdate) SetPreventDefault(v bool) *KeyBindingUpdate {
_u.mutation.SetPreventDefault(v)
return _u
}
// SetNillablePreventDefault sets the "prevent_default" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillablePreventDefault(v *bool) *KeyBindingUpdate {
if v != nil {
_u.SetPreventDefault(*v)
}
return _u
}
// SetScope sets the "scope" field.
func (_u *KeyBindingUpdate) SetScope(v string) *KeyBindingUpdate {
_u.mutation.SetScope(v)
return _u
}
// SetNillableScope sets the "scope" field if the given value is not nil.
func (_u *KeyBindingUpdate) SetNillableScope(v *string) *KeyBindingUpdate {
if v != nil {
_u.SetScope(*v)
}
return _u
}
// Mutation returns the KeyBindingMutation object of the builder. // Mutation returns the KeyBindingMutation object of the builder.
func (_u *KeyBindingUpdate) Mutation() *KeyBindingMutation { func (_u *KeyBindingUpdate) Mutation() *KeyBindingMutation {
return _u.mutation return _u.mutation
@@ -158,14 +260,34 @@ func (_u *KeyBindingUpdate) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *KeyBindingUpdate) check() error { func (_u *KeyBindingUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := keybinding.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.name": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := keybinding.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.type": %w`, err)}
}
}
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil { if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)} return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
} }
} }
if v, ok := _u.mutation.Command(); ok { if v, ok := _u.mutation.Macos(); ok {
if err := keybinding.CommandValidator(v); err != nil { if err := keybinding.MacosValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)} return &ValidationError{Name: "macos", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.macos": %w`, err)}
}
}
if v, ok := _u.mutation.Windows(); ok {
if err := keybinding.WindowsValidator(v); err != nil {
return &ValidationError{Name: "windows", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.windows": %w`, err)}
}
}
if v, ok := _u.mutation.Linux(); ok {
if err := keybinding.LinuxValidator(v); err != nil {
return &ValidationError{Name: "linux", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.linux": %w`, err)}
} }
} }
if v, ok := _u.mutation.Extension(); ok { if v, ok := _u.mutation.Extension(); ok {
@@ -173,6 +295,11 @@ func (_u *KeyBindingUpdate) check() error {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)} return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
} }
} }
if v, ok := _u.mutation.Scope(); ok {
if err := keybinding.ScopeValidator(v); err != nil {
return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.scope": %w`, err)}
}
}
return nil return nil
} }
@@ -194,9 +321,6 @@ func (_u *KeyBindingUpdate) sqlSave(ctx context.Context) (_node int, err error)
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(keybinding.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value) _spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value)
} }
@@ -206,21 +330,48 @@ func (_u *KeyBindingUpdate) sqlSave(ctx context.Context) (_node int, err error)
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(keybinding.FieldDeletedAt, field.TypeString) _spec.ClearField(keybinding.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(keybinding.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(keybinding.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value) _spec.SetField(keybinding.FieldKey, field.TypeString, value)
} }
if value, ok := _u.mutation.Command(); ok { if _u.mutation.KeyCleared() {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value) _spec.ClearField(keybinding.FieldKey, field.TypeString)
}
if value, ok := _u.mutation.Macos(); ok {
_spec.SetField(keybinding.FieldMacos, field.TypeString, value)
}
if _u.mutation.MacosCleared() {
_spec.ClearField(keybinding.FieldMacos, field.TypeString)
}
if value, ok := _u.mutation.Windows(); ok {
_spec.SetField(keybinding.FieldWindows, field.TypeString, value)
}
if _u.mutation.WindowsCleared() {
_spec.ClearField(keybinding.FieldWindows, field.TypeString)
}
if value, ok := _u.mutation.Linux(); ok {
_spec.SetField(keybinding.FieldLinux, field.TypeString, value)
}
if _u.mutation.LinuxCleared() {
_spec.ClearField(keybinding.FieldLinux, field.TypeString)
} }
if value, ok := _u.mutation.Extension(); ok { if value, ok := _u.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value) _spec.SetField(keybinding.FieldExtension, field.TypeString, value)
} }
if _u.mutation.ExtensionCleared() {
_spec.ClearField(keybinding.FieldExtension, field.TypeString)
}
if value, ok := _u.mutation.Enabled(); ok { if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value) _spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
} }
if value, ok := _u.mutation.PreventDefault(); ok {
_spec.SetField(keybinding.FieldPreventDefault, field.TypeBool, value)
}
if value, ok := _u.mutation.Scope(); ok {
_spec.SetField(keybinding.FieldScope, field.TypeString, value)
}
_spec.AddModifiers(_u.modifiers...) _spec.AddModifiers(_u.modifiers...)
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
@@ -277,6 +428,34 @@ func (_u *KeyBindingUpdateOne) ClearDeletedAt() *KeyBindingUpdateOne {
return _u return _u
} }
// SetName sets the "name" field.
func (_u *KeyBindingUpdateOne) SetName(v string) *KeyBindingUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableName(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetType sets the "type" field.
func (_u *KeyBindingUpdateOne) SetType(v string) *KeyBindingUpdateOne {
_u.mutation.SetType(v)
return _u
}
// SetNillableType sets the "type" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableType(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetType(*v)
}
return _u
}
// SetKey sets the "key" field. // SetKey sets the "key" field.
func (_u *KeyBindingUpdateOne) SetKey(v string) *KeyBindingUpdateOne { func (_u *KeyBindingUpdateOne) SetKey(v string) *KeyBindingUpdateOne {
_u.mutation.SetKey(v) _u.mutation.SetKey(v)
@@ -291,20 +470,72 @@ func (_u *KeyBindingUpdateOne) SetNillableKey(v *string) *KeyBindingUpdateOne {
return _u return _u
} }
// SetCommand sets the "command" field. // ClearKey clears the value of the "key" field.
func (_u *KeyBindingUpdateOne) SetCommand(v string) *KeyBindingUpdateOne { func (_u *KeyBindingUpdateOne) ClearKey() *KeyBindingUpdateOne {
_u.mutation.SetCommand(v) _u.mutation.ClearKey()
return _u return _u
} }
// SetNillableCommand sets the "command" field if the given value is not nil. // SetMacos sets the "macos" field.
func (_u *KeyBindingUpdateOne) SetNillableCommand(v *string) *KeyBindingUpdateOne { func (_u *KeyBindingUpdateOne) SetMacos(v string) *KeyBindingUpdateOne {
_u.mutation.SetMacos(v)
return _u
}
// SetNillableMacos sets the "macos" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableMacos(v *string) *KeyBindingUpdateOne {
if v != nil { if v != nil {
_u.SetCommand(*v) _u.SetMacos(*v)
} }
return _u return _u
} }
// ClearMacos clears the value of the "macos" field.
func (_u *KeyBindingUpdateOne) ClearMacos() *KeyBindingUpdateOne {
_u.mutation.ClearMacos()
return _u
}
// SetWindows sets the "windows" field.
func (_u *KeyBindingUpdateOne) SetWindows(v string) *KeyBindingUpdateOne {
_u.mutation.SetWindows(v)
return _u
}
// SetNillableWindows sets the "windows" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableWindows(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetWindows(*v)
}
return _u
}
// ClearWindows clears the value of the "windows" field.
func (_u *KeyBindingUpdateOne) ClearWindows() *KeyBindingUpdateOne {
_u.mutation.ClearWindows()
return _u
}
// SetLinux sets the "linux" field.
func (_u *KeyBindingUpdateOne) SetLinux(v string) *KeyBindingUpdateOne {
_u.mutation.SetLinux(v)
return _u
}
// SetNillableLinux sets the "linux" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableLinux(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetLinux(*v)
}
return _u
}
// ClearLinux clears the value of the "linux" field.
func (_u *KeyBindingUpdateOne) ClearLinux() *KeyBindingUpdateOne {
_u.mutation.ClearLinux()
return _u
}
// SetExtension sets the "extension" field. // SetExtension sets the "extension" field.
func (_u *KeyBindingUpdateOne) SetExtension(v string) *KeyBindingUpdateOne { func (_u *KeyBindingUpdateOne) SetExtension(v string) *KeyBindingUpdateOne {
_u.mutation.SetExtension(v) _u.mutation.SetExtension(v)
@@ -319,12 +550,6 @@ func (_u *KeyBindingUpdateOne) SetNillableExtension(v *string) *KeyBindingUpdate
return _u return _u
} }
// ClearExtension clears the value of the "extension" field.
func (_u *KeyBindingUpdateOne) ClearExtension() *KeyBindingUpdateOne {
_u.mutation.ClearExtension()
return _u
}
// SetEnabled sets the "enabled" field. // SetEnabled sets the "enabled" field.
func (_u *KeyBindingUpdateOne) SetEnabled(v bool) *KeyBindingUpdateOne { func (_u *KeyBindingUpdateOne) SetEnabled(v bool) *KeyBindingUpdateOne {
_u.mutation.SetEnabled(v) _u.mutation.SetEnabled(v)
@@ -339,6 +564,34 @@ func (_u *KeyBindingUpdateOne) SetNillableEnabled(v *bool) *KeyBindingUpdateOne
return _u return _u
} }
// SetPreventDefault sets the "prevent_default" field.
func (_u *KeyBindingUpdateOne) SetPreventDefault(v bool) *KeyBindingUpdateOne {
_u.mutation.SetPreventDefault(v)
return _u
}
// SetNillablePreventDefault sets the "prevent_default" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillablePreventDefault(v *bool) *KeyBindingUpdateOne {
if v != nil {
_u.SetPreventDefault(*v)
}
return _u
}
// SetScope sets the "scope" field.
func (_u *KeyBindingUpdateOne) SetScope(v string) *KeyBindingUpdateOne {
_u.mutation.SetScope(v)
return _u
}
// SetNillableScope sets the "scope" field if the given value is not nil.
func (_u *KeyBindingUpdateOne) SetNillableScope(v *string) *KeyBindingUpdateOne {
if v != nil {
_u.SetScope(*v)
}
return _u
}
// Mutation returns the KeyBindingMutation object of the builder. // Mutation returns the KeyBindingMutation object of the builder.
func (_u *KeyBindingUpdateOne) Mutation() *KeyBindingMutation { func (_u *KeyBindingUpdateOne) Mutation() *KeyBindingMutation {
return _u.mutation return _u.mutation
@@ -386,14 +639,34 @@ func (_u *KeyBindingUpdateOne) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *KeyBindingUpdateOne) check() error { func (_u *KeyBindingUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := keybinding.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.name": %w`, err)}
}
}
if v, ok := _u.mutation.GetType(); ok {
if err := keybinding.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.type": %w`, err)}
}
}
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Key(); ok {
if err := keybinding.KeyValidator(v); err != nil { if err := keybinding.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)} return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.key": %w`, err)}
} }
} }
if v, ok := _u.mutation.Command(); ok { if v, ok := _u.mutation.Macos(); ok {
if err := keybinding.CommandValidator(v); err != nil { if err := keybinding.MacosValidator(v); err != nil {
return &ValidationError{Name: "command", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.command": %w`, err)} return &ValidationError{Name: "macos", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.macos": %w`, err)}
}
}
if v, ok := _u.mutation.Windows(); ok {
if err := keybinding.WindowsValidator(v); err != nil {
return &ValidationError{Name: "windows", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.windows": %w`, err)}
}
}
if v, ok := _u.mutation.Linux(); ok {
if err := keybinding.LinuxValidator(v); err != nil {
return &ValidationError{Name: "linux", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.linux": %w`, err)}
} }
} }
if v, ok := _u.mutation.Extension(); ok { if v, ok := _u.mutation.Extension(); ok {
@@ -401,6 +674,11 @@ func (_u *KeyBindingUpdateOne) check() error {
return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)} return &ValidationError{Name: "extension", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.extension": %w`, err)}
} }
} }
if v, ok := _u.mutation.Scope(); ok {
if err := keybinding.ScopeValidator(v); err != nil {
return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "KeyBinding.scope": %w`, err)}
}
}
return nil return nil
} }
@@ -439,9 +717,6 @@ func (_u *KeyBindingUpdateOne) sqlSave(ctx context.Context) (_node *KeyBinding,
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(keybinding.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value) _spec.SetField(keybinding.FieldUpdatedAt, field.TypeString, value)
} }
@@ -451,21 +726,48 @@ func (_u *KeyBindingUpdateOne) sqlSave(ctx context.Context) (_node *KeyBinding,
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(keybinding.FieldDeletedAt, field.TypeString) _spec.ClearField(keybinding.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(keybinding.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(keybinding.FieldType, field.TypeString, value)
}
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Key(); ok {
_spec.SetField(keybinding.FieldKey, field.TypeString, value) _spec.SetField(keybinding.FieldKey, field.TypeString, value)
} }
if value, ok := _u.mutation.Command(); ok { if _u.mutation.KeyCleared() {
_spec.SetField(keybinding.FieldCommand, field.TypeString, value) _spec.ClearField(keybinding.FieldKey, field.TypeString)
}
if value, ok := _u.mutation.Macos(); ok {
_spec.SetField(keybinding.FieldMacos, field.TypeString, value)
}
if _u.mutation.MacosCleared() {
_spec.ClearField(keybinding.FieldMacos, field.TypeString)
}
if value, ok := _u.mutation.Windows(); ok {
_spec.SetField(keybinding.FieldWindows, field.TypeString, value)
}
if _u.mutation.WindowsCleared() {
_spec.ClearField(keybinding.FieldWindows, field.TypeString)
}
if value, ok := _u.mutation.Linux(); ok {
_spec.SetField(keybinding.FieldLinux, field.TypeString, value)
}
if _u.mutation.LinuxCleared() {
_spec.ClearField(keybinding.FieldLinux, field.TypeString)
} }
if value, ok := _u.mutation.Extension(); ok { if value, ok := _u.mutation.Extension(); ok {
_spec.SetField(keybinding.FieldExtension, field.TypeString, value) _spec.SetField(keybinding.FieldExtension, field.TypeString, value)
} }
if _u.mutation.ExtensionCleared() {
_spec.ClearField(keybinding.FieldExtension, field.TypeString)
}
if value, ok := _u.mutation.Enabled(); ok { if value, ok := _u.mutation.Enabled(); ok {
_spec.SetField(keybinding.FieldEnabled, field.TypeBool, value) _spec.SetField(keybinding.FieldEnabled, field.TypeBool, value)
} }
if value, ok := _u.mutation.PreventDefault(); ok {
_spec.SetField(keybinding.FieldPreventDefault, field.TypeBool, value)
}
if value, ok := _u.mutation.Scope(); ok {
_spec.SetField(keybinding.FieldScope, field.TypeString, value)
}
_spec.AddModifiers(_u.modifiers...) _spec.AddModifiers(_u.modifiers...)
_node = &KeyBinding{config: _u.config} _node = &KeyBinding{config: _u.config}
_spec.Assign = _node.assignValues _spec.Assign = _node.assignValues

View File

@@ -12,7 +12,7 @@ var (
// DocumentsColumns holds the columns for the "documents" table. // DocumentsColumns holds the columns for the "documents" table.
DocumentsColumns = []*schema.Column{ DocumentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeInt, Increment: true},
{Name: "uuid", Type: field.TypeString, Unique: true, Nullable: true}, {Name: "uuid", Type: field.TypeString, Unique: true},
{Name: "created_at", Type: field.TypeString}, {Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString}, {Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true}, {Name: "deleted_at", Type: field.TypeString, Nullable: true},
@@ -56,11 +56,11 @@ var (
// ExtensionsColumns holds the columns for the "extensions" table. // ExtensionsColumns holds the columns for the "extensions" table.
ExtensionsColumns = []*schema.Column{ ExtensionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeInt, Increment: true},
{Name: "uuid", Type: field.TypeString, Unique: true, Nullable: true}, {Name: "uuid", Type: field.TypeString, Unique: true},
{Name: "created_at", Type: field.TypeString}, {Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString}, {Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true}, {Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100}, {Name: "name", Type: field.TypeString, Unique: true, Size: 100},
{Name: "enabled", Type: field.TypeBool, Default: true}, {Name: "enabled", Type: field.TypeBool, Default: true},
{Name: "config", Type: field.TypeJSON, Nullable: true}, {Name: "config", Type: field.TypeJSON, Nullable: true},
} }
@@ -90,14 +90,20 @@ var (
// KeyBindingsColumns holds the columns for the "key_bindings" table. // KeyBindingsColumns holds the columns for the "key_bindings" table.
KeyBindingsColumns = []*schema.Column{ KeyBindingsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeInt, Increment: true},
{Name: "uuid", Type: field.TypeString, Unique: true, Nullable: true}, {Name: "uuid", Type: field.TypeString, Unique: true},
{Name: "created_at", Type: field.TypeString}, {Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString}, {Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true}, {Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100}, {Name: "name", Type: field.TypeString, Size: 100},
{Name: "command", Type: field.TypeString, Size: 100}, {Name: "type", Type: field.TypeString, Size: 20, Default: "standard"},
{Name: "extension", Type: field.TypeString, Nullable: true, Size: 100}, {Name: "key", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "macos", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "windows", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "linux", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "extension", Type: field.TypeString, Size: 100},
{Name: "enabled", Type: field.TypeBool, Default: true}, {Name: "enabled", Type: field.TypeBool, Default: true},
{Name: "prevent_default", Type: field.TypeBool, Default: true},
{Name: "scope", Type: field.TypeString, Size: 100, Default: "editor"},
} }
// KeyBindingsTable holds the schema information for the "key_bindings" table. // KeyBindingsTable holds the schema information for the "key_bindings" table.
KeyBindingsTable = &schema.Table{ KeyBindingsTable = &schema.Table{
@@ -115,26 +121,41 @@ var (
Unique: false, Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[4]}, Columns: []*schema.Column{KeyBindingsColumns[4]},
}, },
{
Name: "keybinding_name",
Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[5]},
},
{
Name: "keybinding_type",
Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[6]},
},
{
Name: "keybinding_type_name",
Unique: true,
Columns: []*schema.Column{KeyBindingsColumns[6], KeyBindingsColumns[5]},
},
{ {
Name: "keybinding_extension", Name: "keybinding_extension",
Unique: false, Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[7]}, Columns: []*schema.Column{KeyBindingsColumns[11]},
}, },
{ {
Name: "keybinding_enabled", Name: "keybinding_enabled",
Unique: false, Unique: false,
Columns: []*schema.Column{KeyBindingsColumns[8]}, Columns: []*schema.Column{KeyBindingsColumns[12]},
}, },
}, },
} }
// ThemesColumns holds the columns for the "themes" table. // ThemesColumns holds the columns for the "themes" table.
ThemesColumns = []*schema.Column{ ThemesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeInt, Increment: true},
{Name: "uuid", Type: field.TypeString, Unique: true, Nullable: true}, {Name: "uuid", Type: field.TypeString, Unique: true},
{Name: "created_at", Type: field.TypeString}, {Name: "created_at", Type: field.TypeString},
{Name: "updated_at", Type: field.TypeString}, {Name: "updated_at", Type: field.TypeString},
{Name: "deleted_at", Type: field.TypeString, Nullable: true}, {Name: "deleted_at", Type: field.TypeString, Nullable: true},
{Name: "key", Type: field.TypeString, Unique: true, Size: 100}, {Name: "name", Type: field.TypeString, Unique: true, Size: 100},
{Name: "type", Type: field.TypeEnum, Enums: []string{"dark", "light"}}, {Name: "type", Type: field.TypeEnum, Enums: []string{"dark", "light"}},
{Name: "colors", Type: field.TypeJSON, Nullable: true}, {Name: "colors", Type: field.TypeJSON, Nullable: true},
} }

File diff suppressed because it is too large Load Diff

View File

@@ -90,18 +90,18 @@ func init() {
extensionDescUpdatedAt := extensionMixinFields1[1].Descriptor() extensionDescUpdatedAt := extensionMixinFields1[1].Descriptor()
// extension.DefaultUpdatedAt holds the default value on creation for the updated_at field. // extension.DefaultUpdatedAt holds the default value on creation for the updated_at field.
extension.DefaultUpdatedAt = extensionDescUpdatedAt.Default.(func() string) extension.DefaultUpdatedAt = extensionDescUpdatedAt.Default.(func() string)
// extensionDescKey is the schema descriptor for key field. // extensionDescName is the schema descriptor for name field.
extensionDescKey := extensionFields[0].Descriptor() extensionDescName := extensionFields[0].Descriptor()
// extension.KeyValidator is a validator for the "key" field. It is called by the builders before save. // extension.NameValidator is a validator for the "name" field. It is called by the builders before save.
extension.KeyValidator = func() func(string) error { extension.NameValidator = func() func(string) error {
validators := extensionDescKey.Validators validators := extensionDescName.Validators
fns := [...]func(string) error{ fns := [...]func(string) error{
validators[0].(func(string) error), validators[0].(func(string) error),
validators[1].(func(string) error), validators[1].(func(string) error),
} }
return func(key string) error { return func(name string) error {
for _, fn := range fns { for _, fn := range fns {
if err := fn(key); err != nil { if err := fn(name); err != nil {
return err return err
} }
} }
@@ -137,50 +137,78 @@ func init() {
keybindingDescUpdatedAt := keybindingMixinFields1[1].Descriptor() keybindingDescUpdatedAt := keybindingMixinFields1[1].Descriptor()
// keybinding.DefaultUpdatedAt holds the default value on creation for the updated_at field. // keybinding.DefaultUpdatedAt holds the default value on creation for the updated_at field.
keybinding.DefaultUpdatedAt = keybindingDescUpdatedAt.Default.(func() string) keybinding.DefaultUpdatedAt = keybindingDescUpdatedAt.Default.(func() string)
// keybindingDescName is the schema descriptor for name field.
keybindingDescName := keybindingFields[0].Descriptor()
// keybinding.NameValidator is a validator for the "name" field. It is called by the builders before save.
keybinding.NameValidator = func() func(string) error {
validators := keybindingDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// keybindingDescType is the schema descriptor for type field.
keybindingDescType := keybindingFields[1].Descriptor()
// keybinding.DefaultType holds the default value on creation for the type field.
keybinding.DefaultType = keybindingDescType.Default.(string)
// keybinding.TypeValidator is a validator for the "type" field. It is called by the builders before save.
keybinding.TypeValidator = keybindingDescType.Validators[0].(func(string) error)
// keybindingDescKey is the schema descriptor for key field. // keybindingDescKey is the schema descriptor for key field.
keybindingDescKey := keybindingFields[0].Descriptor() keybindingDescKey := keybindingFields[2].Descriptor()
// keybinding.KeyValidator is a validator for the "key" field. It is called by the builders before save. // keybinding.KeyValidator is a validator for the "key" field. It is called by the builders before save.
keybinding.KeyValidator = func() func(string) error { keybinding.KeyValidator = keybindingDescKey.Validators[0].(func(string) error)
validators := keybindingDescKey.Validators // keybindingDescMacos is the schema descriptor for macos field.
fns := [...]func(string) error{ keybindingDescMacos := keybindingFields[3].Descriptor()
validators[0].(func(string) error), // keybinding.MacosValidator is a validator for the "macos" field. It is called by the builders before save.
validators[1].(func(string) error), keybinding.MacosValidator = keybindingDescMacos.Validators[0].(func(string) error)
} // keybindingDescWindows is the schema descriptor for windows field.
return func(key string) error { keybindingDescWindows := keybindingFields[4].Descriptor()
for _, fn := range fns { // keybinding.WindowsValidator is a validator for the "windows" field. It is called by the builders before save.
if err := fn(key); err != nil { keybinding.WindowsValidator = keybindingDescWindows.Validators[0].(func(string) error)
return err // keybindingDescLinux is the schema descriptor for linux field.
} keybindingDescLinux := keybindingFields[5].Descriptor()
} // keybinding.LinuxValidator is a validator for the "linux" field. It is called by the builders before save.
return nil keybinding.LinuxValidator = keybindingDescLinux.Validators[0].(func(string) error)
}
}()
// keybindingDescCommand is the schema descriptor for command field.
keybindingDescCommand := keybindingFields[1].Descriptor()
// keybinding.CommandValidator is a validator for the "command" field. It is called by the builders before save.
keybinding.CommandValidator = func() func(string) error {
validators := keybindingDescCommand.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(command string) error {
for _, fn := range fns {
if err := fn(command); err != nil {
return err
}
}
return nil
}
}()
// keybindingDescExtension is the schema descriptor for extension field. // keybindingDescExtension is the schema descriptor for extension field.
keybindingDescExtension := keybindingFields[2].Descriptor() keybindingDescExtension := keybindingFields[6].Descriptor()
// keybinding.ExtensionValidator is a validator for the "extension" field. It is called by the builders before save. // keybinding.ExtensionValidator is a validator for the "extension" field. It is called by the builders before save.
keybinding.ExtensionValidator = keybindingDescExtension.Validators[0].(func(string) error) keybinding.ExtensionValidator = func() func(string) error {
validators := keybindingDescExtension.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(extension string) error {
for _, fn := range fns {
if err := fn(extension); err != nil {
return err
}
}
return nil
}
}()
// keybindingDescEnabled is the schema descriptor for enabled field. // keybindingDescEnabled is the schema descriptor for enabled field.
keybindingDescEnabled := keybindingFields[3].Descriptor() keybindingDescEnabled := keybindingFields[7].Descriptor()
// keybinding.DefaultEnabled holds the default value on creation for the enabled field. // keybinding.DefaultEnabled holds the default value on creation for the enabled field.
keybinding.DefaultEnabled = keybindingDescEnabled.Default.(bool) keybinding.DefaultEnabled = keybindingDescEnabled.Default.(bool)
// keybindingDescPreventDefault is the schema descriptor for prevent_default field.
keybindingDescPreventDefault := keybindingFields[8].Descriptor()
// keybinding.DefaultPreventDefault holds the default value on creation for the prevent_default field.
keybinding.DefaultPreventDefault = keybindingDescPreventDefault.Default.(bool)
// keybindingDescScope is the schema descriptor for scope field.
keybindingDescScope := keybindingFields[9].Descriptor()
// keybinding.DefaultScope holds the default value on creation for the scope field.
keybinding.DefaultScope = keybindingDescScope.Default.(string)
// keybinding.ScopeValidator is a validator for the "scope" field. It is called by the builders before save.
keybinding.ScopeValidator = keybindingDescScope.Validators[0].(func(string) error)
themeMixin := schema.Theme{}.Mixin() themeMixin := schema.Theme{}.Mixin()
themeMixinHooks1 := themeMixin[1].Hooks() themeMixinHooks1 := themeMixin[1].Hooks()
themeMixinHooks2 := themeMixin[2].Hooks() themeMixinHooks2 := themeMixin[2].Hooks()
@@ -206,18 +234,18 @@ func init() {
themeDescUpdatedAt := themeMixinFields1[1].Descriptor() themeDescUpdatedAt := themeMixinFields1[1].Descriptor()
// theme.DefaultUpdatedAt holds the default value on creation for the updated_at field. // theme.DefaultUpdatedAt holds the default value on creation for the updated_at field.
theme.DefaultUpdatedAt = themeDescUpdatedAt.Default.(func() string) theme.DefaultUpdatedAt = themeDescUpdatedAt.Default.(func() string)
// themeDescKey is the schema descriptor for key field. // themeDescName is the schema descriptor for name field.
themeDescKey := themeFields[0].Descriptor() themeDescName := themeFields[0].Descriptor()
// theme.KeyValidator is a validator for the "key" field. It is called by the builders before save. // theme.NameValidator is a validator for the "name" field. It is called by the builders before save.
theme.KeyValidator = func() func(string) error { theme.NameValidator = func() func(string) error {
validators := themeDescKey.Validators validators := themeDescName.Validators
fns := [...]func(string) error{ fns := [...]func(string) error{
validators[0].(func(string) error), validators[0].(func(string) error),
validators[1].(func(string) error), validators[1].(func(string) error),
} }
return func(key string) error { return func(name string) error {
for _, fn := range fns { for _, fn := range fns {
if err := fn(key); err != nil { if err := fn(name); err != nil {
return err return err
} }
} }

View File

@@ -18,15 +18,15 @@ type Theme struct {
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID int `json:"id,omitempty"`
// UUID for cross-device sync (UUIDv7) // UUID for cross-device sync (UUIDv7)
UUID *string `json:"uuid"` UUID string `json:"uuid"`
// creation time // creation time
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
// update time // update time
UpdatedAt string `json:"updated_at"` UpdatedAt string `json:"updated_at"`
// deleted at // deleted at
DeletedAt *string `json:"deleted_at,omitempty"` DeletedAt *string `json:"deleted_at,omitempty"`
// theme key // theme name
Key string `json:"key"` Name string `json:"name"`
// theme type // theme type
Type theme.Type `json:"type"` Type theme.Type `json:"type"`
// theme colors // theme colors
@@ -43,7 +43,7 @@ func (*Theme) scanValues(columns []string) ([]any, error) {
values[i] = new([]byte) values[i] = new([]byte)
case theme.FieldID: case theme.FieldID:
values[i] = new(sql.NullInt64) values[i] = new(sql.NullInt64)
case theme.FieldUUID, theme.FieldCreatedAt, theme.FieldUpdatedAt, theme.FieldDeletedAt, theme.FieldKey, theme.FieldType: case theme.FieldUUID, theme.FieldCreatedAt, theme.FieldUpdatedAt, theme.FieldDeletedAt, theme.FieldName, theme.FieldType:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
default: default:
values[i] = new(sql.UnknownType) values[i] = new(sql.UnknownType)
@@ -70,8 +70,7 @@ func (_m *Theme) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field uuid", values[i]) return fmt.Errorf("unexpected type %T for field uuid", values[i])
} else if value.Valid { } else if value.Valid {
_m.UUID = new(string) _m.UUID = value.String
*_m.UUID = value.String
} }
case theme.FieldCreatedAt: case theme.FieldCreatedAt:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -92,11 +91,11 @@ func (_m *Theme) assignValues(columns []string, values []any) error {
_m.DeletedAt = new(string) _m.DeletedAt = new(string)
*_m.DeletedAt = value.String *_m.DeletedAt = value.String
} }
case theme.FieldKey: case theme.FieldName:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i]) return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid { } else if value.Valid {
_m.Key = value.String _m.Name = value.String
} }
case theme.FieldType: case theme.FieldType:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -148,10 +147,8 @@ func (_m *Theme) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("Theme(") builder.WriteString("Theme(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
if v := _m.UUID; v != nil { builder.WriteString("uuid=")
builder.WriteString("uuid=") builder.WriteString(_m.UUID)
builder.WriteString(*v)
}
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("created_at=") builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt) builder.WriteString(_m.CreatedAt)
@@ -164,8 +161,8 @@ func (_m *Theme) String() string {
builder.WriteString(*v) builder.WriteString(*v)
} }
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("key=") builder.WriteString("name=")
builder.WriteString(_m.Key) builder.WriteString(_m.Name)
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("type=") builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", _m.Type)) builder.WriteString(fmt.Sprintf("%v", _m.Type))

View File

@@ -22,8 +22,8 @@ const (
FieldUpdatedAt = "updated_at" FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database. // FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at" FieldDeletedAt = "deleted_at"
// FieldKey holds the string denoting the key field in the database. // FieldName holds the string denoting the name field in the database.
FieldKey = "key" FieldName = "name"
// FieldType holds the string denoting the type field in the database. // FieldType holds the string denoting the type field in the database.
FieldType = "type" FieldType = "type"
// FieldColors holds the string denoting the colors field in the database. // FieldColors holds the string denoting the colors field in the database.
@@ -39,7 +39,7 @@ var Columns = []string{
FieldCreatedAt, FieldCreatedAt,
FieldUpdatedAt, FieldUpdatedAt,
FieldDeletedAt, FieldDeletedAt,
FieldKey, FieldName,
FieldType, FieldType,
FieldColors, FieldColors,
} }
@@ -68,8 +68,8 @@ var (
DefaultCreatedAt func() string DefaultCreatedAt func() string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field. // DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() string DefaultUpdatedAt func() string
// KeyValidator is a validator for the "key" field. It is called by the builders before save. // NameValidator is a validator for the "name" field. It is called by the builders before save.
KeyValidator func(string) error NameValidator func(string) error
) )
// Type defines the type for the "type" enum field. // Type defines the type for the "type" enum field.
@@ -123,9 +123,9 @@ func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
} }
// ByKey orders the results by the key field. // ByName orders the results by the name field.
func ByKey(opts ...sql.OrderTermOption) OrderOption { func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc() return sql.OrderByField(FieldName, opts...).ToFunc()
} }
// ByType orders the results by the type field. // ByType orders the results by the type field.

View File

@@ -73,9 +73,9 @@ func DeletedAt(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldDeletedAt, v)) return predicate.Theme(sql.FieldEQ(FieldDeletedAt, v))
} }
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. // Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Key(v string) predicate.Theme { func Name(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldKey, v)) return predicate.Theme(sql.FieldEQ(FieldName, v))
} }
// UUIDEQ applies the EQ predicate on the "uuid" field. // UUIDEQ applies the EQ predicate on the "uuid" field.
@@ -133,16 +133,6 @@ func UUIDHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldUUID, v)) return predicate.Theme(sql.FieldHasSuffix(FieldUUID, v))
} }
// UUIDIsNil applies the IsNil predicate on the "uuid" field.
func UUIDIsNil() predicate.Theme {
return predicate.Theme(sql.FieldIsNull(FieldUUID))
}
// UUIDNotNil applies the NotNil predicate on the "uuid" field.
func UUIDNotNil() predicate.Theme {
return predicate.Theme(sql.FieldNotNull(FieldUUID))
}
// UUIDEqualFold applies the EqualFold predicate on the "uuid" field. // UUIDEqualFold applies the EqualFold predicate on the "uuid" field.
func UUIDEqualFold(v string) predicate.Theme { func UUIDEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldUUID, v)) return predicate.Theme(sql.FieldEqualFold(FieldUUID, v))
@@ -358,69 +348,69 @@ func DeletedAtContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldDeletedAt, v)) return predicate.Theme(sql.FieldContainsFold(FieldDeletedAt, v))
} }
// KeyEQ applies the EQ predicate on the "key" field. // NameEQ applies the EQ predicate on the "name" field.
func KeyEQ(v string) predicate.Theme { func NameEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldEQ(FieldKey, v)) return predicate.Theme(sql.FieldEQ(FieldName, v))
} }
// KeyNEQ applies the NEQ predicate on the "key" field. // NameNEQ applies the NEQ predicate on the "name" field.
func KeyNEQ(v string) predicate.Theme { func NameNEQ(v string) predicate.Theme {
return predicate.Theme(sql.FieldNEQ(FieldKey, v)) return predicate.Theme(sql.FieldNEQ(FieldName, v))
} }
// KeyIn applies the In predicate on the "key" field. // NameIn applies the In predicate on the "name" field.
func KeyIn(vs ...string) predicate.Theme { func NameIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldIn(FieldKey, vs...)) return predicate.Theme(sql.FieldIn(FieldName, vs...))
} }
// KeyNotIn applies the NotIn predicate on the "key" field. // NameNotIn applies the NotIn predicate on the "name" field.
func KeyNotIn(vs ...string) predicate.Theme { func NameNotIn(vs ...string) predicate.Theme {
return predicate.Theme(sql.FieldNotIn(FieldKey, vs...)) return predicate.Theme(sql.FieldNotIn(FieldName, vs...))
} }
// KeyGT applies the GT predicate on the "key" field. // NameGT applies the GT predicate on the "name" field.
func KeyGT(v string) predicate.Theme { func NameGT(v string) predicate.Theme {
return predicate.Theme(sql.FieldGT(FieldKey, v)) return predicate.Theme(sql.FieldGT(FieldName, v))
} }
// KeyGTE applies the GTE predicate on the "key" field. // NameGTE applies the GTE predicate on the "name" field.
func KeyGTE(v string) predicate.Theme { func NameGTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldGTE(FieldKey, v)) return predicate.Theme(sql.FieldGTE(FieldName, v))
} }
// KeyLT applies the LT predicate on the "key" field. // NameLT applies the LT predicate on the "name" field.
func KeyLT(v string) predicate.Theme { func NameLT(v string) predicate.Theme {
return predicate.Theme(sql.FieldLT(FieldKey, v)) return predicate.Theme(sql.FieldLT(FieldName, v))
} }
// KeyLTE applies the LTE predicate on the "key" field. // NameLTE applies the LTE predicate on the "name" field.
func KeyLTE(v string) predicate.Theme { func NameLTE(v string) predicate.Theme {
return predicate.Theme(sql.FieldLTE(FieldKey, v)) return predicate.Theme(sql.FieldLTE(FieldName, v))
} }
// KeyContains applies the Contains predicate on the "key" field. // NameContains applies the Contains predicate on the "name" field.
func KeyContains(v string) predicate.Theme { func NameContains(v string) predicate.Theme {
return predicate.Theme(sql.FieldContains(FieldKey, v)) return predicate.Theme(sql.FieldContains(FieldName, v))
} }
// KeyHasPrefix applies the HasPrefix predicate on the "key" field. // NameHasPrefix applies the HasPrefix predicate on the "name" field.
func KeyHasPrefix(v string) predicate.Theme { func NameHasPrefix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasPrefix(FieldKey, v)) return predicate.Theme(sql.FieldHasPrefix(FieldName, v))
} }
// KeyHasSuffix applies the HasSuffix predicate on the "key" field. // NameHasSuffix applies the HasSuffix predicate on the "name" field.
func KeyHasSuffix(v string) predicate.Theme { func NameHasSuffix(v string) predicate.Theme {
return predicate.Theme(sql.FieldHasSuffix(FieldKey, v)) return predicate.Theme(sql.FieldHasSuffix(FieldName, v))
} }
// KeyEqualFold applies the EqualFold predicate on the "key" field. // NameEqualFold applies the EqualFold predicate on the "name" field.
func KeyEqualFold(v string) predicate.Theme { func NameEqualFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldEqualFold(FieldKey, v)) return predicate.Theme(sql.FieldEqualFold(FieldName, v))
} }
// KeyContainsFold applies the ContainsFold predicate on the "key" field. // NameContainsFold applies the ContainsFold predicate on the "name" field.
func KeyContainsFold(v string) predicate.Theme { func NameContainsFold(v string) predicate.Theme {
return predicate.Theme(sql.FieldContainsFold(FieldKey, v)) return predicate.Theme(sql.FieldContainsFold(FieldName, v))
} }
// TypeEQ applies the EQ predicate on the "type" field. // TypeEQ applies the EQ predicate on the "type" field.

View File

@@ -75,9 +75,9 @@ func (_c *ThemeCreate) SetNillableDeletedAt(v *string) *ThemeCreate {
return _c return _c
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_c *ThemeCreate) SetKey(v string) *ThemeCreate { func (_c *ThemeCreate) SetName(v string) *ThemeCreate {
_c.mutation.SetKey(v) _c.mutation.SetName(v)
return _c return _c
} }
@@ -156,18 +156,21 @@ func (_c *ThemeCreate) defaults() error {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_c *ThemeCreate) check() error { func (_c *ThemeCreate) check() error {
if _, ok := _c.mutation.UUID(); !ok {
return &ValidationError{Name: "uuid", err: errors.New(`ent: missing required field "Theme.uuid"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok { if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Theme.created_at"`)} return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Theme.created_at"`)}
} }
if _, ok := _c.mutation.UpdatedAt(); !ok { if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Theme.updated_at"`)} return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Theme.updated_at"`)}
} }
if _, ok := _c.mutation.Key(); !ok { if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Theme.key"`)} return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Theme.name"`)}
} }
if v, ok := _c.mutation.Key(); ok { if v, ok := _c.mutation.Name(); ok {
if err := theme.KeyValidator(v); err != nil { if err := theme.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Theme.name": %w`, err)}
} }
} }
if _, ok := _c.mutation.GetType(); !ok { if _, ok := _c.mutation.GetType(); !ok {
@@ -206,7 +209,7 @@ func (_c *ThemeCreate) createSpec() (*Theme, *sqlgraph.CreateSpec) {
) )
if value, ok := _c.mutation.UUID(); ok { if value, ok := _c.mutation.UUID(); ok {
_spec.SetField(theme.FieldUUID, field.TypeString, value) _spec.SetField(theme.FieldUUID, field.TypeString, value)
_node.UUID = &value _node.UUID = value
} }
if value, ok := _c.mutation.CreatedAt(); ok { if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(theme.FieldCreatedAt, field.TypeString, value) _spec.SetField(theme.FieldCreatedAt, field.TypeString, value)
@@ -220,9 +223,9 @@ func (_c *ThemeCreate) createSpec() (*Theme, *sqlgraph.CreateSpec) {
_spec.SetField(theme.FieldDeletedAt, field.TypeString, value) _spec.SetField(theme.FieldDeletedAt, field.TypeString, value)
_node.DeletedAt = &value _node.DeletedAt = &value
} }
if value, ok := _c.mutation.Key(); ok { if value, ok := _c.mutation.Name(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value) _spec.SetField(theme.FieldName, field.TypeString, value)
_node.Key = value _node.Name = value
} }
if value, ok := _c.mutation.GetType(); ok { if value, ok := _c.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value) _spec.SetField(theme.FieldType, field.TypeEnum, value)

View File

@@ -62,16 +62,16 @@ func (_u *ThemeUpdate) ClearDeletedAt() *ThemeUpdate {
return _u return _u
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_u *ThemeUpdate) SetKey(v string) *ThemeUpdate { func (_u *ThemeUpdate) SetName(v string) *ThemeUpdate {
_u.mutation.SetKey(v) _u.mutation.SetName(v)
return _u return _u
} }
// SetNillableKey sets the "key" field if the given value is not nil. // SetNillableName sets the "name" field if the given value is not nil.
func (_u *ThemeUpdate) SetNillableKey(v *string) *ThemeUpdate { func (_u *ThemeUpdate) SetNillableName(v *string) *ThemeUpdate {
if v != nil { if v != nil {
_u.SetKey(*v) _u.SetName(*v)
} }
return _u return _u
} }
@@ -136,9 +136,9 @@ func (_u *ThemeUpdate) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *ThemeUpdate) check() error { func (_u *ThemeUpdate) check() error {
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Name(); ok {
if err := theme.KeyValidator(v); err != nil { if err := theme.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Theme.name": %w`, err)}
} }
} }
if v, ok := _u.mutation.GetType(); ok { if v, ok := _u.mutation.GetType(); ok {
@@ -167,9 +167,6 @@ func (_u *ThemeUpdate) sqlSave(ctx context.Context) (_node int, err error) {
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(theme.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(theme.FieldUpdatedAt, field.TypeString, value) _spec.SetField(theme.FieldUpdatedAt, field.TypeString, value)
} }
@@ -179,8 +176,8 @@ func (_u *ThemeUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(theme.FieldDeletedAt, field.TypeString) _spec.ClearField(theme.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value) _spec.SetField(theme.FieldName, field.TypeString, value)
} }
if value, ok := _u.mutation.GetType(); ok { if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value) _spec.SetField(theme.FieldType, field.TypeEnum, value)
@@ -247,16 +244,16 @@ func (_u *ThemeUpdateOne) ClearDeletedAt() *ThemeUpdateOne {
return _u return _u
} }
// SetKey sets the "key" field. // SetName sets the "name" field.
func (_u *ThemeUpdateOne) SetKey(v string) *ThemeUpdateOne { func (_u *ThemeUpdateOne) SetName(v string) *ThemeUpdateOne {
_u.mutation.SetKey(v) _u.mutation.SetName(v)
return _u return _u
} }
// SetNillableKey sets the "key" field if the given value is not nil. // SetNillableName sets the "name" field if the given value is not nil.
func (_u *ThemeUpdateOne) SetNillableKey(v *string) *ThemeUpdateOne { func (_u *ThemeUpdateOne) SetNillableName(v *string) *ThemeUpdateOne {
if v != nil { if v != nil {
_u.SetKey(*v) _u.SetName(*v)
} }
return _u return _u
} }
@@ -334,9 +331,9 @@ func (_u *ThemeUpdateOne) ExecX(ctx context.Context) {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (_u *ThemeUpdateOne) check() error { func (_u *ThemeUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok { if v, ok := _u.mutation.Name(); ok {
if err := theme.KeyValidator(v); err != nil { if err := theme.NameValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Theme.key": %w`, err)} return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Theme.name": %w`, err)}
} }
} }
if v, ok := _u.mutation.GetType(); ok { if v, ok := _u.mutation.GetType(); ok {
@@ -382,9 +379,6 @@ func (_u *ThemeUpdateOne) sqlSave(ctx context.Context) (_node *Theme, err error)
} }
} }
} }
if _u.mutation.UUIDCleared() {
_spec.ClearField(theme.FieldUUID, field.TypeString)
}
if value, ok := _u.mutation.UpdatedAt(); ok { if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(theme.FieldUpdatedAt, field.TypeString, value) _spec.SetField(theme.FieldUpdatedAt, field.TypeString, value)
} }
@@ -394,8 +388,8 @@ func (_u *ThemeUpdateOne) sqlSave(ctx context.Context) (_node *Theme, err error)
if _u.mutation.DeletedAtCleared() { if _u.mutation.DeletedAtCleared() {
_spec.ClearField(theme.FieldDeletedAt, field.TypeString) _spec.ClearField(theme.FieldDeletedAt, field.TypeString)
} }
if value, ok := _u.mutation.Key(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(theme.FieldKey, field.TypeString, value) _spec.SetField(theme.FieldName, field.TypeString, value)
} }
if value, ok := _u.mutation.GetType(); ok { if value, ok := _u.mutation.GetType(); ok {
_spec.SetField(theme.FieldType, field.TypeEnum, value) _spec.SetField(theme.FieldType, field.TypeEnum, value)

View File

@@ -3,31 +3,30 @@ package models
// ExtensionConfig 扩展配置项 // ExtensionConfig 扩展配置项
type ExtensionConfig map[string]interface{} type ExtensionConfig map[string]interface{}
// ExtensionKey 扩展标识符 // ExtensionName 扩展标识符
type ExtensionKey string type ExtensionName string
// Extension 扩展配置 // Extension 扩展配置
type Extension struct { type Extension struct {
Key ExtensionKey `json:"key"` Name ExtensionName `json:"key"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
Config ExtensionConfig `json:"config"` Config ExtensionConfig `json:"config"`
} }
const ( const (
// 编辑增强扩展 RainbowBrackets ExtensionName = "rainbowBrackets" // 彩虹括号
ExtensionRainbowBrackets ExtensionKey = "rainbowBrackets" // 彩虹括号 Hyperlink ExtensionName = "hyperlink" // 超链接
ExtensionHyperlink ExtensionKey = "hyperlink" // 超链接 ColorSelector ExtensionName = "colorSelector" // 颜色选择器
ExtensionColorSelector ExtensionKey = "colorSelector" // 颜色选择器 Fold ExtensionName = "fold" // 代码折叠
ExtensionFold ExtensionKey = "fold" // 代码折叠 Translator ExtensionName = "translator" // 划词翻译
ExtensionTranslator ExtensionKey = "translator" // 划词翻译 Markdown ExtensionName = "markdown" // Markdown渲染
ExtensionMarkdown ExtensionKey = "markdown" // Markdown渲染 HighlightWhitespace ExtensionName = "highlightWhitespace" // 显示空白字符
ExtensionHighlightWhitespace ExtensionKey = "highlightWhitespace" // 显示空白字符 HighlightTrailingWhitespace ExtensionName = "highlightTrailingWhitespace" // 高亮行尾空白
ExtensionHighlightTrailingWhitespace ExtensionKey = "highlightTrailingWhitespace" // 高亮行尾空白 Minimap ExtensionName = "minimap" // 小地图
ExtensionMinimap ExtensionKey = "minimap" // 小地图 LineNumbers ExtensionName = "lineNumbers" // 行号显示
ExtensionLineNumbers ExtensionKey = "lineNumbers" // 行号显示 ContextMenu ExtensionName = "contextMenu" // 上下文菜单
ExtensionContextMenu ExtensionKey = "contextMenu" // 上下文菜单 Search ExtensionName = "search" // 搜索功能
ExtensionSearch ExtensionKey = "search" // 搜索功能 HttpClient ExtensionName = "httpClient" // HTTP 客户端
ExtensionHttpClient ExtensionKey = "httpClient" // HTTP 客户端
) )
// NewDefaultExtensions 创建默认扩展配置 // NewDefaultExtensions 创建默认扩展配置
@@ -35,49 +34,49 @@ func NewDefaultExtensions() []Extension {
return []Extension{ return []Extension{
// 编辑增强扩展 // 编辑增强扩展
{ {
Key: ExtensionRainbowBrackets, Name: RainbowBrackets,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionHyperlink, Name: Hyperlink,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionColorSelector, Name: ColorSelector,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionFold, Name: Fold,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionTranslator, Name: Translator,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionMarkdown, Name: Markdown,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionHighlightWhitespace, Name: HighlightWhitespace,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionHighlightTrailingWhitespace, Name: HighlightTrailingWhitespace,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
// UI增强扩展 // UI增强扩展
{ {
Key: ExtensionMinimap, Name: Minimap,
Enabled: true, Enabled: true,
Config: ExtensionConfig{ Config: ExtensionConfig{
"displayText": "characters", "displayText": "characters",
@@ -86,24 +85,24 @@ func NewDefaultExtensions() []Extension {
}, },
}, },
{ {
Key: ExtensionLineNumbers, Name: LineNumbers,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionContextMenu, Name: ContextMenu,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
// 工具扩展 // 工具扩展
{ {
Key: ExtensionSearch, Name: Search,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },
{ {
Key: ExtensionHttpClient, Name: HttpClient,
Enabled: true, Enabled: true,
Config: ExtensionConfig{}, Config: ExtensionConfig{},
}, },

File diff suppressed because it is too large Load Diff

View File

@@ -34,12 +34,12 @@ func (Extension) Mixin() []ent.Mixin {
// Fields of the Extension. // Fields of the Extension.
func (Extension) Fields() []ent.Field { func (Extension) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
field.String("key"). field.String("name").
MaxLen(100). MaxLen(100).
NotEmpty(). NotEmpty().
Unique(). Unique().
StructTag(`json:"key"`). StructTag(`json:"name"`).
Comment("extension key"), Comment("extension name"),
field.Bool("enabled"). field.Bool("enabled").
Default(true). Default(true).
StructTag(`json:"enabled"`). StructTag(`json:"enabled"`).

View File

@@ -34,26 +34,58 @@ func (KeyBinding) Mixin() []ent.Mixin {
// Fields of the KeyBinding. // Fields of the KeyBinding.
func (KeyBinding) Fields() []ent.Field { func (KeyBinding) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
field.String("name").
MaxLen(100).
NotEmpty().
StructTag(`json:"name"`).
Comment("command identifier"),
field.String("type").
MaxLen(20).
Default("standard").
StructTag(`json:"type"`).
Comment("keybinding type: standard or emacs"),
field.String("key"). field.String("key").
MaxLen(100). MaxLen(100).
NotEmpty(). Optional().
Unique(). StructTag(`json:"key,omitempty"`).
StructTag(`json:"key"`). Comment("universal keybinding (cross-platform)"),
Comment("key binding key"), field.String("macos").
field.String("command").
MaxLen(100).
NotEmpty().
StructTag(`json:"command"`).
Comment("key binding command"),
field.String("extension").
MaxLen(100). MaxLen(100).
Optional(). Optional().
StructTag(`json:"extension,omitempty"`). StructTag(`json:"macos,omitempty"`).
Comment("key binding extension"), Comment("macOS specific keybinding"),
field.String("windows").
MaxLen(100).
Optional().
StructTag(`json:"windows,omitempty"`).
Comment("Windows specific keybinding"),
field.String("linux").
MaxLen(100).
Optional().
StructTag(`json:"linux,omitempty"`).
Comment("Linux specific keybinding"),
field.String("extension").
MaxLen(100).
NotEmpty().
StructTag(`json:"extension"`).
Comment("extension name (functional category)"),
field.Bool("enabled"). field.Bool("enabled").
Default(true). Default(true).
StructTag(`json:"enabled"`). StructTag(`json:"enabled"`).
Comment("key binding enabled"), Comment("whether this keybinding is enabled"),
field.Bool("prevent_default").
Default(true).
StructTag(`json:"preventDefault"`).
Comment("prevent browser default behavior"),
field.String("scope").
MaxLen(100).
Default("editor").
StructTag(`json:"scope,omitempty"`).
Comment("keybinding scope (default: editor)"),
} }
} }
@@ -65,7 +97,10 @@ func (KeyBinding) Edges() []ent.Edge {
// Indexes of the KeyBinding. // Indexes of the KeyBinding.
func (KeyBinding) Indexes() []ent.Index { func (KeyBinding) Indexes() []ent.Index {
return []ent.Index{ return []ent.Index{
index.Fields("extension"), index.Fields("name"), // 命令标识符索引
index.Fields("enabled"), index.Fields("type"), // 类型索引
index.Fields("type", "name").Unique(), // 类型+命令的联合唯一索引
index.Fields("extension"), // 扩展索引
index.Fields("enabled"), // 启用状态索引
} }
} }

View File

@@ -33,12 +33,12 @@ func (Theme) Mixin() []ent.Mixin {
// Fields of the Theme. // Fields of the Theme.
func (Theme) Fields() []ent.Field { func (Theme) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
field.String("key"). field.String("name").
MaxLen(100). MaxLen(100).
NotEmpty(). NotEmpty().
Unique(). Unique().
StructTag(`json:"key"`). StructTag(`json:"name"`).
Comment("theme key"), Comment("theme name"),
field.Enum("type"). field.Enum("type").
Values("dark", "light"). Values("dark", "light").
StructTag(`json:"type"`). StructTag(`json:"type"`).

View File

@@ -868,8 +868,8 @@ func (s *BackupService) createExtension(ctx context.Context, client *ent.Client,
if v, ok := record[extension.FieldUUID].(string); ok { if v, ok := record[extension.FieldUUID].(string); ok {
builder.SetUUID(v) builder.SetUUID(v)
} }
if v, ok := record[extension.FieldKey].(string); ok { if v, ok := record[extension.FieldName].(string); ok {
builder.SetKey(v) builder.SetName(v)
} }
if v, ok := record[extension.FieldEnabled].(bool); ok { if v, ok := record[extension.FieldEnabled].(bool); ok {
builder.SetEnabled(v) builder.SetEnabled(v)
@@ -891,8 +891,8 @@ func (s *BackupService) createExtension(ctx context.Context, client *ent.Client,
func (s *BackupService) updateExtension(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error { func (s *BackupService) updateExtension(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error {
builder := client.Extension.UpdateOneID(id) builder := client.Extension.UpdateOneID(id)
if v, ok := record[extension.FieldKey].(string); ok { if v, ok := record[extension.FieldName].(string); ok {
builder.SetKey(v) builder.SetName(v)
} }
if v, ok := record[extension.FieldEnabled].(bool); ok { if v, ok := record[extension.FieldEnabled].(bool); ok {
builder.SetEnabled(v) builder.SetEnabled(v)
@@ -954,11 +954,20 @@ func (s *BackupService) createKeyBinding(ctx context.Context, client *ent.Client
if v, ok := record[keybinding.FieldUUID].(string); ok { if v, ok := record[keybinding.FieldUUID].(string); ok {
builder.SetUUID(v) builder.SetUUID(v)
} }
if v, ok := record[keybinding.FieldName].(string); ok {
builder.SetName(v)
}
if v, ok := record[keybinding.FieldKey].(string); ok { if v, ok := record[keybinding.FieldKey].(string); ok {
builder.SetKey(v) builder.SetKey(v)
} }
if v, ok := record[keybinding.FieldCommand].(string); ok { if v, ok := record[keybinding.FieldMacos].(string); ok {
builder.SetCommand(v) builder.SetMacos(v)
}
if v, ok := record[keybinding.FieldWindows].(string); ok {
builder.SetWindows(v)
}
if v, ok := record[keybinding.FieldLinux].(string); ok {
builder.SetLinux(v)
} }
if v, ok := record[keybinding.FieldExtension].(string); ok { if v, ok := record[keybinding.FieldExtension].(string); ok {
builder.SetExtension(v) builder.SetExtension(v)
@@ -966,6 +975,12 @@ func (s *BackupService) createKeyBinding(ctx context.Context, client *ent.Client
if v, ok := record[keybinding.FieldEnabled].(bool); ok { if v, ok := record[keybinding.FieldEnabled].(bool); ok {
builder.SetEnabled(v) builder.SetEnabled(v)
} }
if v, ok := record[keybinding.FieldPreventDefault].(bool); ok {
builder.SetPreventDefault(v)
}
if v, ok := record[keybinding.FieldScope].(string); ok {
builder.SetScope(v)
}
if v, ok := record[keybinding.FieldCreatedAt].(string); ok { if v, ok := record[keybinding.FieldCreatedAt].(string); ok {
builder.SetCreatedAt(v) builder.SetCreatedAt(v)
} }
@@ -980,11 +995,20 @@ func (s *BackupService) createKeyBinding(ctx context.Context, client *ent.Client
func (s *BackupService) updateKeyBinding(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error { func (s *BackupService) updateKeyBinding(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error {
builder := client.KeyBinding.UpdateOneID(id) builder := client.KeyBinding.UpdateOneID(id)
if v, ok := record[keybinding.FieldName].(string); ok {
builder.SetName(v)
}
if v, ok := record[keybinding.FieldKey].(string); ok { if v, ok := record[keybinding.FieldKey].(string); ok {
builder.SetKey(v) builder.SetKey(v)
} }
if v, ok := record[keybinding.FieldCommand].(string); ok { if v, ok := record[keybinding.FieldMacos].(string); ok {
builder.SetCommand(v) builder.SetMacos(v)
}
if v, ok := record[keybinding.FieldWindows].(string); ok {
builder.SetWindows(v)
}
if v, ok := record[keybinding.FieldLinux].(string); ok {
builder.SetLinux(v)
} }
if v, ok := record[keybinding.FieldExtension].(string); ok { if v, ok := record[keybinding.FieldExtension].(string); ok {
builder.SetExtension(v) builder.SetExtension(v)
@@ -992,6 +1016,12 @@ func (s *BackupService) updateKeyBinding(ctx context.Context, client *ent.Client
if v, ok := record[keybinding.FieldEnabled].(bool); ok { if v, ok := record[keybinding.FieldEnabled].(bool); ok {
builder.SetEnabled(v) builder.SetEnabled(v)
} }
if v, ok := record[keybinding.FieldPreventDefault].(bool); ok {
builder.SetPreventDefault(v)
}
if v, ok := record[keybinding.FieldScope].(string); ok {
builder.SetScope(v)
}
if v, ok := record[keybinding.FieldUpdatedAt].(string); ok { if v, ok := record[keybinding.FieldUpdatedAt].(string); ok {
builder.SetUpdatedAt(v) builder.SetUpdatedAt(v)
} }
@@ -1046,8 +1076,8 @@ func (s *BackupService) createTheme(ctx context.Context, client *ent.Client, rec
if v, ok := record[theme.FieldUUID].(string); ok { if v, ok := record[theme.FieldUUID].(string); ok {
builder.SetUUID(v) builder.SetUUID(v)
} }
if v, ok := record[theme.FieldKey].(string); ok { if v, ok := record[theme.FieldName].(string); ok {
builder.SetKey(v) builder.SetName(v)
} }
if v, ok := record[theme.FieldType].(string); ok { if v, ok := record[theme.FieldType].(string); ok {
builder.SetType(theme.Type(v)) builder.SetType(theme.Type(v))
@@ -1069,8 +1099,8 @@ func (s *BackupService) createTheme(ctx context.Context, client *ent.Client, rec
func (s *BackupService) updateTheme(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error { func (s *BackupService) updateTheme(ctx context.Context, client *ent.Client, id int, record map[string]interface{}) error {
builder := client.Theme.UpdateOneID(id) builder := client.Theme.UpdateOneID(id)
if v, ok := record[theme.FieldKey].(string); ok { if v, ok := record[theme.FieldName].(string); ok {
builder.SetKey(v) builder.SetName(v)
} }
if v, ok := record[theme.FieldType].(string); ok { if v, ok := record[theme.FieldType].(string); ok {
builder.SetType(theme.Type(v)) builder.SetType(theme.Type(v))

View File

@@ -36,9 +36,9 @@ func (s *ExtensionService) ServiceStartup(ctx context.Context, options applicati
// SyncExtensions 同步扩展配置 // SyncExtensions 同步扩展配置
func (s *ExtensionService) SyncExtensions(ctx context.Context) error { func (s *ExtensionService) SyncExtensions(ctx context.Context) error {
defaults := models.NewDefaultExtensions() defaults := models.NewDefaultExtensions()
definedKeys := make(map[models.ExtensionKey]models.Extension) definedKeys := make(map[models.ExtensionName]models.Extension)
for _, ext := range defaults { for _, ext := range defaults {
definedKeys[ext.Key] = ext definedKeys[ext.Name] = ext
} }
// 获取数据库中已有的扩展 // 获取数据库中已有的扩展
@@ -49,7 +49,7 @@ func (s *ExtensionService) SyncExtensions(ctx context.Context) error {
existingKeys := make(map[string]bool) existingKeys := make(map[string]bool)
for _, ext := range existing { for _, ext := range existing {
existingKeys[ext.Key] = true existingKeys[ext.Name] = true
} }
// 批量添加缺失的扩展 // 批量添加缺失的扩展
@@ -57,7 +57,7 @@ func (s *ExtensionService) SyncExtensions(ctx context.Context) error {
for key, ext := range definedKeys { for key, ext := range definedKeys {
if !existingKeys[string(key)] { if !existingKeys[string(key)] {
builders = append(builders, s.db.Client.Extension.Create(). builders = append(builders, s.db.Client.Extension.Create().
SetKey(string(ext.Key)). SetName(string(ext.Name)).
SetEnabled(ext.Enabled). SetEnabled(ext.Enabled).
SetConfig(ext.Config)) SetConfig(ext.Config))
} }
@@ -71,7 +71,7 @@ func (s *ExtensionService) SyncExtensions(ctx context.Context) error {
// 批量删除废弃的扩展 // 批量删除废弃的扩展
var deleteIDs []int var deleteIDs []int
for _, ext := range existing { for _, ext := range existing {
if _, ok := definedKeys[models.ExtensionKey(ext.Key)]; !ok { if _, ok := definedKeys[models.ExtensionName(ext.Name)]; !ok {
deleteIDs = append(deleteIDs, ext.ID) deleteIDs = append(deleteIDs, ext.ID)
} }
} }
@@ -86,15 +86,15 @@ func (s *ExtensionService) SyncExtensions(ctx context.Context) error {
return nil return nil
} }
// GetAllExtensions 获取所有扩展 // GetExtensions 获取所有扩展
func (s *ExtensionService) GetAllExtensions(ctx context.Context) ([]*ent.Extension, error) { func (s *ExtensionService) GetExtensions(ctx context.Context) ([]*ent.Extension, error) {
return s.db.Client.Extension.Query().All(ctx) return s.db.Client.Extension.Query().All(ctx)
} }
// GetExtensionByKey 根据Key获取扩展 // GetExtensionByID 根据ID获取扩展
func (s *ExtensionService) GetExtensionByKey(ctx context.Context, key string) (*ent.Extension, error) { func (s *ExtensionService) GetExtensionByID(ctx context.Context, id int) (*ent.Extension, error) {
ext, err := s.db.Client.Extension.Query(). ext, err := s.db.Client.Extension.Query().
Where(extension.Key(key)). Where(extension.ID(id)).
Only(ctx) Only(ctx)
if err != nil { if err != nil {
if ent.IsNotFound(err) { if ent.IsNotFound(err) {
@@ -106,13 +106,13 @@ func (s *ExtensionService) GetExtensionByKey(ctx context.Context, key string) (*
} }
// UpdateExtensionEnabled 更新扩展启用状态 // UpdateExtensionEnabled 更新扩展启用状态
func (s *ExtensionService) UpdateExtensionEnabled(ctx context.Context, key string, enabled bool) error { func (s *ExtensionService) UpdateExtensionEnabled(ctx context.Context, id int, enabled bool) error {
ext, err := s.GetExtensionByKey(ctx, key) ext, err := s.GetExtensionByID(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if ext == nil { if ext == nil {
return fmt.Errorf("extension not found: %s", key) return fmt.Errorf("extension not found: %d", id)
} }
// 更新扩展状态 // 更新扩展状态
@@ -124,23 +124,23 @@ func (s *ExtensionService) UpdateExtensionEnabled(ctx context.Context, key strin
// 同步更新该扩展关联的快捷键启用状态 // 同步更新该扩展关联的快捷键启用状态
if _, err := s.db.Client.KeyBinding.Update(). if _, err := s.db.Client.KeyBinding.Update().
Where(keybinding.Extension(key)). Where(keybinding.Extension(ext.Name)).
SetEnabled(enabled). SetEnabled(enabled).
Save(ctx); err != nil { Save(ctx); err != nil {
return fmt.Errorf("update keybindings for extension %s error: %w", key, err) return fmt.Errorf("update keybindings for extension %s error: %w", ext.Name, err)
} }
return nil return nil
} }
// UpdateExtensionConfig 更新扩展配置 // UpdateExtensionConfig 更新扩展配置
func (s *ExtensionService) UpdateExtensionConfig(ctx context.Context, key string, config map[string]interface{}) error { func (s *ExtensionService) UpdateExtensionConfig(ctx context.Context, id int, config map[string]interface{}) error {
ext, err := s.GetExtensionByKey(ctx, key) ext, err := s.GetExtensionByID(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if ext == nil { if ext == nil {
return fmt.Errorf("extension not found: %s", key) return fmt.Errorf("extension not found: %d", id)
} }
return s.db.Client.Extension.UpdateOneID(ext.ID). return s.db.Client.Extension.UpdateOneID(ext.ID).
SetConfig(config). SetConfig(config).
@@ -148,25 +148,25 @@ func (s *ExtensionService) UpdateExtensionConfig(ctx context.Context, key string
} }
// ResetExtensionConfig 重置单个扩展到默认状态 // ResetExtensionConfig 重置单个扩展到默认状态
func (s *ExtensionService) ResetExtensionConfig(ctx context.Context, key string) error { func (s *ExtensionService) ResetExtensionConfig(ctx context.Context, id int) error {
defaults := models.NewDefaultExtensions() ext, err := s.GetExtensionByID(ctx, id)
var defaultExt *models.Extension
for _, ext := range defaults {
if string(ext.Key) == key {
defaultExt = &ext
break
}
}
if defaultExt == nil {
return fmt.Errorf("default extension not found: %s", key)
}
ext, err := s.GetExtensionByKey(ctx, key)
if err != nil { if err != nil {
return err return err
} }
if ext == nil { if ext == nil {
return fmt.Errorf("extension not found: %s", key) return fmt.Errorf("extension not found: %d", id)
}
defaults := models.NewDefaultExtensions()
var defaultExt *models.Extension
for _, defExt := range defaults {
if string(defExt.Name) == ext.Name {
defaultExt = &defExt
break
}
}
if defaultExt == nil {
return fmt.Errorf("default extension not found: %s", ext.Name)
} }
return s.db.Client.Extension.UpdateOneID(ext.ID). return s.db.Client.Extension.UpdateOneID(ext.ID).
@@ -175,6 +175,21 @@ func (s *ExtensionService) ResetExtensionConfig(ctx context.Context, key string)
Exec(ctx) Exec(ctx)
} }
// GetExtensionConfig 获取扩展配置
func (s *ExtensionService) GetExtensionConfig(ctx context.Context, id int) (map[string]interface{}, error) {
ext, err := s.GetExtensionByID(ctx, id)
if err != nil {
return nil, err
}
if ext == nil {
return nil, fmt.Errorf("extension not found: %d", id)
}
if ext.Config == nil {
return make(map[string]interface{}), nil
}
return ext.Config, nil
}
// GetDefaultExtensions 获取默认扩展配置(用于前端绑定生成) // GetDefaultExtensions 获取默认扩展配置(用于前端绑定生成)
func (s *ExtensionService) GetDefaultExtensions() []models.Extension { func (s *ExtensionService) GetDefaultExtensions() []models.Extension {
return models.NewDefaultExtensions() return models.NewDefaultExtensions()

View File

@@ -35,9 +35,11 @@ func (s *KeyBindingService) ServiceStartup(ctx context.Context, options applicat
// SyncKeyBindings 同步快捷键配置 // SyncKeyBindings 同步快捷键配置
func (s *KeyBindingService) SyncKeyBindings(ctx context.Context) error { func (s *KeyBindingService) SyncKeyBindings(ctx context.Context) error {
defaults := models.NewDefaultKeyBindings() defaults := models.NewDefaultKeyBindings()
definedKeys := make(map[models.KeyBindingKey]models.KeyBinding) // 使用 type + name 作为唯一键
definedKeys := make(map[string]models.KeyBinding)
for _, kb := range defaults { for _, kb := range defaults {
definedKeys[kb.Key] = kb key := string(kb.Type) + ":" + string(kb.Name)
definedKeys[key] = kb
} }
// 获取数据库中已有的快捷键 // 获取数据库中已有的快捷键
@@ -48,20 +50,38 @@ func (s *KeyBindingService) SyncKeyBindings(ctx context.Context) error {
existingKeys := make(map[string]bool) existingKeys := make(map[string]bool)
for _, kb := range existing { for _, kb := range existing {
existingKeys[kb.Key] = true key := kb.Type + ":" + kb.Name
existingKeys[key] = true
} }
// 批量添加缺失的快捷键 // 批量添加缺失的快捷键
var builders []*ent.KeyBindingCreate var builders []*ent.KeyBindingCreate
for key, kb := range definedKeys { for key, kb := range definedKeys {
if !existingKeys[string(key)] { if !existingKeys[key] {
create := s.db.Client.KeyBinding.Create(). create := s.db.Client.KeyBinding.Create().
SetKey(string(kb.Key)). SetName(string(kb.Name)).
SetCommand(kb.Command). SetType(string(kb.Type)).
SetEnabled(kb.Enabled) SetExtension(string(kb.Extension)).
if kb.Extension != "" { SetEnabled(kb.Enabled).
create.SetExtension(string(kb.Extension)) SetPreventDefault(kb.PreventDefault)
// 设置快捷键字段
if kb.Key != "" {
create.SetKey(kb.Key)
} }
if kb.Macos != "" {
create.SetMacos(kb.Macos)
}
if kb.Windows != "" {
create.SetWindows(kb.Windows)
}
if kb.Linux != "" {
create.SetLinux(kb.Linux)
}
if kb.Scope != "" {
create.SetScope(kb.Scope)
}
builders = append(builders, create) builders = append(builders, create)
} }
} }
@@ -74,7 +94,8 @@ func (s *KeyBindingService) SyncKeyBindings(ctx context.Context) error {
// 批量删除废弃的快捷键(硬删除) // 批量删除废弃的快捷键(硬删除)
var deleteIDs []int var deleteIDs []int
for _, kb := range existing { for _, kb := range existing {
if _, ok := definedKeys[models.KeyBindingKey(kb.Key)]; !ok { key := kb.Type + ":" + kb.Name
if _, ok := definedKeys[key]; !ok {
deleteIDs = append(deleteIDs, kb.ID) deleteIDs = append(deleteIDs, kb.ID)
} }
} }
@@ -89,16 +110,50 @@ func (s *KeyBindingService) SyncKeyBindings(ctx context.Context) error {
return nil return nil
} }
// GetAllKeyBindings 获取所有快捷键 // GetKeyBindings 根据类型获取快捷键
func (s *KeyBindingService) GetAllKeyBindings(ctx context.Context) ([]*ent.KeyBinding, error) { func (s *KeyBindingService) GetKeyBindings(ctx context.Context, kbType models.KeyBindingType) ([]*ent.KeyBinding, error) {
return s.db.Client.KeyBinding.Query().All(ctx) if kbType == models.Standard {
// Standard 模式:只返回 type=standard 且 enabled=true
return s.db.Client.KeyBinding.Query().
Where(
keybinding.Type(string(kbType)),
keybinding.Enabled(true),
).
All(ctx)
}
// Emacs 模式:获取所有 enabled=true 的快捷键
allEnabled, err := s.db.Client.KeyBinding.Query().
Where(keybinding.Enabled(true)).
All(ctx)
if err != nil {
return nil, fmt.Errorf("query enabled key bindings error: %w", err)
}
// 构建 emacs 快捷键的 name 集合
emacsNames := make(map[string]bool)
for _, kb := range allEnabled {
if kb.Type == string(models.Emacs) {
emacsNames[kb.Name] = true
}
}
// 过滤:去掉与 emacs 冲突的 standard 快捷键
var result []*ent.KeyBinding
for _, kb := range allEnabled {
// 如果是 standard 类型,且与 emacs 有 name 冲突,则跳过
if kb.Type == string(models.Standard) && emacsNames[kb.Name] {
continue
}
result = append(result, kb)
}
return result, nil
} }
// GetKeyBindingByKey 根据Key获取快捷键 // GetKeyBindingByID 根据ID获取快捷键
func (s *KeyBindingService) GetKeyBindingByKey(ctx context.Context, key string) (*ent.KeyBinding, error) { func (s *KeyBindingService) GetKeyBindingByID(ctx context.Context, id int) (*ent.KeyBinding, error) {
kb, err := s.db.Client.KeyBinding.Query(). kb, err := s.db.Client.KeyBinding.Get(ctx, id)
Where(keybinding.Key(key)).
Only(ctx)
if err != nil { if err != nil {
if ent.IsNotFound(err) { if ent.IsNotFound(err) {
return nil, nil return nil, nil
@@ -108,28 +163,41 @@ func (s *KeyBindingService) GetKeyBindingByKey(ctx context.Context, key string)
return kb, nil return kb, nil
} }
// UpdateKeyBindingCommand 更新快捷键命令 // UpdateKeyBindingKeys 更新快捷键绑定(根据操作系统自动判断更新哪个字段)
func (s *KeyBindingService) UpdateKeyBindingCommand(ctx context.Context, key string, command string) error { func (s *KeyBindingService) UpdateKeyBindingKeys(ctx context.Context, id int, key string) error {
kb, err := s.GetKeyBindingByKey(ctx, key) kb, err := s.GetKeyBindingByID(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if kb == nil { if kb == nil {
return fmt.Errorf("key binding not found: %s", key) return fmt.Errorf("key binding not found: id=%d", id)
} }
return s.db.Client.KeyBinding.UpdateOneID(kb.ID).
SetCommand(command). update := s.db.Client.KeyBinding.UpdateOneID(kb.ID)
Exec(ctx)
os := application.Get().Env.Info().OS
switch os {
case "darwin":
update.SetMacos(key)
case "windows":
update.SetWindows(key)
case "linux":
update.SetLinux(key)
default:
s.logger.Error("unknown os: %s", os)
}
return update.SetKey(key).Exec(ctx)
} }
// UpdateKeyBindingEnabled 更新快捷键启用状态 // UpdateKeyBindingEnabled 更新快捷键启用状态
func (s *KeyBindingService) UpdateKeyBindingEnabled(ctx context.Context, key string, enabled bool) error { func (s *KeyBindingService) UpdateKeyBindingEnabled(ctx context.Context, id int, enabled bool) error {
kb, err := s.GetKeyBindingByKey(ctx, key) kb, err := s.GetKeyBindingByID(ctx, id)
if err != nil { if err != nil {
return err return err
} }
if kb == nil { if kb == nil {
return fmt.Errorf("key binding not found: %s", key) return fmt.Errorf("key binding not found: id=%d", id)
} }
return s.db.Client.KeyBinding.UpdateOneID(kb.ID). return s.db.Client.KeyBinding.UpdateOneID(kb.ID).
SetEnabled(enabled). SetEnabled(enabled).
@@ -140,3 +208,48 @@ func (s *KeyBindingService) UpdateKeyBindingEnabled(ctx context.Context, key str
func (s *KeyBindingService) GetDefaultKeyBindings() []models.KeyBinding { func (s *KeyBindingService) GetDefaultKeyBindings() []models.KeyBinding {
return models.NewDefaultKeyBindings() return models.NewDefaultKeyBindings()
} }
// ResetKeyBindings 重置所有快捷键到默认值
func (s *KeyBindingService) ResetKeyBindings(ctx context.Context) error {
// 获取默认快捷键
defaults := models.NewDefaultKeyBindings()
// 构建默认快捷键映射 (type:name -> KeyBinding)
defaultsMap := make(map[string]models.KeyBinding)
for _, kb := range defaults {
key := string(kb.Type) + ":" + string(kb.Name)
defaultsMap[key] = kb
}
// 获取数据库中所有快捷键
existing, err := s.db.Client.KeyBinding.Query().All(ctx)
if err != nil {
return fmt.Errorf("query key bindings error: %w", err)
}
// 更新所有快捷键到默认值
for _, existingKb := range existing {
key := existingKb.Type + ":" + existingKb.Name
defaultKb, ok := defaultsMap[key]
if !ok {
// 如果默认配置中没有这个快捷键,跳过
continue
}
// 无条件更新所有字段到默认值
update := s.db.Client.KeyBinding.UpdateOneID(existingKb.ID).
SetKey(defaultKb.Key).
SetMacos(defaultKb.Macos).
SetWindows(defaultKb.Windows).
SetLinux(defaultKb.Linux).
SetScope(defaultKb.Scope).
SetEnabled(defaultKb.Enabled).
SetPreventDefault(defaultKb.PreventDefault)
if err := update.Exec(ctx); err != nil {
return fmt.Errorf("update key binding error: %w", err)
}
}
return nil
}

View File

@@ -32,15 +32,15 @@ func (s *ThemeService) ServiceStartup(ctx context.Context, options application.S
return nil return nil
} }
// GetThemeByKey 根据Key获取主题 // GetThemeByName 根据Key获取主题
func (s *ThemeService) GetThemeByKey(ctx context.Context, key string) (*ent.Theme, error) { func (s *ThemeService) GetThemeByName(ctx context.Context, name string) (*ent.Theme, error) {
trimmed := strings.TrimSpace(key) trimmed := strings.TrimSpace(name)
if trimmed == "" { if trimmed == "" {
return nil, fmt.Errorf("theme key cannot be empty") return nil, fmt.Errorf("theme key cannot be empty")
} }
t, err := s.db.Client.Theme.Query(). t, err := s.db.Client.Theme.Query().
Where(theme.Key(trimmed)). Where(theme.Name(trimmed)).
Only(ctx) Only(ctx)
if err != nil { if err != nil {
if ent.IsNotFound(err) { if ent.IsNotFound(err) {
@@ -68,7 +68,7 @@ func (s *ThemeService) UpdateTheme(ctx context.Context, key string, colors map[s
themeType = theme.TypeLight themeType = theme.TypeLight
} }
existing, err := s.GetThemeByKey(ctx, trimmed) existing, err := s.GetThemeByName(ctx, trimmed)
if err != nil { if err != nil {
return err return err
} }
@@ -76,7 +76,7 @@ func (s *ThemeService) UpdateTheme(ctx context.Context, key string, colors map[s
if existing == nil { if existing == nil {
// 插入新主题 // 插入新主题
_, err = s.db.Client.Theme.Create(). _, err = s.db.Client.Theme.Create().
SetKey(trimmed). SetName(trimmed).
SetType(themeType). SetType(themeType).
SetColors(colors). SetColors(colors).
Save(ctx) Save(ctx)
@@ -98,7 +98,7 @@ func (s *ThemeService) ResetTheme(ctx context.Context, key string) error {
} }
_, err := s.db.Client.Theme.Delete(). _, err := s.db.Client.Theme.Delete().
Where(theme.Key(trimmed)). Where(theme.Name(trimmed)).
Exec(mixin.SkipSoftDelete(ctx)) Exec(mixin.SkipSoftDelete(ctx))
return err return err
} }

View File

@@ -1 +1 @@
VERSION=1.5.4 VERSION=1.5.5