Skip to content

Commit

Permalink
fix: #93 and support upgrading build in custom replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
Benature committed Apr 2, 2024
1 parent fc4506b commit 78cc39e
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 21 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,7 @@ main.js
data.json
obsidian-text-format alias

*.sh
*.sh
*.json
!manifest.json
!manifest-beta.json
76 changes: 72 additions & 4 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import {
} from "obsidian";
import { removeWikiLink, removeUrlLink, url2WikiLink, convertWikiLinkToMarkdown } from "src/link";
import { TextFormatSettingTab } from "src/settings/settingTab";
import { FormatSettings, DEFAULT_SETTINGS, CalloutTypeDecider } from "src/settings/types";
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 } from "src/format";
import { LetterCaseCommands } from "src/commands";
import { CustomReplacementBuiltInCommands, LetterCaseCommands } from "src/commands";
import { getString } from "src/langs/langs";
import { selectionBehavior, FormatSelectionReturn } from "src/types";
import { v4 as uuidv4 } from "uuid";
import { renew } from "src/util";

function getLang() {
let lang = window.localStorage.getItem('language');
Expand Down Expand Up @@ -54,6 +56,7 @@ export default class TextFormat extends Plugin {

async onload() {
await this.loadSettings();
await this.initCustomSettings();
this.addSettingTab(new TextFormatSettingTab(this.app, this));

const lang = getLang();
Expand Down Expand Up @@ -411,7 +414,7 @@ export default class TextFormat extends Plugin {
// });
this.addCommand({
id: "space-word-symbol",
name: { en: "Format space between word and symbol", zh: "格式化单词与符号之间的空格", "zh-TW": "格式化單詞與符號之間的空格" }[lang],
name: { en: "Format space between words and symbols", zh: "格式化单词与符号之间的空格", "zh-TW": "格式化單詞與符號之間的空格" }[lang],
icon: "space",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.editorTextFormat(editor, view, "space-word-symbol");
Expand Down Expand Up @@ -548,7 +551,11 @@ export default class TextFormat extends Plugin {
}
break;
case "space-word-symbol":
replacedText = selectedText.replace(/(\w+)([\(\[]])/g, "$1 $2").replace(/([\)\]])(\w+)/g, "$1 $2");
replacedText = selectedText
.replace(/(\w+)([\(\[\{])/g, "$1 $2")
.replace(/([\)\]\}])(\w+)/g, "$1 $2")
.replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, "$1 $2")
.replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, "$1 $2");
break;
case "remove-citation":
replacedText = selectedText.replace(/\[\d+\]|【\d+】/g, "").replace(/ +/g, " ");
Expand Down Expand Up @@ -905,14 +912,75 @@ export default class TextFormat extends Plugin {

async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.compatibleSettingsUpgrade();
}

async saveSettings() {
await this.saveData(this.settings);

}

async initCustomSettings() {
if (this.manifest.version === this.settings.manifest.version) { return; } // no need to upgrade

await this.compatibleSettingsUpgrade();
for (let command of CustomReplacementBuiltInCommands) {
if (!this.settings.customReplaceBuiltInLog[command.id]) {
this.settings.customReplaceList.push({
id: command.id,
name: getString(["command", command.id]),
data: renew(command.data)
});
this.settings.customReplaceBuiltInLog[command.id] = {
id: command.id,
modified: false,
data: renew(command.data)
};
} else { // build in command is loaded in older version, then check if modified
if (!this.settings.customReplaceBuiltInLog[command.id].modified) {
// upgrade replacement data
const index = this.settings.customReplaceList.findIndex(item => item.id === command.id);
console.log(index);
if (index > -1) {
this.settings.customReplaceList[index].data = renew(command.data);
}
// this.settings.customReplaceBuiltInLog[command.id].data = command.data;
}
}
}
this.settings.manifest.version = this.manifest.version; // update version
await this.saveSettings();
}

async compatibleSettingsUpgrade() {
// uuid init
for (let i in this.settings.customReplaceList)
if (!this.settings.customReplaceList[i].id)
this.settings.customReplaceList[i].id = uuidv4();
for (let i in this.settings.WrapperList)
if (!this.settings.WrapperList[i].id)
this.settings.WrapperList[i].id = uuidv4();
for (let i in this.settings.RequestList)
if (!this.settings.RequestList[i].id)
this.settings.RequestList[i].id = uuidv4();

// @ts-ignore
const oldCustomReplaceBuiltIn = this.settings.customReplaceBuiltIn;
if (oldCustomReplaceBuiltIn &&
(!this.settings.customReplaceBuiltInLog || Object.keys(this.settings.customReplaceBuiltInLog).length == 0)) {
console.log("upgrade customReplaceBuiltInLog")
let newBuiltIn: { [id: string]: CustomReplaceBuiltIn } = {};
for (const i in oldCustomReplaceBuiltIn) {
const id: string = oldCustomReplaceBuiltIn[i]; // string
newBuiltIn[id] = { id: id, modified: false, data: CustomReplacementBuiltInCommands.find(x => x.id === id).data };
}
this.settings.customReplaceBuiltInLog = newBuiltIn;
}
}
}



function selection2range(editor: Editor, selection: EditorSelectionOrCaret): { readonly from: EditorPosition, readonly to: EditorPosition } {
let anchorOffset = editor.posToOffset(selection.anchor),
headOffset = editor.posToOffset(selection.head);
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
"@rollup/plugin-node-resolve": "^11.2.1",
"@rollup/plugin-typescript": "^8.2.1",
"@types/node": "^14.14.37",
"@types/uuid": "^9.0.8",
"obsidian": "latest",
"rollup": "^2.32.1",
"tslib": "^2.2.0",
"typescript": "^4.2.4"
"typescript": "^4.2.4",
"uuid": "9.0.0"
},
"dependencies": {
"handlebars": "^4.7.6"
}
}
}
46 changes: 35 additions & 11 deletions src/settings/settingTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Wikilink2mdPathMode, CalloutTypeDecider } from './types';
import { CustomReplacementBuiltInCommands } from "../commands"
import { getString } from "../langs/langs";
import { addDonationElement } from "./donation"
import { v4 as uuidv4 } from "uuid";

