Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: profile for commands #1

Merged
merged 3 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"delete": "Delete",
"from": "From",
"pattern": "pattern",
"profile": "Profile name",
"replacement": "replacement",
"save": "Save",
"to": "To"
Expand All @@ -35,6 +36,8 @@
"desc": "Show debug log in console",
"title": "Debug information"
},
"delete": {
},
"edit": {
"desc": "Edit view settings",
"title": "Edit"
Expand Down Expand Up @@ -81,10 +84,16 @@
"openTextReplacer": "Open Text replacer",
"other": "Other options",
"overrideCopy": {
"desc": "Replace the native copy (CTRL C, right-click...) with the enhanced copy",
"desc": "Replace the native copy (CTRL C, right-click...) with the enhanced copy (need a reload of Obsidian)",
"title": "Override native copy"
},
"overrides": "Overrides previous settings",
"profile": {
"add": {
"desc": "Add a copy profile. \nAn Obsidian reload is required to use it as a command.",
"title": "Add profile"
},
"delete": "Delete profile"
},
"reading": {
"desc": "Reading view settings",
"title": "Reading"
Expand All @@ -96,7 +105,6 @@
"remove": "Remove all links markup and contents",
"title": "Footnotes format"
},
"settings": "[ COPY OPTIONS ]",
"spaceSize": {
"desc": "Number of spaces to be used for indentation. Use -1 to disable the conversion.",
"title": "Space size"
Expand Down
14 changes: 11 additions & 3 deletions src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"delete": "Supprimer",
"from": "Depuis",
"pattern": "pattern",
"profile": "Nom du profil",
"replacement": "remplacement",
"save": "Sauvegarder",
"to": "Vers"
Expand All @@ -35,6 +36,8 @@
"desc": "Affiche le journal de débogage dans la console",
"title": "Informations de débogage"
},
"delete": {
},
"edit": {
"desc": "Paramètre pour la vue d'édition",
"title": "Édition"
Expand Down Expand Up @@ -81,10 +84,16 @@
"openTextReplacer": "Ouvrir le remplacement de texte",
"other": "Autres options",
"overrideCopy": {
"desc": "Remplacer la copie native (CTRL + C, clic-droit...) par la copie améliorée",
"desc": "Remplacer la copie native (CTRL + C, clic-droit...) par la copie améliorée (nécessite un rechargement d'Obsidian)",
"title": "Prendre en charge la copie native"
},
"overrides": "Remplace les paramètres précédents",
"profile": {
"add": {
"desc": "Ajouter un profil de copy. Un rechargement d'Obsidian est nécessaire pour l'utiliser comme commande.",
"title": "Ajouter un profile"
},
"delete": "Supprimer le profile"
},
"reading": {
"desc": "Paramètre pour la vue de lecture",
"title": "Lecture"
Expand All @@ -96,7 +105,6 @@
"remove": "Supprimer balises et contenu",
"title": "Format des footnotes"
},
"settings": "[ COPY OPTIONS ]",
"spaceSize": {
"desc": "Modification du nombre d'espace pour la mise en retrait. Utiliser -1 pour désactiver la fonction de conversion.",
"title": "Nombre d'espace"
Expand Down
34 changes: 20 additions & 14 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,11 @@ export interface EnhancedCopySettings {
exportAsHTML: boolean;
applyingTo: ApplyingToView;
separateHotkey: boolean;
wikiToMarkdown: boolean;
tabToSpace: boolean;
tabSpaceSize: number;
spaceReadingSize: number;
editing: GlobalSettings;
reading: GlobalSettings;
overrideCopy: boolean;
devMode: boolean;
profiles: GlobalSettings[];

}

/**
Expand All @@ -93,37 +90,46 @@ export const DEFAULT_SETTINGS: EnhancedCopySettings = {
exportAsHTML: false,
applyingTo: ApplyingToView.all,
separateHotkey: false,
wikiToMarkdown: false,
tabToSpace: false,
tabSpaceSize: 4,
spaceReadingSize: -1, //disabled
editing: {
footnotes: ConversionOfFootnotes.keep,
links: ConversionOfLinks.keep,
callout: CalloutKeepType.obsidian,
highlight: false,
hardBreak: false,
replaceText: []
replaceText: [],
overrideNativeCopy: false
},
reading: {
footnotes: ConversionOfFootnotes.keep,
links: ConversionOfLinks.keep,
callout: CalloutKeepType.obsidian,
highlight: false,
hardBreak: false,
replaceText: []
replaceText: [],
overrideNativeCopy: false,
spaceReadingSize: -1, // -1 disabled
wikiToMarkdown: false
},
overrideCopy: false,
devMode: false
devMode: false,
profiles: []
};

export interface GlobalSettings {
name?: string,
copyAsHTML?: boolean,
footnotes: ConversionOfFootnotes,
links: ConversionOfLinks,
callout: CalloutKeepType,
highlight: boolean,
hardBreak: boolean,
replaceText: ReplaceText[]
replaceText: ReplaceText[],
overrideNativeCopy: boolean,
spaceReadingSize?: number, //only work in reading mode
tabToSpace?: boolean //only work in edit mode
tabSpaceSize?: number //only work in edit mode
wikiToMarkdown?: boolean
applyingTo?: ApplyingToView //only work in profiles

}

export interface ReplaceText {
Expand Down
90 changes: 59 additions & 31 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import {EditorView} from "@codemirror/view";
import { EditorView } from "@codemirror/view";
import i18next from "i18next";
import {around} from "monkey-around";
import { ItemView, MarkdownView, Platform, Plugin, WorkspaceLeaf} from "obsidian";
import { around } from "monkey-around";
import { ItemView, MarkdownView, Platform, Plugin, WorkspaceLeaf } from "obsidian";
import merge from "ts-deepmerge";

import {resources, translationLanguage} from "./i18n/i18next";
import {ApplyingToView, DEFAULT_SETTINGS,EnhancedCopySettings} from "./interface";
import {EnhancedCopySettingTab} from "./settings";
import {convertEditMarkdown, convertMarkdown,} from "./utils/conversion";
import {removeDataBasePluginRelationShip} from "./utils/pluginFix";
import {canvasSelectionText, copySelectionRange, getSelectionAsHTML} from "./utils/selection";
import { resources, translationLanguage } from "./i18n/i18next";
import { ApplyingToView, DEFAULT_SETTINGS, EnhancedCopySettings, GlobalSettings } from "./interface";
import { EnhancedCopySettingTab } from "./settings";
import { convertEditMarkdown, convertMarkdown, } from "./utils/conversion";
import { removeDataBasePluginRelationShip } from "./utils/pluginFix";
import { canvasSelectionText, copySelectionRange, getSelectionAsHTML } from "./utils/selection";

export default class EnhancedCopy extends Plugin {
settings: EnhancedCopySettings = DEFAULT_SETTINGS;
//eslint-disable-next-line @typescript-eslint/no-explicit-any
activeMonkeys: Record<string, any> = {};

enhancedCopy() {
enhancedCopy(profile?: GlobalSettings) {
//get default if a modal is opened
if (document.querySelector(".modal-container")) {
return activeWindow.getSelection()?.toString() ?? "";
Expand All @@ -26,7 +26,7 @@ export default class EnhancedCopy extends Plugin {
let selectedText: string;
if (activeView && activeView.getMode() !== "source") {
this.devLog(i18next.t("log.readingMode"));
selectedText = getSelectionAsHTML(this.settings);
selectedText = getSelectionAsHTML(profile ?? this.settings.reading);
viewIn = ApplyingToView.reading;
} else if (activeView) {
this.devLog(i18next.t("log.editMode"));
Expand All @@ -43,15 +43,17 @@ export default class EnhancedCopy extends Plugin {
viewIn = ApplyingToView.reading;
}
}

const exportAsHTML = profile ? profile?.copyAsHTML ?? false : this.settings.reading.copyAsHTML;
const applyingTo = profile?.applyingTo ?? this.settings.applyingTo;
if (selectedText && selectedText.trim().length > 0) {
if (!this.settings.exportAsHTML &&
(this.settings.applyingTo === ApplyingToView.all || this.settings.applyingTo === viewIn)
if (!exportAsHTML &&
(applyingTo === ApplyingToView.all || applyingTo === viewIn)
) {
console.log(profile);
selectedText = viewIn === ApplyingToView.edit
?
convertEditMarkdown(selectedText, this.settings.editing, this) :
convertMarkdown(selectedText, this.settings.reading, this);
convertEditMarkdown(selectedText, profile ?? this.settings.editing, this) :
convertMarkdown(selectedText, profile ?? this.settings.reading, this);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic within enhancedCopy to determine whether to export as HTML or convert markdown based on the selected profile or default settings is correctly implemented. However, the console log on line 52 seems to be for debugging purposes and should be removed or guarded by a development mode check.

- console.log(profile);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const exportAsHTML = profile ? profile?.copyAsHTML ?? false : this.settings.reading.copyAsHTML;
const applyingTo = profile?.applyingTo ?? this.settings.applyingTo;
if (selectedText && selectedText.trim().length > 0) {
if (!this.settings.exportAsHTML &&
(this.settings.applyingTo === ApplyingToView.all || this.settings.applyingTo === viewIn)
if (!exportAsHTML &&
(applyingTo === ApplyingToView.all || applyingTo === viewIn)
) {
console.log(profile);
selectedText = viewIn === ApplyingToView.edit
?
convertEditMarkdown(selectedText, this.settings.editing, this) :
convertMarkdown(selectedText, this.settings.reading, this);
convertEditMarkdown(selectedText, profile ?? this.settings.editing, this) :
convertMarkdown(selectedText, profile ?? this.settings.reading, this);
const exportAsHTML = profile ? profile?.copyAsHTML ?? false : this.settings.reading.copyAsHTML;
const applyingTo = profile?.applyingTo ?? this.settings.applyingTo;
if (selectedText && selectedText.trim().length > 0) {
if (!exportAsHTML &&
(applyingTo === ApplyingToView.all || applyingTo === viewIn)
) {
selectedText = viewIn === ApplyingToView.edit
?
convertEditMarkdown(selectedText, profile ?? this.settings.editing, this) :
convertMarkdown(selectedText, profile ?? this.settings.reading, this);

return selectedText;
} else if (viewIn === ApplyingToView.edit) {
Expand All @@ -61,10 +63,13 @@ export default class EnhancedCopy extends Plugin {
}

overrideNativeCopy(leaf: WorkspaceLeaf) {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView && activeView.getMode() !== "source" && !this.settings.reading.overrideNativeCopy) return;
if (activeView && activeView.getMode() === "source" && !this.settings.editing.overrideNativeCopy) return;
try {
return around(leaf.view, {
//@ts-ignore
handleCopy: () =>{
handleCopy: () => {
return (event: ClipboardEvent) => {
try {
const selectedText = this.enhancedCopy();
Expand Down Expand Up @@ -116,14 +121,35 @@ export default class EnhancedCopy extends Plugin {
fallbackLng: "en",
resources,
returnNull: false,
returnEmptyString: false,
});

await this.loadSettings();
this.addSettingTab(new EnhancedCopySettingTab(this.app, this));

/**
* Copy the selected text in markdown format
*/

for (const profile of this.settings.profiles) {
if (!profile.name) continue;
this.addCommand({
id: `copy-${profile.name}-in-markdown`,
name: profile.name,
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
const readingMode = view && view.getMode() !== "source";
if (profile.applyingTo === ApplyingToView.all ||
(profile.applyingTo === ApplyingToView.reading && readingMode) ||
(profile.applyingTo === ApplyingToView.edit && !readingMode)
) {
if (!checking) {
navigator.clipboard.writeText(this.enhancedCopy(profile));
}
return true;
}
return false;
}
});
}

if (!this.settings.separateHotkey || this.settings.applyingTo !== ApplyingToView.all) {
this.addCommand({
id: "copy-all-in-markdown",
Expand Down Expand Up @@ -153,7 +179,7 @@ export default class EnhancedCopy extends Plugin {
const readingMode = view && view.getMode() !== "source";
if (readingMode) {
if (!checking) {
let selectedText = getSelectionAsHTML(this.settings);
let selectedText = getSelectionAsHTML(this.settings.reading);
if (!this.settings.exportAsHTML) {
selectedText = convertMarkdown(selectedText, this.settings.reading, this);
}
Expand Down Expand Up @@ -203,7 +229,7 @@ export default class EnhancedCopy extends Plugin {
});
}

if (this.settings.overrideCopy) {
if (this.settings.reading.overrideNativeCopy || this.settings.editing.overrideNativeCopy) {
this.registerEvent(this.app.workspace.on("active-leaf-change", async (leaf) => {
if (!leaf) {
for (const monkey of Object.values(this.activeMonkeys)) {
Expand All @@ -215,7 +241,7 @@ export default class EnhancedCopy extends Plugin {
//@ts-ignore
this.activeMonkeys[leaf.id] = this.overrideNativeCopy(leaf);
//enable clipboard event in canvas read-only
if (leaf.view instanceof ItemView && leaf.view.getViewType() === "canvas") {
if (leaf.view instanceof ItemView && leaf.view.getViewType() === "canvas" && this.settings.reading.overrideNativeCopy) {
leaf.view.containerEl.addEventListener("copy", (event) => {
this.editorCopyHandler(event);
});
Expand All @@ -225,16 +251,18 @@ export default class EnhancedCopy extends Plugin {

}
}));
if (this.settings.editing.overrideNativeCopy) {
//register for editor
const copyExt = EditorView.domEventHandlers({
copy: this.editorCopyHandler.bind(this)
});
const cutExt = EditorView.domEventHandlers({
cut: this.editorCutHandler.bind(this)
});
const copyExt = EditorView.domEventHandlers({
copy: this.editorCopyHandler.bind(this)
});
const cutExt = EditorView.domEventHandlers({
cut: this.editorCutHandler.bind(this)
});

this.registerEditorExtension(copyExt);
this.registerEditorExtension(cutExt);
this.registerEditorExtension(copyExt);
this.registerEditorExtension(cutExt);
}
}
}
onunload() {
Expand Down
44 changes: 44 additions & 0 deletions src/modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,47 @@ export class EnhancedCopyViewModal extends Modal {
contentEl.empty();
}
}

export class NameProfile extends Modal {
name: string = "";
onSubmit: (result: string) => void;
constructor(app: App, onSubmit: (result: string) => void) {
super(app);
this.onSubmit = onSubmit;
}
onOpen() {
const {contentEl} = this;
contentEl.empty();
contentEl.addClass("enhanced-copy");
new Setting(contentEl)
.setName(i18next.t("common.profile"))
.setClass("modal-title")
.addText(text => text
.setPlaceholder(i18next.t("common.profile"))
.setValue(this.name)
.onChange(async (value) => {
this.name = value;
})
.inputEl.classList.add("full-width")
);

new Setting(contentEl)
.addButton(button => button
.setButtonText(i18next.t("common.save"))
.setCta()
.onClick(async () => {
this.onSubmit(this.name);
this.close();
}))
.addButton(button => button
.setButtonText(i18next.t("common.cancel"))
.setWarning()
.onClick(async () => {
this.close();
}));
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
Loading
Loading