Spaces:
Sleeping
Sleeping
File size: 11,035 Bytes
c63ff03 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
This page lists common review comments plugin authors get when submitting their plugin.
While the guidelines on this page are recommendations, depending on their severity, we may still require you to address any violations.
> [!important] Policies for plugin developers
> Make sure that you've read our [[Developer policies]] as well as the [[Submission requirements for plugins]].
## General
### Avoid using global app instance
Avoid using the global app object, `app` (or `window.app`). Instead, use the reference provided by your plugin instance, `this.app`.
The global app object is intended for debugging purposes and might be removed in the future.
## UI text
This section lists guidelines for formatting text in the user interface, such as settings, commands, and buttons.
The example below from **Settings → Appearance** demonstrates the guidelines for text in the user interface.
![[settings-headings.png]]
1. [[#Only use headings under settings if you have more than one section.|General settings are at the top and don't have a heading]].
2. [[#Avoid "settings" in settings headings|Section headings don't have "settings" in the heading text]].
3. [[#Use Sentence case in UI]].
For more information on writing and formatting text for Obsidian, refer to our [Style guide](https://help.obsidian.md/Contributing+to+Obsidian/Style+guide).
### Only use headings under settings if you have more than one section.
Avoid adding a top-level heading in the settings tab, such as "General", "Settings", or the name of your plugin.
If you have more than one section under settings, and one contains general settings, keep them at the top without adding a heading.
For example, look at the settings under **Settings → Appearance**:
### Avoid "settings" in settings headings
In the settings tab, you can add headings to organize settings. Avoid including the word "settings" to these headings. Since everything in under the settings tab is settings, repeating it for every heading becomes redundant.
- Prefer "Advanced" over "Advanced settings".
- Prefer "Templates" over "Settings for templates".
### Use sentence case in UI
Any text in UI elements should be using [Sentence case](https://en.wiktionary.org/wiki/sentence_case) instead of [Title Case](https://en.wikipedia.org/wiki/Title_case), where only the first word in a sentence, and proper nouns, should be capitalized.
- Prefer "Template folder location" over "Template Folder Location".
- Prefer "Create new note" over "Create New Note".
## Security
### Avoid `innerHTML`, `outerHTML` and `insertAdjacentHTML`
Building DOM elements from user-defined input, using `innerHTML`, `outerHTML` and `insertAdjacentHTML` can pose a security risk.
The following example builds a DOM element using a string that contains user input, `${name}`. `name` can contain other DOM elements, such as `<script>alert()</script>`, and can allow a potential attacker to execute arbitrary code on the user's computer.
```ts
function showName(name: string) {
let containerElement = document.querySelector('.my-container');
// DON'T DO THIS
containerElement.innerHTML = `<div class="my-class"><b>Your name is: </b>${name}</div>`;
}
```
Instead, use the DOM API or the Obsidian helper functions, such as `createEl()`, `createDiv()` and `createSpan()` to build the DOM element programmatically. For more information, refer to [[HTML elements]].
## Resource management
### Clean up resources when plugin unloads
Any resources created by the plugin, such as event listeners, must be destroyed or released when the plugin unloads.
When possible, use methods like [[registerEvent|registerEvent()]] or [[addCommand|addCommand()]] to automatically clean up resources when the plugin unloads.
```ts
export default class MyPlugin extends Plugin {
onload() {
this.registerEvent(this.app.vault.on("create", this.onCreate));
}
onCreate: (file: TAbstractFile) => {
// ...
}
}
```
> [!note]
> You don't need to clean up resources that are guaranteed to be removed when your plugin unloads. For example, if you register a `mouseenter` listener on a DOM element, the event listener will be garbage-collected when the element goes out of scope.
### Don't detach leaves in `onunload`
When the user updates your plugin, any open leaves will be reinitialized at their original position, regardless of where the user had moved them.
## Commands
### Avoid setting a default hotkey for commands
Setting a default hotkey may lead to conflicts between plugins and may override hotkeys that the user has already configured.
It's also difficult to choose a default hotkey that is available on all operating systems.
### Use the appropriate callback type for commands
When you add a command in your plugin, use the appropriate callback type.
- Use `callback` if the command runs unconditionally.
- Use `checkCallback` if the command only runs under certain conditions.
If the command requires an open and active Markdown editor, use `editorCallback`, or the corresponding `editorCheckCallback`.
## Workspace
### Avoid accessing `workspace.activeLeaf` directly
If you want to access the active view, use [[getActiveViewOfType|getActiveViewOfType()]] instead:
```ts
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
// getActiveViewOfType will return null if the active view is null, or if it's not a MarkdownView.
if (view) {
// ...
}
```
If you want to access the editor in the active note, use `activeEditor` instead:
```ts
const editor = this.app.workspace.activeEditor;
```
### Avoid managing references to custom views
Managing references to custom view can cause memory leaks or unintended consequences.
**Don't** do this:
```ts
this.registerViewType(MY_VIEW_TYPE, () => this.view = new MyCustomView());
```
Do this instead:
```ts
this.registerViewType(MY_VIEW_TYPE, () => new MyCustomView());
```
To access the view from your plugin, use `Workspace.getActiveLeavesOfType()`:
```ts
for (let leaf of app.workspace.getActiveLeavesOfType(MY_VIEW_TYPE)) {
let view = leaf.view;
if (view instanceof MyCustomView) {
// ...
}
}
```
## Vault
### Prefer the Editor API instead of `Vault.modify`
If you want to edit an active note, use the [[Editor]] interface instead of [[Vault/modify|Vault.modify()]].
Editor maintains information about the active note, such as cursor position, selection, and folded content. When you use [[Vault/modify|Vault.modify()]] to edit the note, all that information is lost, which leads to a poor experience for the user.
Editor is also more efficient when making small changes to parts of the note.
Only use [[Vault/modify|Vault.modify()]] if you're editing a file in the background.
### Prefer the Vault API over the Adapter API
Obsidian exposes two APIs for file operations: the Vault API (`app.vault`) and the Adapter API (`app.vault.adapter`).
While the file operations in the Adapter API are often more familiar to many developers, the Vault API has two main advantages over the adapter.
- **Performance:** The Vault API has a caching layer that can speed up file reads when the file is already known to Obsidian.
- **Safety:** The Vault API performs file operations serially to avoid any race conditions, for example when reading a file that is being written to at the same time.
### Avoid iterating all files to find a file by its path
This is inefficient, especially for large vaults. Use [[Vault/getAbstractFileByPath|getAbstractFileByPath()]] instead.
**Don't** do this:
```ts
vault.getAllFiles().find(file => file.path === filePath)
```
Do this instead:
```ts
const filePath = 'folder/file.md';
const file = app.vault.getAbstractFileByPath(filePath);
// Check if it exists and is of the correct type
if (file instanceof TFile) {
// file is automatically casted to TFile within this scope.
}
```
### Use `normalizePath()` to clean up user-defined paths
Use [[normalizePath|normalizePath()]] whenever you accept user-defined paths to files or folders in the vault, or when you construct your own paths in the plugin code.
`normalizePath()` takes a path and scrubs it to be safe for the file system and for cross-platform use. This function:
- Cleans up the use of forward and backward slashes, such as replacing 1 or more of `\` or `/` with a single `/`.
- Removes leading and trailing forward and backward slashes.
- Replaces any non-breaking spaces, `\u00A0`, with a regular space.
- Runs the path through [String.prototype.normalize](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize).
```ts
import { normalizePath } from "obsidian";
const pathToPlugin = normalizePath(app.vault.configDir + "//plugins/my-plugin");
// pathToPlugin contains ".obsidian/plugins/my-plugin" not .obsidian//plugins/my-plugin
```
## Editor
### Change or reconfigure editor extensions
If you want to change or reconfigure an [[Editor extensions|editor extension]] after you've registered using [[registerEditorExtension|registerEditorExtension()]], use [[updateOptions|updateOptions()]] to update all editors.
```ts
class MyPlugin extends Plugin {
private editorExtension: Extension[] = [];
onload() {
//...
this.registerEditorExtension(this.editorExtension);
}
updateEditorExtension() {
// Empty the array while keeping the same reference
// (Don't create a new array here)
this.editorExtension.length = 0;
// Create new editor extension
let myNewExtension = this.createEditorExtension();
// Add it to the array
this.editorExtension.push(myNewExtension);
// Flush the changes to all editors
this.app.workspace.updateOptions();
}
}
```
## TypeScript
### Prefer `const` and `let` over `var`
For more information, refer to [4 Reasons Why var is Considered Obsolete in Modern JavaScript](https://javascript.plainenglish.io/4-reasons-why-var-is-considered-obsolete-in-modern-javascript-a30296b5f08f).
### Prefer async/await over Promise
Recent versions of JavaScript and TypeScript support the `async` and `await` keywords to run code asynchronously, which allow for more readable code than using Promises.
**Don't** do this:
```ts
function test(): Promise<string | null> {
return requestUrl('https://example.com')
.then(res => res.text
.catch(e => {
console.log(e);
return null;
});
}
```
Do this instead:
```ts
async function AsyncTest(): Promise<string | null> {
try {
let res = await requestUrl('https://example.com');
let text = await r.text;
return text;
}
catch (e) {
console.log(e);
return null;
}
}
```
### Consider organizing your code base using folders
If your plugin uses more than one `.ts` file, consider organizing them into folders to make it easier to review and maintain.
### Rename placeholder class names
The sample plugin contains placeholder names for common classes, such as `MyPlugin`, `MyPluginSettings`, and `SampleSettingTab`. Rename these to reflect the name of your plugin.
|