### Install Project Dependencies Source: https://ohmymn.marginnote.cn/dev/module/how Installs all necessary project dependencies using pnpm. This command should be run after cloning the repository to ensure all required packages are available. ```bash pnpm install ``` ```bash pnpm install ``` -------------------------------- ### Install pnpm using curl Source: https://ohmymn.marginnote.cn/dev This command downloads and executes the pnpm installation script from the official source. It requires curl to be installed on the system. The script installs pnpm globally. ```shell curl -fsSL https://get.pnpm.io/install.sh | sh - ``` -------------------------------- ### Build Plugin for Installation (.mnaddon) (TypeScript) Source: https://ohmymn.marginnote.cn/en/dev/ohmymn/esbuild This command builds the plugin, generating a .mnaddon file in the dist directory, which can be directly installed into MarginNote. This is the standard procedure for creating distributable plugin packages. ```typescript pnpm build ``` -------------------------------- ### NodeNote Constructor and Usage Source: https://ohmymn.marginnote.cn/api/marginnote/nodenote Demonstrates how to create a new NodeNote instance and provides a basic example of its usage. ```APIDOC ## NodeNote Class ### Description `NodeNote` is an extension of `MbBookNote` used to represent a node in a mind map or a card. A card might contain multiple `MbBookNote` instances. `NodeNote` can control the card regardless of which `MbBookNote` is passed to it. ### Constructor - **note** (`MbBookNote`) - The `MbBookNote` object to be represented as a `NodeNote`. ### Usage Example ```typescript import { NodeNote } from "marginnote" const note: MbBookNote = /* ... get your MbBookNote object ... */ const node = new NodeNote(note) ``` ``` -------------------------------- ### OhMyMN Lifecycle Static Methods Source: https://ohmymn.marginnote.cn/dev/lifecycle Static methods that are called when a plugin is installed, enabled, or disabled, as well as when the MarginNote application starts. ```APIDOC ## OhMyMN Lifecycle Static Methods ### Description Static methods that are invoked during plugin management events (installation, enabling, disabling) and application startup. ### Methods - **addonDidConnect()** - **Description**: Triggered when a plugin is installed or enabled. This method is also called when MarginNote starts up. - **addonWillDisconnect()** - **Description**: Triggered when a plugin is uninstalled or disabled. ``` -------------------------------- ### Example: POST JSON Request (TypeScript) Source: https://ohmymn.marginnote.cn/en/api/marginnote/fetch Shows how to send a POST request with a JSON payload using the custom `fetch` function. This example targets a translation API, sending text and language pair information to get a translation. ```typescript const res = (await fetch( "http://api.interpreter.caiyunai.com/v1/translator", { method: "POST", headers: { "X-Authorization": `token ${caiyunToken}` }, json: { source: [text], trans_type: `${fromLangKey[fromLang]}2${toLangKey[toLang]}`, request_id: "ohmymn", detect: true } } ).then(res => res.json())) as { target: string[] } ``` -------------------------------- ### Example: Bind Multiple Options (AND Logic) Source: https://ohmymn.marginnote.cn/api/ohmymn/module Sets up an option to be displayed only if all specified bound conditions are met simultaneously. This employs an 'AND' logic for visibility. ```typescript [ [ ["quickSwitch", [0,1,2]], ["on", true] ] ] ``` -------------------------------- ### Example: Bind Multiple Options (OR Logic) Source: https://ohmymn.marginnote.cn/api/ohmymn/module Configures an option to be displayed if any of the multiple bound conditions are met. This uses an 'OR' logic for visibility. ```typescript [ ["quickSwitch", [0,1,2]], ["on", true] ] ``` -------------------------------- ### Install mnaddon CLI Source: https://ohmymn.marginnote.cn/dev/lite Installs the mnaddon command-line interface globally using pnpm. This tool is essential for managing Lite plugin projects. ```shell pnpm add mnaddon -g ``` -------------------------------- ### Example: Bind Option to 'quickSwitch' Value Source: https://ohmymn.marginnote.cn/api/ohmymn/module Demonstrates binding an option's visibility to a specific value of 'quickSwitch'. The option appears only when 'quickSwitch' is set to the specified value. ```typescript ["quickSwitch", 0] ``` -------------------------------- ### Install airdrop-cli using Homebrew Source: https://ohmymn.marginnote.cn/dev/ohmymn/esbuild Installs the 'airdrop-cli' command-line tool using the Homebrew package manager. This tool is a prerequisite for using the build:iPad script to transfer plugins to an iPad. ```bash brew install vldmrkl/formulae/airdrop-cli ``` -------------------------------- ### Example: Bind Option to 'quickSwitch' Array Value Source: https://ohmymn.marginnote.cn/api/ohmymn/module Shows how to bind an option's visibility to a 'quickSwitch' that accepts an array of values. The option is displayed if 'quickSwitch' matches any value within the provided array. ```typescript ["quickSwitch", [0,1,2]] ``` -------------------------------- ### Example: Bind Option to 'on' State Source: https://ohmymn.marginnote.cn/api/ohmymn/module Illustrates how to bind an option's display to a boolean 'on' property. The option will only be visible when the 'on' property is true. ```typescript ["on", true] ``` -------------------------------- ### Example Usage of Confirmation Dialog (TypeScript) Source: https://ohmymn.marginnote.cn/api/marginnote/popup Demonstrates how to use the `popup` function to implement a simple confirmation dialog, returning true if the 'sure' button is pressed. ```typescript import { popup } from "marginnote" async function confirm(title = MN.currentAddon.title, message = "") { const { buttonIndex: option } = await popup({ title, message, buttons: [lang.sure], multiLine: false, canCancel: true }) return option === 0 } ``` ```typescript import { popup } from "marginnote" async function confirm(title = MN.currentAddon.title, message = "") { const { buttonIndex: option } = await popup({ title, message, buttons: [lang.sure], multiLine: false, canCancel: true }) return option === 0 } ``` -------------------------------- ### Get Current Addon Information Source: https://ohmymn.marginnote.cn/en/api/marginnote Retrieves information about the current plugin, including its key and title, from `self.addon`. It provides default values if `self.addon` is not set. ```typescript get currentAddon(): { key: string title: string } { return { key: self.addon?.key ?? "mnaddon", title: self.addon?.title ?? "MarginNote" } } ``` -------------------------------- ### Build OhMyMN Plugin for Distribution Source: https://ohmymn.marginnote.cn/dev/ohmymn/esbuild Bundles the OhMyMN plugin into a single .mnaddon file located in the 'dist' directory, ready for installation in MarginNote. This command is used for creating the final production build. ```bash pnpm build ``` -------------------------------- ### Create and Build a Lite Plugin Project Source: https://ohmymn.marginnote.cn/dev/lite Demonstrates the basic workflow for creating a new Lite plugin project using the 'create' command, navigating into the project directory, and then building the plugin package using the 'build' command. ```shell # Create a new plugin project named 'template' mnaddon create template # Enter the project directory cd template # Build the plugin into a package mnaddon build ``` -------------------------------- ### Perform GET Request with Custom Fetch in TypeScript Source: https://ohmymn.marginnote.cn/api/marginnote/fetch Example of making a GET request using the custom `fetch` function in OhMyMN plugins. It demonstrates fetching data from a dictionary API and parsing the JSON response. ```typescript const res = await fetch("http://dict.e.opac.vip/dict.php?sw=" + word).then( res => res.json() ) ``` -------------------------------- ### Create OhMyMN Base Template Source: https://ohmymn.marginnote.cn/dev/ohmymn This command initializes a new MarginNote plugin project using the 'base' template. This template provides a minimal setup without a control panel, configuration, modules, actions, gestures, or shortcuts, suitable for simple plugins. ```bash pnpm create ohmymn -t base ``` -------------------------------- ### MN Add-on Lifecycle Methods Source: https://ohmymn.marginnote.cn/en/dev/lifecycle These static methods are related to the connection and disconnection of add-ons (plugins) within the MarginNote (MN) application. addonDidConnect() is triggered when an add-on is installed, enabled, or when MN starts, while addonWillDisconnect() is called when an add-on is uninstalled or disabled. ```swift static func addonDidConnect() { // Called when an add-on is installed, enabled, or when MN starts. } static func addonWillDisconnect() { // Called when an add-on is uninstalled or disabled. } ``` -------------------------------- ### NodeNote Initialization Source: https://ohmymn.marginnote.cn/en/api/marginnote/nodenote Demonstrates how to initialize a NodeNote instance. ```APIDOC ## NodeNote Initialization ### Description Initializes a new NodeNote instance with a given MbBookNote. ### Method `new NodeNote(note: MbBookNote)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { NodeNote } from "marginnote" const node = new NodeNote(note) ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Instantiate SettingViewController in TypeScript Source: https://ohmymn.marginnote.cn/dev/ohmymn/structure This snippet demonstrates how to instantiate the settingViewController and assign various profile data to its properties. This is a crucial step for initializing the control panel with relevant configuration. ```typescript self.settingViewController = SettingViewController.new() self.settingViewController.addon = self.addon self.settingViewController.dataSource = self.dataSource self.settingViewController.globalProfile = self.globalProfile self.settingViewController.docProfile = self.docProfile self.settingViewController.notebookProfile = self.notebookProfile ``` ```typescript self.settingViewController = SettingViewController.new() self.settingViewController.addon = self.addon self.settingViewController.dataSource = self.dataSource self.settingViewController.globalProfile = self.globalProfile self.settingViewController.docProfile = self.docProfile self.settingViewController.notebookProfile = self.notebookProfile ``` -------------------------------- ### Get and Set tags in TypeScript Source: https://ohmymn.marginnote.cn/api/marginnote/nodenote Gets or sets the tags of the card. Setting `tags` overwrites existing tags. Tags are not prefixed with '#'. Use `appendTags` to add to existing tags. ```ts get tags(): string[]; set tags(tags: string[]); ``` -------------------------------- ### Create OhMyMN Profile Template Source: https://ohmymn.marginnote.cn/dev/ohmymn This command initializes a new MarginNote plugin project using the 'profile' template. This is the most comprehensive template, featuring a control panel, support for URL Scheme invocation, and robust configuration management, including export/import and initialization capabilities. It's ideal for complex plugins requiring extensive customization. ```bash pnpm create ohmymn -t profile ``` -------------------------------- ### Get All Content with Picture Formats Source: https://ohmymn.marginnote.cn/en/api/marginnote/nodenote Retrieves all content, including text and images, from both excerpts and comments. Images are provided in HTML, OCR'd text, and Markdown formats. This is the most comprehensive way to get all card data. ```typescript get allTextPic(): { html: string ocr: string md: string } ``` ```typescript get allTextPic(): { html: string ocr: string md: string } ``` -------------------------------- ### Get Comment Index in TypeScript Source: https://ohmymn.marginnote.cn/api/marginnote/nodenote Gets the index of a comment within the card, or the index of a merged note which is also considered as a comment. Returns -1 if not found. Accepts either the comment content (string) or a MbBookNote object. ```ts getCommentIndex(comment: MbBookNote | string): number; ``` -------------------------------- ### Create OhMyMN Panel Template Source: https://ohmymn.marginnote.cn/dev/ohmymn This command initializes a new MarginNote plugin project using the 'panel' template. This template includes a control panel and supports URL Scheme invocation for actions, offering a more interactive plugin experience than the base template. Configuration options are simplified compared to the profile template. ```bash pnpm create ohmymn -t panel ``` -------------------------------- ### Run Addon Development Mode Source: https://ohmymn.marginnote.cn/dev/module/how Starts the addon in development mode. This command copies the plugin code to MarginNote's plugin directory, allowing you to see and test your module within MarginNote. A restart of MarginNote might be required to see the changes. ```bash pnpm run addon dev ``` ```bash pnpm run addon dev ``` -------------------------------- ### Get excerptsCommentsText, allText, and allTextPic in TypeScript Source: https://ohmymn.marginnote.cn/api/marginnote/nodenote Gets the combined text and picture information from excerpts and comments. `excerptsCommentsText` returns an array of strings. `allText` returns a single concatenated string separated by '\n'. `allTextPic` provides html, ocr, and md formatted representations. The order is based on the card order. ```ts get excerptsCommentsText(): string[]; get allText(): string get allTextPic(): { html: string ocr: string md: string } ``` -------------------------------- ### Get Study Controller Source: https://ohmymn.marginnote.cn/en/api/marginnote Retrieves the study controller associated with the current window. This controller manages study-related functionalities. ```typescript get studyController() { return this.app.studyController(this.app.focusWindow) } ``` -------------------------------- ### Importing Local Data Storage Functions (TypeScript) Source: https://ohmymn.marginnote.cn/dev/store Example demonstrating how to import the `getLocalDataByKey` and `setLocalDataByKey` functions from the 'marginnote' module. This allows for easy integration of local data storage capabilities into your project. ```typescript import { getLocalDataByKey, setLocalDataByKey } from "marginnote" ``` ```typescript import { getLocalDataByKey, setLocalDataByKey } from "marginnote" ``` -------------------------------- ### NodeNote Instance Methods Source: https://ohmymn.marginnote.cn/en/api/marginnote/nodenote Documentation for instance methods available on a NodeNote object. ```APIDOC ## NodeNote Instance Methods ### appendTitles #### Description Appends new titles to the existing titles of the card. Accepts a variable number of string arguments. #### Method `appendTitles(...titles: string[]): this` #### Parameters - **titles** (string) - One or more strings to append as titles. #### Returns - `this` - The current NodeNote instance, allowing for chaining. #### Example ```typescript node.appendTitles("New Title 1") node.appendTitles("New Title 2", "New Title 3") ``` ### appendTags #### Description Appends new tags to the existing tags of the card. The '#' prefix is automatically added. Accepts a variable number of string arguments. #### Method `appendTags(...tags: string[]): this` #### Parameters - **tags** (string) - One or more strings to append as tags (without the '#' prefix). #### Returns - `this` - The current NodeNote instance, allowing for chaining. #### Example ```typescript node.appendTags("tag4") node.appendTags("tag5", "tag6") ``` ### appendTextComments #### Description Appends new text comments to the card. Accepts a variable number of string arguments. #### Method `appendTextComments(...comments: string[]): this` #### Parameters - **comments** (string) - One or more strings to append as comments. #### Returns - `this` - The current NodeNote instance, allowing for chaining. #### Example ```typescript node.appendTextComments("New comment 1") node.appendTextComments("New comment 2", "New comment 3") ``` ### tidyupTags #### Description Cleans up the tags by removing duplicates and organizing them, typically placing them at the end. #### Method `tidyupTags(): this` #### Returns - `this` - The current NodeNote instance, allowing for chaining. #### Example ```typescript node.tidyupTags() ``` ### getCommentIndex #### Description Gets the index of a specific comment within the card. The comment can be provided as its content string or as a merged `MbBookNote` object. #### Method `getCommentIndex(comment: MbBookNote | string): number` #### Parameters - **comment** (MbBookNote | string) - The comment content (string) or the merged note object (`MbBookNote`) whose index is to be found. #### Returns - `number` - The zero-based index of the comment, or -1 if not found. #### Example ```typescript const commentIndex = node.getCommentIndex("Specific comment text") // or // const mergedNote = new MbBookNote(...) // const mergedNoteIndex = node.getCommentIndex(mergedNote) ``` ``` -------------------------------- ### Get Selected Nodes in TypeScript Source: https://ohmymn.marginnote.cn/api/marginnote/nodenote Retrieves the currently selected cards from the mind map. This is a static method of the NodeNote class. ```ts const nodes = NodeNote.getSelectedNodes() ``` -------------------------------- ### Get Notebook Controller Source: https://ohmymn.marginnote.cn/en/api/marginnote Retrieves the notebook controller from the current study controller. This controller handles operations related to notebooks. ```typescript get notebookController() { return this.studyController.notebookController } ``` -------------------------------- ### Access Application Instance in MarginNote Plugins Source: https://ohmymn.marginnote.cn/api/marginnote Retrieves the singleton Application instance, which serves as the main entry point for interacting with the MarginNote application. This instance allows access to various application-level features and settings. ```typescript readonly app = Application.sharedInstance() ``` -------------------------------- ### Database Utility Functions Source: https://ohmymn.marginnote.cn/en/api/marginnote/database Provides utility functions for database operations, including getting a shared instance and transforming data structures. ```APIDOC ## Database Utility Functions ### Description Provides utility functions for database operations, including getting a shared instance and transforming data structures. ### Method N/A (Static methods) ### Endpoints N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Shared Instance ### Description Returns the shared instance of the MbModelTool for database operations. It is recommended to use `MN.db` instead. ### Method `sharedInstance()` ### Endpoint N/A ### Parameters None ### Response - **MbModelTool**: An instance of MbModelTool. ## Data Transformation ### Description These methods transform unreadable Objective-C dictionary or array structures into JavaScript-compatible formats. ### Method - `transDictionaryToJSCompatible(dic: any): any` - `transArrayToJSCompatible(arr: any): any` ### Endpoint N/A ### Parameters - **dic** (any) - The dictionary to transform. - **arr** (any) - The array to transform. ### Response - **any**: The transformed JavaScript-compatible data. ## MbModelTool Class ### Description Provides methods for managing and retrieving data related to notebooks, notes, and documents. ### Methods - **getNotebookById(notebookid: string): MbTopic | undefined** - Retrieves a notebook by its ID. - **getMediaByHash(hash: string): NSData | undefined** - Retrieves media data by its hash. - **getNoteById(noteid: string): MbBookNote | undefined** - Retrieves a note by its ID. - **getDocumentById(md5: string): MbBook | undefined** - Retrieves a document by its MD5 hash. - **getFlashcardByNoteId(noteid: string, notebookid: string): MbBookNote | undefined** - Retrieves a note in review mode by its note ID and notebook ID. - **getFlashcardsByNoteId(noteid: string): MbBookNote[] | undefined** - Retrieves all notes in review mode for a given note ID. - **hasFlashcardByNoteId(noteid: string): boolean** - Checks if there are any notes in review mode for a given note ID. - **savedb(): void** - Saves the current database state. - **allNotebooks(): MbTopic[]** - Fetches all notebooks. - **allDocuments(): MbBook[]** - Fetches all documents. - **setNotebookSyncDirty(notebookid: string): void** - Marks a notebook as dirty for synchronization. - **saveHistoryArchiveKey(notebookid: string, key: string): any[]** - Saves history archive data for a notebook and key. - **loadHistoryArchiveKey(notebookid: string, key: string): any[]** - Loads history archive data for a notebook and key. - **deleteBookNote(noteid: string): void** - Deletes a single note by its ID. - **deleteBookNoteTree(noteid: string): void** - Deletes a note and all its descendant notes. - **cloneNotesToTopic(notes: MbBookNote[], notebookid: string): MbBookNote[]** - Clones a list of notes to a specified notebook. - **cloneNotesToFlashcardsToTopic(notes: MbBookNote[], notebookid: string): MbBookNote[]** - Clones a list of notes as flashcards to a specified notebook. - **exportNotebookStorePath(notebookid: string, storePath: string): boolean** - Exports a notebook to a specified store path. - **importNotebookFromStorePathMerge(storePath: string, merge: boolean): any** - Imports a notebook from a store path, with an option to merge. - **getSketchNotesForMindMap(notebookid: string): MbBookNote[]** - Retrieves sketch notes associated with a notebook's mind map. - **getSketchNotesForDocumentMd5Page(notebookid: string, docmd5: string, page: number): MbBookNote[]** - Retrieves sketch notes for a specific document page within a notebook. ### Endpoint N/A (Methods of MbModelTool instance) ### Parameters (See method descriptions above for individual parameters) ### Request Example N/A ### Response - **MbTopic | undefined**: A notebook object or undefined. - **NSData | undefined**: Media data or undefined. - **MbBookNote | undefined**: A note object or undefined. - **MbBook | undefined**: A document object or undefined. - **boolean**: True if export was successful, false otherwise. - **any**: Result of import operation. - **MbBookNote[]**: An array of notes. - **MbTopic[]**: An array of notebooks. - **MbBook[]**: An array of documents. ``` -------------------------------- ### Run Development Server for OhMyMN Plugins Source: https://ohmymn.marginnote.cn/dev/ohmymn/esbuild Starts a development server that watches for file changes, automatically recompiles the plugin into a main.js file, and performs TypeScript type checking. Errors will be displayed in the console. Manual MarginNote restart is required to load changes. ```bash pnpm dev ``` -------------------------------- ### Plugin Manifest (mnaddon.json) Source: https://ohmymn.marginnote.cn/dev/structure The mnaddon.json file serves as the plugin's description manifest, containing essential information such as the addon ID, author, title, version, minimum supported MarginNote version, and certificate key. The addon ID must be unique and start with 'marginnote.extension.'. The cert_key is for official signing and requires application to MarginNote. ```json { "addonid": "marginnote.extension.ohmymn", "author": "ourongxing", "title": "OhMyMN", "version": "4.2.0", "marginnote_version_min": "3.7.21", "cert_key": "" } ``` -------------------------------- ### Get MarginNote Version Source: https://ohmymn.marginnote.cn/en/api/marginnote Retrieves the current version of the MarginNote application. It provides a fallback version number if the application version is unavailable. ```typescript readonly version = this.app.appVersion ?? "3.7.21" ``` -------------------------------- ### Specific Event Details Source: https://ohmymn.marginnote.cn/dev/events Details on various events like `AddonBroadcast`, `ProcessNewExcerpt`, `ChangeExcerptRange`, `PopupMenuOnNote`, `ClosePopupMenuOnNote`, `PopupMenuOnSelection`, `ClosePopupMenuOnSelection`, `OCRImageBegin`, and `OCRImageEnd`, including their `userInfo` properties. ```APIDOC ## All Events ### Description Provides details for various events and their associated `userInfo` parameters. ### AddonBroadcast Triggered when a URL like `marginnote3app://addon/ohmymn?type=card&shortcut=1` is opened. - `userInfo.message`: Will contain the URL string (e.g., `"ohmymn?type=card&shortcut=1"`). ### ProcessNewExcerpt Triggered when an excerpt is created from a PDF. - `userInfo.noteid`: The ID of the newly created note. ### ChangeExcerptRange Triggered when the selection range of an excerpt in a PDF is modified. - `userInfo.noteid`: The ID of the note associated with the excerpt. ### PopupMenuOnNote Triggered when a context menu appears after clicking on a note (in PDF or mind map). - `userInfo.note`: The note object that was clicked. ### ClosePopupMenuOnNote Triggered when the context menu for a note disappears. - `userInfo.note`: The note object associated with the menu. ### PopupMenuOnSelection Triggered when a context menu appears after selecting text or an area in the PDF. - `userInfo`: An object containing: - `arrow` (Object): Information about the menu arrow. - `documentController` (Object): Controller for the document view. - `winRect` (Object): The window rectangle of the selection. - To get selected text: `userInfo.documentController.selectionText` ### ClosePopupMenuOnSelection Triggered when the context menu for a selection disappears. - `userInfo`: Same structure as `PopupMenuOnSelection`. ### OCRImageBegin Triggered when the Optical Character Recognition (OCR) process begins (automatic or manual). ### OCRImageEnd Triggered when the OCR process finishes. ``` -------------------------------- ### Get Current Window Reference Source: https://ohmymn.marginnote.cn/en/api/marginnote Provides a getter for the currently focused window within MarginNote. This is crucial for operations targeting the active window. ```typescript get currentWindow() { return this.app.focusWindow } ``` -------------------------------- ### Create a New Addon with JSB.newAddon Source: https://ohmymn.marginnote.cn/dev/jsextension This snippet demonstrates how to create a new MarginNote plugin using `JSB.newAddon`. It defines instance methods such as `sceneWillConnect`, `queryAddonCommandStatus`, and `onToggle` to manage the plugin's lifecycle and user interactions. The `go` function within this snippet is responsible for opening external URLs, specifically for accessing Chinese development documents. ```javascript JSB.newAddon = () => { const showHUD = (text, duration = 2) => { self.app.showHUD(text, self.window, duration) } const go = async () => { const { option } = await popup( "Template Popup", "Whether to view the Chinese development documents (old version, new version is not updated)?" ) if (option === -1) return self.app.openURL( NSURL.URLWithString(encodeURI("http://docs.test.marginnote.cn/")) ) } // 返回一个 JSExtension 类,也就是插件 return JSB.defineClass( Addon.name + ": JSExtension", // 实例方法 { // 新的 MN 窗口打开 sceneWillConnect() { self.status = false self.app = Application.sharedInstance() self.studyController = self.app.studyController(self.window) }, // 设置插件按钮图标以及选中状态。点击插件按钮会触发 "onToggle" 方法。 // 只在脑图模式下才显示图标。 queryAddonCommandStatus() { return self.studyController.studyMode !== 3 ? { image: "logo_44x44.png", object: self, selector: "onToggle:", checked: self.status } : null }, // 点击插件图标执行的方法。效果就是按钮被选中,然后弹窗,然后取消选中。 async onToggle() { self.status = true // 刷新插件按钮状态 self.studyController.refreshAddonCommands() await go() self.status = false self.studyController.refreshAddonCommands() } }, // 类方法 {} ) } ``` -------------------------------- ### Get Selected Text from PopupMenuOnSelection Event (JavaScript) Source: https://ohmymn.marginnote.cn/dev/events Shows how to retrieve the selected text using 'userInfo.documentController.selectionText' when the PopupMenuOnSelection event occurs in a PDF. ```javascript userInfo.documentController.selectionText ``` -------------------------------- ### Build MarginNote API Source: https://ohmymn.marginnote.cn/dev/module/how Builds the latest MarginNote API. This step is crucial for ensuring that your module can interact correctly with MarginNote functionalities. ```bash pnpm run api build ``` ```bash pnpm run api build ``` -------------------------------- ### ZipArchive: Compress and Decompress Files (TypeScript) Source: https://ohmymn.marginnote.cn/en/api/marginnote/utility Provides static methods for initializing ZipArchive, unzipping files with or without passwords, and creating zip archives from files or directory contents. Requires path strings for file operations. ```typescript const ZipArchive: { initWithPath(path: string): ZipArchive unzipFileAtPathToDestination(path: string, destination: string): boolean unzipFileAtPathToDestinationOverwritePassword( path: string, destination: string, overwrite: boolean, password: string ): boolean createZipFileAtPathWithFilesAtPaths(path: string, filenames: any[]): boolean createZipFileAtPathWithContentsOfDirectory( path: string, directoryPath: string ): boolean } ``` -------------------------------- ### Defining Control Panel Settings in TypeScript Source: https://ohmymn.marginnote.cn/en/dev/ohmymn/profile Demonstrates how to define control panel settings for a module using `defineConfig`. This example shows settings for 'AutoReplace', including a Switch for 'on', a MuiltSelect for 'preset', and an Input for 'customReplace'. These settings are programmatically linked to module functionalities. ```typescript export default defineConfig({ name: "AutoReplace", key: "autoreplace", settings: [ { key: "on", type: CellViewType.Switch, label: lang.on, auto: { modifyExcerptText: { index: 999, method({ node, text }) { return replaceText(node, text) } } } }, { key: "preset", type: CellViewType.MuiltSelect, option: lang.preset.$option1, label: lang.preset.label }, { key: "customReplace", type: CellViewType.Input, help: lang.custom_replace.help, bind: ["preset", 0], link: lang.custom_replace.link } ], }) ``` -------------------------------- ### Use HUDController for Loading and Done Messages (TypeScript) Source: https://ohmymn.marginnote.cn/api/marginnote/popup Example of using the HUDController to display a 'Loading...' message before an operation and 'Done' after completion. ```typescript import { HUDController } from "marginnote" HUDController.show("Loading...") // do something HUDController.hidden("Done") ``` ```typescript import { HUDController } from "marginnote" HUDController.show("Loading...") // do something HUDController.hidden("Done") ``` -------------------------------- ### Note Instance Methods - Comments and Strokes Source: https://ohmymn.marginnote.cn/en/api/marginnote/mbbooknote Methods for appending comments (HTML and text), appending note links, removing comments, and getting stroke counts. ```APIDOC ## POST /notes/appendHtmlComment ### Description Appends an HTML comment to the note. This method allows for rich text comments that can be rendered by Markdown editor plugins. ### Method POST ### Endpoint /notes/appendHtmlComment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **html** (string) - The HTML content of the comment. - **text** (string) - The plain text version of the comment. - **size** (CGSize) - An object specifying the width and height of the comment display area (e.g., `{ width: 420, height: 100 }`). - **tag** (string) - A markdown editor plugin ID. The HTML comment will be rendered by this plugin. ### Request Example ```json { "html": "```math\n{\n \"result\": \"10\"\n}\n```", "text": "10", "size": { "width": 420, "height": 100 }, "tag": "MarkDownEditor" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` ```APIDOC ## POST /notes/appendTextComment ### Description Appends a plain text comment to the note. ### Method POST ### Endpoint /notes/appendTextComment ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **text** (string) - The text content of the comment. ### Request Example ```json { "text": "This is a plain text comment." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` ```APIDOC ## POST /notes/appendNoteLink ### Description Appends a link to another note within the current note. ### Method POST ### Endpoint /notes/appendNoteLink ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **noteLink** (MbBookNote) - The note object to be linked. ### Request Example ```json { "noteLink": { "id": "linked_note_id", "title": "Linked Note Title" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` ```APIDOC ## DELETE /notes/removeCommentByIndex ### Description Removes a comment from the note by its index. ### Method DELETE ### Endpoint /notes/removeCommentByIndex ### Parameters #### Path Parameters None #### Query Parameters - **index** (number) - The index of the comment to remove. #### Request Body None ### Request Example ```json { "example": "No request body needed, use query parameter 'index'" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` ```APIDOC ## GET /notes/getStrokesCount ### Description Retrieves the number of handwritten strokes in the note. ### Method GET ### Endpoint /notes/getStrokesCount ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed" } ``` ### Response #### Success Response (200) - **count** (number) - The number of handwritten strokes. #### Response Example ```json { "count": 150 } ``` ``` -------------------------------- ### Get Stroke Count Source: https://ohmymn.marginnote.cn/en/api/marginnote/mbbooknote Retrieves the number of handwritten strokes in the note. This method provides a quantitative measure of handwritten content. It takes no arguments and returns a number. ```typescript getStrokesCount(): number ``` ```typescript getStrokesCount(): number ``` -------------------------------- ### Eudic Dictionary URL Scheme Source: https://ohmymn.marginnote.cn/guide/modules/copysearch This example shows the URL scheme for the Eudic dictionary. The format `eudic://dict/` enables direct lookups in the Eudic application by passing a search term. This is beneficial for quickly accessing dictionary definitions from within OhMyMN. ```text eudic://dict/ ```