Initial commit

Signed-off-by: Felvesthe <23108389+Felvesthe@users.noreply.github.com>
This commit is contained in:
Felvesthe 2025-03-24 20:05:58 +01:00
parent 6d09ce3e39
commit 1dde3618c7
5 changed files with 140 additions and 138 deletions

22
LICENSE
View file

@ -1,5 +1,21 @@
Copyright (C) 2020-2025 by Dynalist Inc.
MIT License
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
Copyright (c) 2025 Felvesthe
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

231
main.ts
View file

@ -1,134 +1,129 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import { MarkdownView, Menu, Notice, Platform, Plugin, TFile, WorkspaceLeaf } from "obsidian";
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
interface NoteLockerSettings {
lockedNotes: Set<string>;
mobileNotificationMaxLength: number;
desktopNotificationMaxLength: number;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
const DEFAULT_SETTINGS: NoteLockerSettings = {
lockedNotes: new Set(),
mobileNotificationMaxLength: 18,
desktopNotificationMaxLength: 22
};
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
export default class NoteLockerPlugin extends Plugin {
settings = DEFAULT_SETTINGS;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
this.registerEventHandlers();
this.initializeExistingLeaves();
}
onunload() {
private registerEventHandlers() {
this.registerEvent(
this.app.workspace.on("file-menu", (menu, file) =>
this.addLockMenuItem(menu, file.path)
)
);
this.registerEvent(
this.app.workspace.on("editor-menu",(menu, _, view) =>
view.file && this.addLockMenuItem(menu, view.file.path)
)
);
this.registerEvent(
this.app.workspace.on("active-leaf-change", (leaf) =>
this.updateLeafMode(leaf)
)
);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
private initializeExistingLeaves() {
this.app.workspace
.getLeavesOfType("markdown")
.forEach((leaf) => this.updateLeafMode(leaf));
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
private addLockMenuItem(menu: Menu, filePath: string) {
const isLocked = this.settings.lockedNotes.has(filePath);
menu.addItem((item) =>
item
.setTitle(isLocked ? "Unlock" : "Lock")
.setIcon(isLocked ? "unlock" : "lock")
.onClick(() => this.toggleNoteLock(filePath))
);
}
private async toggleNoteLock(notePath: string) {
const isLocked = this.settings.lockedNotes.has(notePath);
isLocked
? this.settings.lockedNotes.delete(notePath)
: this.settings.lockedNotes.add(notePath);
await this.saveSettings();
const file = this.app.vault.getAbstractFileByPath(notePath);
const fileName = file instanceof TFile ? file.basename :
notePath.split('/').pop()?.replace(/\..+$/, '') || notePath;
const displayName = this.truncateFileName(fileName);
new Notice(`${isLocked ? '🔓 Unlocked' : '🔒 Locked'}: ${displayName}`);
this.updateAllNoteInstances(notePath);
}
private truncateFileName(name: string): string {
const maxLength = Platform.isMobile
? this.settings.mobileNotificationMaxLength
: this.settings.desktopNotificationMaxLength;
return name.length > maxLength
? `${name.slice(0, maxLength)}`
: name;
}
private updateAllNoteInstances(notePath: string) {
this.app.workspace
.getLeavesOfType("markdown")
.filter((leaf) => this.isSameNote(leaf, notePath))
.forEach((leaf) => this.updateLeafMode(leaf));
}
private isSameNote(leaf: WorkspaceLeaf, notePath: string): boolean {
const view = leaf.view;
return view instanceof MarkdownView && view.file?.path === notePath;
}
private updateLeafMode(leaf: WorkspaceLeaf | null) {
if (!leaf || !(leaf.view instanceof MarkdownView)) return;
const { view } = leaf;
const targetMode =
view.file && this.settings.lockedNotes.has(view.file.path)
? "preview"
: "source";
if (leaf.getViewState().state?.mode !== targetMode) {
leaf.setViewState({
...leaf.getViewState(),
state: { ...leaf.getViewState().state, mode: targetMode },
});
}
}
private async loadSettings() {
const loaded = await this.loadData();
if (loaded) {
this.settings.lockedNotes = new Set(loaded.lockedNotes);
}
}
private async saveSettings() {
await this.saveData({
lockedNotes: Array.from(this.settings.lockedNotes),
});
}
}

View file

@ -1,11 +1,10 @@
{
"id": "sample-plugin",
"name": "Sample Plugin",
"id": "note-locker",
"name": "Note Locker",
"version": "1.0.0",
"minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"description": "Note Locker allows you to \"lock\" a note so that it opens in preview mode by default",
"author": "Felvesthe",
"authorUrl": "https://github.com/Felvesthe",
"isDesktopOnly": false
}

View file

@ -1,7 +1,7 @@
{
"name": "obsidian-sample-plugin",
"name": "note-locker",
"version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"description": "Note Locker allows you to \"lock\" a note so that it opens in preview mode by default",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
@ -9,7 +9,7 @@
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
"author": "",
"author": "Felvesthe",
"license": "MIT",
"devDependencies": {
"@types/node": "^16.11.6",

View file

@ -1,8 +0,0 @@
/*
This CSS file will be included with your plugin, and
available in the app when your plugin is enabled.
If your plugin does not need CSS, delete this file.
*/