Skip to content

Commit

Permalink
several commands (e.g. decode URI) support in front matter (metadata)
Browse files Browse the repository at this point in the history
  • Loading branch information
Benature committed Jun 14, 2024
1 parent 63d3e85 commit 0c10862
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 53 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
## 🏗️ developed
> to be update in the next version
## 3.1.0-b1
- [feature] several commands (e.g. decode URI) support in front matter (metadata)
- [feature] command for open settings tab directly

## 3.0.5
Expand Down
141 changes: 91 additions & 50 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { removeWikiLink, removeUrlLink, url2WikiLink, convertWikiLinkToMarkdown
import { TextFormatSettingTab } from "src/settings/settingTab";
import { FormatSettings, DEFAULT_SETTINGS, CalloutTypeDecider, CustomReplaceBuiltIn } from "src/settings/types";
import { array2markdown, table2bullet, capitalizeWord, capitalizeSentence, removeAllSpaces, zoteroNote, textWrapper, replaceLigature, ankiSelection, sortTodo, requestAPI, headingLevel, slugify, snakify, extraDoubleSpaces, toTitleCase, customReplace, convertLatex, camelCase } from "src/format";
import { CustomReplacementBuiltInCommands, LetterCaseCommands } from "src/commands";
import { CustomReplacementBuiltInCommands, GlobalCommands } from "src/commands";
import { getString } from "src/langs/langs";
import { selectionBehavior, FormatSelectionReturn } from "src/types";
import { v4 as uuidv4 } from "uuid";
Expand All @@ -18,10 +18,6 @@ function getLang() {
return lang;
}

function isActiveTitle(): boolean {
const activeClasses = document.activeElement.classList;
return activeClasses.contains("inline-title") || activeClasses.contains("view-header-title");
}

export default class TextFormat extends Plugin {
settings: FormatSettings;
Expand All @@ -34,16 +30,59 @@ export default class TextFormat extends Plugin {
this.app.commands.executeCommandById(cmd);
}

async formatEditorOrTitle(cmd: string) {
if (isActiveTitle()) {
const file = this.app.workspace.getActiveFile();
const formatResult = await this.formatSelection(file.basename, cmd);
const newName = formatResult.editorChange.text;
const newPath = normalizePath(file.parent.path + "/" + newName + "." + file.extension)
this.app.vault.adapter.rename(file.path, newPath);
} else {
// @ts-ignore
this.app.commands.executeCommandById(`obsidian-text-format::private:${cmd}`);
async quickFormat(text: string, cmd: string) {
let formatRes = await this.formatSelection(text, cmd);
let res = formatRes.editorChange.text
if (res)
return res;
return text;
}

async formatGlobal(cmd: string) {
let activeElement = document.activeElement;
const activeClasses = activeElement.classList;

let where = "editor";
if (activeClasses.contains("inline-title") || activeClasses.contains("view-header-title")) {
where = "title";
} else if (activeClasses.contains("metadata-input-longtext")) {
where = "metadata-long-text"
} else if (activeClasses.contains("metadata-property")) {
let longtext = activeElement.querySelector(".metadata-input-longtext");
if (longtext) {
activeElement = longtext;
where = "metadata-long-text"
}
}
const file = this.app.workspace.getActiveFile();

switch (where) {
case "editor":
this.executeCommandById(`obsidian-text-format::private:${cmd}`);
break;
case "title":
const formatResult = await this.formatSelection(file.basename, cmd);
const newName = formatResult.editorChange.text;
const newPath = normalizePath(file.parent.path + "/" + newName + "." + file.extension)
this.app.vault.adapter.rename(file.path, newPath);
break;
case "metadata-long-text":
const activePPElement = activeElement.parentElement.parentElement;
let metadataKey = activePPElement.getAttribute("data-property-key");
// focus on parent element, so that the new frontmatter can be updated
activePPElement.focus();
if (!file)
break;
const text = activeElement.textContent;
const replacedText = await this.quickFormat(text, cmd);
await this.app.fileManager.processFrontMatter(file, (fm) => {
fm[metadataKey] = replacedText;
});
// let keyboardEvent = new KeyboardEvent('keydown', {
// keyCode: 13, code: 'KeyEnter', key: 'Enter'
// })
// document.activeElement.dispatchEvent(keyboardEvent);
break;
}
}

Expand Down Expand Up @@ -116,13 +155,13 @@ export default class TextFormat extends Plugin {
},
});

LetterCaseCommands.forEach(command => {
GlobalCommands.forEach(command => {
this.addCommand({
id: command.id,
name: getString(["command", command.id]),
icon: "case-sensitive",
callback: () => {
this.formatEditorOrTitle(command.id);
callback: async () => {
await this.formatGlobal(command.id);
},
});
this.addCommand({
Expand Down Expand Up @@ -412,37 +451,38 @@ export default class TextFormat extends Plugin {
this.debounceUpdateCommandRequest();
this.debounceUpdateCommandCustomReplace();

this.addCommand({
id: "decodeURI",
name: { en: "Decode URL", zh: "解码 URL", "zh-TW": "解碼 URL" }[lang],
icon: "link",
callback: async () => {
const activeElement = document.activeElement;
if (activeElement.classList.contains("metadata-input-longtext")) {
let metadataKey = activeElement.parentElement.parentElement.getAttribute("data-property-key");
// focus on parent element, so that the new frontmatter can be updated
activeElement.parentElement.parentElement.focus();
const file = this.app.workspace.getActiveFile();
const frontmatter = this.app.metadataCache.getCache(file?.path as string)?.frontmatter;
let formatRes = await this.formatSelection(frontmatter[metadataKey], "decodeURI");
if (file) {
await this.app.fileManager.processFrontMatter(file, (fm) => {
fm[metadataKey] = formatRes.editorChange.text;
});
}
} else {
this.executeCommandById(`obsidian-text-format::editor:decodeURI`);
}
},
});
this.addCommand({
id: ":editor:decodeURI",
name: { en: "Decode URL", zh: "解码 URL", "zh-TW": "解碼 URL" }[lang] + " (Editor)",
icon: "link",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.editorTextFormat(editor, view, "decodeURI");
},
});
// this.addCommand({
// id: "decodeURI",
// name: { en: "Decode URL", zh: "解码 URL", "zh-TW": "解碼 URL" }[lang],
// icon: "link",
// callback: async () => {
// const activeElement = document.activeElement;
// if (activeElement.classList.contains("metadata-input-longtext")) {
// let metadataKey = activeElement.parentElement.parentElement.getAttribute("data-property-key");
// // focus on parent element, so that the new frontmatter can be updated
// activeElement.parentElement.parentElement.focus();
// const file = this.app.workspace.getActiveFile();
// const frontmatter = this.app.metadataCache.getCache(file?.path as string)?.frontmatter;
// let formatRes = await this.formatSelection(frontmatter[metadataKey], "decodeURI");
// if (file) {
// await this.app.fileManager.processFrontMatter(file, (fm) => {
// fm[metadataKey] = formatRes.editorChange.text;
// });
// // activeElement.parentElement.focus();
// }
// } else {
// this.executeCommandById(`obsidian-text-format::editor:decodeURI`);
// }
// },
// });
// this.addCommand({
// id: ":editor:decodeURI",
// name: { en: "Decode URL", zh: "解码 URL", "zh-TW": "解碼 URL" }[lang] + " (Editor)",
// icon: "link",
// editorCallback: (editor: Editor, view: MarkdownView) => {
// this.editorTextFormat(editor, view, "decodeURI");
// },
// });

this.addCommand({
id: "space-word-symbol",
Expand Down Expand Up @@ -642,7 +682,7 @@ export default class TextFormat extends Plugin {
case "Chinese-punctuation":
replacedText = selectedText;
replacedText = replacedText
.replace(/(?:[\u4e00-\u9fa5])( ?, ?)(?:[\u4e00-\u9fa5])/g,(t, t1) => t.replace(t1, ","))
.replace(/(?:[\u4e00-\u9fa5])( ?, ?)(?:[\u4e00-\u9fa5])/g, (t, t1) => t.replace(t1, ","))
.replace(/(?:[^\d])( ?\. ?)/g, (t, t1) => t.replace(t1, "。"))
.replace(/ ?、 ?/g, "、")
.replace(/;/g, ";")
Expand Down Expand Up @@ -671,6 +711,7 @@ export default class TextFormat extends Plugin {
.replace(/%2F/g, "/");
}
);
console.log(replacedText);
break;
case "hyphen":
replacedText = selectedText.replace(/(\w)-[ ]/g, "$1");
Expand Down
2 changes: 1 addition & 1 deletion manifest-beta.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-text-format",
"name": "Text Format",
"version": "3.0.5",
"version": "3.1.0-b1",
"minAppVersion": "0.9.7",
"description": "Format text such as lowercase/uppercase/capitalize/titlecase, converting order/bullet list, removing redundant spaces/newline characters.",
"author": "Benature",
Expand Down
13 changes: 11 additions & 2 deletions src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
export const LetterCaseCommands = [
export const GlobalCommands = [
{
id: "lowercase",
icon: "case-sensitive",
}, {
id: "uppercase",
icon: "case-sensitive",
}, {
id: "capitalize-word",
icon: "case-sensitive",
}, {
id: "capitalize-sentence",
icon: "case-sensitive",
}, {
id: "title-case",
icon: "case-sensitive",
}, {
id: "cycle-case",
},
icon: "case-sensitive",
}, {
id: "decodeURI",
icon: "link",
}
]

export const CustomReplacementBuiltInCommands = [
Expand Down
2 changes: 2 additions & 0 deletions src/langs/langs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const EN = {
"cycle-case": "Cycle-case",
"slugify": "Slugify",
"snakify": "Snakify",
"decodeURI": "Decode URL",
"remove-trailing-spaces": "Remove trailing spaces",
"remove-blank-line": "Remove blank line(s)",
"add-line-break": "Add extra line break between paragraphs",
Expand Down Expand Up @@ -129,6 +130,7 @@ const ZH = {
"heading-upper": "降级标题(加 #)",
"heading-lower": "升级标题(减 #)",
"open-settings": "打开插件设置选项卡",
"decodeURI": "解码 URL",
},
setting: {
"more-details": "在 Github 查看更多详情:",
Expand Down

0 comments on commit 0c10862

Please sign in to comment.