# Excalidraw Script Library Examples This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools). Its purpose: - Provide a single, query-friendly corpus of all Excalidraw Automate scripts. - Serve as a practical pattern and snippet library for developers learning Excalidraw Automate. - Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall. - Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples. Content structure: 1. SCRIPT_INTRO (this section) 2. The curated script overview (index-new.md) 3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation) Generated on: 2026-06-01T17:57:32.010Z ---
**It looks like you want to get more out of Excalidraw!** Scripts are a true superpower in Excalidraw. If you are ready to eliminate tool friction and build heavy-duty workflows, join [Excalidraw Mastery](https://community.sketch-your-mind.com/em). Master Excalidraw and Visual PKM alongside a supportive community of fellow visual thinkers in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)! --- If you are enjoying the Excalidraw plugin then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt). [
](https://ko-fi.com/zsolt)
---
Jump ahead to the [[#List of available scripts]]
# Introducing Excalidraw Automate Script Engine
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
In the `Command Palette` installed scripts are prefixed with `Downloaded/`, thus you can always know if you are executing a local script of your own, or one that you have downloaded from GitHub.
## Create Your Own Scripts with AI Superpowers
You don't need to know how to code to build custom scripts! In this video, I show how to create powerful, custom Excalidraw scripts from scratch using the power of AI.
Follow along as I generate a complete Layer Manager script for Excalidraw in Obsidian, allowing you to hide, show, lock, and manage elements on different layers. I'll walk you through the entire process, from using a custom training library for Excalidraw Automate to prompting Google's Gemini AI Studio to write the code for us. Discover how to unlock a true superpower for your Obsidian and Excalidraw workflow by generating any script you can imagine.
## Attention developers and hobby hackers
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will add a small circle to the top left of each text element in the selection and add the text and the "connector point" to a group. You can use the connector points to link text elements with an arrow (in for example a Wardley Map).![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script performs automatic layout for the selected top-level grouping objects. It is powered by elkjs and needs to be connected to the Internet.![]() |
| Author | @GColoy |
| Source | File on GitHub |
| Description | With This Script it is possible to make boolean Operations on Shapes. The style of the resulting shape will be the style of the highest ranking Element that was used. The ranking of the elements is based on their background. The "denser" the background, the higher the ranking (the order of backgroundstyles is shown below). If they have the same background the opacity will decide. If thats also the same its decided by the order they were created. The ranking is also important for the difference operation, so a transparent object for example will cut a hole into a solid object. ![]() ![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will add an encapsulating box around the currently selected elements in Excalidraw.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script implements the unified "Capture Note" workflow, allowing users to select or search for note titles, automatically resolve their template and folder rules, and contextually back-embed visual frames or markdown sections.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script allows you to change the shape and fill style of selected Rectangles, Diamonds, Ellipses, Lines, Arrows and Freedraw.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Converts selected plain text elements to sticky notes with transparent background and transparent stroke color (default setting, can be changed in plugin settings). Essentially converts text element into a wrappable format.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.original text - [[selected folder/original text|original text]] |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script will copy styles of any selected element into Excalidraw's global styles.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the Diagram plugin, in a new tab.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script will prompt you for a filename, then create a new markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Adds a rounded mask to the image by adding a full cover black mask and a rounded rectangle white mask. The script is also useful for adding just a black mask. In this case, run the script, then delete the white mask and add your custom white mask.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | You can set a custom zoom level with this script. This allows you to set a zoom level below 10% or set the zoom level to a specific value. Note however, that Excalidraw has a bug under 10% zoom... a phantom copy of your image may appear on screen. If this happens, increase the zoom and the phantom should disappear, if it doesn't, then close and open the drawing. |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.![]() ![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script converts the selected connectors to elbows.![]() |
| Author | @mazurov |
| Source | File on GitHub |
| Description | This script will add an encapsulating ellipse around the currently selected elements in Excalidraw.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script expands the width of the selected rectangles until they are all the same width and keep the text centered.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script expands the width of the selected rectangles until they are all the same width.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script expands the height of the selected rectangles until they are all the same height and keep the text centered.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script expands the height of the selected rectangles until they are all the same height.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script arranges the selected elements horizontally with a fixed center spacing.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script arranges selected elements and groups with a fixed inner distance.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script arranges the selected elements vertically with a fixed center spacing.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script adds the `Folder Note Core: Make current document folder note` function to Excalidraw drawings. Running this script will convert the active Excalidraw drawing into a folder note. If you already have embedded images in your drawing, those attachments will not be moved when the folder note is created. You need to take care of those attachments separately, or convert the drawing to a folder note prior to adding the attachments. The script requires the Folder Note Core plugin. |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script performs two different functions depending on the elements selected in the view. 1) In case you select text elements, the script will cycle through a set of font scales. First the 2 larger fonts following the Fibonacci sequence (fontsize * φ; fonsize * φ^2), then the 2 smaller fonts (fontsize / φ; fontsize / φ^2), finally the original size, followed again by the 2 larger fonts. If you wait 2 seconds, the sequence clears and starts from which ever font size you are on. So if you want the 3rd larges font, then toggle twice, wait 2 sec, then toggle again. 2) In case you select a single rectangle, the script will open the "Golden Grid", "Golden Spiral" window, where you can set up the type of grid or spiral you want to insert into the document. ![]() ![]() |
| Author | @7flash |
| Source | File on GitHub |
| Description | This script arranges selected images into compact grid view, removing gaps in-between, resizing when necessary and breaking into multiple rows/columns.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Various AI features based on GPT Vision.![]() ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Creates a hierarchical Markdown document out of a visual layout of an article that can be fed to Templater and converted into an article using AI for Templater. Watch this video to understand how the script is intended to work: ![]() You can download the sample Obsidian Templater file from here. You can download the demo PDF document showcased in the video from here. |
| Author | @simonperet |
| Source | File on GitHub |
| Description | Generates a complete calendar for a specified year.![]() |
| Author | @TrillStones |
| Source | File on GitHub |
| Description | An Excalidraw script for creating Anki image occlusion cards in Obsidian, similar to Anki's Image Occlusion Enhanced add-on but integrated into your Obsidian workflow.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script inverts the colors on the canvas including the color palette in Element Properties.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.![]() |
| Author | @iwanhoogendoorn |
| Source | File on GitHub |
| Description | Generates a complete calendar for a specified year.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the MindMap Builder Self-Paced Course!![]() Link to video on YouTube ![]() Link to video on YouTube ![]() |
| Author | @xllowl |
| Source | File on GitHub |
| Description | This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.![]() |
| Author | @pandoralink |
| Source | File on GitHub |
| Description | Automatically formats a mindmap from left to right based on the creation sequence of arrows.![]() A mindmap is actually a tree, so you must have a root node. The script will determine the leftmost element of the selected element as the root element (the node must be a rectangle, diamond, ellipse, text, image, but it can't be an arrow, line, freedraw, or group) The element connecting node and node must be an arrow and have the correct direction, e.g. parent node -> child node. The order of nodes in the Y axis or vertical direction is determined by the creation time of the arrow connecting it. ![]() If you want to readjust the order, you can delete arrows and reconnect them. The script provides options to adjust the style of the mindmap. Options are at the bottom of excalidraw plugin options (Settings -> Community plugins -> Excalidraw -> drag to bottom). Since the start bingding and end bingding of the arrows are easily disconnected from the node, if there are unformatted parts, please check the connection and use the script to reformat. |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps. The script has been superseded by Custom Pens that you can enable in plugin settings. Find out more by watching this video ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps. This is the old script from this video. Since it's release this has been superseded by custom pens that you can enable in plugin settings. For more on custom pens, watch this The benefit of the approach in this implementation of custom pens is that it will look the same on excalidraw.com when you copy your drawing over for sharing with non-Obsidian users. Otherwise custom pens are faster to use and much more configurable. ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Design your palette at paletton.com Once you are happy with your colors, click Tables/Export in the bottom right of the screen. Then click "Color swatches/as Sketch Palette", and copy the contents of the page to a markdown file in the palette folder of your vault (default is Excalidraw/Palette)![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Mobile & desktop palm‑rejection and distraction‑free drawing mode: optionally enters fullscreen, hides ALL Excalidraw UI chrome (top toolbar, side / bottom bars, plugin panels) for a clean / zen / immersive / kiosk / focus mode canvas. Provides a tiny draggable micro toolbar (toggle visibility + exit) so you gain maximum drawing area while preventing accidental palm taps. Uses the hotkey you assign in Obsidian’s Hotkey settings for this script to instantly show / hide controls (if no hotkey is set, use the on‑screen toggle). Ideal for stylus sketching, presentations, screen recording, split‑view space saving, or anyone searching for: palm rejection, hide toolbar, hide UI controls, clean mode, distraction free Excalidraw.![]() Link to video on YouTube |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.![]() Link to video on YouTube |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script will cycle through S, M, L, XL font sizes scaled to the current canvas zoom. |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Select an image on the canvas and run the script. You will be prompted to provide a new filename / filepath. This cuts down the time to name images you paste from the web or drag and drop from your file system.![]() |
| Author | @1-2-3 |
| Source | File on GitHub |
| Description | This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.![]() |
| Author | @soraliu |
| Source | File on GitHub |
| Description | In the following script, we address the concept of repetition through the lens of numerical progression. As visualized by the image, where multiple circles each labeled with an even task number are being condensed into a linear sequence, our script will similarly iterate through a set of numbers |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Reverse the direction of **arrows** within the scope of selected elements.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.![]() ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements. The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc. ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script allows you to streamline your Obsidian-Excalidraw workflows by enabling the selection of elements based on similar properties. you can precisely define which attributes such as stroke color, fill style, font family, and more, should match for selection. It's perfect for large canvases where manual selection would be cumbersome. You can either run the script to find and select matching elements across the entire scene, or define a specific group of elements to apply the selection criteria within a defined timeframe.![]() |
| Author | @firai |
| Source | File on GitHub |
| Description | Reset the sizes of embedded LaTeX equations to the default sizes or a multiple of the default sizes.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Use this script to set the background color of unclosed (i.e. open) line and freedraw objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | You can modify the colors of SVG images, embedded files, and Excalidraw elements in a drawing by changing Hue, Saturation, Lightness and Transparency; and if only a single SVG or nested Excalidraw drawing is selected, then you can remap image colors.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | The script will convert your drawing into a slideshow presentation.![]() |
| Author | @GColoy |
| Source | File on GitHub |
| Description | This script splits an ellipse at any point where a line intersects it. If no lines are selected, it will use every line that intersects the ellipse. Otherwise, it will only use the selected lines. If there is no intersecting line, the ellipse will be converted into a line object. There is also the option to close the object along the cut, which will close the cut in the shape of the line. ![]() ![]() Tip: To use an ellipse as the cutting object, you first have to use this script on it, since it will convert the ellipse into a line. |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Split lines of text into separate text elements for easier reorganization![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Select a single text element, or a text element in a container. The container must have a transparent background. The script will add an aura to the text by adding 4 copies of the text each with the inverted stroke color of the original text element and with a very small X and Y offset. The resulting 4 + 1 (original) text elements or containers will be grouped. If you copy a color string on the clipboard before running the script, the script will use that color instead of the inverted color. ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | This script allows you to fit a text element along a selected path: line, arrow, freedraw, ellipse, rectangle, or diamond. You can select either a path or a text element, or both: - If only a path is selected, you will be prompted to provide the text. - If only a text element is selected and it was previously fitted to a path, the script will use the original path if it is still present in the scene. - If both a text and a path are selected, the script will fit the text to the selected path. If the path is a perfect circle, you will be prompted to choose whether to fit the text above or below the circle. After fitting, the text will no longer be editable as a standard text element or function as a markdown link. Emojis are not supported. ![]() |
| Author | @GColoy |
| Source | File on GitHub |
| Description | Toggles the grid on and off. Especially useful when drawing with just a pen without a mouse or keyboard, as toggling the grid by left-clicking with the pen is sometimes quite tedious. |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Converts selected plain text element to sticky notes by dividing the text element line by line into separate sticky notes. The color of the stikcy note as well as the arrangement of the grid can be configured in plugin settings.![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | ![]() The script will standardize the sizes of rectangles, diamonds and ellipses adjusting all the elements to match the largest width and height within the group. |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.![]() Link to video on YouTube ![]() Link to video on YouTube ![]() ![]() |
| Author | @zsviczian |
| Source | File on GitHub |
| Description | Similar to Excalidraw standard SHIFT+2 feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272) |
```js
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.3")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
// -------------------------------
// Utility variables and functions
// -------------------------------
const excalidrawTemplates = ea.getListOfTemplateFiles();
if(typeof window.ExcalidrawDeconstructElements === "undefined") {
window.ExcalidrawDeconstructElements = {
openDeconstructedImage: true,
reuseTab: true,
templatePath: excalidrawTemplates?.[0]?.path??""
};
} else if (typeof window.ExcalidrawDeconstructElements.reuseTab === "undefined") {
window.ExcalidrawDeconstructElements.reuseTab = true;
}
// Helper class for Folder Autocomplete
class FolderSuggest extends ea.obsidian.AbstractInputSuggest {
constructor(app, inputEl) {
super(app, inputEl);
this.inputEl = inputEl;
}
getSuggestions(query) {
const folders = app.vault.getAllLoadedFiles().filter(f => f instanceof ea.obsidian.TFolder);
const lowerQuery = query.toLowerCase();
// Filter folders that match the query
const matches = folders.filter(f => f.path.toLowerCase().includes(lowerQuery));
// Custom Sort
matches.sort((a, b) => {
const aPath = a.path;
const bPath = b.path;
const aLower = aPath.toLowerCase();
const bLower = bPath.toLowerCase();
// Priority 1: Starts with query (e.g. "Projects" comes before "Hobbies/Projects")
const aStarts = aLower.startsWith(lowerQuery);
const bStarts = bLower.startsWith(lowerQuery);
if (aStarts && !bStarts) return -1;
if (!aStarts && bStarts) return 1;
// Priority 2: Alphabetical
return aPath.localeCompare(bPath);
});
return matches.map(f => f.path);
}
renderSuggestion(value, el) {
el.setText(value);
}
selectSuggestion(value, evt) {
this.inputEl.value = value;
this.inputEl.dispatchEvent(new Event('input'));
this.close();
}
}
let settings = ea.getScriptSettings();
//set default values on first run
if(!settings["Templates"]) {
settings = {
"Templates" : {
value: "",
description: "Comma-separated list of template filepaths"
}
};
await ea.setScriptSettings(settings);
}
if(!settings["Default file name"]) {
settings["Default file name"] = {
value: "deconstructed",
description: "The default filename to use when deconstructing elements."
};
await ea.setScriptSettings(settings);
}
const DEFAULT_FILENAME = settings["Default file name"].value;
const templates = settings["Templates"]
.value
.split(",")
.map(p=>app.metadataCache.getFirstLinkpathDest(p.trim(),""))
.concat(excalidrawTemplates)
.filter(f=>Boolean(f))
.sort((a,b) => a.basename.localeCompare(b.basename));
// ------------------------------------
// Prepare elements to be deconstructed
// ------------------------------------
const els = ea.getViewSelectedElements();
if (els.length === 0) {
new Notice("You must select elements first")
return;
}
const bb = ea.getBoundingBox(els);
ea.copyViewElementsToEAforEditing(els);
// Handle Image elements logic from original script
ea.getElements().filter(el=>el.type==="image").forEach(el=>{
const img = ea.targetView.excalidrawData.getFile(el.fileId);
const path = (img?.linkParts?.original)??(img?.file?.path);
const hyperlink = img?.hyperlink;
if(img && (path || hyperlink)) {
const colorMap = ea.getColorMapForImageElement(el);
ea.imagesDict[el.fileId] = {
mimeType: img.mimeType,
id: el.fileId,
dataURL: img.img,
created: img.mtime,
file: path,
hyperlink,
hasSVGwithBitmap: img.isSVGwithBitmap,
latex: null,
colorMap,
};
return;
}
const equation = ea.targetView.excalidrawData.getEquation(el.fileId);
const eqImg = ea.targetView.getScene()?.files[el.fileId]
if(equation && eqImg) {
ea.imagesDict[el.fileId] = {
mimeType: eqImg.mimeType,
id: el.fileId,
dataURL: eqImg.dataURL,
created: eqImg.created,
file: null,
hasSVGwithBitmap: null,
latex: equation.latex,
};
return;
}
});
// ----------------------
// Execution Logic
// ----------------------
const executeDeconstruction = async (folderPath, fileName, shouldAnchor) => {
// Ensure filename has extension
if (!fileName.endsWith(".md")) fileName += ".md";
// Construct full path
// normalizePath handles cases where folderPath might be empty or root
const fullPath = ea.obsidian.normalizePath(`${folderPath}/${fileName}`);
// Separate back into folder and filename for ea.create
const pathParts = fullPath.split("/");
const finalFileName = pathParts.pop();
const finalFolderName = pathParts.join("/");
// We use silent: true to prevent ea.create from opening the file automatically.
// We handle opening manually based on user preference.
const newPath = await ea.create ({
filename: finalFileName,
foldername: finalFolderName,
templatePath: window.ExcalidrawDeconstructElements.templatePath,
onNewPane: true,
silent: true
});
let f = app.vault.getAbstractFileByPath(newPath);
let counter = 0;
while((!f || !ea.isExcalidrawFile(f)) && counter++<100) {
await sleep(50);
f = app.vault.getAbstractFileByPath(newPath);
}
if(!f || !ea.isExcalidrawFile(f)) {
new Notice("Something went wrong");
return;
}
let padding = parseFloat(app.metadataCache.getCache(f.path)?.frontmatter["excalidraw-export-padding"]);
if(isNaN(padding)) {
padding = ea.plugin.settings.exportPaddingSVG;
}
// Remove elements from current view and replace with image of new file
ea.getElements().forEach(el=>el.isDeleted = true);
await ea.addImage(bb.topX-padding, bb.topY-padding, f, false, shouldAnchor);
await ea.addElementsToView(false, true, true);
ea.getExcalidrawAPI().history.clear();
if(window.ExcalidrawDeconstructElements.openDeconstructedImage) {
const reuse = window.ExcalidrawDeconstructElements.reuseTab;
if (reuse) {
ea.openFileInNewOrAdjacentLeaf(f);
} else {
// Force new tab
await app.workspace.getLeaf('tab').openFile(f);
}
} else {
new Notice("Deconstruction ready");
}
};
// ----------------------
// Floating Modal UI
// ----------------------
const modal = new ea.FloatingModal(ea.plugin.app);
modal.titleEl.setText("Deconstruct Elements");
modal.onOpen = () => {
const content = modal.contentEl;
content.empty();
// -- Folder Path Input --
const folderDiv = content.createDiv({ cls: "setting-item" });
folderDiv.createDiv({ cls: "setting-item-info" }).createEl("label", { text: "Folder path" });
const folderControl = folderDiv.createDiv({ cls: "setting-item-control" });
const folderInput = new ea.obsidian.TextComponent(folderControl);
// Set default folder to current file's parent
const currentFolder = ea.targetView.file.parent.path;
folderInput.setValue(currentFolder);
folderInput.inputEl.style.width = "100%";
// Attach Autocomplete
new FolderSuggest(ea.plugin.app, folderInput.inputEl);
// -- Filename Input --
const fileDiv = content.createDiv({ cls: "setting-item" });
fileDiv.createDiv({ cls: "setting-item-info" }).createEl("label", { text: "File name" });
const fileControl = fileDiv.createDiv({ cls: "setting-item-control" });
const fileInput = new ea.obsidian.TextComponent(fileControl);
fileInput.setValue(DEFAULT_FILENAME);
fileInput.inputEl.style.width = "100%";
// Set focus to file input
setTimeout(() => fileInput.inputEl.focus(), 50);
// -- Template Dropdown --
new ea.obsidian.Setting(content)
.setName(`Select template`)
.addDropdown(dropdown => {
templates.forEach(file => dropdown.addOption(file.path, file.basename));
if(templates.length === 0) dropdown.addOption(null, "none");
dropdown
.setValue(window.ExcalidrawDeconstructElements.templatePath)
.onChange(value => {
window.ExcalidrawDeconstructElements.templatePath = value;
})
});
// -- Open Toggle --
new ea.obsidian.Setting(content)
.setName(`Open deconstructed image`)
.addToggle((toggle) => toggle
.setValue(window.ExcalidrawDeconstructElements.openDeconstructedImage)
.onChange(value => {
window.ExcalidrawDeconstructElements.openDeconstructedImage = value;
// Update visibility of the sub-toggle
reuseSetting.settingEl.style.display = value ? "" : "none";
})
);
// -- Reuse Tab Toggle --
const reuseSetting = new ea.obsidian.Setting(content)
.setName(`Reuse existing tab`)
.setDesc("If available, open in an adjacent tab. Otherwise open in a new tab.")
.setClass("reuse-tab-setting")
.addToggle((toggle) => toggle
.setValue(window.ExcalidrawDeconstructElements.reuseTab)
.onChange(value => {
window.ExcalidrawDeconstructElements.reuseTab = value;
})
);
// Initialize visibility and style
reuseSetting.settingEl.style.display = window.ExcalidrawDeconstructElements.openDeconstructedImage ? "" : "none";
reuseSetting.settingEl.style.borderTop = "none";
// -- Buttons --
const buttonContainer = content.createDiv({ cls: "excalidraw-dialog-buttons", style: "margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;" });
const btnInsert = new ea.obsidian.ButtonComponent(buttonContainer)
.setButtonText("Insert")
.setTooltip("Insert without anchoring")
.onClick(async () => {
const folder = folderInput.getValue();
const filename = fileInput.getValue();
if (!filename) {
new Notice("Filename is required");
return;
}
modal.close();
await executeDeconstruction(folder, filename, false);
});
const btnInsertAnchor = new ea.obsidian.ButtonComponent(buttonContainer)
.setButtonText("Insert @100%")
.setTooltip("Anchor to 100% size")
.setCta()
.onClick(async () => {
const folder = folderInput.getValue();
const filename = fileInput.getValue();
if (!filename) {
new Notice("Filename is required");
return;
}
modal.close();
await executeDeconstruction(folder, filename, true);
});
};
modal.open();
```
---
## Elbow connectors.md
/*

Download this file and save to your Obsidian Vault including the first line, or open it in "Raw" and copy the entire contents to Obsidian.

This script converts the selected connectors to elbows.
See documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
const selectedCenterConnectPoints = await utils.suggester(
['Yes', 'No'],
[true, false],
"Center connect points?"
);
const centerConnectPoints = selectedCenterConnectPoints??false;
const allElements = ea.getViewElements();
const elements = ea.getViewSelectedElements();
const lines = elements.filter((el)=>el.type==="arrow" || el.type==="line");
for (const line of lines) {
if (line.points.length >= 3) {
if(centerConnectPoints) {
const startBindingEl = allElements.filter(el => el.id === (line.startBinding||{}).elementId)[0];
const endBindingEl = allElements.filter(el => el.id === (line.endBinding||{}).elementId)[0];
if(startBindingEl) {
const startPointX = line.x +line.points[0][0];
if(startPointX >= startBindingEl.x && startPointX <= startBindingEl.x + startBindingEl.width) {
line.points[0][0] = startBindingEl.x + startBindingEl.width / 2 - line.x;
}
const startPointY = line.y +line.points[0][1];
if(startPointY >= startBindingEl.y && startPointY <= startBindingEl.y + startBindingEl.height) {
line.points[0][1] = startBindingEl.y + startBindingEl.height / 2 - line.y;
}
}
if(endBindingEl) {
const startPointX = line.x +line.points[line.points.length-1][0];
if(startPointX >= endBindingEl.x && startPointX <= endBindingEl.x + endBindingEl.width) {
line.points[line.points.length-1][0] = endBindingEl.x + endBindingEl.width / 2 - line.x;
}
const startPointY = line.y +line.points[line.points.length-1][1];
if(startPointY >= endBindingEl.y && startPointY <= endBindingEl.y + endBindingEl.height) {
line.points[line.points.length-1][1] = endBindingEl.y + endBindingEl.height / 2 - line.y;
}
}
}
for (var i = 0; i < line.points.length - 2; i++) {
var p1;
var p3;
if (line.points[i][0] < line.points[i + 2][0]) {
p1 = line.points[i];
p3 = line.points[i+2];
} else {
p1 = line.points[i + 2];
p3 = line.points[i];
}
const p2 = line.points[i + 1];
if (p1[0] === p3[0]) {
continue;
}
const k = (p3[1] - p1[1]) / (p3[0] - p1[0]);
const b = p1[1] - k * p1[0];
y0 = k * p2[0] + b;
const up = p2[1] < y0;
if ((k > 0 && !up) || (k < 0 && up)) {
p2[0] = p1[0];
p2[1] = p3[1];
} else {
p2[0] = p3[0];
p2[1] = p1[1];
}
}
}
}
ea.copyViewElementsToEAforEditing(lines);
await ea.addElementsToView(false,false);
```
---
## Ellipse Selected Elements.md
/*

This script will add an encapsulating ellipse around the currently selected elements in Excalidraw.
See documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.21")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
settings = ea.getScriptSettings();
//set default values on first run
if(!settings["Default padding"]) {
settings = {
"Prompt for padding?": true,
"Default padding" : {
value: 10,
description: "Padding between the bounding box of the selected elements, and the ellipse the script creates"
}
};
ea.setScriptSettings(settings);
}
let padding = settings["Default padding"].value;
if(settings["Prompt for padding?"]) {
padding = parseInt (await utils.inputPrompt("padding?","number",padding.toString()));
}
if(isNaN(padding)) {
new Notice("The padding value provided is not a number");
return;
}
elements = ea.getViewSelectedElements();
const box = ea.getBoundingBox(elements);
color = ea
.getExcalidrawAPI()
.getAppState()
.currentItemStrokeColor;
//uncomment for random color:
//color = '#'+(Math.random()*0xFFFFFF<<0).toString(16).padStart(6,"0");
ea.style.strokeColor = color;
const ellipseWidth = box.width/Math.sqrt(2);
const ellipseHeight = box.height/Math.sqrt(2);
const topX = box.topX - (ellipseWidth - box.width/2);
const topY = box.topY - (ellipseHeight - box.height/2);
id = ea.addEllipse(
topX - padding,
topY - padding,
2*ellipseWidth + 2*padding,
2*ellipseHeight + 2*padding
);
ea.copyViewElementsToEAforEditing(elements);
ea.addToGroup([id].concat(elements.map((el)=>el.id)));
ea.addElementsToView(false,false);
```
---
## ExcaliAI.md
/*

```js*/
let dirty=false;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.0")) {
new Notice("This script requires Excalidraw 2.23.0 or later. Please update the plugin.");
return;
}
const EXCALIAI_SETTINGS_VERSION = 1;
const DEFAULT_IMAGE_SIZE = "1024x1024";
const TASK_EXECUTION_MODES = {
TEXT_RESULT: "text-result",
IMAGE_PROMPT: "image-prompt",
IMAGE_DIRECT: "image-direct",
IMAGE_EDIT: "image-edit",
};
const TASK_RESULT_TYPES = {
HTML: "html",
MINDMAP: "mindmap",
MERMAID: "mermaid",
SVG: "svg",
IMAGE: "image",
IMAGE_SILENT: "image-silent",
};
const TASK_INPUT_RULES = {
DISABLED: "disabled",
OPTIONAL: "optional",
REQUIRED: "required",
};
const TASK_MASK_MODES = {
DISABLED: "disabled",
OPTIONAL: "optional",
REQUIRED: "required",
};
const TASK_RUNTIME_APIS = {
NONE: "",
MINDMAP_BUILDER: "mindmap-builder",
};
const VALID_TASK_EXECUTION_MODES = Object.values(TASK_EXECUTION_MODES);
const VALID_TASK_RESULT_TYPES = Object.values(TASK_RESULT_TYPES);
const VALID_TASK_INPUT_RULES = Object.values(TASK_INPUT_RULES);
const VALID_TASK_MASK_MODES = Object.values(TASK_MASK_MODES);
const VALID_TASK_RUNTIME_APIS = Object.values(TASK_RUNTIME_APIS);
const TASK_EXECUTION_MODE_META = {
[TASK_EXECUTION_MODES.TEXT_RESULT]: {
label: "Text response",
description: "Uses the text or multimodal model and returns structured output such as HTML, Mermaid, a mind map, or Excalidraw strokes.",
},
[TASK_EXECUTION_MODES.IMAGE_PROMPT]: {
label: "Write prompt, then generate image",
description: "Uses the text model to write an image prompt from the canvas selection and/or user prompt, then sends that prompt to the image model.",
},
[TASK_EXECUTION_MODES.IMAGE_DIRECT]: {
label: "Send prompt straight to image model",
description: "Sends only the user's prompt to the image model. No text-model prompt writing step and no canvas image input.",
},
[TASK_EXECUTION_MODES.IMAGE_EDIT]: {
label: "Edit selected image",
description: "Uses the selected image as the source and applies either a mask edit or a prompt-based transform.",
},
};
const TASK_RESULT_TYPE_META = {
[TASK_RESULT_TYPES.HTML]: {
label: "HTML",
description: "Embeds the response as a single HTML result.",
},
[TASK_RESULT_TYPES.MINDMAP]: {
label: "Mind Map",
description: "Imports the response into MindMap Builder.",
runtimeRequirement: TASK_RUNTIME_APIS.MINDMAP_BUILDER,
},
[TASK_RESULT_TYPES.MERMAID]: {
label: "Mermaid",
description: "Creates a Mermaid diagram.",
},
[TASK_RESULT_TYPES.SVG]: {
label: "Excalidraw Strokes",
description: "Uses SVG behind the scenes to generate Excalidraw strokes.",
},
[TASK_RESULT_TYPES.IMAGE]: {
label: "Image + prompt note",
description: "Generates an image and adds the model's revised prompt underneath when available.",
},
[TASK_RESULT_TYPES.IMAGE_SILENT]: {
label: "Image only",
description: "Generates only the image, without adding the revised prompt underneath.",
},
};
const getTaskExecutionModeMeta = (mode) => (
TASK_EXECUTION_MODE_META[mode] ?? TASK_EXECUTION_MODE_META[TASK_EXECUTION_MODES.TEXT_RESULT]
);
const getTaskExecutionModeLabel = (mode) => (
getTaskExecutionModeMeta(mode).label
);
const getTaskExecutionModeDescription = (mode) => (
getTaskExecutionModeMeta(mode).description
);
const getTaskResultTypeMeta = (resultType) => (
TASK_RESULT_TYPE_META[resultType] ?? TASK_RESULT_TYPE_META[TASK_RESULT_TYPES.HTML]
);
const getTaskResultTypeLabel = (resultType) => (
getTaskResultTypeMeta(resultType).label
);
const getTaskResultTypeDescription = (resultType) => (
getTaskResultTypeMeta(resultType).description
);
const getTaskRuntimeRequirement = (taskConfig) => (
getTaskResultTypeMeta(taskConfig?.execution?.resultType ?? TASK_RESULT_TYPES.HTML).runtimeRequirement
?? TASK_RUNTIME_APIS.NONE
);
const getTaskRuntimeRequirementLabel = (runtimeRequirement) => {
switch(runtimeRequirement) {
case TASK_RUNTIME_APIS.MINDMAP_BUILDER:
return "MindMap Builder";
default:
return "None";
}
};
const normalizeEnumValue = (value, validValues, fallbackValue) => (
validValues.includes(value) ? value : fallbackValue
);
const cloneJSON = (value) => {
if(value == null) {
return value;
}
return JSON.parse(JSON.stringify(value));
};
const createTaskIdFromName = (value = "") => {
const normalizedValue = String(value ?? "")
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
return normalizedValue || "task";
};
const getDefaultOutputInstruction = (resultType) => {
switch(resultType) {
case TASK_RESULT_TYPES.HTML:
return "Turn this into a single html file using tailwind. Return a single message containing only the html file in a codeblock.";
case TASK_RESULT_TYPES.MINDMAP:
return "Return only the mind map as plain text. Use one # heading for the central node, then nested - bullets for branches. Do not use bold, italics, code fences, tables, or explanatory text.";
case TASK_RESULT_TYPES.MERMAID:
return "Return a single message containing only the mermaid diagram in a codeblock.";
case TASK_RESULT_TYPES.SVG:
return "Return a single message containing only the SVG code in an html codeblock.";
case TASK_RESULT_TYPES.IMAGE:
case TASK_RESULT_TYPES.IMAGE_SILENT:
return "Return a single message with the generated image prompt in a codeblock";
default:
return "";
}
};
const getDefaultResultTypeForMode = (mode) => {
switch(mode) {
case TASK_EXECUTION_MODES.IMAGE_PROMPT:
case TASK_EXECUTION_MODES.IMAGE_DIRECT:
case TASK_EXECUTION_MODES.IMAGE_EDIT:
return TASK_RESULT_TYPES.IMAGE;
default:
return TASK_RESULT_TYPES.HTML;
}
};
const normalizeTaskConfig = (task = {}, index = 0) => {
const execution = task.execution ?? {};
const mode = normalizeEnumValue(
execution.mode,
VALID_TASK_EXECUTION_MODES,
TASK_EXECUTION_MODES.TEXT_RESULT,
);
const resultType = normalizeEnumValue(
execution.resultType,
VALID_TASK_RESULT_TYPES,
getDefaultResultTypeForMode(mode),
);
const imageInputFallback = mode === TASK_EXECUTION_MODES.IMAGE_DIRECT
? TASK_INPUT_RULES.DISABLED
: mode === TASK_EXECUTION_MODES.IMAGE_EDIT
? TASK_INPUT_RULES.REQUIRED
: TASK_INPUT_RULES.OPTIONAL;
return {
id: createTaskIdFromName(task.id ?? task.name ?? `task-${index + 1}`),
name: String(task.name ?? "").trim() || `Task ${index + 1}`,
help: String(task.help ?? "").trim(),
systemPrompt: task.systemPrompt == null ? null : String(task.systemPrompt),
outputInstruction: String(task.outputInstruction ?? getDefaultOutputInstruction(resultType)),
execution: {
mode,
resultType,
userPrompt: normalizeEnumValue(
execution.userPrompt,
VALID_TASK_INPUT_RULES,
TASK_INPUT_RULES.OPTIONAL,
),
imageInput: normalizeEnumValue(
execution.imageInput,
VALID_TASK_INPUT_RULES,
imageInputFallback,
),
maskMode: normalizeEnumValue(
execution.maskMode,
VALID_TASK_MASK_MODES,
mode === TASK_EXECUTION_MODES.IMAGE_EDIT
? TASK_MASK_MODES.OPTIONAL
: TASK_MASK_MODES.DISABLED,
),
requiresApi: getTaskResultTypeMeta(resultType).runtimeRequirement ?? TASK_RUNTIME_APIS.NONE,
},
};
};
const normalizeTaskConfigs = (tasks, {fallbackToDefaults = false} = {}) => {
if(!Array.isArray(tasks)) {
return fallbackToDefaults ? normalizeTaskConfigs(createDefaultTaskConfigs()) : [];
}
const usedIds = new Set();
return tasks.map((task, index) => {
const normalizedTask = normalizeTaskConfig(task, index);
if(normalizedTask.execution.mode !== TASK_EXECUTION_MODES.IMAGE_EDIT) {
normalizedTask.execution.maskMode = TASK_MASK_MODES.DISABLED;
}
let nextId = normalizedTask.id || createTaskIdFromName(normalizedTask.name) || `task-${index + 1}`;
let duplicateCount = 2;
while(usedIds.has(nextId)) {
nextId = `${normalizedTask.id}-${duplicateCount++}`;
}
usedIds.add(nextId);
normalizedTask.id = nextId;
return normalizedTask;
});
};
const createDefaultTaskConfigs = () => ([
{
id: "challenge-my-thinking",
name: "Challenge my thinking",
help: "Turn the selected image and optional prompt into a Mermaid mind map. If conversion fails, open More Tools > Mermaid to Excalidraw and edit the generated script.",
systemPrompt: `Your task is to interpret a screenshot of a whiteboard, translating its ideas into a Mermaid graph. The whiteboard will encompass thoughts on a subject. Within the mind map, distinguish ideas that challenge, dispute, or contradict the whiteboard content. Additionally, include concepts that expand, complement, or advance the user's thinking. Utilize the Mermaid graph diagram type and present the resulting Mermaid diagram within a code block. Ensure the Mermaid script excludes the use of parentheses ().`,
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.MERMAID),
execution: {
mode: TASK_EXECUTION_MODES.TEXT_RESULT,
resultType: TASK_RESULT_TYPES.MERMAID,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "convert-sketch-to-shapes",
name: "Convert sketch to shapes",
help: "Convert selected sketches into Excalidraw strokes. Works best with a small number of simple shapes. Experimental.",
systemPrompt: `Given an image featuring various geometric shapes drawn by the user, your objective is to analyze the input and generate SVG code that accurately represents these shapes. Your output will be the SVG code enclosed in an HTML code block.`,
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.SVG),
execution: {
mode: TASK_EXECUTION_MODES.TEXT_RESULT,
resultType: TASK_RESULT_TYPES.SVG,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "create-a-simple-excalidraw-icon",
name: "Create a simple Excalidraw icon",
help: "Turn a text prompt into a simple icon and insert it into Excalidraw as strokes. Text prompt only. Experimental.",
systemPrompt: `Given a description of an SVG image from the user, your objective is to generate the corresponding SVG code. Avoid incorporating textual elements within the generated SVG. Your output should be the resulting SVG code enclosed in an HTML code block.`,
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.SVG),
execution: {
mode: TASK_EXECUTION_MODES.TEXT_RESULT,
resultType: TASK_RESULT_TYPES.SVG,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.DISABLED,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "create-a-stick-figure",
name: "Create a stick figure",
help: "Send only the text prompt to the configured image model. Be specific. To keep the prompt unchanged, start with: 'DO NOT add any detail, just use it AS-IS:'",
systemPrompt: "You will receive a prompt from the user. Your task involves drawing a simple stick figure or a scene involving a few stick figures based on the user's prompt. Create the stick figure based on the following style description. DO NOT add any detail, just use it AS-IS: Create a simple stick figure character with a large round head and a face in the style of sketchy caricatures. The stick figure should have a rudimentary body composed of straight lines representing the arms and legs. Hands and toes should be represented with round shapes, do not add details such as fingers or toes. Use fine lines, smooth curves, rounded shapes. The stick figure should retain a playful and childlike simplicity, reminiscent of a doodle someone might draw on the corner of a notebook page. Create a black and white drawing, a hand-drawn figure on white background.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_PROMPT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.DISABLED,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "edit-an-image",
name: "Edit an image",
help: "Image elements are used as the source image. In mask mode, shapes on top become the mask. Turn mask edit off to flatten non-image elements into the source image and apply a prompt-based transform.",
systemPrompt: null,
outputInstruction: "",
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_EDIT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.REQUIRED,
imageInput: TASK_INPUT_RULES.REQUIRED,
maskMode: TASK_MASK_MODES.OPTIONAL,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "generate-an-image-from-image-and-prompt",
name: "Generate an image from image and prompt",
help: "Generate an image from the selected image and your prompt. Add context in the prompt to guide how the image should be interpreted.",
systemPrompt: "Your task involves receiving an image and a textual prompt from the user. Your goal is to craft a detailed, accurate, and descriptive narrative of the image, tailored for effective image generation. Utilize the user-provided text prompt to inform and guide your depiction of the image. Ensure the resulting image remains text-free.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_PROMPT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "generate-an-image-from-prompt",
name: "Generate an image from prompt",
help: "Send only the text prompt to the configured image model. Be specific. To keep the prompt unchanged, start with: 'DO NOT add any detail, just use it AS-IS:'",
systemPrompt: null,
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_DIRECT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.DISABLED,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "generate-an-image-to-illustrate-a-quote",
name: "Generate an image to illustrate a quote",
help: "Turn a quote into an illustrated scene. Include the author's name if you want the result to reference them.",
systemPrompt: "Your task involves transforming a user-provided quote into a detailed and imaginative illustration. Craft a visual representation that captures the essence of the quote and resonates well with a broad audience. If the Author's name is provided, aim to establish a connection between the illustration and the Author. This can be achieved by referencing a well-known story from the Author, situating the image in the Author's era or setting, or employing other creative methods of association. Additionally, provide preferences for styling, such as the chosen medium and artistic direction, to guide the image creation process. Ensure the resulting image remains text-free. Your task output should comprise a descriptive and detailed narrative aimed at facilitating the creation of a captivating illustration from the quote.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_PROMPT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.DISABLED,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "generate-4-icon-variants-based-on-input-image",
name: "Generate 4 icon-variants based on input image",
help: "Generate a 2x2 sheet of four icon variations from the selected sketch. Add a prompt if you want to steer the result.",
systemPrompt: "Given a simple sketch and an optional text prompt from the user, your task is to generate a descriptive narrative tailored for effective image generation, capturing the style of the sketch. Utilize the text prompt to guide the description. Your objective is to instruct DALL-E to create a collage of four minimalist black and white hand-drawn pencil sketches in a 2x2 matrix format. Each sketch should convert the user's sketch into simple artistic SVG icons with transparent backgrounds. Ensure the resulting images remain text-free, maintaining a minimalist, easy-to-understand style, and omit framing borders. Only include a pencil in the drawing if it is explicitly mentioned in the user prompt or included in the sketch.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE_SILENT),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_PROMPT,
resultType: TASK_RESULT_TYPES.IMAGE_SILENT,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "visual-brainstorm",
name: "Visual brainstorm",
help: "Generate an image from the selected image and prompt to spark new ideas.",
systemPrompt: "Your objective is to interpret a screenshot of a whiteboard, creating an image aimed at sparking further thoughts on the subject. The whiteboard will present diverse ideas about a specific topic. Your generated image should achieve one of two purposes: highlighting concepts that challenge, dispute, or contradict the whiteboard content, or introducing ideas that expand, complement, or enrich the user's thinking. You have the option to include multiple tiles in the resulting image, resembling a sequence akin to a comic strip. Ensure that the image remains devoid of text.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.IMAGE),
execution: {
mode: TASK_EXECUTION_MODES.IMAGE_PROMPT,
resultType: TASK_RESULT_TYPES.IMAGE,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "wireframe-to-code",
name: "Wireframe to code",
help: "Interpret the selected wireframe and generate a web app as a single HTML file. You can copy the result from the embeddable menu.",
systemPrompt: `You are an expert tailwind developer. A user will provide you with a low-fidelity wireframe of an application and you will return a single html file that uses tailwind to create the website. Use creative license to make the application more fleshed out. Write the necessary javascript code. If you need to insert an image, use placehold.co to create a placeholder image.`,
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.HTML),
execution: {
mode: TASK_EXECUTION_MODES.TEXT_RESULT,
resultType: TASK_RESULT_TYPES.HTML,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.NONE,
},
},
{
id: "create-mindmap",
name: "Create Mindmap",
help: "Create a hierarchical mind map from the selected image, if any, and your prompt, then import it into MindMap Builder. Requires MindMap Builder to be available.",
systemPrompt: "You will receive a text prompt and may also receive an image. Create a mind map as a hierarchical plain-text outline based on the image content, if provided, and the text prompt. Return only the mind map. Use exactly one markdown H1 heading for the central node, then - bullets for branches and indented - bullets for sub-branches. Do not use bold, italics, code fences, numbering, commentary, or any markdown formatting other than the heading and bullet list.",
outputInstruction: getDefaultOutputInstruction(TASK_RESULT_TYPES.MINDMAP),
execution: {
mode: TASK_EXECUTION_MODES.TEXT_RESULT,
resultType: TASK_RESULT_TYPES.MINDMAP,
userPrompt: TASK_INPUT_RULES.OPTIONAL,
imageInput: TASK_INPUT_RULES.OPTIONAL,
maskMode: TASK_MASK_MODES.DISABLED,
requiresApi: TASK_RUNTIME_APIS.MINDMAP_BUILDER,
},
},
]);
const DEFAULT_TASK_CONFIGS = normalizeTaskConfigs(createDefaultTaskConfigs());
const DEFAULT_TASK_ID = DEFAULT_TASK_CONFIGS.find(task => task.id === "wireframe-to-code")?.id
?? DEFAULT_TASK_CONFIGS[0]?.id
?? "";
const createDefaultState = (taskConfigs = []) => ({
selectedTaskId: taskConfigs.find(task => task.id === DEFAULT_TASK_ID)?.id ?? taskConfigs[0]?.id ?? "",
userPrompt: "",
maskEdit: true,
textModel: "",
imageModel: "",
maxTokens: "",
imageSize: DEFAULT_IMAGE_SIZE,
});
const normalizeState = (state = {}, taskConfigs = []) => {
const defaultState = createDefaultState(taskConfigs);
const knownTaskIds = new Set(taskConfigs.map(task => task.id));
const selectedTaskId = String(state.selectedTaskId ?? defaultState.selectedTaskId).trim();
return {
selectedTaskId: knownTaskIds.has(selectedTaskId) ? selectedTaskId : defaultState.selectedTaskId,
userPrompt: String(state.userPrompt ?? defaultState.userPrompt),
maskEdit: state.maskEdit !== false,
textModel: String(state.textModel ?? defaultState.textModel),
imageModel: String(state.imageModel ?? defaultState.imageModel),
maxTokens: String(state.maxTokens ?? defaultState.maxTokens).trim(),
imageSize: String(state.imageSize ?? defaultState.imageSize).trim() || defaultState.imageSize,
};
};
const createDefaultExcaliAISettings = () => ({
schemaVersion: EXCALIAI_SETTINGS_VERSION,
config: {
tasks: cloneJSON(DEFAULT_TASK_CONFIGS),
},
state: createDefaultState(DEFAULT_TASK_CONFIGS),
});
const LEGACY_TASK_NAME_TO_ID = Object.fromEntries(
DEFAULT_TASK_CONFIGS.map(task => [task.name, task.id]),
);
const loadExcaliAISettings = (rawSettings) => {
const sourceSettings = rawSettings && typeof rawSettings === "object" ? rawSettings : {};
const normalizedSettings = createDefaultExcaliAISettings();
normalizedSettings.config.tasks = normalizeTaskConfigs(sourceSettings.config?.tasks, {fallbackToDefaults: true});
const legacyState = {
selectedTaskId: LEGACY_TASK_NAME_TO_ID[String(sourceSettings["Agent's Task"] ?? "").trim()] ?? normalizedSettings.state.selectedTaskId,
userPrompt: sourceSettings["User Prompt"] ?? normalizedSettings.state.userPrompt,
maskEdit: sourceSettings["Mask Edit"] !== false,
textModel: sourceSettings["Text Model"] ?? normalizedSettings.state.textModel,
imageModel: sourceSettings["Image Model"] ?? normalizedSettings.state.imageModel,
maxTokens: sourceSettings["Max Tokens"] ?? normalizedSettings.state.maxTokens,
imageSize: sourceSettings["Image Size"] ?? normalizedSettings.state.imageSize,
};
normalizedSettings.state = normalizeState({
...legacyState,
...(sourceSettings.state ?? {}),
}, normalizedSettings.config.tasks);
return {
settings: normalizedSettings,
needsSave: JSON.stringify(sourceSettings) !== JSON.stringify(normalizedSettings),
};
};
// --------------------------------------
// Initialize values and settings
// --------------------------------------
let settings = ea.getScriptSettings();
const loadedExcaliAISettings = loadExcaliAISettings(settings);
settings = loadedExcaliAISettings.settings;
if(loadedExcaliAISettings.needsSave) {
await ea.setScriptSettings(settings);
}
let userPrompt = settings.state.userPrompt ?? "";
let selectedTaskId = settings.state.selectedTaskId;
let imageSize = settings.state.imageSize ?? DEFAULT_IMAGE_SIZE;
let selectedTextModel = settings.state.textModel ?? "";
let selectedImageModel = settings.state.imageModel ?? "";
let selectedMaxTokens = String(settings.state.maxTokens ?? "").trim();
let prefersMaskEdit = settings.state.maskEdit !== false;
const aiSettings = ea.getAISettings();
if(!aiSettings?.enabled) {
new Notice("Excalidraw AI is disabled or unavailable. Enable it in plugin settings.");
return;
}
let textModel, imageModel, validSizes;
let imageDataURL = null;
let maskDataURL = null;
const parsePositiveInteger = (value) => {
const normalizedValue = String(value ?? "").trim();
if(!normalizedValue) {
return null;
}
const parsedValue = parseInt(normalizedValue, 10);
if(Number.isNaN(parsedValue) || parsedValue <= 0) {
return null;
}
return parsedValue;
};
const getTaskConfigs = () => settings.config?.tasks ?? [];
const isTaskRuntimeAvailable = (taskConfig) => {
switch(getTaskRuntimeRequirement(taskConfig)) {
case TASK_RUNTIME_APIS.MINDMAP_BUILDER:
return Boolean(window?.MindMapBuilderAPI);
default:
return true;
}
};
const getVisibleTaskConfigs = () => getTaskConfigs().filter(isTaskRuntimeAvailable);
const getTaskConfigById = (taskId = selectedTaskId) => (
getTaskConfigs().find(taskConfig => taskConfig.id === taskId) ?? null
);
const getVisibleTaskConfigById = (taskId = selectedTaskId) => (
getVisibleTaskConfigs().find(taskConfig => taskConfig.id === taskId) ?? null
);
const ensureSelectedTaskId = () => {
const activeVisibleTask = getVisibleTaskConfigById(selectedTaskId);
const fallbackTask = activeVisibleTask ?? getVisibleTaskConfigs()[0] ?? null;
const nextTaskId = fallbackTask?.id ?? "";
if(selectedTaskId !== nextTaskId) {
selectedTaskId = nextTaskId;
dirty = true;
}
return fallbackTask;
};
const getActiveTaskConfig = () => ensureSelectedTaskId();
const getTaskExecutionConfig = (taskId = selectedTaskId) => (
getTaskConfigById(taskId)?.execution ?? null
);
const getTaskOutputType = (taskId = selectedTaskId) => {
const taskConfig = typeof taskId === "string" ? getTaskConfigById(taskId) : taskId;
return {
instruction: taskConfig?.outputInstruction ?? "",
blocktype: taskConfig?.execution?.resultType ?? TASK_RESULT_TYPES.HTML,
};
};
const isImageEditTask = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.mode === TASK_EXECUTION_MODES.IMAGE_EDIT
);
const isImageGenerationTask = (taskId = selectedTaskId) => {
const mode = getTaskExecutionConfig(taskId)?.mode;
return mode === TASK_EXECUTION_MODES.IMAGE_PROMPT
|| mode === TASK_EXECUTION_MODES.IMAGE_DIRECT
|| mode === TASK_EXECUTION_MODES.IMAGE_EDIT;
};
const doesTaskUseTextModel = (taskId = selectedTaskId) => {
const mode = getTaskExecutionConfig(taskId)?.mode;
return mode === TASK_EXECUTION_MODES.TEXT_RESULT || mode === TASK_EXECUTION_MODES.IMAGE_PROMPT;
};
const doesTaskAllowUserPrompt = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.userPrompt !== TASK_INPUT_RULES.DISABLED
);
const taskRequiresUserPrompt = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.userPrompt === TASK_INPUT_RULES.REQUIRED
);
const doesTaskAllowImageInput = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.imageInput !== TASK_INPUT_RULES.DISABLED
);
const taskRequiresImageInput = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.imageInput === TASK_INPUT_RULES.REQUIRED
);
const taskUsesDirectImageModel = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.mode === TASK_EXECUTION_MODES.IMAGE_DIRECT
);
const taskUsesImagePromptPipeline = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.mode === TASK_EXECUTION_MODES.IMAGE_PROMPT
);
const getTaskMaskMode = (taskId = selectedTaskId) => (
getTaskExecutionConfig(taskId)?.maskMode ?? TASK_MASK_MODES.DISABLED
);
const getTaskConfigValidationMessage = (taskConfig = getActiveTaskConfig()) => {
if(!taskConfig) {
return "No runnable AI tasks are configured. Open Task Editor to add a task or reset the shipped presets.";
}
const {mode, resultType, maskMode} = taskConfig.execution;
const isImageResultType = resultType === TASK_RESULT_TYPES.IMAGE || resultType === TASK_RESULT_TYPES.IMAGE_SILENT;
if(mode === TASK_EXECUTION_MODES.TEXT_RESULT && isImageResultType) {
return `Task \"${taskConfig.name}\" uses an image result with ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.TEXT_RESULT)}. Use ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_PROMPT)} or ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_DIRECT)} instead.`;
}
if(mode === TASK_EXECUTION_MODES.IMAGE_PROMPT && !isImageResultType) {
return `Task \"${taskConfig.name}\" must use an image result when ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_PROMPT)} is selected.`;
}
if(mode === TASK_EXECUTION_MODES.IMAGE_DIRECT && !isImageResultType) {
return `Task \"${taskConfig.name}\" must use an image result when ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_DIRECT)} is selected.`;
}
if(mode === TASK_EXECUTION_MODES.IMAGE_DIRECT && taskConfig.execution.imageInput !== TASK_INPUT_RULES.DISABLED) {
return `Task \"${taskConfig.name}\" cannot send a canvas image when ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_DIRECT)} is selected.`;
}
if(mode === TASK_EXECUTION_MODES.IMAGE_EDIT && resultType !== TASK_RESULT_TYPES.IMAGE) {
return `Task \"${taskConfig.name}\" must use the image result when ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_EDIT)} is selected.`;
}
if(mode !== TASK_EXECUTION_MODES.IMAGE_EDIT && maskMode !== TASK_MASK_MODES.DISABLED) {
return `Task \"${taskConfig.name}\" can only enable mask mode when ${getTaskExecutionModeLabel(TASK_EXECUTION_MODES.IMAGE_EDIT)} is selected.`;
}
return "";
};
const getConfiguredTextMaxTokens = () => {
const scriptOverride = parsePositiveInteger(selectedMaxTokens);
if(scriptOverride) {
return scriptOverride;
}
const pluginDefault = parsePositiveInteger(aiSettings.defaultMaxResponseTokens);
return pluginDefault;
};
const getProviderProfiles = () => (
aiSettings.providerProfiles ?? {}
);
const getTextModelConfigs = () => (
aiSettings.textModels ?? {}
);
const getImageModelConfigs = () => (
aiSettings.imageModels ?? {}
);
const hasConfiguredProviderApiKey = (providerId) => (
Boolean(getProviderProfiles()[providerId]?.hasApiKey)
);
const getConfiguredModelIdsForKind = (kind) => {
const configs = kind === "text"
? getTextModelConfigs()
: getImageModelConfigs();
return Object.keys(configs)
.filter(modelId => hasConfiguredProviderApiKey(configs[modelId]?.providerId))
.sort((left, right) => left.localeCompare(right));
};
const getMissingModelConfigurationMessage = (kind) => {
if(kind === "text") {
return "No text or multimodal models are ready to use. Add an API key to a provider profile and assign at least one text model in Excalidraw AI settings.";
}
return "No image models are ready to use. Add an API key to a provider profile and assign at least one image model in Excalidraw AI settings.";
};
const getConfiguredTextModel = () => (
((doesTaskAllowImageInput() && imageDataURL) ? aiSettings.defaultMultimodalTextModel : aiSettings.defaultTextModel)
|| aiSettings.defaultTextModel
|| aiSettings.defaultMultimodalTextModel
|| getConfiguredModelIdsForKind("text")[0]
|| ""
);
const getConfiguredImageModel = () => (
aiSettings.defaultImageModel
|| getConfiguredModelIdsForKind("image")[0]
|| ""
);
const getModelConfigId = (configs, modelId) => {
if(configs[modelId]) {
return modelId;
}
return Object.keys(configs).find(configId => configs[configId]?.model === modelId) ?? "";
};
const getTextModelConfigId = (modelId) => getModelConfigId(getTextModelConfigs(), modelId);
const getImageModelConfigId = (modelId) => {
return getModelConfigId(getImageModelConfigs(), modelId);
};
const getTextModelConfig = (modelId) => {
const configId = getTextModelConfigId(modelId);
return configId ? getTextModelConfigs()[configId] ?? null : null;
};
const getImageModelConfig = (modelId) => {
const configId = getImageModelConfigId(modelId);
return configId ? getImageModelConfigs()[configId] ?? null : null;
};
const getAvailableTextModels = () => {
const configuredModels = getConfiguredModelIdsForKind("text");
if(configuredModels.length > 0) {
return configuredModels;
}
return [];
};
const getAvailableImageModels = () => {
const configuredModels = getConfiguredModelIdsForKind("image");
if(configuredModels.length > 0) {
return configuredModels;
}
return [];
};
const getValidSizesForModel = (model) => {
if(!model) {
return [];
}
const configuredSizes = getImageModelConfig(model)?.supportedSizes
?.map(size => size?.trim())
.filter(Boolean);
if(configuredSizes?.length) {
return configuredSizes;
}
return ["1024x1024"];
};
const parseImageSizeDimensions = (size) => {
const match = String(size ?? "").trim().match(/^(\d+)x(\d+)$/i);
if(!match) {
return null;
}
const width = parseInt(match[1], 10);
const height = parseInt(match[2], 10);
if(Number.isNaN(width) || Number.isNaN(height) || width <= 0 || height <= 0) {
return null;
}
return {width, height};
};
const greatestCommonDivisor = (a, b) => {
let x = Math.abs(a);
let y = Math.abs(b);
while(y !== 0) {
const remainder = x % y;
x = y;
y = remainder;
}
return x || 1;
};
const CANONICAL_ASPECT_RATIOS = [
"1:8",
"1:4",
"2:3",
"3:4",
"4:5",
"9:16",
"1:1",
"16:9",
"5:4",
"4:3",
"3:2",
"4:1",
"8:1",
"21:9",
].map((label) => {
const [width, height] = label.split(":").map((value) => parseInt(value, 10));
return {
label,
ratio: width/height,
};
});
const ASPECT_RATIO_LABEL_RELATIVE_EPSILON = 0.02;
const getCanonicalAspectRatioLabel = (width, height) => {
const ratio = width/height;
const nearest = CANONICAL_ASPECT_RATIOS
.map((candidate) => ({
...candidate,
delta: Math.abs(candidate.ratio - ratio),
}))
.sort((left, right) => left.delta - right.delta)[0];
if(
nearest &&
nearest.delta/Math.max(nearest.ratio, Number.EPSILON)
<= ASPECT_RATIO_LABEL_RELATIVE_EPSILON
) {
return nearest.label;
}
const divisor = greatestCommonDivisor(width, height);
return `${Math.round(width/divisor)}:${Math.round(height/divisor)}`;
};
const getAspectRatioLabelFromDimensions = (width, height) => {
return getCanonicalAspectRatioLabel(width, height);
};
const getImageSizeDropdownOptions = (sizes = []) => {
return sizes
.map((size) => {
const dimensions = parseImageSizeDimensions(size);
if(!dimensions) {
return {
value: size,
label: String(size ?? ""),
ratioOrder: Number.POSITIVE_INFINITY,
pixels: Number.POSITIVE_INFINITY,
width: Number.POSITIVE_INFINITY,
height: Number.POSITIVE_INFINITY,
};
}
const ratioLabel = getAspectRatioLabelFromDimensions(dimensions.width, dimensions.height);
return {
value: size,
label: `(${ratioLabel}) ${dimensions.width}x${dimensions.height}`,
ratioOrder: dimensions.width/dimensions.height,
pixels: dimensions.width * dimensions.height,
width: dimensions.width,
height: dimensions.height,
};
})
.sort((left, right) => {
if(left.ratioOrder !== right.ratioOrder) {
return left.ratioOrder - right.ratioOrder;
}
if(left.pixels !== right.pixels) {
return left.pixels - right.pixels;
}
if(left.width !== right.width) {
return left.width - right.width;
}
if(left.height !== right.height) {
return left.height - right.height;
}
return String(left.value).localeCompare(String(right.value));
});
};
const getResolvedTextModelSelection = (requestedModelId = selectedTextModel) => {
const availableModels = getAvailableTextModels();
const requestedConfigId = getTextModelConfigId(requestedModelId);
const configuredDefaultId = getTextModelConfigId(getConfiguredTextModel());
const resolvedModelId = [requestedConfigId, configuredDefaultId, availableModels[0], requestedModelId]
.find(modelId => modelId && availableModels.includes(modelId))
|| "";
const modelConfig = getTextModelConfig(resolvedModelId);
const providerProfiles = getProviderProfiles();
const providerId = modelConfig?.providerId ?? Object.keys(providerProfiles)[0] ?? "";
const providerProfile = providerProfiles[providerId] ?? null;
return {
modelId: resolvedModelId,
modelConfig,
providerId,
providerProfile,
requestConfig: {
textModelId: resolvedModelId,
},
};
};
const getResolvedImageModelSelection = (requestedModelId = selectedImageModel) => {
const availableModels = getAvailableImageModels();
const requestedConfigId = getImageModelConfigId(requestedModelId);
const configuredDefaultId = getImageModelConfigId(getConfiguredImageModel());
const resolvedModelId = [requestedConfigId, configuredDefaultId, availableModels[0], requestedModelId]
.find(modelId => modelId && availableModels.includes(modelId))
|| "";
const modelConfig = getImageModelConfig(resolvedModelId);
const providerProfiles = getProviderProfiles();
const providerId = modelConfig?.providerId ?? Object.keys(providerProfiles)[0] ?? "";
const providerProfile = providerProfiles[providerId] ?? null;
return {
modelId: resolvedModelId,
modelConfig,
providerId,
providerProfile,
requestConfig: {
imageModelId: resolvedModelId,
},
};
};
const getTextModelValidationMessage = (modelId, {requireMultimodal = false} = {}) => {
if(getAvailableTextModels().length === 0) {
return getMissingModelConfigurationMessage("text");
}
const textSelection = getResolvedTextModelSelection(modelId);
if(!textSelection.modelConfig) {
return `The selected text model (${modelId || "unknown"}) isn't configured in Excalidraw AI settings.`;
}
if(!textSelection.providerProfile) {
return `The provider profile (${textSelection.providerId || "unknown"}) for text model ${textSelection.modelId} is missing from Excalidraw AI settings.`;
}
if(!textSelection.providerProfile.hasApiKey) {
return `The selected provider profile (${textSelection.providerId}) doesn't have an API key configured.`;
}
if(requireMultimodal && textSelection.modelConfig.multimodalSupport === false) {
return `The selected text model (${textSelection.modelId}) is set to text-only. Choose a multimodal model for image analysis tasks.`;
}
return "";
};
const getImageModelValidationMessage = (modelId, {requirePromptTransformSupport = false, requireMaskEditSupport = false} = {}) => {
if(getAvailableImageModels().length === 0) {
return getMissingModelConfigurationMessage("image");
}
const imageSelection = getResolvedImageModelSelection(modelId);
if(!imageSelection.modelConfig) {
return getMissingModelConfigurationMessage("image");
}
if(!imageSelection.providerProfile) {
return `The provider profile (${imageSelection.providerId || "unknown"}) for image model ${imageSelection.modelId} is missing from Excalidraw AI settings.`;
}
if(!imageSelection.providerProfile.hasApiKey) {
return `The selected provider profile (${imageSelection.providerId}) doesn't have an API key configured.`;
}
if(requirePromptTransformSupport && imageSelection.modelConfig.supportsPromptImageTransforms === false) {
return `The selected image model (${imageSelection.modelId}) doesn't support prompt-based transforms in Excalidraw AI settings.`;
}
if(requireMaskEditSupport && imageSelection.modelConfig.supportsMaskImageEdits === false) {
return `The selected image model (${imageSelection.modelId}) doesn't support mask-based edits in Excalidraw AI settings.`;
}
return "";
};
const getImageRequestErrorMessage = (result, modelId) => {
const baseMessage = result?.json?.error?.message ?? "The image request failed.";
const errorContext = result?.json?.error;
const imageSelection = getResolvedImageModelSelection(modelId);
const contextParts = [];
if(errorContext?.provider) {
contextParts.push(`provider=${errorContext.provider}`);
}
if(errorContext?.status) {
contextParts.push(`status=${errorContext.status}`);
}
if(errorContext?.endpoint) {
contextParts.push(`endpoint=${errorContext.endpoint}`);
}
if(errorContext?.imageRequest?.model) {
contextParts.push(`model=${errorContext.imageRequest.model}`);
}
if(errorContext?.imageRequest?.size) {
contextParts.push(`size=${errorContext.imageRequest.size}`);
}
if(errorContext?.imageRequest?.mode) {
contextParts.push(`mode=${errorContext.imageRequest.mode}`);
}
const contextText = contextParts.length > 0 ? ` (${contextParts.join(", ")})` : "";
return `${baseMessage}${contextText}`;
};
const getTaskValidationMessage = ({
usesTextModel,
requiresMultimodalText,
isImageGenRequest,
isImageEditRequest,
requiresPromptTransformSupport,
requiresMaskEditSupport,
activeTextSelection,
activeImageSelection,
}) => {
if(usesTextModel) {
const textValidationMessage = getTextModelValidationMessage(activeTextSelection.modelId, {
requireMultimodal: requiresMultimodalText,
});
if(textValidationMessage) {
return textValidationMessage;
}
}
if(isImageGenRequest || isImageEditRequest) {
return getImageModelValidationMessage(activeImageSelection.modelId, {
requirePromptTransformSupport: requiresPromptTransformSupport,
requireMaskEditSupport: requiresMaskEditSupport,
});
}
return "";
};
const getActiveTextModel = () => {
return getResolvedTextModelSelection(selectedTextModel).modelId;
};
const getActiveImageModel = () => {
return getResolvedImageModelSelection(selectedImageModel).modelId;
};
const activeImageModelSupportsMaskEdits = () => {
const modelConfig = getResolvedImageModelSelection(selectedImageModel).modelConfig;
return Boolean(modelConfig) && modelConfig.supportsMaskImageEdits !== false;
};
const canUseMaskEdit = () => (
isImageEditTask()
&& getTaskMaskMode() !== TASK_MASK_MODES.DISABLED
&& activeImageModelSupportsMaskEdits()
);
const shouldUseMaskEdit = () => {
switch(getTaskMaskMode()) {
case TASK_MASK_MODES.REQUIRED:
return canUseMaskEdit();
case TASK_MASK_MODES.OPTIONAL:
return canUseMaskEdit() && prefersMaskEdit;
default:
return false;
}
};
const shouldGenerateMaskPreview = () => (
shouldUseMaskEdit()
);
const hasAvailableTextModels = () => getAvailableTextModels().length > 0;
const hasAvailableImageModels = () => getAvailableImageModels().length > 0;
const parseImageSize = (size) => {
const [width, height] = (size ?? "1024x1024").split("x").map(value => parseInt(value, 10));
if(Number.isNaN(width) || Number.isNaN(height) || width <= 0 || height <= 0) {
return {width: 1024, height: 1024};
}
return {width, height};
};
const getEditTargetBoundingBox = (bb, size) => {
const {width: targetWidth, height: targetHeight} = parseImageSize(size);
const targetRatio = targetWidth/targetHeight;
const sourceRatio = bb.width/bb.height;
let width = bb.width;
let height = bb.height;
let topX = bb.topX;
let topY = bb.topY;
if(sourceRatio > targetRatio) {
height = width/targetRatio;
topY = bb.topY - (height - bb.height)/2;
} else if(sourceRatio < targetRatio) {
width = height*targetRatio;
topX = bb.topX - (width - bb.width)/2;
}
return {topX, topY, width, height, targetWidth, targetHeight};
};
const setTextAndImageModels = () => {
const nextTextModel = getActiveTextModel();
if(selectedTextModel !== nextTextModel) {
dirty = true;
}
textModel = nextTextModel;
selectedTextModel = textModel;
const nextImageModel = getActiveImageModel();
if(selectedImageModel !== nextImageModel) {
dirty = true;
}
imageModel = nextImageModel;
selectedImageModel = imageModel;
validSizes = imageModel ? getValidSizesForModel(imageModel) : [];
if(imageModel && !validSizes.includes(imageSize)) {
imageSize = validSizes[0] ?? "1024x1024";
dirty = true;
}
}
setTextAndImageModels();
// --------------------------------------
// Generate Image Blob From Selected Excalidraw Elements
// --------------------------------------
const calculateImageScale = (elements) => {
const bb = ea.getBoundingBox(elements);
const size = (bb.width*bb.height);
const minRatio = Math.sqrt(360000/size);
const maxRatio = Math.sqrt(size/16000000);
return minRatio > 1
? minRatio
: (
maxRatio > 1
? 1/maxRatio
: 1
);
}
const createMask = async (dataURL) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
// If opaque (alpha > 0), make it transparent
if (data[i + 3] > 0) {
data[i + 3] = 0; // Set alpha to 0 (transparent)
} else if (data[i + 3] === 0) {
// If fully transparent, make it red
data[i] = 255; // Red
data[i + 1] = 0; // Green
data[i + 2] = 0; // Blue
data[i + 3] = 255; // make it opaque
}
}
ctx.putImageData(imageData, 0, 0);
const maskDataURL = canvas.toDataURL();
resolve(maskDataURL);
};
img.onerror = error => {
reject(error);
};
img.src = dataURL;
});
}
// For image edits, the selected content is padded to the requested output aspect ratio
// so the exported image and mask match the requested model size.
const generateCanvasDataURL = async (view, targetImageEdit=false) => {
let PADDING = 5;
await view.forceSave(true); //to ensure recently embedded PNG and other images are saved to file
const viewElements = ea.getViewSelectedElements();
if(viewElements.length === 0) {
return {imageDataURL: null, maskDataURL: null} ;
}
ea.copyViewElementsToEAforEditing(viewElements, true); //copying the images objects over to EA for PNG generation
let maskDataURL;
const loader = ea.getEmbeddedFilesLoader(false);
let scale = calculateImageScale(ea.getElements());
const bb = ea.getBoundingBox(viewElements);
if(ea.getElements()
.filter(el=>el.type==="image")
.some(el=>Math.round(el.width) === Math.round(bb.width) && Math.round(el.height) === Math.round(bb.height))
) { PADDING = 0; }
let exportSettings = {withBackground: true, withTheme: true};
if(targetImageEdit) {
PADDING = 0;
const strokeColor = ea.style.strokeColor;
const backgroundColor = ea.style.backgroundColor;
ea.style.backgroundColor = "transparent";
ea.style.strokeColor = "transparent";
const targetBounds = getEditTargetBoundingBox(bb, imageSize);
const rectID = ea.addRect(targetBounds.topX, targetBounds.topY, targetBounds.width, targetBounds.height);
const rect = ea.getElement(rectID);
ea.style.strokeColor = strokeColor;
ea.style.backgroundColor = backgroundColor;
ea.getElements().filter(el=>el.type === "image").forEach(el=>{el.isDeleted = true});
scale = targetBounds.targetWidth/rect.width;
exportSettings = {withBackground: false, withTheme: true};
maskDataURL= await ea.createPNGBase64(
null, scale, exportSettings, loader, "light", PADDING
);
maskDataURL = await createMask(maskDataURL)
ea.getElements().filter(el=>el.type === "image").forEach(el=>{el.isDeleted = false});
ea.getElements().filter(el=>el.type !== "image" && el.id !== rectID).forEach(el=>{el.isDeleted = true});
}
const imageDataURL = await ea.createPNGBase64(
null, scale, exportSettings, loader, "light", PADDING
);
ea.clear();
return {imageDataURL, maskDataURL};
}
({imageDataURL, maskDataURL} = await generateCanvasDataURL(ea.targetView, shouldGenerateMaskPreview()));
// --------------------------------------
// Support functions - embeddable spinner and error
// --------------------------------------
const spinner = await ea.convertStringToDataURL(`
${message}
` : ""; const errorDataURL = await ea.convertStringToDataURL(`