Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
iLiftALot committed Nov 11, 2024
0 parents commit 2e07756
Show file tree
Hide file tree
Showing 18 changed files with 7,954 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Obsidian Sample Plugin

This is a sample plugin for Obsidian (https://obsidian.md).

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.

**Note:** The Obsidian API is still in early alpha and is subject to change at any time!

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.

## 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 the [plugin guidelines](https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines).
- 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"
}
```

If you have multiple URLs, you can also do:

```json
{
"fundingUrl": {
"Buy Me a Coffee": "https://buymeacoffee.com",
"GitHub Sponsor": "https://github.com/sponsors",
"Patreon": "https://www.patreon.com/"
}
}
```

## API Documentation

See https://github.com/obsidianmd/obsidian-api
1 change: 1 addition & 0 deletions data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
46 changes: 46 additions & 0 deletions dist/dev/main.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 152 additions & 0 deletions esbuild.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import esbuild from "esbuild";
import process from "process";
import builtins from "builtin-modules";
import { config } from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
import {
existsSync,
writeFileSync,
readFileSync,
symlinkSync,
unlinkSync
} from "fs";

const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;

const prod = process.argv.includes('production');

// Correctly handle the file URL to path conversion
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Load the package.json file
const packageJsonPath = path.join(__dirname, 'package.json'); // use path.join instead of resolve
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));

const manifestJsonPath = path.join(__dirname, 'manifest.json');
const manifestJson = JSON.parse(readFileSync(manifestJsonPath, 'utf-8'));

if (!existsSync(`${__dirname}/data.json`)) {
writeFileSync(`${__dirname}/data.json`, "{}", 'utf-8');
}
const dataJsonPath = path.join(__dirname, 'data.json');
const dataJson = JSON.parse(readFileSync(dataJsonPath, 'utf-8'));

// Retrieve the name of the package
const packageName = packageJson.name;
const packageMain = prod ? "dist/build/main.js" : "dist/dev/main.js";
packageJson.main = packageMain;
writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 4), 'utf-8');

console.log('Package Name:', packageName);
console.log(`Set main.js directory to ${packageJson.main}`);

// Function to find .env file by traversing upward
function findEnvFile(startDir) {
let currentDir = startDir;

while (currentDir !== path.parse(currentDir).root) {
const envPath = path.join(currentDir, '.env');
if (existsSync(envPath)) {
return envPath;
}
currentDir = path.dirname(currentDir);
console.log(`CURRENT DIR: ${currentDir}`);
}
return null;
}

// Start searching from the current directory
const dirYielder = path.resolve(path.dirname(import.meta.url));
let envFilePath = findEnvFile(dirYielder);

if (!envFilePath) {
envFilePath = `${dirYielder.split('/file:')[0]}/.env`;
writeFileSync(envFilePath, '');
}
console.log(`Found .env file at ${envFilePath}`);

const { pluginRoot, projectRoot, vaultRoot, envPath } = {
pluginRoot: `${path.dirname(dirYielder.split('/file:')[0])}/${packageName}`,
projectRoot: dirYielder.split('/file:')[1],
vaultRoot: dirYielder.split('/file:')[1].replace(/\/\.obsidian.*/, ''),
envPath: envFilePath
};
console.log(`pluginRoot: ${pluginRoot}\nprojectRoot: ${projectRoot}\nvaultRoot: ${vaultRoot}\nenvPath: ${envPath}`);
const vaultName = vaultRoot.split('/').pop().trim();

let parsedEnv = {};
if (envFilePath) {
const envConfig = config({ path: envFilePath });
if (envConfig?.parsed) {
console.log(`Loaded .env file from ${envFilePath}`);
parsedEnv = envConfig.parsed;
parsedEnv["envPath"] = envPath;
parsedEnv["pluginRoot"] = pluginRoot;
parsedEnv["projectRoot"] = projectRoot;
parsedEnv["vaultRoot"] = vaultRoot;
parsedEnv["pluginManifest"] = manifestJson;
parsedEnv["vaultName"] = vaultName;
}
}
console.log(`parsedEnv: ${JSON.stringify(parsedEnv, null, 4)}`);

const sourcePath = `${pluginRoot}/${packageMain}`;
const targetPath = `${pluginRoot}/main.js`;

const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["src/main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins],
format: "cjs",
target: "es2021",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: packageMain,
minify: prod,
}).catch((error) => {
console.error(error);
process.exit(1);
})

try {
if (existsSync(targetPath)) {
unlinkSync(targetPath); // Remove existing symlink or file
}
symlinkSync(sourcePath, targetPath);
console.log(`Symlink created: ${targetPath} -> ${sourcePath}`);
} catch (error) {
console.error('Error creating symlink:', error);
process.exit(1);
}

if (prod) {
await context.rebuild();
process.exit(0);
} else {
await context.watch();
}
1 change: 1 addition & 0 deletions main.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"id": "template-plugin",
"name": "Template Plugin",
"version": "1.0.0",
"minAppVersion": "0.15.0",
"description": "Template for creating plugins for the Obsidian API.",
"author": "Obsidian",
"isDesktopOnly": false
}
Loading

0 comments on commit 2e07756

Please sign in to comment.