export class TextFormatSettingTab extends PluginSettingTab {
plugin: TextFormat;
Expand All @@ -14,19 +15,18 @@ export class TextFormatSettingTab extends PluginSettingTab {
super(app, plugin);
this.plugin = plugin;
this.collapseMemory = {}
this.builtInCustomReplacement();
}

async builtInCustomReplacement() {
for (let command of CustomReplacementBuiltInCommands) {
if (!this.plugin.settings.customReplaceBuiltIn.includes(command.id)) {
this.plugin.settings.customReplaceList.push({ name: getString(["command", command.id]), data: command.data });
this.plugin.settings.customReplaceBuiltIn.push(command.id);
}
}
await this.plugin.saveSettings();
// this.builtInCustomReplacement();
}

// async builtInCustomReplacement() {
// for (let command of CustomReplacementBuiltInCommands) {
// if (this.plugin.settings.customReplaceBuiltInLog[command.id] == null) {
// this.plugin.settings.customReplaceList.push({ name: getString(["command", command.id]), data: command.data });
// this.plugin.settings.customReplaceBuiltInLog[command.id] = { id: command.id, modified: false };
// }
// }
// await this.plugin.saveSettings();
// }

display(): void {
let { containerEl } = this;
Expand Down Expand Up @@ -209,6 +209,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
});
});
}

