Repository: terrastruct/d2-obsidian Branch: master Commit: 16a7adfed2ae Files: 22 Total size: 43.7 KB Directory structure: gitextract_lcbfl00g/ ├── .eslintignore ├── .eslintrc ├── .github/ │ └── workflows/ │ ├── ci.yml │ └── daily.yml ├── .gitignore ├── .gitmodules ├── .npmrc ├── LICENSE.txt ├── Makefile ├── README.md ├── esbuild.config.mjs ├── make.sh ├── manifest.json ├── package.json ├── src/ │ ├── constants.ts │ ├── main.ts │ ├── processor.ts │ └── settings.ts ├── styles.css ├── tsconfig.json ├── version-bump.mjs └── versions.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ npm node_modules build ================================================ FILE: .eslintrc ================================================ { "root": true, "parser": "@typescript-eslint/parser", "env": { "node": true }, "plugins": [ "@typescript-eslint" ], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ], "parserOptions": { "sourceType": "module" }, "rules": { "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": ["error", { "args": "none" }], "@typescript-eslint/ban-ts-comment": "off", "no-prototype-builtins": "off", "@typescript-eslint/no-empty-function": "off" } } ================================================ FILE: .github/workflows/ci.yml ================================================ name: ci on: [push, pull_request] concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: true jobs: ci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/cache@v2 with: path: ~/.cache/yarn/v6 key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }} restore-keys: | ${{ runner.os }}-yarn- - run: COLOR=1 ./make.sh env: GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }} DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} nofixups: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: git submodule update --init - run: COLOR=1 ./ci/sub/bin/nofixups.sh env: GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }} DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} signed: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: git submodule update --init - run: COLOR=1 ./ci/sub/bin/ensure_signed.sh env: GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }} DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} ================================================ FILE: .github/workflows/daily.yml ================================================ name: daily on: workflow_dispatch: schedule: - cron: '42 0 * * *' # daily at 00:42 concurrency: group: ${{ github.workflow }} cancel-in-progress: true jobs: ci: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/cache@v2 with: path: ~/.cache/yarn/v6 key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }} restore-keys: | ${{ runner.os }}-yarn- - run: COLOR=1 CI_FORCE=1 ./make.sh env: GITHUB_TOKEN: ${{ secrets._GITHUB_TOKEN }} DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }} ================================================ FILE: .gitignore ================================================ # vscode .vscode # Intellij *.iml .idea # npm node_modules # Don't include the compiled main.js file in the repo. # They should be uploaded to GitHub releases instead. main.js # Exclude sourcemaps *.map # obsidian data.json # Exclude macOS Finder (System Explorer) View States .DS_Store .make-log .changed-files .make-log.txt ================================================ FILE: .gitmodules ================================================ [submodule "ci/sub"] path = ci/sub url = https://github.com/terrastruct/ci.git ================================================ FILE: .npmrc ================================================ tag-version-prefix="" ================================================ FILE: LICENSE.txt ================================================ Copyright 2022 Terrastruct Inc. Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ================================================ FILE: Makefile ================================================ .POSIX: .PHONY: all all: fmt build .PHONY: fmt fmt: node_modules prefix "$@" ./ci/sub/bin/fmt.sh .PHONY: build build: node_modules prefix "$@" yarn run build .PHONY: node_modules node_modules: prefix "$@" yarn $${CI:+--immutable} $${CI:+--immutable-cache} ================================================ FILE: README.md ================================================
D2

D2 Obsidian Plugin

