Skip to content

Commit

Permalink
feat: 新增置顶命令功能 #31,历史命令添加图标
Browse files Browse the repository at this point in the history
  • Loading branch information
lazyloong committed Dec 22, 2023
1 parent f5d8d2d commit b41e2fb
Show file tree
Hide file tree
Showing 9 changed files with 427 additions and 235 deletions.
12 changes: 6 additions & 6 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"arrowParens": "always",
"printWidth": 140,
"semi": true,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "es5"
"arrowParens": "always",
"printWidth": 100,
"semi": true,
"singleQuote": false,
"tabWidth": 4,
"trailingComma": "es5"
}
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"author": "lazyloong",

"minAppVersion": "1.0.0",
"version": "2.10.3"
"version": "2.11.0"
}
35 changes: 18 additions & 17 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
{
"name": "fuzyy_chinese",
"version": "0.0.1",
"description": "",
"main": "lib/main.js",
"license": "MIT",
"scripts": {
"build": "obsidian-plugin build ./src/main.ts && cp styles.css dist",
"build-win": "obsidian-plugin build ./src/main.ts && copy styles.css dist",
"dev": "obsidian-plugin dev src/main.ts",
"help": "obsidian-plugin --help"
},
"devDependencies": {
"builtin-modules": "^3.3.0",
"obsidian": "github:obsidianmd/obsidian-api",
"obsidian-plugin-cli": "^0.9.0",
"typescript": "^4.9.5"
}
"name": "fuzyy_chinese",
"version": "0.0.1",
"description": "",
"main": "lib/main.js",
"license": "MIT",
"scripts": {
"build": "obsidian-plugin build ./src/main.ts && cp styles.css dist",
"build-win": "obsidian-plugin build ./src/main.ts && copy styles.css dist",
"dev": "obsidian-plugin dev src/main.ts",
"help": "obsidian-plugin --help"
},
"devDependencies": {
"builtin-modules": "^3.3.0",
"obsidian": "github:obsidianmd/obsidian-api",
"templater": "github:SilentVoid13/Templater",
"obsidian-plugin-cli": "^0.9.0",
"typescript": "^4.9.5"
}
}
67 changes: 53 additions & 14 deletions src/fuzzyCommandModal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { App, Hotkey, Modifier, Platform } from "obsidian";
import { App, Hotkey, Modifier, Platform, getIcon } from "obsidian";
import FuzzyModal from "./fuzzyModal";
import { PinyinIndex as PI, Pinyin, MatchData } from "./utils";
import FuzzyChinesePinyinPlugin from "./main";
Expand Down Expand Up @@ -53,11 +53,11 @@ function generateHotKeyText(hotkey: Hotkey): string {
}