addSettingsAboutLink(containerEl: HTMLElement) {
let headerDiv = containerEl.createDiv({ cls: "header-div" });
let headerEl = headerDiv.createEl("h3", { text: "Link format" });
Expand Down Expand Up @@ -348,6 +349,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
.setCta()
.onClick(async () => {
this.plugin.settings.WrapperList.push({
id: uuidv4(),
name: "",
prefix: "",
suffix: "",
Expand Down Expand Up @@ -418,6 +420,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
.setButtonText("+")
.setCta().onClick(async () => {
this.plugin.settings.RequestList.push({
id: uuidv4(),
name: "",
url: "",
});
Expand Down Expand Up @@ -474,6 +477,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
.setButtonText("+")
.setCta().onClick(async () => {
this.plugin.settings.customReplaceList.push({
id: uuidv4(),
name: "",
data: [{
search: "",
Expand All @@ -485,6 +489,24 @@ export class TextFormatSettingTab extends PluginSettingTab {
});
})
this.plugin.settings.customReplaceList.forEach((replaceSetting, index) => {
const checkIsBuiltIn = () => {
if (this.plugin.settings.customReplaceBuiltInLog[replaceSetting.id]) {
let logData = this.plugin.settings.customReplaceBuiltInLog[replaceSetting.id].data;
let nowData = replaceSetting.data;
if (logData.length != nowData.length) {
this.plugin.settings.customReplaceBuiltInLog[replaceSetting.id].modified = true;
return;
}
for (let i = 0; i < logData.length; i++) {
console.log(logData[i], nowData[i])
if (logData[i].search !== nowData[i].search || logData[i].replace !== nowData[i].replace) {
this.plugin.settings.customReplaceBuiltInLog[replaceSetting.id].modified = true;
return;
}
}
this.plugin.settings.customReplaceBuiltInLog[replaceSetting.id].modified = false;
}
};
const s = new Setting(this.contentEl)
.addText((cb) => {
cb.setPlaceholder("Command name")
Expand All @@ -500,6 +522,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
.setValue(replaceSetting.data[0].search)
.onChange(async (newValue) => {
this.plugin.settings.customReplaceList[index].data[0].search = newValue;
checkIsBuiltIn();
await this.plugin.saveSettings();
this.plugin.debounceUpdateCommandCustomReplace();
});
Expand All @@ -509,6 +532,7 @@ export class TextFormatSettingTab extends PluginSettingTab {
.setValue(replaceSetting.data[0].replace)
.onChange(async (newValue) => {
this.plugin.settings.customReplaceList[index].data[0].replace = newValue;
checkIsBuiltIn();
await this.plugin.saveSettings();
this.plugin.debounceUpdateCommandCustomReplace();
});
Expand Down
21 changes: 18 additions & 3 deletions src/settings/types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@

export interface WrapperSetting {
id: string;
name: string;
prefix: string;
suffix: string;
}

export interface APIRequestSetting {
id: string;
name: string;
url: string;
}
Expand All @@ -22,6 +24,7 @@ export interface customReplaceSettingPair {
}

export interface customReplaceSetting {
id: string;
name: string;
data: Array<customReplaceSettingPair>;
}
Expand All @@ -39,7 +42,16 @@ export enum CalloutTypeDecider {
fix = "fix",
}

export interface CustomReplaceBuiltIn {
id: string;
modified: boolean;
data: Array<customReplaceSettingPair>;
}

export interface FormatSettings {
manifest: {
version: string;
}
MergeParagraph_Newlines: boolean;
MergeParagraph_Spaces: boolean;
LowercaseFirst: boolean;
Expand All @@ -50,7 +62,7 @@ export interface FormatSettings {
WrapperList: Array<WrapperSetting>;
RequestList: Array<APIRequestSetting>;
customReplaceList: Array<customReplaceSetting>;
customReplaceBuiltIn: Array<string>;
customReplaceBuiltInLog: { [id: string]: CustomReplaceBuiltIn };
ToggleSequence: string;
RemoveWikiURL2: boolean;
WikiLinkFormat: WikiLinkFormatGroup;
Expand All @@ -65,17 +77,20 @@ export interface FormatSettings {
}

export const DEFAULT_SETTINGS: FormatSettings = {
manifest: {
version: "0.0.0",
},
MergeParagraph_Newlines: true,
MergeParagraph_Spaces: true,
LowercaseFirst: true,
RemoveBlanksWhenChinese: false,
ZoteroNoteRegExp: String.raw`“(?<text>.*)” \((?<item>.*?)\) \(\[pdf\]\((?<pdf_url>.*?)\)\)`,
ZoteroNoteTemplate: "{text} [🔖]({pdf_url})",
BulletPoints: "•–§",
WrapperList: [{ name: "underline", prefix: "<u>", suffix: "</u>" }],
WrapperList: [{ name: "underline", prefix: "<u>", suffix: "</u>", id: "underline" }],
RequestList: [],
customReplaceList: [],
customReplaceBuiltIn: [],
customReplaceBuiltInLog: {},
ToggleSequence: "titleCase\nlowerCase\nupperCase",
RemoveWikiURL2: false,
WikiLinkFormat: { headingOnly: "{title} (> {heading})", aliasOnly: "{alias} ({title})", both: "{alias} ({title} > {heading})" },
Expand Down
3 changes: 3 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function renew(data: any) {
return JSON.parse(JSON.stringify(data));
}

0 comments on commit 78cc39e

Please sign in to comment.