D2 is a modern diagram scripting language thats turns text to diagrams. The source code for D2, as well as install instructions and all other information, can be found at [https://github.com/terrastruct/d2](https://github.com/terrastruct/d2). [![ci](https://github.com/terrastruct/d2-obsidian/actions/workflows/ci.yml/badge.svg)](https://github.com/terrastruct/d2-obsidian/actions/workflows/ci.yml) [![ci](https://github.com/terrastruct/d2-obsidian/actions/workflows/daily.yml/badge.svg)](https://github.com/terrastruct/d2-obsidian/actions/workflows/daily.yml) [![license](https://img.shields.io/github/license/terrastruct/d2-obsidian?color=9cf)](./LICENSE.txt) [![discord](https://img.shields.io/discord/1039184639652265985?label=discord)](https://discord.gg/NF6X8K4eDq) https://user-images.githubusercontent.com/6413609/205414613-5b2559f1-0645-4432-bb7b-d980de527201.mp4
## Installation Settings > Community plugins > Browse > Search for "D2" **important**: [D2](https://github.com/terrastruct/d2) must be installed for this plugin to work currently. We will later on introduce a remote API as an option, but currently this plugin calls your local installation of D2. ## Configurations - `Layout engine`: D2 supports multiple layout engines, which can significantly affect the look of your diagram. - `Theme ID`: For a list of available themes, visit the [D2 repository](https://github.com/terrastruct/d2/tree/master/d2themes). - `Pad`: Number of pixels padded around the rendered diagram. - `Sketch mode`: Render the diagram to look like it was sketched by hand. - `Container height`: Diagram max render height in pixels (Requires d2 v0.2.2 and up). - `Debounce`: Number of milliseconds to wait after a change has made to refresh the diagram (min 100). - `Path`: Customize the path to `d2` (optional). We check common places D2 might be installed, along with your system path. However, your OS or setup may require you to input your path to `d2` manually. To do so, type `where d2` into your terminal, and copy everything in the path up until `/d2` and paste it into this configuration. ## Usage Create a fenced codeblock with `d2` as the language tag: ```d2 Hello -> World ``` ## How to run this plugin locally - Clone this repo. - Run `yarn` to install dependencies. - Run `yarn run dev` to start compilation in watch mode. - Copy over `main.js`, `styles.css`, `manifest.json` to your vault `[VaultFolder]/.obsidian/plugins/d2/`. ## FAQ - I have D2 installed but I'm running into `D2 Compilation Error: d2: command not found` - The Obsidian plugin may not be able to locate your D2 installation. Get the path to the D2 installation by executing `where d2` in the command line, then copy that path minus the executable itself into the `Path` plugin setting (so if the path is `/usr/local/bin/d2`, then you want to copy `/usr/local/bin`). - I have a question or need help. - The best way to get help is to ask on [D2 Discord](https://discord.gg/NF6X8K4eDq). - I'd like to contribute. - We welcome contributions! Please pick one from an existing Issue, or open one if none exists. - I have a feature request, proposal, or bug report. - Please open up a Github Issue. If it's D2-specific, please open it in the [D2 repository](https://github.com/terrastruct/d2). If it's specific to this plugin, please open it here. - I have a private inquiry. - Please reach out at [hi@d2lang.com](hi@d2lang.com). ================================================ FILE: esbuild.config.mjs ================================================ import esbuild from "esbuild"; import process from "process"; import builtins from "builtin-modules"; const banner = `/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin: https://github.com/terrastruct/d2-obsidian */`; const prod = process.argv[2] === "production"; esbuild .build({ banner: { js: banner, }, entryPoints: ["./src/main.ts"], bundle: true, external: [ "obsidian", "electron", "@codemirror/autocomplete", "@codemirror/collab", "@codemirror/commands", "@codemirror/language", "@codemirror/lint", "@codemirror/search", "@codemirror/state", "@codemirror/view", "@lezer/common", "@lezer/highlight", "@lezer/lr", ...builtins, ], format: "cjs", watch: !prod, target: "es2018", logLevel: "info", sourcemap: prod ? false : "inline", treeShaking: true, outfile: "main.js", }) .catch(() => process.exit(1)); ================================================ FILE: make.sh ================================================ #!/bin/sh set -eu if [ ! -e "$(dirname "$0")/ci/sub/.git" ]; then set -x git submodule update --init set +x fi . "$(dirname "$0")/ci/sub/lib.sh" PATH="$(cd -- "$(dirname "$0")" && pwd)/ci/sub/bin:$PATH" cd "$(dirname "$0")" _make "$@" ================================================ FILE: manifest.json ================================================ { "id": "d2-obsidian", "name": "D2", "version": "1.1.4", "minAppVersion": "0.15.0", "description": "The official D2 plugin for Obsidian. D2 is a modern diagram scripting language that turns text to diagrams.", "author": "Terrastruct", "authorUrl": "https://d2lang.com", "isDesktopOnly": true } ================================================ FILE: package.json ================================================ { "name": "d2-obsidian", "version": "1.1.4", "description": "This is the official D2 plugin for Obsidian.", "main": "main.js", "scripts": { "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json" }, "keywords": [], "author": "", "license": "MIT", "devDependencies": { "@types/lodash.debounce": "^4.0.7", "@types/node": "^16.11.6", "@typescript-eslint/eslint-plugin": "5.29.0", "@typescript-eslint/parser": "5.29.0", "builtin-modules": "3.3.0", "esbuild": "0.14.47", "obsidian": "latest", "tslib": "2.4.0", "typescript": "4.7.4" }, "dependencies": { "child_process": "^1.0.2", "lodash.debounce": "^4.0.8" } } ================================================ FILE: src/constants.ts ================================================ const LAYOUT_ENGINES = { DAGRE: { value: "dagre", label: "dagre", }, ELK: { value: "elk", label: "ELK", }, TALA: { value: "tala", label: "TALA", }, }; const RecompileIcon = ` `; export { LAYOUT_ENGINES, RecompileIcon }; ================================================ FILE: src/main.ts ================================================ import { Plugin, addIcon } from "obsidian"; import { D2PluginSettings, D2SettingsTab, DEFAULT_SETTINGS } from "./settings"; import { D2Processor } from "./processor"; import { RecompileIcon } from "./constants"; export default class D2Plugin extends Plugin { settings: D2PluginSettings; processor: D2Processor; async onload() { addIcon("recompile", RecompileIcon); await this.loadSettings(); this.addSettingTab(new D2SettingsTab(this.app, this)); const processor = new D2Processor(this); this.registerMarkdownCodeBlockProcessor("d2", processor.attemptExport); this.processor = processor; } onunload() { const abortControllers = this.processor.abortControllerMap.values(); Array.from(abortControllers).forEach((controller) => { controller.abort(); }); } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } } ================================================ FILE: src/processor.ts ================================================ import { MarkdownPostProcessorContext, ButtonComponent } from "obsidian"; import { exec, execSync } from "child_process"; import { delimiter } from "path"; import debounce from "lodash.debounce"; import os from "os"; import D2Plugin from "./main"; export class D2Processor { plugin: D2Plugin; debouncedMap: Map< string, ( source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext, signal?: AbortSignal ) => Promise >; abortControllerMap: Map; prevImage: string; abortController: AbortController; constructor(plugin: D2Plugin) { this.plugin = plugin; this.debouncedMap = new Map(); this.abortControllerMap = new Map(); } attemptExport = async ( source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext ) => { el.createEl("h6", { text: "Generating D2 diagram...", cls: "D2__Loading", }); // we need to generate a debounce per split page, and ctx.containerEl is the only element we have access to that's page specific // however, it is not publically available in MarkdownPostProcessorContext, so we hack its access by casting it to an 'any' type const pageContainer = (ctx as any).containerEl; let pageID = pageContainer.dataset.pageID; if (!pageID) { pageID = Math.floor(Math.random() * Date.now()).toString(); pageContainer.dataset.pageID = pageID; } let debouncedFunc = this.debouncedMap.get(pageID); if (!debouncedFunc) { // No need to debounce initial render await this.export(source, el, ctx); debouncedFunc = debounce(this.export, this.plugin.settings.debounce, { leading: true, }); this.debouncedMap.set(pageID, debouncedFunc); return; } this.abortControllerMap.get(pageID)?.abort(); const newAbortController = new AbortController(); this.abortControllerMap.set(pageID, newAbortController); await debouncedFunc(source, el, ctx, newAbortController.signal); }; isValidUrl = (urlString: string) => { let url; try { url = new URL(urlString); } catch (e) { return false; } return url.protocol === "http:" || url.protocol === "https:"; }; formatLinks = (svgEl: HTMLElement) => { // Add attributes to tags to make them Obsidian compatible : const links = svgEl.querySelectorAll("a"); links.forEach((link: HTMLElement) => { const href = link.getAttribute("href") ?? ""; // Check for internal link if (!this.isValidUrl(href)) { link.classList.add("internal-link"); link.setAttribute("data-href", href); link.setAttribute("target", "_blank"); link.setAttribute("rel", "noopener"); } }); }; sanitizeSVGIDs = (svgEl: HTMLElement, docID: string): string => { // append docId to || || id's so that they're unique across different panels & edit/view mode const overrides = svgEl.querySelectorAll("marker, mask, filter"); const overrideIDs: string[] = []; overrides.forEach((override) => { const id = override.getAttribute("id"); if (id) { overrideIDs.push(id); } }); return overrideIDs.reduce((svgHTML, overrideID) => { return svgHTML.replaceAll(overrideID, [overrideID, docID].join("-")); }, svgEl.outerHTML); }; insertImage(image: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) { const parser = new DOMParser(); const svg = parser.parseFromString(image, "image/svg+xml"); const containerEl = el.createDiv(); const svgEl = svg.documentElement; svgEl.style.maxHeight = `${this.plugin.settings.containerHeight}px`; svgEl.style.maxWidth = "100%"; svgEl.style.height = "fit-content"; svgEl.style.width = "fit-content"; this.formatLinks(svgEl); containerEl.innerHTML = this.sanitizeSVGIDs(svgEl, ctx.docId); } export = async ( source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext, signal?: AbortSignal ) => { try { const image = await this.generatePreview(source, signal); if (image) { el.empty(); this.prevImage = image; this.insertImage(image, el, ctx); const button = new ButtonComponent(el) .setClass("Preview__Recompile") .setIcon("recompile") .onClick((e) => { e.preventDefault(); e.stopPropagation(); el.empty(); this.attemptExport(source, el, ctx); }); button.buttonEl.createEl("span", { text: "Recompile", }); } } catch (err) { el.empty(); const errorEl = el.createEl("pre", { cls: "markdown-rendered pre Preview__Error", }); errorEl.createEl("code", { text: "D2 Compilation Error:", cls: "Preview__Error--Title", }); errorEl.createEl("code", { text: err.message, }); if (this.prevImage) { this.insertImage(this.prevImage, el, ctx); } } finally { const pageContainer = (ctx as any).containerEl; this.abortControllerMap.delete(pageContainer.dataset.id); } }; async generatePreview(source: string, signal?: AbortSignal): Promise { const pathArray = [process.env.PATH, "/opt/homebrew/bin", "/usr/local/bin"]; // platform will be win32 even on 64 bit windows if (os.platform() === "win32") { pathArray.push(`C:\Program Files\D2`); } else { pathArray.push(`${process.env.HOME}/.local/bin`); } let GOPATH = ""; try { GOPATH = execSync("go env GOPATH", { env: { ...process.env, PATH: pathArray.join(delimiter), }, }).toString(); } catch (error) { // ignore if go is not installed } if (GOPATH) { pathArray.push(`${GOPATH.replace("\n", "")}/bin`); } if (this.plugin.settings.d2Path) { pathArray.push(this.plugin.settings.d2Path); } const options: any = { ...process.env, env: { PATH: pathArray.join(delimiter), }, signal, }; if (this.plugin.settings.apiToken) { options.env.TSTRUCT_TOKEN = this.plugin.settings.apiToken; } let args = [ `d2`, "-", `--theme=${this.plugin.settings.theme}`, `--layout=${this.plugin.settings.layoutEngine}`, `--pad=${this.plugin.settings.pad}`, `--sketch=${this.plugin.settings.sketch}`, "--bundle=false", "--scale=1", ]; const cmd = args.join(" "); const child = exec(cmd, options); child.stdin?.write(source); child.stdin?.end(); let stdout: any; let stderr: any; if (child.stdout) { child.stdout.on("data", (data) => { if (stdout === undefined) { stdout = data; } else { stdout += data; } }); } if (child.stderr) { child.stderr.on("data", (data) => { if (stderr === undefined) { stderr = data; } else { stderr += data; } }); } return new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code: number) => { if (code === 0) { resolve(stdout); return; } else if (stderr) { console.error(stderr); reject(new Error(stderr)); } else if (stdout) { console.error(stdout); reject(new Error(stdout)); } }); }); } } ================================================ FILE: src/settings.ts ================================================ import { Notice, App, PluginSettingTab, Setting } from "obsidian"; import D2Plugin from "./main"; import { LAYOUT_ENGINES } from "./constants"; export interface D2PluginSettings { layoutEngine: string; apiToken: string; debounce: number; theme: number; d2Path: string; pad: number; sketch: boolean; containerHeight: number; } export const DEFAULT_SETTINGS: D2PluginSettings = { layoutEngine: "dagre", debounce: 500, theme: 0, apiToken: "", d2Path: "", pad: 100, sketch: false, containerHeight: 800, }; export class D2SettingsTab extends PluginSettingTab { plugin: D2Plugin; talaSettings: HTMLDivElement; constructor(app: App, plugin: D2Plugin) { super(app, plugin); this.plugin = plugin; } addTALASettings() { const talaSettings = this.containerEl.createEl("div"); talaSettings.createEl("h3", { text: "TALA settings", }); new Setting(talaSettings) .setName("API token") .setDesc( 'To use TALA, copy your API token here or in ~/.local/state/tstruct/auth.json under the field "api_token"' ) .addText((text) => text .setPlaceholder("tstruct_...") .setValue(this.plugin.settings.apiToken) .setDisabled(this.plugin.settings.layoutEngine !== LAYOUT_ENGINES.TALA.value) .onChange(async (value) => { if (value && !value.startsWith("tstruct_")) { new Notice("Invalid API token"); } else { this.plugin.settings.apiToken = value; await this.plugin.saveSettings(); } }) ); this.talaSettings = talaSettings; } display(): void { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h1", { text: "D2 plugin settings" }); new Setting(containerEl) .setName("Layout engine") .setDesc( 'Available layout engines include "dagre", "ELK", and "TALA" (TALA must be installed separately from D2)' ) .addDropdown((dropdown) => { dropdown .addOption(LAYOUT_ENGINES.DAGRE.value, LAYOUT_ENGINES.DAGRE.label) .addOption(LAYOUT_ENGINES.ELK.value, LAYOUT_ENGINES.ELK.label) .addOption(LAYOUT_ENGINES.TALA.value, LAYOUT_ENGINES.TALA.label) .setValue(this.plugin.settings.layoutEngine) .onChange(async (value) => { this.plugin.settings.layoutEngine = value; await this.plugin.saveSettings(); if (value === LAYOUT_ENGINES.TALA.value) { this.addTALASettings(); } else { this.talaSettings?.remove(); } }); }); new Setting(containerEl) .setName("Theme ID") .setDesc( "Available themes are located at https://github.com/terrastruct/d2/tree/master/d2themes" ) .addText((text) => text .setPlaceholder("Enter a theme ID") .setValue(String(this.plugin.settings.theme)) .onChange(async (value) => { if (!isNaN(Number(value)) || value === "") { this.plugin.settings.theme = Number(value || DEFAULT_SETTINGS.theme); await this.plugin.saveSettings(); } else { new Notice("Please specify a valid number"); } }) ); new Setting(containerEl) .setName("Pad") .setDesc("Pixels padded around the rendered diagram") .addText((text) => text .setPlaceholder(String(DEFAULT_SETTINGS.pad)) .setValue(String(this.plugin.settings.pad)) .onChange(async (value) => { if (isNaN(Number(value))) { new Notice("Please specify a valid number"); this.plugin.settings.pad = Number(DEFAULT_SETTINGS.pad); } else if (value === "") { this.plugin.settings.pad = Number(DEFAULT_SETTINGS.pad); } else { this.plugin.settings.pad = Number(value); } await this.plugin.saveSettings(); }) ); new Setting(containerEl) .setName("Sketch mode") .setDesc("Render the diagram to look like it was sketched by hand") .addToggle((toggle) => toggle.setValue(this.plugin.settings.sketch).onChange(async (value) => { this.plugin.settings.sketch = value; await this.plugin.saveSettings(); }) ); new Setting(containerEl) .setName("Container height") .setDesc("Diagram max render height in pixels (Requires d2 v0.2.2 and up)") .addText((text) => text .setPlaceholder(String(DEFAULT_SETTINGS.containerHeight)) .setValue(String(this.plugin.settings.containerHeight)) .onChange(async (value) => { if (isNaN(Number(value))) { new Notice("Please specify a valid number"); this.plugin.settings.containerHeight = Number( DEFAULT_SETTINGS.containerHeight ); } else if (value === "") { this.plugin.settings.containerHeight = Number( DEFAULT_SETTINGS.containerHeight ); } else { this.plugin.settings.containerHeight = Number(value); } await this.plugin.saveSettings(); }) ); new Setting(containerEl) .setName("Debounce") .setDesc("How often should the diagram refresh in milliseconds (min 100)") .addText((text) => text .setPlaceholder(String(DEFAULT_SETTINGS.debounce)) .setValue(String(this.plugin.settings.debounce)) .onChange(async (value) => { if (isNaN(Number(value))) { new Notice("Please specify a valid number"); this.plugin.settings.debounce = Number(DEFAULT_SETTINGS.debounce); } else if (value === "") { this.plugin.settings.debounce = Number(DEFAULT_SETTINGS.debounce); } else if (Number(value) < 100) { new Notice("The value must be greater than 100"); this.plugin.settings.debounce = Number(DEFAULT_SETTINGS.debounce); } else { this.plugin.settings.debounce = Number(value); } await this.plugin.saveSettings(); }) ); new Setting(containerEl) .setName("Path (optional)") .setDesc( "Customize the local path to the directory `d2` is installed in (ex. if d2 is located at `/usr/local/bin/d2`, then the path is `/usr/local/bin`). This is only necessary if `d2` is not found automatically by the plugin (but is installed)." ) .addText((text) => { text .setPlaceholder("/usr/local/Cellar") .setValue(this.plugin.settings.d2Path) .onChange(async (value) => { this.plugin.settings.d2Path = value; await this.plugin.saveSettings(); }); }); if (this.plugin.settings.layoutEngine === LAYOUT_ENGINES.TALA.value) { this.addTALASettings(); } } } ================================================ FILE: styles.css ================================================ .D2__Loading { font-style: italic; } .Preview__Error--Title { color: #be0b41 !important; } .Preview__Error { display: flex; flex-direction: column; white-space: pre; white-space: pre-wrap; } .Preview__Recompile { position: absolute; top: 4px; left: 4px; height: 24px; padding: 6px; background-color: white !important; color: #2e3346; display: flex; gap: 4px; box-shadow: none !important; border: 1px solid #dee1eb; filter: drop-shadow(1px 1px 4px rgba(31, 36, 58, 0.08)); } .Preview__Recompile:hover { filter: drop-shadow(2px 2px 16px rgba(31, 36, 58, 0.12)); cursor: pointer; } .Preview__Recompile > .svg-icon { height: 12px !important; width: 12px !important; } .block-language-d2 { position: relative; } @media print { .Preview__Recompile { display: none; } } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "inlineSourceMap": true, "inlineSources": true, "module": "ESNext", "target": "ES6", "allowJs": true, "noImplicitAny": true, "moduleResolution": "node", "importHelpers": true, "isolatedModules": true, "allowSyntheticDefaultImports": true, "strictNullChecks": true, "lib": [ "ES2021", "DOM", "ES5", "ES6", "ES7", ] }, "include": [ "**/*.ts" ] } ================================================ FILE: version-bump.mjs ================================================ import { readFileSync, writeFileSync } from "fs"; const targetVersion = process.env.npm_package_version; // read minAppVersion from manifest.json and bump version to target version let manifest = JSON.parse(readFileSync("manifest.json", "utf8")); const { minAppVersion } = manifest; manifest.version = targetVersion; writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t")); // update versions.json with target version and minAppVersion from manifest.json let versions = JSON.parse(readFileSync("versions.json", "utf8")); versions[targetVersion] = minAppVersion; writeFileSync("versions.json", JSON.stringify(versions, null, "\t")); ================================================ FILE: versions.json ================================================ { "1.1.4": "0.15.0", "1.1.3": "0.15.0", "1.1.2": "0.15.0", "1.1.1": "0.15.0", "1.1.0": "0.15.0", "1.0.1": "0.15.0", "1.0.0": "0.15.0" }