export default class FuzzyCommandModal extends FuzzyModal<Item> {
historyCommand: Array<Item>;
historyCommands: Array<Item>;
constructor(app: App, plugin: FuzzyChinesePinyinPlugin) {
super(app, plugin);
this.index = this.plugin.addChild(new PinyinIndex(this.app, this.plugin));
this.historyCommand = [];
this.historyCommands = [];
this.emptyStateText = "未发现命令。";
this.setPlaceholder("输入命令……");
let prompt = [
Expand All @@ -77,16 +77,42 @@ export default class FuzzyCommandModal extends FuzzyModal<Item> {
this.index.update();
}
getEmptyInputSuggestions(): MatchData<Item>[] {
return this.historyCommand
.concat(this.index.items.filter((p) => !this.historyCommand.includes(p)))
.slice(0, 100)
.map((p) => {
return { item: p, score: 0, range: null };
});
let pinnedCommands: MatchData<Item>[] = this.plugin.settings.command.pinnedCommands.map(
(p) => ({
item: this.index.items.find((q) => q.name == p),
score: -2,
range: null,
})
),
historyCommands: MatchData<Item>[] = this.historyCommands
.filter((p) => !this.plugin.settings.command.pinnedCommands.includes(p.name))
.map((p) => ({
item: this.index.items.find((q) => q.name == p.name),
score: -1,
range: null,
})),
commonCommands: MatchData<Item>[] = this.index.items
.filter(
(p) =>
!this.plugin.settings.command.pinnedCommands.includes(p.name) &&
!this.historyCommands.includes(p)
)
.map((p) => ({
item: p,
score: 0,
range: null,
}));
return pinnedCommands
.concat(historyCommands)
.concat(commonCommands)
.filter((p) => p.item)
.slice(0, 100);
}
onChooseSuggestion(matchData: MatchData<Item>, evt: MouseEvent | KeyboardEvent) {
this.historyCommand = this.historyCommand.filter((p) => p.command.id != matchData.item.command.id);
this.historyCommand.unshift(matchData.item);
this.historyCommands = this.historyCommands.filter(
(p) => p.command.id != matchData.item.command.id
);
this.historyCommands.unshift(matchData.item);
app.commands.executeCommand(matchData.item.command);
}
renderSuggestion(matchData: MatchData<Item>, el: HTMLElement): void {
Expand All @@ -104,7 +130,10 @@ export default class FuzzyCommandModal extends FuzzyModal<Item> {
if (range) {
for (const r of range) {
e_content.appendText(text.slice(index, r[0]));
e_content.createSpan({ cls: "suggestion-highlight", text: text.slice(r[0], r[1] + 1) });
e_content.createSpan({
cls: "suggestion-highlight",
text: text.slice(r[0], r[1] + 1),
});
index = r[1] + 1;
}
}
Expand All @@ -116,6 +145,12 @@ export default class FuzzyCommandModal extends FuzzyModal<Item> {
text: generateHotKeyText(hotkey),
});
});

let e_flair = el.createEl("span", {
cls: "suggestion-flair",
});
if (matchData.score == -2) e_flair.appendChild(getIcon("pin"));
else if (matchData.score == -1) e_flair.appendChild(getIcon("history"));
}
}
class PinyinIndex extends PI<Item> {
Expand All @@ -136,8 +171,12 @@ class PinyinIndex extends PI<Item> {
let commands = app.commands.listCommands();
let oldCommandsNames = this.items.map((item) => item.name);
let newCommandsNames = commands.map((command) => command.name);
let addedCommands = newCommandsNames.filter((command) => !oldCommandsNames.includes(command));
let removedCommands = oldCommandsNames.filter((command) => !newCommandsNames.includes(command));
let addedCommands = newCommandsNames.filter(
(command) => !oldCommandsNames.includes(command)
);
let removedCommands = oldCommandsNames.filter(
(command) => !newCommandsNames.includes(command)
);
if (addedCommands.length > 0) {
// 添加新命令
this.items.push(
Expand Down
87 changes: 67 additions & 20 deletions src/fuzzyFileModal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TFile, App, WorkspaceLeaf, TAbstractFile, CachedMetadata } from "obsidian";
import { TFile, App, WorkspaceLeaf, TAbstractFile, CachedMetadata, getIcon } from "obsidian";
import { Pinyin, PinyinIndex as PI, HistoryMatchDataNode } from "./utils";
import FuzzyChinesePinyinPlugin from "./main";
import FuzzyModal from "./fuzzyModal";
Expand Down Expand Up @@ -75,19 +75,28 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
this.scope.register(["Shift"], "Enter", async (e) => {
if (this.inputEl.value == "") return;
this.close();
let nf = await app.vault.create(app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md", "");
let nf = await app.vault.create(
app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md",
""
);
app.workspace.getMostRecentLeaf().openFile(nf);
});
this.scope.register(["Mod", "Shift"], "Enter", async (e) => {
if (this.inputEl.value == "") return;
this.close();
let nf = await app.vault.create(app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md", "");
let nf = await app.vault.create(
app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md",
""
);
app.workspace.getLeaf("tab").openFile(nf);
});
this.scope.register(["Shift", "Alt"], "Enter", async (e) => {
if (this.inputEl.value == "") return;
this.close();
let nf = await app.vault.create(app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md", "");
let nf = await app.vault.create(
app.fileManager.getNewFileParent("").path + "/" + this.inputEl.value + ".md",
""
);
getNewOrAdjacentLeaf(app.workspace.getMostRecentLeaf()).openFile(nf);
});
this.scope.register(["Alt"], "Enter", async (e) => {
Expand All @@ -99,8 +108,9 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
this.scope.register(["Mod"], "p", (event: KeyboardEvent) => {
this.close();
let item = this.chooser.values[this.chooser.selectedItem];
const newLeaf = app.plugins.plugins["obsidian-hover-editor"].spawnPopover(undefined, () =>
this.app.workspace.setActiveLeaf(newLeaf)
const newLeaf = app.plugins.plugins["obsidian-hover-editor"].spawnPopover(
undefined,
() => this.app.workspace.setActiveLeaf(newLeaf)
);
newLeaf.openFile(item.item.file);
});
Expand Down Expand Up @@ -158,8 +168,13 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
}

if (this.plugin.settings.file.usePathToSearch && matchData1.length <= 10) {
toMatchData = indexNode.itemIndexByPath.length == 0 ? this.index.items : indexNode.itemIndexByPath;
for (let p of toMatchData.filter((p) => p.type == "file" && !matchData1.map((p) => p.item.path).includes(p.path))) {
toMatchData =
indexNode.itemIndexByPath.length == 0
? this.index.items
: indexNode.itemIndexByPath;
for (let p of toMatchData.filter(
(p) => p.type == "file" && !matchData1.map((p) => p.item.path).includes(p.path)
)) {
let d = <MatchData>p.pinyinOfPath.match(query, p, smathCase);
if (d) {
d.usePath = true;
Expand Down Expand Up @@ -201,7 +216,10 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
if (range) {
for (const r of range) {
e_title.appendText(text.slice(index, r[0]));
e_title.createSpan({ cls: "suggestion-highlight", text: text.slice(r[0], r[1] + 1) });
e_title.createSpan({
cls: "suggestion-highlight",
text: text.slice(r[0], r[1] + 1),
});
index = r[1] + 1;
}
}
Expand Down Expand Up @@ -231,8 +249,7 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
let e_flair = el.createEl("span", {
cls: "fz-suggestion-flair",
});
e_flair.innerHTML +=
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon lucide-forward"><polyline points="15 17 20 12 15 7"></polyline><path d="M4 18v-2a4 4 0 0 1 4-4h12"></path></svg>';
e_flair.appendChild(getIcon("forward"));
if (!this.plugin.settings.file.showPath) e_flair.style.top = "9px";
if (e_note) e_note.style.width = "calc(100% - 30px)";
}
Expand All @@ -251,13 +268,20 @@ export default class FuzzyFileModal extends FuzzyModal<Item> {
}
}
onNoSuggestion(): void {
super.onNoSuggestion(<MatchData>{ item: { type: "file", path: this.inputEl.value }, score: -1, usePath: true });
super.onNoSuggestion(<MatchData>{
item: { type: "file", path: this.inputEl.value },
score: -1,
usePath: true,
});
}
async getChoosenItemFile(matchData?: MatchData): Promise<TFile> {
matchData = matchData ?? this.chooser.values[this.chooser.selectedItem];
let file =
matchData.score == -1
? await app.vault.create(app.fileManager.getNewFileParent("").path + "/" + matchData.item.path + ".md", "")
? await app.vault.create(
app.fileManager.getNewFileParent("").path + "/" + matchData.item.path + ".md",
""
)
: matchData.item.file;
return file;
}
Expand All @@ -281,13 +305,18 @@ const getNewOrAdjacentLeaf = (leaf: WorkspaceLeaf): WorkspaceLeaf => {

const getMainLeaf = (): WorkspaceLeaf => {
let mainLeaf = app.workspace.getMostRecentLeaf();
if (mainLeaf && mainLeaf !== leaf && mainLeaf.view?.containerEl.ownerDocument === document) {
if (
mainLeaf &&
mainLeaf !== leaf &&
mainLeaf.view?.containerEl.ownerDocument === document
) {
return mainLeaf;
}

mainLeavesIds.forEach((id: any) => {
const l = app.workspace.getLeafById(id);
if ((leaf.parent.id == l.parent.id && mainLeaf) || !l.view?.navigation || leaf === l) return;
if ((leaf.parent.id == l.parent.id && mainLeaf) || !l.view?.navigation || leaf === l)
return;
mainLeaf = l;
});
let newLeaf: WorkspaceLeaf;
Expand Down Expand Up @@ -316,12 +345,22 @@ class PinyinIndex extends PI<Item> {
}
}
initEvent() {
this.registerEvent(this.metadataCache.on("changed", (file, data, cache) => this.update("changed", file, { data, cache })));
this.registerEvent(this.vault.on("rename", (file, oldPath) => this.update("rename", file, { oldPath })));
this.registerEvent(
this.metadataCache.on("changed", (file, data, cache) =>
this.update("changed", file, { data, cache })
)
);
this.registerEvent(
this.vault.on("rename", (file, oldPath) => this.update("rename", file, { oldPath }))
);
this.registerEvent(this.vault.on("create", (file) => this.update("create", file)));
this.registerEvent(this.vault.on("delete", (file) => this.update("delete", file)));
}
update(type: string, file: TAbstractFile, keys?: { oldPath?: string; data?: string; cache?: CachedMetadata }) {
update(
type: string,
file: TAbstractFile,
keys?: { oldPath?: string; data?: string; cache?: CachedMetadata }
) {
if (!this.isEffectiveFile(file)) return;
switch (type) {
case "changed": {
Expand Down Expand Up @@ -353,7 +392,10 @@ class PinyinIndex extends PI<Item> {

if (this.plugin.settings.file.showAllFileTypes) return true;
else if (DOCUMENT_EXTENSIONS.includes(file.extension)) return true;
else if (this.plugin.settings.file.showAttachments && this.plugin.settings.file.attachmentExtensions.includes(file.extension))
else if (
this.plugin.settings.file.showAttachments &&
this.plugin.settings.file.attachmentExtensions.includes(file.extension)
)
return true;
else return false;
}
Expand Down Expand Up @@ -381,7 +423,12 @@ function TFile2Item(file: TFile, plugin: FuzzyChinesePinyinPlugin): Item {
};
}

function CachedMetadata2Item(file: TFile, plugin: FuzzyChinesePinyinPlugin, items: Item[], cache?: CachedMetadata): Item[] {
function CachedMetadata2Item(
file: TFile,
plugin: FuzzyChinesePinyinPlugin,
items: Item[],
cache?: CachedMetadata
): Item[] {
cache = cache ?? app.metadataCache.getFileCache(file);
let alias = cache?.frontmatter?.alias || cache?.frontmatter?.aliases;
let item = items.find((item) => item.path == file.path && item.type == "file");
Expand Down
1 change: 1 addition & 0 deletions src/fuzzyModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default abstract class FuzzyModal<T extends Item> extends SuggestModal<Ma
index: PinyinIndex<T>;
plugin: FuzzyChinesePinyinPlugin;
useInput: boolean;
onInput: any;
constructor(app: App, plugin: FuzzyChinesePinyinPlugin) {
super(app);
this.useInput = false;
Expand Down
Loading

0 comments on commit b41e2fb

Please sign in to comment.