mirror of
https://github.com/runofthemillgeek/swarnam-obsidian.git
synced 2025-01-17 21:30:12 +00:00
feat: implement MVP version of Swarnam
This commit is contained in:
parent
e60294b950
commit
bc89b3d9a2
129
README.md
129
README.md
@ -1,96 +1,57 @@
|
||||
# Obsidian Sample Plugin
|
||||
# Swarnam
|
||||
|
||||
This is a sample plugin for Obsidian (https://obsidian.md).
|
||||
A no-frills web code blocks plugin for Obsidian.
|
||||
|
||||
This project uses Typescript to provide type checking and documentation.
|
||||
The repo depends on the latest plugin API (obsidian.d.ts) in Typescript Definition format, which contains TSDoc comments describing what it does.
|
||||
## Usage
|
||||
|
||||
**Note:** The Obsidian API is still in early alpha and is subject to change at any time!
|
||||
Install the extension from Obsidian community plugins list (you need to enable this first from
|
||||
Settings).
|
||||
|
||||
This sample plugin demonstrates some of the basic functionality the plugin API can do.
|
||||
- Adds a ribbon icon, which shows a Notice when clicked.
|
||||
- Adds a command "Open Sample Modal" which opens a Modal.
|
||||
- Adds a plugin setting tab to the settings page.
|
||||
- Registers a global click event and output 'click' to the console.
|
||||
- Registers a global interval which logs 'setInterval' to the console.
|
||||
To create a new Swarnam block, you need to open a block code snippet and give it the `swarnam` tag
|
||||
like so:
|
||||
|
||||
## First time developing plugins?
|
||||
|
||||
Quick starting guide for new plugin devs:
|
||||
|
||||
- Check if [someone already developed a plugin for what you want](https://obsidian.md/plugins)! There might be an existing plugin similar enough that you can partner up with.
|
||||
- Make a copy of this repo as a template with the "Use this template" button (login to GitHub if you don't see it).
|
||||
- Clone your repo to a local development folder. For convenience, you can place this folder in your `.obsidian/plugins/your-plugin-name` folder.
|
||||
- Install NodeJS, then run `npm i` in the command line under your repo folder.
|
||||
- Run `npm run dev` to compile your plugin from `main.ts` to `main.js`.
|
||||
- Make changes to `main.ts` (or create new `.ts` files). Those changes should be automatically compiled into `main.js`.
|
||||
- Reload Obsidian to load the new version of your plugin.
|
||||
- Enable plugin in settings window.
|
||||
- For updates to the Obsidian API run `npm update` in the command line under your repo folder.
|
||||
|
||||
## Releasing new releases
|
||||
|
||||
- Update your `manifest.json` with your new version number, such as `1.0.1`, and the minimum Obsidian version required for your latest release.
|
||||
- Update your `versions.json` file with `"new-plugin-version": "minimum-obsidian-version"` so older versions of Obsidian can download an older version of your plugin that's compatible.
|
||||
- Create new GitHub release using your new version number as the "Tag version". Use the exact version number, don't include a prefix `v`. See here for an example: https://github.com/obsidianmd/obsidian-sample-plugin/releases
|
||||
- Upload the files `manifest.json`, `main.js`, `styles.css` as binary attachments. Note: The manifest.json file must be in two places, first the root path of your repository and also in the release.
|
||||
- Publish the release.
|
||||
|
||||
> You can simplify the version bump process by running `npm version patch`, `npm version minor` or `npm version major` after updating `minAppVersion` manually in `manifest.json`.
|
||||
> The command will bump version in `manifest.json` and `package.json`, and add the entry for the new version to `versions.json`
|
||||
|
||||
## Adding your plugin to the community plugin list
|
||||
|
||||
- Check https://github.com/obsidianmd/obsidian-releases/blob/master/plugin-review.md
|
||||
- Publish an initial version.
|
||||
- Make sure you have a `README.md` file in the root of your repo.
|
||||
- Make a pull request at https://github.com/obsidianmd/obsidian-releases to add your plugin.
|
||||
|
||||
## How to use
|
||||
|
||||
- Clone this repo.
|
||||
- Make sure your NodeJS is at least v16 (`node --version`).
|
||||
- `npm i` or `yarn` to install dependencies.
|
||||
- `npm run dev` to start compilation in watch mode.
|
||||
|
||||
## Manually installing the plugin
|
||||
|
||||
- Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/your-plugin-id/`.
|
||||
|
||||
## Improve code quality with eslint (optional)
|
||||
- [ESLint](https://eslint.org/) is a tool that analyzes your code to quickly find problems. You can run ESLint against your plugin to find common bugs and ways to improve your code.
|
||||
- To use eslint with this project, make sure to install eslint from terminal:
|
||||
- `npm install -g eslint`
|
||||
- To use eslint to analyze this project use this command:
|
||||
- `eslint main.ts`
|
||||
- eslint will then create a report with suggestions for code improvement by file and line number.
|
||||
- If your source code is in a folder, such as `src`, you can use eslint with this command to analyze all files in that folder:
|
||||
- `eslint .\src\`
|
||||
|
||||
## Funding URL
|
||||
|
||||
You can include funding URLs where people who use your plugin can financially support it.
|
||||
|
||||
The simple way is to set the `fundingUrl` field to your link in your `manifest.json` file:
|
||||
|
||||
```json
|
||||
{
|
||||
"fundingUrl": "https://buymeacoffee.com"
|
||||
}
|
||||
```swarnam
|
||||
<h1>Hello, world</h1>
|
||||
```
|
||||
|
||||
If you have multiple URLs, you can also do:
|
||||
When you preview this, it'll show the source and render the HTML side-by-side. You can hover on the
|
||||
top-right and click the `</>` icon to edit the snippet to make some changes.
|
||||
|
||||
```json
|
||||
{
|
||||
"fundingUrl": {
|
||||
"Buy Me a Coffee": "https://buymeacoffee.com",
|
||||
"GitHub Sponsor": "https://github.com/sponsors",
|
||||
"Patreon": "https://www.patreon.com/"
|
||||
}
|
||||
You can also add CSS and JS by separating them with `---*---` like so:
|
||||
|
||||
```swarnam
|
||||
<h1 id="h1">Hello world</h1>
|
||||
|
||||
---*---
|
||||
|
||||
h1 {
|
||||
font-family: "Manjari";
|
||||
color: red;
|
||||
animation: rainbow 5s ease infinite forwards;
|
||||
}
|
||||
|
||||
@keyframes rainbow {
|
||||
0% { filter: hue-rotate(0); }
|
||||
100% { filter: hue-rotate(360deg); }
|
||||
}
|
||||
|
||||
---*---
|
||||
|
||||
let i = 0;
|
||||
|
||||
setInterval(() => {
|
||||
h1.textContent = `${["Hello", "Hola", "നമസ്കാരം"][i++ % 3]} Obsidian!`;
|
||||
}, 1500)
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
This'll render the three snippets on the left side and show the preview of a web page that has all
|
||||
these 3 blocks injected.
|
||||
|
||||
See https://github.com/obsidianmd/obsidian-api
|
||||
## How does it work
|
||||
|
||||
We split the code block snippet into 3 parts and form an HTML document string by injecting the CSS
|
||||
and JS pieces into `<style>` and `<script>` tags. Once we have the final HTML document, we convert
|
||||
this into Base64 and create a data URI. Finally, an `<iframe>` element is created and the data URI
|
||||
is given as the `src`. Data URIs of mime type `text/html` and base64 enoding can be rendered by most
|
||||
browsers including the Chromium renderer Obsidian is built on top of. There are no additional build
|
||||
steps involved and thus, this is not a full-blown replacement for something like Sandpack.
|
||||
|
336
main.ts
336
main.ts
@ -1,134 +1,232 @@
|
||||
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
|
||||
import { Plugin } from "obsidian";
|
||||
|
||||
// Remember to rename these classes and interfaces!
|
||||
const PREFIX = "swarnam";
|
||||
|
||||
interface MyPluginSettings {
|
||||
mySetting: string;
|
||||
const SWARNAM_CSS = `
|
||||
.swarnam-root {
|
||||
--${PREFIX}-html-color: #e34c26;
|
||||
--${PREFIX}-css-color: #2965f1;
|
||||
--${PREFIX}-js-color: #f0db4f;
|
||||
--${PREFIX}-box-padding: var(--size-4-3) var(--size-4-4);
|
||||
--${PREFIX}-border-color: var(--divider-color);
|
||||
--${PREFIX}-border-radius: var(--code-radius);
|
||||
--${PREFIX}-source-font: var(--font-monospace);
|
||||
--${PREFIX}-source-font-size: var(--code-size);
|
||||
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: MyPluginSettings = {
|
||||
mySetting: 'default'
|
||||
.swarnam-root.error {
|
||||
display: block;
|
||||
padding: var(--${PREFIX}-box-padding);
|
||||
background-color: var(--code-background);
|
||||
text-align: center;
|
||||
|
||||
.icon {
|
||||
font-family: "Apple Emoji Color", sans-serif;
|
||||
font-size: 1.5em;
|
||||
}
|
||||
}
|
||||
|
||||
export default class MyPlugin extends Plugin {
|
||||
settings: MyPluginSettings;
|
||||
.swarnam-source-root {
|
||||
flex: 1 1 0;
|
||||
overflow-x: scroll;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.swarnam-preview {
|
||||
flex: 1 1 0;
|
||||
border: 1px solid var(--${PREFIX}-border-color);
|
||||
border-left: 0;
|
||||
border-top-right-radius: var(--${PREFIX}-border-radius);
|
||||
border-bottom-right-radius: var(--${PREFIX}-border-radius);
|
||||
padding: var(--${PREFIX}-box-padding);
|
||||
}
|
||||
|
||||
.swarnam-source-container {
|
||||
position: relative;
|
||||
flex: 1 1 0;
|
||||
|
||||
& + & {
|
||||
border-top: 1px solid var(--${PREFIX}-border-color);
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.markdown-rendered .swarnam-source {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
font-family: var(--${PREFIX}-source-font);
|
||||
font-size: var(--${PREFIX}-source-font-size);
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.swarnam-badge {
|
||||
position: absolute;
|
||||
top: calc(var(--size-4-3) / 1.5);
|
||||
right: calc(var(--size-4-3) / 1.5);
|
||||
font-size: 0.65em;
|
||||
}
|
||||
|
||||
.swarnam-html-badge {
|
||||
color: var(--${PREFIX}-html-color);
|
||||
}
|
||||
|
||||
.swarnam-css-badge {
|
||||
color: var(--${PREFIX}-css-color);
|
||||
}
|
||||
|
||||
.swarnam-js-badge {
|
||||
color: var(--${PREFIX}-js-color);
|
||||
}
|
||||
`;
|
||||
|
||||
function base64ToBytes(base64: string) {
|
||||
const binString = atob(base64);
|
||||
// @ts-expect-error
|
||||
return Uint8Array.from(binString, (m) => m.codePointAt(0));
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array) {
|
||||
const binString = Array.from(bytes, (byte) =>
|
||||
String.fromCodePoint(byte)
|
||||
).join("");
|
||||
return btoa(binString);
|
||||
}
|
||||
|
||||
function asBase64(text: string) {
|
||||
console.log({ text });
|
||||
const b64 = bytesToBase64(new TextEncoder().encode(text));
|
||||
console.log(console.log(new TextDecoder().decode(base64ToBytes(b64))));
|
||||
return b64;
|
||||
}
|
||||
|
||||
function getIframeDoc(htmlSource: string, cssSource: string, jsSource: string) {
|
||||
const isDarkMode = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)"
|
||||
).matches;
|
||||
|
||||
return `
|
||||
<style>
|
||||
body { font-family: sans-serif; color: ${isDarkMode ? "#fff" : "#000"} }
|
||||
</style>
|
||||
<style>
|
||||
${cssSource}
|
||||
</style>
|
||||
<div class="swarnam-html-container">
|
||||
${htmlSource}
|
||||
</div>
|
||||
<script>
|
||||
${jsSource}
|
||||
</script>
|
||||
`;
|
||||
}
|
||||
|
||||
function showError(msg: string, root: HTMLElement) {
|
||||
root.classList.add("error");
|
||||
root.createEl("p", { cls: "icon", text: "⚠️" });
|
||||
root.createEl("p", { text: msg });
|
||||
}
|
||||
|
||||
export default class SwarnamPlugin extends Plugin {
|
||||
async onload() {
|
||||
await this.loadSettings();
|
||||
this.registerMarkdownCodeBlockProcessor(
|
||||
"swarnam",
|
||||
(source, el, ctx) => {
|
||||
const root = el.createDiv({ cls: "swarnam-root" });
|
||||
const head = el.ownerDocument.head;
|
||||
|
||||
// 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');
|
||||
head.createEl("style", {
|
||||
text: SWARNAM_CSS,
|
||||
});
|
||||
|
||||
// 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');
|
||||
let [
|
||||
htmlSource = "",
|
||||
cssSource = "",
|
||||
jsSource = "",
|
||||
// eslint-disable-next-line prefer-const
|
||||
...others
|
||||
] = source.split(/^\s*---\*---\s*$/m);
|
||||
|
||||
// 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;
|
||||
if (others.length > 0) {
|
||||
showError(
|
||||
"Swarnam only supports HTML, CSS and JS blocks but your snippet has more than 3 blocks.",
|
||||
root
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
htmlSource = htmlSource.trim();
|
||||
cssSource = cssSource.trim();
|
||||
jsSource = jsSource.trim();
|
||||
|
||||
if (!htmlSource) {
|
||||
showError(
|
||||
"A Swarnam block must at least contain HTML",
|
||||
root
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceRoot = root.createDiv({
|
||||
cls: "swarnam-source-root",
|
||||
});
|
||||
|
||||
const htmlContainer = sourceRoot.createDiv({
|
||||
cls: "swarnam-source-container",
|
||||
});
|
||||
const htmlEl = htmlContainer.createEl("pre", {
|
||||
cls: "swarnam-source swarnam-html-source",
|
||||
});
|
||||
htmlContainer.createDiv({
|
||||
text: "HTML",
|
||||
cls: "swarnam-badge swarnam-html-badge",
|
||||
});
|
||||
htmlEl.setText(htmlSource);
|
||||
|
||||
if (cssSource) {
|
||||
const cssContainer = sourceRoot.createDiv({
|
||||
cls: "swarnam-source-container",
|
||||
});
|
||||
const cssEl = cssContainer.createEl("pre", {
|
||||
cls: "swarnam-source swarnam-css-source",
|
||||
});
|
||||
cssContainer.createDiv({
|
||||
text: "CSS",
|
||||
cls: "swarnam-badge swarnam-css-badge",
|
||||
});
|
||||
cssEl.setText(cssSource);
|
||||
}
|
||||
|
||||
if (jsSource) {
|
||||
const jsContainer = sourceRoot.createDiv({
|
||||
cls: "swarnam-source-container",
|
||||
});
|
||||
|
||||
const jsEl = jsContainer.createEl("pre", {
|
||||
cls: "swarnam-source swarnam-js-source",
|
||||
});
|
||||
|
||||
jsContainer.createDiv({
|
||||
text: "JS",
|
||||
cls: "swarnam-badge swarnam-js-badge",
|
||||
});
|
||||
jsEl.setText(jsSource);
|
||||
}
|
||||
|
||||
const iframeEl = root.createEl("iframe", {
|
||||
cls: "swarnam-preview",
|
||||
});
|
||||
|
||||
iframeEl.src = `data:text/html;base64;charset=UTF-8,${asBase64(
|
||||
getIframeDoc(htmlSource, cssSource, jsSource)
|
||||
)}`;
|
||||
}
|
||||
});
|
||||
|
||||
// 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));
|
||||
}
|
||||
|
||||
onunload() {
|
||||
|
||||
}
|
||||
|
||||
async loadSettings() {
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||
}
|
||||
|
||||
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();
|
||||
}));
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,11 @@
|
||||
{
|
||||
"id": "sample-plugin",
|
||||
"name": "Sample Plugin",
|
||||
"id": "swarnam",
|
||||
"name": "Swarnam",
|
||||
"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": "A no-frills web code blocks plugin for Obsidian.",
|
||||
"author": "runofthemillgeek",
|
||||
"authorUrl": "https://dg.sangeeth.dev",
|
||||
"fundingUrl": "https://dg.sangeeth.dev",
|
||||
"isDesktopOnly": true
|
||||
}
|
||||
|
2229
package-lock.json
generated
Normal file
2229
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user