Adds basic functionality

This commit is contained in:
Scott Tomaszewski 2024-01-25 17:03:37 -05:00
parent 7667bd3359
commit 1b2bc32f73
4 changed files with 1403 additions and 98 deletions

305
main.ts
View file

@ -1,134 +1,257 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import {
App,
Editor,
MarkdownPreviewView,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
WorkspaceLeaf
} from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
interface InlineAdmonitionSettings {
mySetting: string;
inlineAdmonitions: Map<string, InlineAdmonition>;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
class InlineAdmonition {
prefix: string;
backgroundColor: string;
color: string;
static create() {
return new InlineAdmonition("", "#f1f1f1", "#000000");
}
constructor(prefix, backgroundColor, color) {
this.prefix = prefix;
this.backgroundColor = backgroundColor;
this.color = color;
}
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
const DEFAULT_SETTINGS: InlineAdmonitionSettings = {
mySetting: 'default',
inlineAdmonitions: new Map<string, InlineAdmonition>()
}
export default class InlineAdmonitionPlugin extends Plugin {
settings: InlineAdmonitionSettings;
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');
// Actual processor to render the inline admonitions
this.registerMarkdownPostProcessor((element, context) => {
const codeblocks = element.findAll("code");
// 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();
for (let codeblock of codeblocks) {
this.settings.inlineAdmonitions.forEach((iad, identifier) => {
if (codeblock.innerText.startsWith(iad.prefix)) {
codeblock.classList.add("iad");
codeblock.classList.add("iad-" + slugify(iad.prefix));
codeblock.setAttribute(
"style",
`background-color: ${iad.backgroundColor};color: ${iad.color}`);
}
});
// 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.addSettingTab(new InlineAdmonitionSettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
let settingData = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, settingData);
let iads = new Map<string, InlineAdmonition>();
for (const identifier in settingData.inlineAdmonitions) {
let iad = settingData.inlineAdmonitions[identifier]
iads.set(identifier, {prefix: iad.prefix, backgroundColor: iad.backgroundColor, color: iad.color})
}
this.settings.inlineAdmonitions = iads;
}
async saveSettings() {
await this.saveData(this.settings);
let settingData = Object.assign({}, DEFAULT_SETTINGS, this.settings);
settingData.inlineAdmonitions = Object.fromEntries(this.settings.inlineAdmonitions.entries());
await this.saveData(settingData);
this.rerenderMarkdownViews();
}
private rerenderMarkdownViews() {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
view?.previewMode.rerender(true);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
// Settings
class InlineAdmonitionSettingTab extends PluginSettingTab {
plugin: InlineAdmonitionPlugin;
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
constructor(app: App, plugin: InlineAdmonitionPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
// Create Inline Admonition Button
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();
.addButton(b => b
.setButtonText("Create New Inline Admonition")
.onClick(async evt => {
EditInlineAdmonitionModal.new(this.app, async result => {
this.plugin.settings.inlineAdmonitions.set(result.prefix, result);
await this.plugin.saveSettings();
this.rebuildSettingRows(containerEl);
}).open();
}));
this.rebuildSettingRows(containerEl);
}
// Renders the "samples" with options in the main settings view
private rebuildSettingRows(containerEl: HTMLElement) {
containerEl.findAll(".iad-setting-row").forEach(e => e.remove());
new Map([...this.plugin.settings.inlineAdmonitions].sort()).forEach((iad, identifier) => {
this.displaySampleIAD(containerEl, iad, identifier);
});
}
// Renders a single Inline Admonition "sample" with options
private displaySampleIAD(containerEl: HTMLElement, iad: InlineAdmonition, identifier: string) {
let row: HTMLElement = containerEl.createDiv();
row.addClass("iad-setting-row")
row.createEl("code", {
text: iad.prefix + " sample text",
cls: "iad iad-sample iad-" + iad.prefix,
parent: row,
attr: {"style": `background-color: ${iad.backgroundColor}; color: ${iad.color}; margin: 0.5em;`}
});
let editButton = row.createEl("button", {text: "Edit"})
editButton.addEventListener("click", evt => {
EditInlineAdmonitionModal.edit(this.app, iad, async result => {
// if the iad prefix changed, we need to kill the original
this.plugin.settings.inlineAdmonitions.delete(identifier);
this.plugin.settings.inlineAdmonitions.set(result.prefix, result);
await this.plugin.saveSettings();
this.rebuildSettingRows(containerEl);
}).open();
});
let deleteButton = row.createEl("button", {text: "Delete"})
deleteButton.addEventListener("click", async evt => {
this.plugin.settings.inlineAdmonitions.delete(identifier);
await this.plugin.saveSettings();
row.remove();
});
}
}
// Model to edit a single Inline Admonition's settings
export class EditInlineAdmonitionModal extends Modal {
result: InlineAdmonition;
onSubmit: (result: InlineAdmonition) => void;
sample: HTMLElement;
static edit(app: App, toEdit: InlineAdmonition, onSubmit: (result: InlineAdmonition) => void) {
return new EditInlineAdmonitionModal(app, toEdit, onSubmit);
}
static new(app: App, onSubmit: (result: InlineAdmonition) => void) {
return new EditInlineAdmonitionModal(app, InlineAdmonition.create(), onSubmit);
}
constructor(app: App, toEdit: InlineAdmonition, onSubmit: (result: InlineAdmonition) => void) {
super(app);
this.result = toEdit ? toEdit : new InlineAdmonition();
this.onSubmit = onSubmit;
}
onOpen() {
let {contentEl} = this;
contentEl.createEl("br");
this.sample = contentEl.createEl("code", {
text: this.result.prefix + " sample text",
cls: "iad iad-sample iad-sample-editor iad-" + this.result.prefix,
attr: {"style": `background-color: ${this.result.backgroundColor}; color: ${this.result.color};`}
});
new Setting(contentEl)
.setName("Prefix")
.setDesc("Inline codeblock prefix to trigger this formatting")
.addText((text) => text
.setPlaceholder("Enter prefix")
.setValue(this.result.prefix)
.onChange((value) => {
this.result.prefix = value;
this.updateSample();
})
);
new Setting(contentEl)
.setName("Background Color")
.setDesc("Color of the background of the inline admonition")
.addColorPicker(cp => cp
.setValue(this.result.backgroundColor)
.onChange(val => {
this.result.backgroundColor = val;
this.updateSample();
})
);
new Setting(contentEl)
.setName("Text Color")
.setDesc("Color of the text of the inline admonition")
.addColorPicker(cp => cp
.setValue(this.result.color)
.onChange(val => {
this.result.color = val;
this.updateSample();
})
);
new Setting(contentEl)
.addButton((btn) => btn
.setButtonText("Submit")
.setCta()
.onClick(() => {
this.close();
this.onSubmit(this.result);
}));
}
private updateSample() {
this.sample.setText(this.result.prefix + " sample text");
this.sample.setAttr("style", `background-color: ${this.result.backgroundColor}; color: ${this.result.color}; margin: 0.5em;`);
}
onClose() {
let {contentEl} = this;
contentEl.empty();
}
}
function slugify(str) {
return String(str)
.normalize('NFKD') // split accented characters into their base characters and diacritical marks
.replace(/[\u0300-\u036f]/g, '') // remove all the accents, which happen to be all in the \u03xx UNICODE block.
.trim() // trim leading or trailing whitespace
.toLowerCase() // convert to lowercase
.replace(/[^a-z0-9 -]/g, '') // remove non-alphanumeric characters
.replace(/\s+/g, '-') // replace spaces with hyphens
.replace(/-+/g, '-'); // remove consecutive hyphens
}

View file

@ -1,11 +1,10 @@
{
"id": "sample-plugin",
"name": "Sample Plugin",
"id": "inline-admonition-plugin",
"name": "Inline Admonitions",
"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",
"isDesktopOnly": false
"description": "Inline callouts for Obsidian.md",
"author": "Scott Tomaszewski (Xentis)",
"authorUrl": "",
"isDesktopOnly": true
}

1156
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -6,3 +6,30 @@ available in the app when your plugin is enabled.
If your plugin does not need CSS, delete this file.
*/
code.iad {
background-color: var(--tag-background);
border: var(--tag-border-width) solid var(--tag-border-color);
border-radius: var(--tag-radius);
color: var(--tag-color);
font-size: var(--tag-size);
font-weight: var(--tag-weight);
text-decoration: var(--tag-decoration);
padding: var(--tag-padding-y) var(--tag-padding-x);
line-height: 1;
}
.iad-setting-row {
display: flex;
justify-content: end;
}
.iad-setting-row * {
margin-left: 0.5em;
}
.iad-sample-editor {
margin: 0.5em;
display: inline-block;
}