mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b09fa3b1ed | ||
|
|
6001ef3f1f | ||
|
|
40e204c2d9 | ||
|
|
e6c07bb615 | ||
|
|
7aa3f044cf | ||
|
|
b901bfbcac | ||
|
|
642ba63a9f | ||
|
|
c0ab59c3aa | ||
|
|
fd62c158db | ||
|
|
cabe90927d | ||
|
|
3220889563 | ||
|
|
907e2267d5 | ||
|
|
730705efe6 | ||
|
|
f8338b6d46 | ||
|
|
4c1ffcb104 | ||
|
|
52c54a999e | ||
|
|
1cedf7a7a9 | ||
|
|
341edde683 | ||
|
|
d64ae78795 | ||
|
|
b45457437f | ||
|
|
ee66e134d3 | ||
|
|
2fadcd8533 | ||
|
|
693e990aef | ||
|
|
dbb75479f3 | ||
|
|
b40f72ba13 | ||
|
|
30d48562c4 | ||
|
|
8b2080d3b9 | ||
|
|
fce2bc11ff | ||
|
|
906db1b80a | ||
|
|
4a11d9bef6 | ||
|
|
60c1ade6b5 | ||
|
|
3f6bfd7c4f | ||
|
|
9b730af586 | ||
|
|
88c02b6017 | ||
|
|
c7f5de2ee1 | ||
|
|
99edf67e98 | ||
|
|
d609d0af29 | ||
|
|
878fb5bcf7 | ||
|
|
c542d7661f | ||
|
|
97f05e1629 | ||
|
|
31d5d86af0 | ||
|
|
95dc44e56b | ||
|
|
27f2765e7a | ||
|
|
4e5399283c |
No files matched your search
@@ -77,6 +77,15 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
- Use arrow notation for navigation: **Settings → Community plugins**.
|
||||
- Keep in-app strings short, consistent, and free of jargon.
|
||||
|
||||
## DOM Styling And Visibility
|
||||
|
||||
- Prefer Obsidian's established classes such as `mod-warning` before adding plugin-specific CSS. Consult the Obsidian CSS variables and component conventions when styling settings or dialogs.
|
||||
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Always use Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers. When an element must deliberately belong to a specific document that Obsidian's helpers cannot target, such as a canvas used for drawing or an element inside an iframe, use the `deliberateCreateElement` function injected by `rollup.config.mjs` and declare it in the consuming module, for example `declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;`.
|
||||
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
|
||||
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
|
||||
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
|
||||
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
|
||||
|
||||
## Performance
|
||||
|
||||
- Keep startup light. Defer heavy work until needed.
|
||||
@@ -669,4 +678,4 @@ When you are asked to modify this repository:
|
||||
|
||||
- All types and helpers for Excalidraw element `customData` (extensible metadata on elements, e.g., for LaTeX, PDF, image, or plugin-specific keys) are centralized in `src/utils/elementCustomDataUtils.ts`.
|
||||
- If you need to add a new `customData` key, type, or helper, always add it to this file and import from here in all consumers. This avoids type duplication and ensures discoverability for future maintainers and agents.
|
||||
- See `ExcalidrawCustomData`, `ExcalidrawCustomDataPatch`, `ExcalidrawPDFCustomData`, `ExcalidrawLatexCustomData`, and `addAppendUpdateCustomData` in that file for canonical patterns.
|
||||
- See `ExcalidrawCustomData`, `ExcalidrawCustomDataPatch`, `ExcalidrawPDFCustomData`, `ExcalidrawLatexCustomData`, and `addAppendUpdateCustomData` in that file for canonical patterns.
|
||||
@@ -280,7 +280,7 @@ For more details, see this [video](https://youtu.be/yZQoJg2RCKI)
|
||||
- If the `group=` prefix is found, Excalidraw will select the group of elements in the
|
||||
same group as the element referenced by the elementID (block reference) or the section heading.
|
||||
- If the `area=` prefix is found, Excalidraw will insert a cutout of the image around the referenced element.
|
||||
- Note that the `area=` selector is not supported when embedding Excalidraw as a PNG into your markdown documents.
|
||||
- You can append `,padding=N` to `area=`, `group=`, `frame=`, and `clippedframe=` image references to override the exported image padding, e.g. `![[file#^area=elementID,padding=120]]`. For `area=`, the value also controls how far around the referenced element Excalidraw searches for surrounding elements. Use `padding=0` for no added margin. This works with both SVG and PNG previews.
|
||||
- Referencing the elementID of a text element without the `group=` or `area=` prefix will
|
||||
transclude the element as plain text. Referencing a non-Text Element (e.g. rectangle,
|
||||
ellipse, etc.) without the `group=` or `area=` prefix will result in an Obsidian error.
|
||||
|
||||
+1017
-77
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.
|
||||
|
||||
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
|
||||
- Frame width (default: 100)
|
||||
- Roughness (default: 0)
|
||||
- Stroke width (default: 2)
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
Check info button for howto help during applying the script.
|
||||
|
||||
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
|
||||
|
||||
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
|
||||
|
||||
```js*/
|
||||
// ExcalidrawAutomate: Voronoi Diagram Generator
|
||||
ea.clear();
|
||||
|
||||
const DEFAULTS = {
|
||||
frameWidth: 100,
|
||||
roughness: 0,
|
||||
strokeWidth: 2,
|
||||
groupVoronoi: true
|
||||
};
|
||||
|
||||
let config = ea.getScriptSettings() || { ...DEFAULTS };
|
||||
|
||||
// --- UI SETTINGS MODAL ---
|
||||
async function openSettings() {
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ea.obsidian.Modal(app);
|
||||
modal.contentEl.style.padding = "20px";
|
||||
|
||||
// Header container with Title and Info Button
|
||||
const headerContainer = modal.contentEl.createDiv();
|
||||
headerContainer.style.display = "flex";
|
||||
headerContainer.style.justifyContent = "space-between";
|
||||
headerContainer.style.alignItems = "center";
|
||||
headerContainer.style.marginBottom = "20px";
|
||||
|
||||
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
|
||||
|
||||
// Info button using Obsidian's native icon
|
||||
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
|
||||
btnInfo.setAttribute("aria-label", "Information & Help");
|
||||
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
|
||||
|
||||
// Info modal content on click
|
||||
btnInfo.onclick = () => {
|
||||
const infoModal = new ea.obsidian.Modal(app);
|
||||
infoModal.contentEl.style.padding = "20px";
|
||||
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
|
||||
|
||||
// Native Obsidian Icon as HTML string
|
||||
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
|
||||
|
||||
const p = infoModal.contentEl.createEl("p");
|
||||
p.innerHTML = `
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
|
||||
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
|
||||
<div line-height: 1.4;">
|
||||
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
|
||||
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
|
||||
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
|
||||
- <b>Frame width:</b> Spacing around the diagram.<br>
|
||||
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
|
||||
- <b>Stroke width:</b> Line thickness.<br>
|
||||
- <b>Grouping:</b> Group generated cells together.<br>
|
||||
</div>
|
||||
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
|
||||
</div><br>
|
||||
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
|
||||
</span>
|
||||
`;
|
||||
infoModal.open();
|
||||
};
|
||||
|
||||
const inputs = {};
|
||||
|
||||
// Helper function to create input rows
|
||||
const createInput = (label, key, type = "number") => {
|
||||
const container = modal.contentEl.createDiv();
|
||||
container.style.marginBottom = "15px";
|
||||
|
||||
container.createEl("label", { text: label });
|
||||
const input = container.createEl("input", { type: type });
|
||||
input.style.display = "block";
|
||||
input.style.marginTop = "5px";
|
||||
input.value = config[key];
|
||||
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
|
||||
inputs[key] = input;
|
||||
};
|
||||
|
||||
createInput("Frame width:", "frameWidth");
|
||||
createInput("Roughness (0-3):", "roughness");
|
||||
createInput("Stroke width:", "strokeWidth");
|
||||
|
||||
const checkContainer = modal.contentEl.createDiv();
|
||||
checkContainer.style.marginBottom = "25px";
|
||||
checkContainer.createEl("label", { text: "Grouping: " });
|
||||
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
|
||||
|
||||
// Button container
|
||||
const btnContainer = modal.contentEl.createDiv();
|
||||
btnContainer.style.display = "flex";
|
||||
btnContainer.style.gap = "10px";
|
||||
btnContainer.style.justifyContent = "flex-end";
|
||||
|
||||
const btnDefault = btnContainer.createEl("button", { text: "Default" });
|
||||
const btnOk = btnContainer.createEl("button", { text: "OK" });
|
||||
|
||||
btnDefault.onclick = () => {
|
||||
config = { ...DEFAULTS };
|
||||
inputs.frameWidth.value = config.frameWidth;
|
||||
inputs.roughness.value = config.roughness;
|
||||
inputs.strokeWidth.value = config.strokeWidth;
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
new Notice("Settings reset to default");
|
||||
};
|
||||
|
||||
btnOk.onclick = () => {
|
||||
ea.setScriptSettings(config);
|
||||
modal.close();
|
||||
resolve(true);
|
||||
};
|
||||
|
||||
modal.open();
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for user to configure settings
|
||||
const proceed = await openSettings();
|
||||
if (!proceed) return;
|
||||
|
||||
// --- ALGORITHM & EXECUTION ---
|
||||
const els = ea.getViewSelectedElements();
|
||||
|
||||
if (els.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
|
||||
|
||||
if (seeds.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
|
||||
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
|
||||
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
|
||||
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
|
||||
|
||||
const bbox = [
|
||||
{ x: minX, y: minY },
|
||||
{ x: maxX, y: minY },
|
||||
{ x: maxX, y: maxY },
|
||||
{ x: minX, y: maxY }
|
||||
];
|
||||
|
||||
function clipPolygon(poly, p1, p2) {
|
||||
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
|
||||
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
|
||||
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
|
||||
|
||||
const intersect = (a, b) => {
|
||||
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
|
||||
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
|
||||
if (den === 0) return null;
|
||||
const t = -num / den;
|
||||
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
|
||||
};
|
||||
|
||||
const result = [];
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const cur = poly[i];
|
||||
const prev = poly[(i - 1 + poly.length) % poly.length];
|
||||
const curIn = isInside(cur);
|
||||
const prevIn = isInside(prev);
|
||||
|
||||
if (curIn !== prevIn) {
|
||||
const ix = intersect(prev, cur);
|
||||
if (ix) result.push(ix);
|
||||
}
|
||||
if (curIn) result.push(cur);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const polygons = seeds.map((s, i) => {
|
||||
let poly = [...bbox];
|
||||
seeds.forEach((_, j) => {
|
||||
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
|
||||
});
|
||||
return poly;
|
||||
});
|
||||
|
||||
ea.style.roughness = config.roughness;
|
||||
ea.style.strokeWidth = config.strokeWidth;
|
||||
ea.style.backgroundColor = "transparent";
|
||||
|
||||
const ids = [];
|
||||
|
||||
for (const poly of polygons) {
|
||||
if (poly.length < 3) continue;
|
||||
const points = poly.map(p => [p.x, p.y]);
|
||||
points.push(points[0]);
|
||||
ids.push(ea.addLine(points));
|
||||
}
|
||||
|
||||
if (config.groupVoronoi && ids.length > 0) {
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
// Clear selection so nothing remains selected on the canvas
|
||||
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
|
||||
|
||||
new Notice("Voronoi diagram created!");
|
||||
@@ -0,0 +1,2 @@
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00000000000006 111.59685711952335" width="120.00000000000006" height="111.59685711952335" class="excalidraw-svg"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
|
||||
</style></defs><g stroke-linecap="round"><g transform="translate(10 57.19446226550917) rotate(0 23.90392712157481 -23.597231132754587)"><path d="M0 0 C0 -10.48, 0 -20.95, 0 -47.19 M0 0 C0 -12.02, 0 -24.03, 0 -47.19 M0 -47.19 C13.84 -47.19, 27.68 -47.19, 47.81 -47.19 M0 -47.19 C9.79 -47.19, 19.58 -47.19, 47.81 -47.19 M47.81 -47.19 C46.81 -36.92, 45.82 -26.65, 44.57 -13.77 M47.81 -47.19 C46.84 -37.23, 45.88 -27.26, 44.57 -13.77 M44.57 -13.77 C28.62 -8.84, 12.67 -3.91, 0 0 M44.57 -13.77 C29.97 -9.26, 15.37 -4.75, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(69.1483201541107 61.21647526335062) rotate(0 13.138057949164534 -25.60823763167531)"><path d="M0 0 C-3.38 -4.12, -6.75 -8.24, -14.58 -17.79 M0 0 C-2.94 -3.58, -5.87 -7.17, -14.58 -17.79 M-14.58 -17.79 C-13.53 -28.61, -12.48 -39.43, -11.34 -51.22 M-14.58 -17.79 C-13.43 -29.64, -12.28 -41.49, -11.34 -51.22 M-11.34 -51.22 C5.87 -51.22, 23.09 -51.22, 40.85 -51.22 M-11.34 -51.22 C0.91 -51.22, 13.17 -51.22, 40.85 -51.22 M40.85 -51.22 C40.85 -41.63, 40.85 -32.05, 40.85 -8.17 M40.85 -51.22 C40.85 -39.67, 40.85 -28.12, 40.85 -8.17 M40.85 -8.17 C31.76 -6.35, 22.66 -4.53, 0 0 M40.85 -8.17 C31.97 -6.39, 23.08 -4.62, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(10 57.19446226550917) rotate(0 29.574160077055353 15.318639483348534)"><path d="M0 0 C12.58 -3.88, 25.16 -7.77, 44.57 -13.77 M0 0 C9.22 -2.85, 18.45 -5.7, 44.57 -13.77 M44.57 -13.77 C47.71 -9.94, 50.84 -6.12, 59.15 4.02 M44.57 -13.77 C47.84 -9.78, 51.1 -5.8, 59.15 4.02 M59.15 4.02 C56.04 14.66, 52.93 25.3, 47.35 44.4 M59.15 4.02 C56.49 13.12, 53.83 22.23, 47.35 44.4 M47.35 44.4 C34.36 44.4, 21.37 44.4, 0 44.4 M47.35 44.4 C29.87 44.4, 12.39 44.4, 0 44.4 M0 44.4 C0 35.21, 0 26.03, 0 0 M0 44.4 C0 30.19, 0 15.98, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(69.1483201541107 61.21647526335062) rotate(0 14.527581899009334 16.105022943497403)"><path d="M0 0 C14.31 -2.86, 28.62 -5.72, 40.85 -8.17 M0 0 C8.55 -1.71, 17.1 -3.42, 40.85 -8.17 M40.85 -8.17 C40.85 3.52, 40.85 15.21, 40.85 40.38 M40.85 -8.17 C40.85 7.02, 40.85 22.21, 40.85 40.38 M40.85 40.38 C27.51 40.38, 14.16 40.38, -11.8 40.38 M40.85 40.38 C24.32 40.38, 7.79 40.38, -11.8 40.38 M-11.8 40.38 C-8.16 27.95, -4.53 15.51, 0 0 M-11.8 40.38 C-8.75 29.96, -5.71 19.55, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round" transform="translate(77.71307083157171 28.22928207659868) rotate(0 9.41776545535356 9.41776545535356)"><path d="M18.84 9.42 C18.84 9.96, 18.79 10.52, 18.69 11.05 C18.6 11.59, 18.45 12.13, 18.27 12.64 C18.08 13.15, 17.85 13.65, 17.57 14.13 C17.3 14.6, 16.98 15.05, 16.63 15.47 C16.28 15.89, 15.89 16.28, 15.47 16.63 C15.05 16.98, 14.6 17.3, 14.13 17.57 C13.65 17.85, 13.15 18.08, 12.64 18.27 C12.13 18.45, 11.59 18.6, 11.05 18.69 C10.52 18.79, 9.96 18.84, 9.42 18.84 C8.87 18.84, 8.32 18.79, 7.78 18.69 C7.25 18.6, 6.71 18.45, 6.2 18.27 C5.68 18.08, 5.18 17.85, 4.71 17.57 C4.24 17.3, 3.78 16.98, 3.36 16.63 C2.95 16.28, 2.55 15.89, 2.2 15.47 C1.85 15.05, 1.53 14.6, 1.26 14.13 C0.99 13.65, 0.75 13.15, 0.57 12.64 C0.38 12.13, 0.24 11.59, 0.14 11.05 C0.05 10.52, 0 9.96, 0 9.42 C0 8.87, 0.05 8.32, 0.14 7.78 C0.24 7.25, 0.38 6.71, 0.57 6.2 C0.75 5.68, 0.99 5.18, 1.26 4.71 C1.53 4.24, 1.85 3.78, 2.2 3.36 C2.55 2.95, 2.95 2.55, 3.36 2.2 C3.78 1.85, 4.24 1.53, 4.71 1.26 C5.18 0.99, 5.68 0.75, 6.2 0.57 C6.71 0.38, 7.25 0.24, 7.78 0.14 C8.32 0.05, 8.87 0, 9.42 0 C9.96 0, 10.52 0.05, 11.05 0.14 C11.59 0.24, 12.13 0.38, 12.64 0.57 C13.15 0.75, 13.65 0.99, 14.13 1.26 C14.6 1.53, 15.05 1.85, 15.47 2.2 C15.89 2.55, 16.28 2.95, 16.63 3.36 C16.98 3.78, 17.3 4.24, 17.57 4.71 C17.85 5.18, 18.08 5.68, 18.27 6.2 C18.45 6.71, 18.6 7.25, 18.69 7.78 C18.79 8.32, 18.81 9.15, 18.84 9.42 C18.86 9.69, 18.86 9.15, 18.84 9.42" stroke="none" stroke-width="0" fill="#1e1e1e"></path><path d="M18.84 9.42 C18.84 9.96, 18.79 10.52, 18.69 11.05 C18.6 11.59, 18.45 12.13, 18.27 12.64 C18.08 13.15, 17.85 13.65, 17.57 14.13 C17.3 14.6, 16.98 15.05, 16.63 15.47 C16.28 15.89, 15.89 16.28, 15.47 16.63 C15.05 16.98, 14.6 17.3, 14.13 17.57 C13.65 17.85, 13.15 18.08, 12.64 18.27 C12.13 18.45, 11.59 18.6, 11.05 18.69 C10.52 18.79, 9.96 18.84, 9.42 18.84 C8.87 18.84, 8.32 18.79, 7.78 18.69 C7.25 18.6, 6.71 18.45, 6.2 18.27 C5.68 18.08, 5.18 17.85, 4.71 17.57 C4.24 17.3, 3.78 16.98, 3.36 16.63 C2.95 16.28, 2.55 15.89, 2.2 15.47 C1.85 15.05, 1.53 14.6, 1.26 14.13 C0.99 13.65, 0.75 13.15, 0.57 12.64 C0.38 12.13, 0.24 11.59, 0.14 11.05 C0.05 10.52, 0 9.96, 0 9.42 C0 8.87, 0.05 8.32, 0.14 7.78 C0.24 7.25, 0.38 6.71, 0.57 6.2 C0.75 5.68, 0.99 5.18, 1.26 4.71 C1.53 4.24, 1.85 3.78, 2.2 3.36 C2.55 2.95, 2.95 2.55, 3.36 2.2 C3.78 1.85, 4.24 1.53, 4.71 1.26 C5.18 0.99, 5.68 0.75, 6.2 0.57 C6.71 0.38, 7.25 0.24, 7.Line truncated
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -689,7 +689,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Comic Strip Director.md",
|
||||
"mtime": 1783547608665
|
||||
"mtime": 1785613946789
|
||||
},
|
||||
{
|
||||
"fname": "Comic Strip Director.svg",
|
||||
@@ -702,5 +702,13 @@
|
||||
{
|
||||
"fname": "Icon Library.svg",
|
||||
"mtime": 1783432036549
|
||||
},
|
||||
{
|
||||
"fname": "VoronoiDiagramGenerator.md",
|
||||
"mtime": 1785733307861
|
||||
},
|
||||
{
|
||||
"fname": "VoronoiDiagramGenerator.svg",
|
||||
"mtime": 1785564296587
|
||||
}
|
||||
]
|
||||
]
|
||||
@@ -101,6 +101,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.svg"/></div>|[[#Voronoi Diagram Generator]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
|
||||
|
||||
## Connectors and Arrows
|
||||
@@ -744,6 +745,23 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">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.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
|
||||
|
||||
## Voronoi Diagram Generator
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/FreeCutter'>@FreeCutter</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/VoronoiDiagramGenerator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script generates a Voronoi diagram from selected elements on the drawing canvas.
|
||||
|
||||
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
|
||||
- Frame width (default: 100)
|
||||
- Roughness (default: 0)
|
||||
- Stroke width (default: 2)
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
|
||||
See background information about [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) at Wikipedia.
|
||||
|
||||
Comments and discussion are welcomed in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/Voronoi_diagram_example.svg'></td></tr></table>
|
||||
|
||||
## Zoom to Fit Selected Elements
|
||||
```excalidraw-script-install
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1263.8361813410443 1175.0090977499947" width="1263.8361813410443" height="1175.0090977499947" class="excalidraw-svg"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
|
||||
</style></defs><rect x="0" y="0" width="1263.8361813410443" height="1175.0090977499947" fill="#ffffff"></rect><g stroke-linecap="round"><g transform="translate(54.70368721081013 565.1536157189742) rotate(0 176.3834212571344 -0.43978715755929443)"><path d="M0 0 C83.59 -44.85, 167.18 -89.69, 243.74 -130.77 M0 0 C76.87 -41.24, 153.74 -82.48, 243.74 -130.77 M243.74 -130.77 C275.1 -122.97, 306.45 -115.17, 347.23 -105.03 M243.74 -130.77 C269.96 -124.25, 296.18 -117.73, 347.23 -105.03 M347.23 -105.03 C348.69 -102.84, 350.16 -100.65, 352.77 -96.75 M347.23 -105.03 C349.17 -102.13, 351.11 -99.23, 352.77 -96.75 M352.77 -96.75 C346.03 -31.37, 339.29 34.01, 330.72 117.18 M352.77 -96.75 C344.5 -16.53, 336.23 63.7, 330.72 117.18 M330.72 117.18 C325.89 122.19, 321.06 127.19, 318.46 129.89 M330.72 117.18 C327.16 120.87, 323.61 124.55, 318.46 129.89 M318.46 129.89 C215.83 88.03, 113.21 46.17, 0 0 M318.46 129.89 C219.02 89.33, 119.58 48.77, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(787.0151296423978 50.95181640257783) rotate(0 24.21503087586143 268.49136541140206)"><path d="M0 0 C34.58 51.71, 69.16 103.43, 151.56 226.64 M0 0 C46.53 69.58, 93.06 139.16, 151.56 226.64 M151.56 226.64 C146.83 272.55, 142.1 318.45, 129.51 440.58 M151.56 226.64 C143.97 300.28, 136.38 373.92, 129.51 440.58 M129.51 440.58 C96.11 475.2, 62.71 509.82, 40.15 533.21 M129.51 440.58 C101.05 470.07, 72.6 499.57, 40.15 533.21 M40.15 533.21 C34.45 534.4, 28.75 535.6, 22.18 536.98 M40.15 533.21 C33.78 534.54, 27.41 535.88, 22.18 536.98 M22.18 536.98 C-10.55 498.88, -43.27 460.78, -80.4 417.56 M22.18 536.98 C-6.64 503.43, -35.46 469.88, -80.4 417.56 M-80.4 417.56 C-87.39 336.03, -94.38 254.51, -103.13 152.37 M-80.4 417.56 C-89.28 313.96, -98.16 210.36, -103.13 152.37 M-103.13 152.37 C-66.57 98.35, -30.01 44.34, 0 0 M-103.13 152.37 C-72.3 106.82, -41.47 61.27, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(291.93518791000906 67.8208608237735) rotate(0 -139.01064058404268 58.91726978854547)"><path d="M0 0 C-33.52 35.28, -67.03 70.57, -148.12 155.93 M0 0 C-48.23 50.78, -96.47 101.55, -148.12 155.93 M-148.12 155.93 C-200.08 163.59, -252.03 171.25, -281.94 175.66 M-148.12 155.93 C-198.35 163.34, -248.59 170.74, -281.94 175.66 M-281.94 175.66 C-281.94 125.38, -281.94 75.11, -281.94 -57.82 M-281.94 175.66 C-281.94 116.18, -281.94 56.7, -281.94 -57.82 M-281.94 -57.82 C-182.76 -57.82, -83.59 -57.82, 3.91 -57.82 M-281.94 -57.82 C-221.24 -57.82, -160.54 -57.82, 3.91 -57.82 M3.91 -57.82 C2.65 -39.11, 1.38 -20.4, 0 0 M3.91 -57.82 C3.12 -46.05, 2.32 -34.28, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(323.64815744858697 1008.5657439379145) rotate(0 134.74696302032476 -35.20122701427704)"><path d="M0 0 C9.07 -78.24, 18.14 -156.47, 24.77 -213.64 M0 0 C7.02 -60.54, 14.04 -121.08, 24.77 -213.64 M24.77 -213.64 C28.93 -217.85, 33.1 -222.05, 37.84 -226.85 M24.77 -213.64 C29.16 -218.07, 33.54 -222.5, 37.84 -226.85 M37.84 -226.85 C105.87 -198.49, 173.9 -170.13, 269.49 -130.28 M37.84 -226.85 C97 -202.18, 156.17 -177.52, 269.49 -130.28 M269.49 -130.28 C266.42 -65.14, 263.34 0, 261.06 48.48 M269.49 -130.28 C266.98 -76.95, 264.46 -23.62, 261.06 48.48 M261.06 48.48 C250.95 70.84, 240.85 93.2, 212.28 156.44 M261.06 48.48 C249.67 73.68, 238.28 98.88, 212.28 156.44 M212.28 156.44 C168.91 156.44, 125.54 156.44, 101.76 156.44 M212.28 156.44 C189.88 156.44, 167.48 156.44, 101.76 156.44 M101.76 156.44 C63.51 97.63, 25.26 38.83, 0 0 M101.76 156.44 C73.22 112.57, 44.68 68.7, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(978.0191004485864 1027.221004937913) rotate(0 137.90854044622893 -100.5203977296942)"><path d="M0 0 C9.87 -85.14, 19.74 -170.29, 24.77 -213.64 M0 0 C6.63 -57.21, 13.27 -114.41, 24.77 -213.64 M24.77 -213.64 C50.99 -240.13, 77.21 -266.63, 116.71 -306.55 M24.77 -213.64 C46.7 -235.8, 68.64 -257.97, 116.71 -306.55 M116.71 -306.55 C149.12 -313.12, 181.54 -319.7, 275.82 -338.83 M116.71 -306.55 C168.67 -317.09, 220.63 -327.63, 275.82 -338.83 M275.82 -338.83 C275.82 -155.19, 275.82 28.46, 275.82 137.79 M275.82 -338.83 C275.82 -230.05, 275.82 -121.27, 275.82 137.79 M275.82 137.79 C210.28 137.79, 144.75 137.79, 89.63 137.79 M275.82 137.79 C216.35 137.79, 156.88 137.79, 89.63 137.79 M89.63 137.79 C67.12 103.19, 44.62 68.59, 0 0 M89.63 137.79 C56.38 86.67, 23.13 35.56, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(558.7327432421484 682.3377911470559) rotate(0 -86.65644819683712 -106.9678206846113)"><path d="M0 0 C-42.87 0, -85.74 0, -173.31 0 M0 0 C-63.58 0, -127.17 0, -173.31 0 M-173.31 0 C-164.71 -83.5, -156.1 -167, -151.26 -213.94 M-173.31 0 C-166.91 -62.13, -160.51 -124.25Line truncated
|
||||
|
After Width: | Height: | Size: 64 KiB |
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.26.0-beta.4",
|
||||
"version": "2.26.0-rc.4",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+4
-5
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.114",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -5274,10 +5274,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.114",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.114.tgz",
|
||||
"integrity": "sha512-Dgtt4uYNi7+XOoPsbIgPu/x3NtKuiaRTmDfBJr27/6d/6ucjoBa7RZoNLsWBMe88jBLRcxOAQxcVQ+gqfU8JtQ==",
|
||||
"license": "MIT",
|
||||
"version": "0.18.116",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.116.tgz",
|
||||
"integrity": "sha512-cq/jChIEDdmWt/B1ZQUauMqi7wj/vNda0TZjqQ89ju9n8mLrvh9J7f3OZJQ+m/BYOesd1RrY8Nm4SZfBj37Ajg==",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
"@codemirror/commands": "^6.0.0",
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.114",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
|
||||
@@ -109,6 +109,7 @@ export let {
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restoreElements,
|
||||
restoreLibraryItems,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
@@ -136,6 +137,7 @@ export function updateExcalidrawLib() {
|
||||
"measureText",
|
||||
"getLineHeight",
|
||||
"restoreElements",
|
||||
"restoreLibraryItems",
|
||||
];
|
||||
|
||||
for (const fnName of requiredFunctions) {
|
||||
@@ -166,6 +168,7 @@ export function updateExcalidrawLib() {
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restoreElements,
|
||||
restoreLibraryItems,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
|
||||
+55
-5
@@ -124,6 +124,8 @@ import { installButton } from "src/utils/scriptLibraryUtils";
|
||||
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
|
||||
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
|
||||
import type { MarkdownImageData } from "src/types/markdownImageTypes";
|
||||
import { StencilLibraryManager } from "./managers/StencilLibraryManager";
|
||||
import type { StencilLibraryData } from "src/types/stencilLibraryTypes";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -585,6 +587,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
private monkeyPatchManager: MonkeyPatchManager;
|
||||
private commandManager: CommandManager;
|
||||
private eventManager: EventManager;
|
||||
public stencilLibraryManager: StencilLibraryManager;
|
||||
public eaInstances = new WeakArray<ExcalidrawAutomate>();
|
||||
public fourthFontLoaded: boolean = false;
|
||||
public excalidrawConfig: ExcalidrawConfig;
|
||||
@@ -879,6 +882,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.observerManager = new ObserverManager(this);
|
||||
this.monkeyPatchManager = new MonkeyPatchManager(this);
|
||||
this.commandManager = new CommandManager(this);
|
||||
this.stencilLibraryManager = new StencilLibraryManager(this);
|
||||
|
||||
try {
|
||||
initCompressionWorker();
|
||||
@@ -1625,6 +1629,29 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
|
||||
let didSettingsMigration = false;
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, decryptedSettings);
|
||||
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
|
||||
const legacyLibrary: unknown =
|
||||
typeof decryptedSettings.library === "string" &&
|
||||
decryptedSettings.library !== "" &&
|
||||
decryptedSettings.library !== "deprecated"
|
||||
? JSON_parse(decryptedSettings.library)
|
||||
: decryptedSettings.library2;
|
||||
const legacyLibraryRecord =
|
||||
typeof legacyLibrary === "object" && legacyLibrary !== null
|
||||
? (legacyLibrary as Record<string, unknown>)
|
||||
: null;
|
||||
const hasLegacyItems = Boolean(
|
||||
(Array.isArray(legacyLibraryRecord?.library) &&
|
||||
legacyLibraryRecord.library.length) ||
|
||||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
|
||||
legacyLibraryRecord.libraryItems.length),
|
||||
);
|
||||
this.settings.libraryStorageMode = hasLegacyItems ? "data-json" : "vault";
|
||||
this.settings.libraryMigrationStatus = hasLegacyItems
|
||||
? "pending"
|
||||
: "not-required";
|
||||
didSettingsMigration = true;
|
||||
}
|
||||
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
|
||||
if (!savedMarkdownImageSettings) {
|
||||
this.settings.markdownImageSettings = {
|
||||
@@ -1632,12 +1659,12 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
|
||||
width: this.settings.mdSVGwidth,
|
||||
fontFamily: this.settings.mdFont,
|
||||
fontColor: this.settings.mdFontColor,
|
||||
fontColor: this.settings.mdFontColor ?? "#000000",
|
||||
border: {
|
||||
enabled: false,
|
||||
color: this.settings.mdBorderColor,
|
||||
},
|
||||
css: this.settings.mdCSS,
|
||||
css: "",
|
||||
transclusion: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
|
||||
border: {
|
||||
@@ -1720,6 +1747,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
async onExternalSettingsChange() {
|
||||
await this.loadSettings();
|
||||
this.stencilLibraryManager?.invalidate();
|
||||
}
|
||||
|
||||
public async openSidepanel(
|
||||
@@ -1728,7 +1756,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
return ExcalidrawSidepanelView.getOrCreate(this, reveal);
|
||||
}
|
||||
|
||||
public getStencilLibrary(): object {
|
||||
public getLegacyStencilLibrary(): StencilLibraryData {
|
||||
if (
|
||||
this.settings.library === "" ||
|
||||
this.settings.library === "deprecated"
|
||||
@@ -1738,13 +1766,35 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
return JSON_parse(this.settings.library);
|
||||
}
|
||||
|
||||
public async setStencilLibrary(library: object) {
|
||||
public async setLegacyStencilLibrary(
|
||||
library: StencilLibraryData,
|
||||
save: boolean = true,
|
||||
) {
|
||||
this.settings.library = "deprecated";
|
||||
if (JSON.stringify(this.settings.library2) === JSON.stringify(library)) {
|
||||
return;
|
||||
}
|
||||
this.settings.library2 = library;
|
||||
await this.saveSettings();
|
||||
if (save) {
|
||||
await this.saveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public getStencilLibrary():
|
||||
| StencilLibraryData
|
||||
| Promise<StencilLibraryData> {
|
||||
return this.stencilLibraryManager.getLibrary().then((libraryItems) => ({
|
||||
type: "excalidrawlib" as const,
|
||||
version: 2,
|
||||
libraryItems,
|
||||
}));
|
||||
}
|
||||
|
||||
public async setStencilLibrary(library: StencilLibraryData) {
|
||||
const data = library;
|
||||
await this.stencilLibraryManager.setLibrary(
|
||||
data.libraryItems ?? data.library ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
public triggerEmbedUpdates(filepath?: string) {
|
||||
|
||||
@@ -20,7 +20,8 @@ import {
|
||||
nanoid,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
} from "src/constants/constants";
|
||||
import { Prompt, templatePromt } from "src/shared/Dialogs/Prompt";
|
||||
import { templatePromt } from "src/shared/Dialogs/Prompt";
|
||||
import { FileAndFolderSelectorModal } from "src/shared/Dialogs/FileAndFolderSelectorModal";
|
||||
import {
|
||||
changeThemeOfExcalidrawMD,
|
||||
ExcalidrawData,
|
||||
@@ -32,6 +33,7 @@ import ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
checkAndCreateFolder,
|
||||
createFileAndAwaitMetacacheUpdate,
|
||||
createOrOverwriteFile,
|
||||
download,
|
||||
getIMGFilename,
|
||||
getLink,
|
||||
@@ -47,6 +49,7 @@ import {
|
||||
import { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { getImageCache } from "src/shared/ImageCache";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export class PluginFileManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -384,29 +387,29 @@ export class PluginFileManager {
|
||||
|
||||
public async exportLibrary() {
|
||||
if (DEVICE.isMobile) {
|
||||
const prompt = new Prompt(
|
||||
this.app,
|
||||
"Please provide a filename",
|
||||
"my-library",
|
||||
"filename, leave blank to cancel action",
|
||||
const location = await new FileAndFolderSelectorModal(this.app, {
|
||||
title: t("FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE"),
|
||||
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
|
||||
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
|
||||
submitButtonText: t("FILE_AND_FOLDER_SELECTOR_EXPORT"),
|
||||
folderPath: normalizePath(this.settings.folder),
|
||||
fileName: "my-library.excalidrawlib",
|
||||
}).start();
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
const filename = location.fileName
|
||||
.toLowerCase()
|
||||
.endsWith(".excalidrawlib")
|
||||
? location.fileName
|
||||
: `${location.fileName}.excalidrawlib`;
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
location.folderPath,
|
||||
);
|
||||
void prompt.openAndGetValue((filename: string) => {
|
||||
void (async () => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
filename = `${filename}.excalidrawlib`;
|
||||
const folderpath = normalizePath(this.settings.folder);
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
await this.app.vault.create(fname, this.settings.library);
|
||||
new Notice(`Exported library to ${fname}`, 6000);
|
||||
})();
|
||||
});
|
||||
await createOrOverwriteFile(this.app, fname, this.settings.library);
|
||||
new Notice(`Exported library to ${fname}`, 6000);
|
||||
return;
|
||||
}
|
||||
download(
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
getWithBackground,
|
||||
hasExportTheme,
|
||||
convertSVGStringToElement,
|
||||
isImagePartRef,
|
||||
isMaskFile,
|
||||
} from "../../utils/utils";
|
||||
import {
|
||||
@@ -150,24 +151,20 @@ const _getPNG = async ({
|
||||
|
||||
if (cacheReady) {
|
||||
const src = await getImageCache().getImageFromCache(cacheKey);
|
||||
//In case of PNG I cannot change the viewBox to select the area of the element
|
||||
//being referenced. For PNG only the group reference works
|
||||
if (src && typeof src === "string") {
|
||||
img.src = src;
|
||||
return img;
|
||||
}
|
||||
}
|
||||
|
||||
const quickPNG = !(filenameParts.hasGroupref || filenameParts.hasFrameref)
|
||||
const quickPNG = !isImagePartRef(filenameParts)
|
||||
? await getQuickImagePreview(plugin, file.path, "png")
|
||||
: undefined;
|
||||
|
||||
const png =
|
||||
quickPNG ??
|
||||
(await createPNG(
|
||||
filenameParts.hasGroupref ||
|
||||
filenameParts.hasFrameref ||
|
||||
filenameParts.hasClippedFrameref
|
||||
isImagePartRef(filenameParts)
|
||||
? filenameParts.filepath + filenameParts.linkpartReference
|
||||
: file.path,
|
||||
scale,
|
||||
@@ -189,6 +186,7 @@ const _getPNG = async ({
|
||||
[],
|
||||
plugin,
|
||||
0,
|
||||
getExportPadding(plugin, file),
|
||||
));
|
||||
if (!png) {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
import { Notice, normalizePath, TFolder } from "obsidian";
|
||||
import type {
|
||||
LibraryItem,
|
||||
LibraryItems,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { restoreLibraryItems } from "src/constants/constants";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { StencilLibraryMigrationPrompt } from "src/shared/Dialogs/StencilLibraryMigrationPrompt";
|
||||
import type {
|
||||
StencilLibraryData,
|
||||
StencilLibraryFileData,
|
||||
} from "src/types/stencilLibraryTypes";
|
||||
import { getExcalidrawViews } from "src/utils/obsidianUtils";
|
||||
|
||||
const LIBRARY_EXTENSION = "excalidrawlib";
|
||||
const MIGRATION_SNOOZE_MS = 24 * 60 * 60 * 1000;
|
||||
const LIBRARY_RELOAD_DEBOUNCE_MS = 300;
|
||||
const OWN_WRITE_EVENT_WINDOW_MS = 2000;
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
const getLibraryItems = (data: StencilLibraryData | null): LibraryItems =>
|
||||
data?.libraryItems ?? data?.library ?? [];
|
||||
|
||||
const normalizeLibraryFileName = (fileName: string): string => {
|
||||
const trimmed = fileName.trim().replace(/[\\/]/g, "-");
|
||||
const withoutExtension = trimmed.replace(/\.excalidrawlib$/i, "");
|
||||
return withoutExtension || "local-library";
|
||||
};
|
||||
|
||||
/**
|
||||
* Owns stencil-library persistence and keeps each item's source file stable.
|
||||
* Vault writes are reconciled with the latest file contents to avoid clobbering
|
||||
* files updated by sync after the library was loaded.
|
||||
*/
|
||||
export class StencilLibraryManager {
|
||||
private itemSource = new Map<LibraryItem["id"], string>();
|
||||
private currentItems: LibraryItems = [];
|
||||
private loaded = false;
|
||||
private migrationPrompt: Promise<void> | null = null;
|
||||
private saveQueue: Promise<void> = Promise.resolve();
|
||||
private reloadTimer: number | null = null;
|
||||
private readonly ownWritePaths = new Set<string>();
|
||||
private isUpdatingOpenViews = false;
|
||||
|
||||
constructor(private readonly plugin: ExcalidrawPlugin) {
|
||||
const handleLibraryFileChange = (file: { path: string }) => {
|
||||
if (
|
||||
file.path.startsWith(`${this.getFolderPath()}/`) &&
|
||||
file.path.toLowerCase().endsWith(`.${LIBRARY_EXTENSION}`)
|
||||
) {
|
||||
if (this.ownWritePaths.has(file.path)) {
|
||||
return;
|
||||
}
|
||||
this.invalidate();
|
||||
if (this.plugin.settings.libraryStorageMode === "vault") {
|
||||
this.scheduleOpenViewReload();
|
||||
}
|
||||
}
|
||||
};
|
||||
plugin.registerEvent(
|
||||
plugin.app.vault.on("create", handleLibraryFileChange),
|
||||
);
|
||||
plugin.registerEvent(
|
||||
plugin.app.vault.on("modify", handleLibraryFileChange),
|
||||
);
|
||||
plugin.registerEvent(
|
||||
plugin.app.vault.on("delete", handleLibraryFileChange),
|
||||
);
|
||||
plugin.registerEvent(
|
||||
plugin.app.vault.on("rename", (file, oldPath) => {
|
||||
handleLibraryFileChange(file);
|
||||
handleLibraryFileChange({ path: oldPath });
|
||||
}),
|
||||
);
|
||||
plugin.register(() => {
|
||||
if (this.reloadTimer !== null) {
|
||||
window.clearTimeout(this.reloadTimer);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public hasLegacyItems(): boolean {
|
||||
return getLibraryItems(this.plugin.getLegacyStencilLibrary()).length > 0;
|
||||
}
|
||||
|
||||
public invalidate(): void {
|
||||
this.loaded = false;
|
||||
this.itemSource.clear();
|
||||
this.currentItems = [];
|
||||
}
|
||||
|
||||
public async getLibrary(): Promise<LibraryItems> {
|
||||
await this.ensureMigrationDecision();
|
||||
if (this.plugin.settings.libraryStorageMode === "data-json") {
|
||||
return restoreLibraryItems(
|
||||
getLibraryItems(this.plugin.getLegacyStencilLibrary()),
|
||||
"unpublished",
|
||||
);
|
||||
}
|
||||
if (
|
||||
this.hasLegacyItems() &&
|
||||
(this.plugin.settings.libraryMigrationStatus === "completed" ||
|
||||
this.plugin.settings.libraryMigrationStatus === "not-required")
|
||||
) {
|
||||
// A sync conflict can restore stale data.json items after migration.
|
||||
// Merge them idempotently before clearing the legacy copy again.
|
||||
await this.migrateLegacyLibrary();
|
||||
}
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
}
|
||||
return this.currentItems;
|
||||
}
|
||||
|
||||
public async setLibrary(items: LibraryItems): Promise<void> {
|
||||
if (this.isUpdatingOpenViews) {
|
||||
return;
|
||||
}
|
||||
if (this.plugin.settings.libraryStorageMode === "data-json") {
|
||||
await this.plugin.setLegacyStencilLibrary(this.createFileData(items));
|
||||
return;
|
||||
}
|
||||
this.saveQueue = this.saveQueue.then(() => this.persistChanges(items));
|
||||
await this.saveQueue;
|
||||
}
|
||||
|
||||
public async showMigrationPrompt(): Promise<void> {
|
||||
if (this.migrationPrompt !== null) {
|
||||
return this.migrationPrompt;
|
||||
}
|
||||
this.migrationPrompt = this.runMigrationPrompt().finally(() => {
|
||||
this.migrationPrompt = null;
|
||||
});
|
||||
return this.migrationPrompt;
|
||||
}
|
||||
|
||||
public async switchToLegacyStorage(): Promise<void> {
|
||||
const items = await this.getVaultLibrary();
|
||||
await this.plugin.setLegacyStencilLibrary(
|
||||
this.createFileData(items),
|
||||
false,
|
||||
);
|
||||
this.plugin.settings.libraryStorageMode = "data-json";
|
||||
this.plugin.settings.libraryMigrationStatus = "opted-out";
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil = 0;
|
||||
await this.plugin.saveSettings();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
/** Reloads the merged vault library in every initialized Excalidraw view. */
|
||||
public async reloadLibrariesInOpenViews(): Promise<void> {
|
||||
if (this.plugin.settings.libraryStorageMode !== "vault") {
|
||||
return;
|
||||
}
|
||||
await this.saveQueue;
|
||||
this.invalidate();
|
||||
await this.loadFromVault();
|
||||
this.isUpdatingOpenViews = true;
|
||||
try {
|
||||
for (const view of getExcalidrawViews(this.plugin.app, true)) {
|
||||
await view.excalidrawAPI.updateLibrary({
|
||||
libraryItems: this.currentItems,
|
||||
merge: false,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
this.isUpdatingOpenViews = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureMigrationDecision(): Promise<void> {
|
||||
const status = this.plugin.settings.libraryMigrationStatus;
|
||||
const isSnoozed =
|
||||
status === "later" &&
|
||||
Date.now() < this.plugin.settings.libraryMigrationSnoozeUntil;
|
||||
if (status !== "pending" && (status !== "later" || isSnoozed)) {
|
||||
return;
|
||||
}
|
||||
await this.showMigrationPrompt();
|
||||
}
|
||||
|
||||
private async runMigrationPrompt(): Promise<void> {
|
||||
const result = await new StencilLibraryMigrationPrompt(this.plugin).start();
|
||||
this.plugin.settings.libraryFolderPath = result.folderPath;
|
||||
this.plugin.settings.libraryFileName = normalizeLibraryFileName(
|
||||
result.fileName,
|
||||
);
|
||||
|
||||
if (result.choice === "migrate") {
|
||||
try {
|
||||
await this.migrateLegacyLibrary();
|
||||
new Notice(t("LIBRARY_MIGRATION_SUCCESS"));
|
||||
} catch (error) {
|
||||
console.error("Stencil library migration failed", error);
|
||||
this.plugin.settings.libraryStorageMode = "data-json";
|
||||
this.plugin.settings.libraryMigrationStatus = "later";
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil =
|
||||
Date.now() + MIGRATION_SNOOZE_MS;
|
||||
await this.plugin.saveSettings();
|
||||
new Notice(t("LIBRARY_MIGRATION_FAILED"), 8000);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.plugin.settings.libraryStorageMode = "data-json";
|
||||
this.plugin.settings.libraryMigrationStatus =
|
||||
result.choice === "later" ? "later" : "opted-out";
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil =
|
||||
result.choice === "later" ? Date.now() + MIGRATION_SNOOZE_MS : 0;
|
||||
await this.plugin.saveSettings();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
private async migrateLegacyLibrary(): Promise<void> {
|
||||
const previousLibrary = this.plugin.settings.library;
|
||||
const previousLibrary2 = this.plugin.settings.library2;
|
||||
const previousStorageMode = this.plugin.settings.libraryStorageMode;
|
||||
const previousMigrationStatus = this.plugin.settings.libraryMigrationStatus;
|
||||
const previousMigrationSnoozeUntil =
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil;
|
||||
const legacyItems = restoreLibraryItems(
|
||||
getLibraryItems(this.plugin.getLegacyStencilLibrary()),
|
||||
"unpublished",
|
||||
);
|
||||
const path = this.getLocalLibraryPath();
|
||||
const existing = await this.readLibraryFile(path);
|
||||
const existingItems = restoreLibraryItems(
|
||||
getLibraryItems(existing),
|
||||
"unpublished",
|
||||
);
|
||||
const merged = this.mergeById(existingItems, legacyItems);
|
||||
await this.persistLibraryFile(path, this.createFileData(merged));
|
||||
|
||||
const verified = await this.readLibraryFile(path);
|
||||
const verifiedIds = new Set(
|
||||
restoreLibraryItems(getLibraryItems(verified), "unpublished").map(
|
||||
(item) => item.id,
|
||||
),
|
||||
);
|
||||
if (legacyItems.some((item) => !verifiedIds.has(item.id))) {
|
||||
throw new Error("Not all legacy library items were written");
|
||||
}
|
||||
|
||||
this.plugin.settings.libraryStorageMode = "vault";
|
||||
this.plugin.settings.libraryMigrationStatus = "completed";
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil = 0;
|
||||
await this.plugin.setLegacyStencilLibrary(this.createFileData([]), false);
|
||||
try {
|
||||
await this.plugin.saveSettings();
|
||||
} catch (error) {
|
||||
// The verified vault file remains as a safe recovery copy, while the
|
||||
// in-memory settings are restored so a retry cannot clear data.json.
|
||||
this.plugin.settings.library = previousLibrary;
|
||||
this.plugin.settings.library2 = previousLibrary2;
|
||||
this.plugin.settings.libraryStorageMode = previousStorageMode;
|
||||
this.plugin.settings.libraryMigrationStatus = previousMigrationStatus;
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil =
|
||||
previousMigrationSnoozeUntil;
|
||||
throw error;
|
||||
}
|
||||
await this.reloadLibrariesInOpenViews();
|
||||
}
|
||||
|
||||
private scheduleOpenViewReload(): void {
|
||||
if (this.reloadTimer !== null) {
|
||||
window.clearTimeout(this.reloadTimer);
|
||||
}
|
||||
this.reloadTimer = window.setTimeout(() => {
|
||||
this.reloadTimer = null;
|
||||
void this.reloadLibrariesInOpenViews().catch((error) =>
|
||||
console.error("Could not reload stencil libraries", error),
|
||||
);
|
||||
}, LIBRARY_RELOAD_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
private async getVaultLibrary(): Promise<LibraryItems> {
|
||||
const previousMode = this.plugin.settings.libraryStorageMode;
|
||||
this.plugin.settings.libraryStorageMode = "vault";
|
||||
this.invalidate();
|
||||
try {
|
||||
return await this.getLibrary();
|
||||
} finally {
|
||||
this.plugin.settings.libraryStorageMode = previousMode;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadFromVault(): Promise<void> {
|
||||
this.itemSource.clear();
|
||||
const folderPath = this.getFolderPath();
|
||||
const localPath = this.getLocalLibraryPath();
|
||||
const files = this.plugin.app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(file) =>
|
||||
file.parent?.path === folderPath &&
|
||||
file.extension.toLowerCase() === LIBRARY_EXTENSION,
|
||||
)
|
||||
.sort((a, b) => {
|
||||
if (a.path === localPath) return -1;
|
||||
if (b.path === localPath) return 1;
|
||||
return a.path.localeCompare(b.path);
|
||||
});
|
||||
|
||||
const combined: LibraryItem[] = [];
|
||||
for (const file of files) {
|
||||
const data = await this.readLibraryFile(file.path);
|
||||
if (!data) {
|
||||
continue;
|
||||
}
|
||||
const isLocalFile = file.path === localPath;
|
||||
const items = restoreLibraryItems(
|
||||
getLibraryItems(data),
|
||||
isLocalFile ? "unpublished" : "published",
|
||||
);
|
||||
for (const item of items) {
|
||||
if (this.itemSource.has(item.id)) {
|
||||
console.warn(
|
||||
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
this.itemSource.set(item.id, file.path);
|
||||
combined.push(
|
||||
isLocalFile ? item : { ...item, status: "published" as const },
|
||||
);
|
||||
}
|
||||
}
|
||||
this.currentItems = combined;
|
||||
this.loaded = true;
|
||||
}
|
||||
|
||||
private async persistChanges(nextItems: LibraryItems): Promise<void> {
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
}
|
||||
const previousById = new Map(
|
||||
this.currentItems.map((item) => [item.id, item]),
|
||||
);
|
||||
const nextById = new Map(nextItems.map((item) => [item.id, item]));
|
||||
const affectedPaths = new Set<string>();
|
||||
const additions: LibraryItem[] = [];
|
||||
|
||||
for (const item of this.currentItems) {
|
||||
const next = nextById.get(item.id);
|
||||
if (!next || JSON.stringify(next) !== JSON.stringify(item)) {
|
||||
affectedPaths.add(
|
||||
this.itemSource.get(item.id) ?? this.getLocalLibraryPath(),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const item of nextItems) {
|
||||
if (!previousById.has(item.id)) {
|
||||
additions.push(item);
|
||||
affectedPaths.add(this.getLocalLibraryPath());
|
||||
}
|
||||
}
|
||||
|
||||
for (const path of affectedPaths) {
|
||||
const existingData =
|
||||
(await this.readLibraryFile(path)) ?? this.createFileData([]);
|
||||
const existingItems = restoreLibraryItems(
|
||||
getLibraryItems(existingData),
|
||||
path === this.getLocalLibraryPath() ? "unpublished" : "published",
|
||||
);
|
||||
const updated: LibraryItem[] = [];
|
||||
for (const diskItem of existingItems) {
|
||||
if (this.itemSource.get(diskItem.id) !== path) {
|
||||
updated.push(diskItem);
|
||||
continue;
|
||||
}
|
||||
const next = nextById.get(diskItem.id);
|
||||
if (next) {
|
||||
updated.push(this.withFileStatus(next, path));
|
||||
}
|
||||
}
|
||||
if (path === this.getLocalLibraryPath()) {
|
||||
for (const item of additions) {
|
||||
if (!updated.some((candidate) => candidate.id === item.id)) {
|
||||
updated.unshift(this.withFileStatus(item, path));
|
||||
this.itemSource.set(item.id, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextData: StencilLibraryFileData = {
|
||||
...existingData,
|
||||
type: "excalidrawlib",
|
||||
version: 2,
|
||||
libraryItems: updated,
|
||||
};
|
||||
if (JSON.stringify(existingData) !== JSON.stringify(nextData)) {
|
||||
await this.persistLibraryFile(path, nextData);
|
||||
}
|
||||
}
|
||||
|
||||
const nextItemSource = new Map<LibraryItem["id"], string>();
|
||||
this.currentItems = nextItems.map((item) => {
|
||||
const path = this.itemSource.get(item.id) ?? this.getLocalLibraryPath();
|
||||
nextItemSource.set(item.id, path);
|
||||
return this.withFileStatus(item, path);
|
||||
});
|
||||
this.itemSource = nextItemSource;
|
||||
}
|
||||
|
||||
private withFileStatus(item: LibraryItem, path: string): LibraryItem {
|
||||
return path === this.getLocalLibraryPath()
|
||||
? item
|
||||
: { ...item, status: "published" };
|
||||
}
|
||||
|
||||
private mergeById(
|
||||
preferred: LibraryItems,
|
||||
additional: LibraryItems,
|
||||
): LibraryItems {
|
||||
const seen = new Set(preferred.map((item) => item.id));
|
||||
return [...preferred, ...additional.filter((item) => !seen.has(item.id))];
|
||||
}
|
||||
|
||||
private createFileData(items: LibraryItems): StencilLibraryFileData {
|
||||
return {
|
||||
type: "excalidrawlib",
|
||||
version: 2,
|
||||
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
|
||||
libraryItems: items,
|
||||
};
|
||||
}
|
||||
|
||||
private getFolderPath(): string {
|
||||
return normalizePath(
|
||||
this.plugin.settings.libraryFolderPath.trim() ||
|
||||
`${this.plugin.settings.folder}/Libraries`,
|
||||
);
|
||||
}
|
||||
|
||||
private getLocalLibraryPath(): string {
|
||||
return normalizePath(
|
||||
`${this.getFolderPath()}/${normalizeLibraryFileName(
|
||||
this.plugin.settings.libraryFileName,
|
||||
)}.${LIBRARY_EXTENSION}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async ensureFolder(): Promise<TFolder> {
|
||||
const path = this.getFolderPath();
|
||||
const folder = this.plugin.app.vault.getFolderByPath(path);
|
||||
if (folder) {
|
||||
return folder;
|
||||
}
|
||||
if (this.plugin.app.vault.getFileByPath(path)) {
|
||||
throw new Error(`Library folder path is a file: ${path}`);
|
||||
}
|
||||
return this.plugin.app.vault.createFolder(path);
|
||||
}
|
||||
|
||||
private async readLibraryFile(
|
||||
path: string,
|
||||
): Promise<StencilLibraryData | null> {
|
||||
const file = this.plugin.app.vault.getFileByPath(path);
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(
|
||||
await this.plugin.app.vault.read(file),
|
||||
) as StencilLibraryData;
|
||||
} catch (error) {
|
||||
console.error(`Could not read stencil library ${path}`, error);
|
||||
new Notice(t("LIBRARY_FILE_READ_ERROR").replace("{PATH}", path), 8000);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes a non-empty library or removes its file when no items remain. */
|
||||
private async persistLibraryFile(
|
||||
path: string,
|
||||
data: StencilLibraryFileData,
|
||||
): Promise<void> {
|
||||
const existing = this.plugin.app.vault.getFileByPath(path);
|
||||
if (data.libraryItems.length === 0 && !existing) {
|
||||
return;
|
||||
}
|
||||
this.ownWritePaths.add(path);
|
||||
try {
|
||||
if (data.libraryItems.length === 0) {
|
||||
await this.plugin.app.fileManager.trashFile(existing);
|
||||
return;
|
||||
}
|
||||
await this.ensureFolder();
|
||||
const content = JSON.stringify(data);
|
||||
if (existing) {
|
||||
await this.plugin.app.vault.modify(existing, content);
|
||||
return;
|
||||
}
|
||||
if (this.plugin.app.vault.getFolderByPath(path)) {
|
||||
throw new Error(`Library file path is a folder: ${path}`);
|
||||
}
|
||||
await this.plugin.app.vault.create(path, content);
|
||||
} finally {
|
||||
window.setTimeout(
|
||||
() => this.ownWritePaths.delete(path),
|
||||
OWN_WRITE_EVENT_WINDOW_MS,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,10 +69,20 @@ export class StylesManager {
|
||||
}
|
||||
|
||||
private async onCSSChange() {
|
||||
await this.harvestStyles();
|
||||
getAllWindowDocuments(this.plugin.app).forEach((doc) => {
|
||||
this.copyPropertiesToTheme(doc);
|
||||
});
|
||||
const harvest = async () => {
|
||||
await this.harvestStyles();
|
||||
getAllWindowDocuments(this.plugin.app).forEach((doc) => {
|
||||
this.copyPropertiesToTheme(doc);
|
||||
});
|
||||
};
|
||||
|
||||
if (!this.plugin.app.workspace.layoutReady) {
|
||||
this.plugin.app.workspace.onLayoutReady(async () => {
|
||||
await harvest();
|
||||
});
|
||||
return;
|
||||
}
|
||||
await harvest();
|
||||
}
|
||||
|
||||
private onWindowOpen(win: WorkspaceWindow) {
|
||||
@@ -143,8 +153,10 @@ export class StylesManager {
|
||||
const cm = this.plugin.ea.getCM(
|
||||
computedStyles.getPropertyValue("--background-primary"),
|
||||
);
|
||||
cm.alphaTo(0.9);
|
||||
allVariables["--background-primary"] = cm.stringHEX();
|
||||
if(cm) {
|
||||
cm.alphaTo(0.9);
|
||||
allVariables["--background-primary"] = cm.stringHEX();
|
||||
}
|
||||
return Object.entries(allVariables)
|
||||
.map(([key, value]) => `${key}: ${value} !important;`)
|
||||
.join(" ");
|
||||
|
||||
+357
-199
@@ -25,7 +25,11 @@ import {
|
||||
} from "src/utils/fileUtils";
|
||||
import { PENS } from "src/utils/pens";
|
||||
import { addYouTubeThumbnail, fragWithHTML } from "src/utils/utils";
|
||||
import { setElementIconAndText, setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import {
|
||||
setElementHidden,
|
||||
setElementIconAndText,
|
||||
setSanitizedHtml,
|
||||
} from "src/utils/htmlUtils";
|
||||
import { getImageCache } from "src/shared/ImageCache";
|
||||
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
@@ -69,7 +73,15 @@ import { decryptProviderProfiles } from "src/utils/settingsKeyObfuscation";
|
||||
import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
import { getSelectableFontFiles } from "src/utils/fontUtils";
|
||||
import { getSelectableFontOptions } from "src/utils/fontUtils";
|
||||
import { FontPickerComponent } from "src/shared/components/FontPickerComponent";
|
||||
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
|
||||
import { confirmAndCreateFolder } from "src/shared/Dialogs/CreateFolderPrompt";
|
||||
import type {
|
||||
StencilLibraryData,
|
||||
StencilLibraryMigrationStatus,
|
||||
StencilLibraryStorageMode,
|
||||
} from "src/types/stencilLibraryTypes";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare type SettingDefinitionItem = string;
|
||||
@@ -82,6 +94,11 @@ export interface ExcalidrawSettings {
|
||||
phoneFooterSafeAreaPadding: boolean;
|
||||
tabletFooterSafeAreaPadding: boolean;
|
||||
folder: string;
|
||||
libraryFolderPath: string;
|
||||
libraryFileName: string;
|
||||
libraryStorageMode: StencilLibraryStorageMode;
|
||||
libraryMigrationStatus: StencilLibraryMigrationStatus;
|
||||
libraryMigrationSnoozeUntil: number;
|
||||
cropFolder: string;
|
||||
annotateFolder: string;
|
||||
embedUseExcalidrawFolder: boolean;
|
||||
@@ -198,7 +215,7 @@ export interface ExcalidrawSettings {
|
||||
//loadCount: number; //version 1.2 migration counter
|
||||
drawingOpenCount: number;
|
||||
library: string;
|
||||
library2: object;
|
||||
library2: StencilLibraryData;
|
||||
//patchCommentBlock: boolean; //1.3.12
|
||||
imageElementNotice: boolean; //1.4.0
|
||||
//runWYSIWYGpatch: boolean; //1.4.9
|
||||
@@ -568,6 +585,11 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
phoneFooterSafeAreaPadding: false,
|
||||
tabletFooterSafeAreaPadding: false,
|
||||
folder: "Excalidraw",
|
||||
libraryFolderPath: "Excalidraw/Libraries",
|
||||
libraryFileName: "local-library",
|
||||
libraryStorageMode: "vault",
|
||||
libraryMigrationStatus: "not-required",
|
||||
libraryMigrationSnoozeUntil: 0,
|
||||
cropFolder: "",
|
||||
annotateFolder: "",
|
||||
embedUseExcalidrawFolder: false,
|
||||
@@ -700,6 +722,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
markdownImageSettings: {
|
||||
defaults: {
|
||||
width: 500,
|
||||
paddingBottom: 10,
|
||||
fontFamily: "Cascadia",
|
||||
fontColor: "Black",
|
||||
border: {
|
||||
@@ -1124,11 +1147,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private requestReloadDrawings: boolean = false;
|
||||
private requestUpdatePinnedPens: boolean = false;
|
||||
private requestUpdateDynamicStyling: boolean = false;
|
||||
private settingsDirty: boolean = false;
|
||||
private settingsRevision: number = 0;
|
||||
private isPersistingSettings: boolean = false;
|
||||
private settingsFocusoutHandler: ((event: FocusEvent) => void) | null = null;
|
||||
private settingsPersistenceChain: Promise<void> = Promise.resolve();
|
||||
private hotkeyEditor: HotkeyEditor;
|
||||
private fontPickers: FontPickerComponent[] = [];
|
||||
//private reloadMathJax: boolean = false;
|
||||
//private applyDebounceTimer: number = 0;
|
||||
|
||||
@@ -1137,6 +1158,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
private destroyFontPickers(): void {
|
||||
for (const picker of this.fontPickers) {
|
||||
picker.destroy();
|
||||
}
|
||||
this.fontPickers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the existing imperative settings UI while declaring support for the
|
||||
* settings definitions API.
|
||||
@@ -1151,11 +1179,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
return [];
|
||||
}
|
||||
|
||||
private markSettingsDirty() {
|
||||
this.settingsDirty = true;
|
||||
this.settingsRevision += 1;
|
||||
}
|
||||
|
||||
private normalizeSettingsBeforeSave() {
|
||||
this.plugin.settings.scriptFolderPath = normalizePath(
|
||||
this.plugin.settings.scriptFolderPath,
|
||||
@@ -1166,72 +1189,92 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
) {
|
||||
this.plugin.settings.scriptFolderPath = "Excalidraw/Scripts";
|
||||
}
|
||||
this.plugin.settings.libraryFolderPath = normalizePath(
|
||||
this.plugin.settings.libraryFolderPath ||
|
||||
`${this.plugin.settings.folder}/Libraries`,
|
||||
);
|
||||
this.plugin.settings.libraryFileName =
|
||||
this.plugin.settings.libraryFileName
|
||||
.trim()
|
||||
.replace(/[\\/]/g, "-")
|
||||
.replace(/\.excalidrawlib$/i, "") || "local-library";
|
||||
}
|
||||
|
||||
private async persistDirtySettings() {
|
||||
if (!this.settingsDirty || this.isPersistingSettings) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isPersistingSettings = true;
|
||||
try {
|
||||
while (this.settingsDirty) {
|
||||
const revisionToSave = this.settingsRevision;
|
||||
this.normalizeSettingsBeforeSave();
|
||||
await this.plugin.saveSettings();
|
||||
if (this.settingsRevision === revisionToSave) {
|
||||
this.settingsDirty = false;
|
||||
}
|
||||
private addVaultPathSupport(
|
||||
setting: Setting,
|
||||
text: TextComponent,
|
||||
kind: "file" | "folder",
|
||||
options: {
|
||||
optional?: boolean;
|
||||
extensions?: readonly string[];
|
||||
resolvePath?: (value: string) => string;
|
||||
createFolder?: boolean;
|
||||
validate?: boolean;
|
||||
} = {},
|
||||
): void {
|
||||
new VaultPathSuggest(this.app, text.inputEl, kind, options.extensions);
|
||||
let createFolderButtonEl: HTMLButtonElement | null = null;
|
||||
const updateWarning = () => {
|
||||
setting.descEl
|
||||
.querySelectorAll(".excalidraw-path-warning")
|
||||
.forEach((element) => element.remove());
|
||||
setting.settingEl.removeClass("mod-warning", "mod_warning");
|
||||
const value = text.getValue().trim();
|
||||
const resolvedValue = options.resolvePath?.(value) ?? value;
|
||||
const path = resolvedValue ? normalizePath(resolvedValue) : "";
|
||||
const exists = path
|
||||
? kind === "folder"
|
||||
? Boolean(this.app.vault.getFolderByPath(path))
|
||||
: Boolean(this.app.vault.getFileByPath(path))
|
||||
: false;
|
||||
if (createFolderButtonEl) {
|
||||
setElementHidden(
|
||||
createFolderButtonEl,
|
||||
kind !== "folder" || !value || exists,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
this.isPersistingSettings = false;
|
||||
}
|
||||
}
|
||||
|
||||
private detachSettingsFocusoutHandler() {
|
||||
if (!this.settingsFocusoutHandler) {
|
||||
return;
|
||||
}
|
||||
this.containerEl.removeEventListener(
|
||||
"focusout",
|
||||
this.settingsFocusoutHandler,
|
||||
);
|
||||
this.settingsFocusoutHandler = null;
|
||||
}
|
||||
|
||||
private hasPendingActions(): boolean {
|
||||
return (
|
||||
this.requestUpdatePinnedPens ||
|
||||
this.requestUpdateDynamicStyling ||
|
||||
this.requestReloadDrawings ||
|
||||
this.requestEmbedUpdate
|
||||
);
|
||||
}
|
||||
|
||||
private attachSettingsFocusoutHandler() {
|
||||
this.detachSettingsFocusoutHandler();
|
||||
this.settingsFocusoutHandler = (event: FocusEvent) => {
|
||||
window.setTimeout(() => {
|
||||
if (!this.containerEl?.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextFocusTarget =
|
||||
(event.relatedTarget as Node | null) ??
|
||||
this.containerEl.ownerDocument.activeElement;
|
||||
if (nextFocusTarget && this.containerEl.contains(nextFocusTarget)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute pending actions if settings are dirty or if there are pending actions
|
||||
if (this.settingsDirty || this.hasPendingActions()) {
|
||||
void this.persistDirtySettings().then(() =>
|
||||
this.applyPendingActions(),
|
||||
);
|
||||
}
|
||||
}, 0);
|
||||
if ((!value && options.optional) || options.validate === false) {
|
||||
return;
|
||||
}
|
||||
if (exists) {
|
||||
return;
|
||||
}
|
||||
setting.settingEl.addClass("mod-warning", "mod_warning");
|
||||
setting.descEl.createDiv({
|
||||
cls: "excalidraw-path-warning mod-warning",
|
||||
text: t("LIBRARY_PATH_MISSING"),
|
||||
});
|
||||
};
|
||||
this.containerEl.addEventListener("focusout", this.settingsFocusoutHandler);
|
||||
if (kind === "folder" && options.createFolder !== false) {
|
||||
setting.addButton((button) => {
|
||||
createFolderButtonEl = button.buttonEl;
|
||||
setElementHidden(button.buttonEl, true);
|
||||
button.setButtonText(t("CREATE_FOLDER")).onClick(async () => {
|
||||
if (await confirmAndCreateFolder(this.plugin, text.getValue())) {
|
||||
updateWarning();
|
||||
}
|
||||
});
|
||||
});
|
||||
setting.controlEl.addClass("excalidraw-folder-path-control");
|
||||
const createFolderRow = setting.controlEl.createDiv({
|
||||
cls: "excalidraw-folder-create-row",
|
||||
});
|
||||
createFolderRow.appendChild(createFolderButtonEl);
|
||||
}
|
||||
text.inputEl.addEventListener("input", updateWarning);
|
||||
updateWarning();
|
||||
}
|
||||
|
||||
private persistSettingsAndApplyPendingActions() {
|
||||
const persistAndApply = async () => {
|
||||
this.normalizeSettingsBeforeSave();
|
||||
await this.plugin.saveSettings();
|
||||
await this.applyPendingActions();
|
||||
};
|
||||
// Keep queuing updates even if an earlier save failed.
|
||||
this.settingsPersistenceChain = this.settingsPersistenceChain
|
||||
.catch((): void => undefined)
|
||||
.then(persistAndApply);
|
||||
}
|
||||
|
||||
private async applyPendingActions() {
|
||||
@@ -1269,14 +1312,14 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
applySettingsUpdate(requestReloadDrawings: boolean = false) {
|
||||
this.markSettingsDirty();
|
||||
if (requestReloadDrawings) {
|
||||
this.requestReloadDrawings = true;
|
||||
}
|
||||
this.persistSettingsAndApplyPendingActions();
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.detachSettingsFocusoutHandler();
|
||||
this.destroyFontPickers();
|
||||
if (this.plugin.settings.overrideObsidianFontSize) {
|
||||
setStyle(mainDocument.documentElement, { fontSize: "" });
|
||||
setRootElementSize(16);
|
||||
@@ -1289,15 +1332,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
setRootElementSize();
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
void (await this.persistDirtySettings());
|
||||
void (await this.applyPendingActions());
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
})();
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
/* if(this.reloadMathJax) {
|
||||
this.plugin.loadMathJax();
|
||||
}*/
|
||||
@@ -1307,13 +1346,12 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
let detailsEl: HTMLElement;
|
||||
|
||||
//await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
|
||||
this.settingsDirty = false;
|
||||
this.requestEmbedUpdate = false;
|
||||
this.requestReloadDrawings = false;
|
||||
this.destroyFontPickers();
|
||||
const { containerEl } = this;
|
||||
containerEl.addClass("excalidraw-settings");
|
||||
this.containerEl.empty();
|
||||
this.attachSettingsFocusoutHandler();
|
||||
|
||||
// ------------------------------------------------
|
||||
// Search and Settings to Clipboard
|
||||
@@ -1542,18 +1580,111 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const drawingFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("FOLDER_DESC")))
|
||||
.setDesc(fragWithHTML(t("FOLDER_DESC")));
|
||||
drawingFolderSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.folder)
|
||||
.onChange(async (value) => {
|
||||
const previousFolder = this.plugin.settings.folder;
|
||||
this.plugin.settings.folder = value;
|
||||
if (
|
||||
this.plugin.settings.libraryFolderPath ===
|
||||
normalizePath(`${previousFolder}/Libraries`)
|
||||
) {
|
||||
this.plugin.settings.libraryFolderPath = normalizePath(
|
||||
`${value}/Libraries`,
|
||||
);
|
||||
}
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(drawingFolderSetting, text, "folder");
|
||||
});
|
||||
|
||||
const libraryStorageSetting = new Setting(detailsEl)
|
||||
.setName(t("LIBRARY_STORAGE_NAME"))
|
||||
.setDesc(t("LIBRARY_STORAGE_DESC"));
|
||||
libraryStorageSetting.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("vault", t("LIBRARY_STORAGE_VAULT"))
|
||||
.addOption("data-json", t("LIBRARY_STORAGE_DATA_JSON"))
|
||||
.setValue(this.plugin.settings.libraryStorageMode)
|
||||
.onChange(async (value) => {
|
||||
if (value === this.plugin.settings.libraryStorageMode) {
|
||||
return;
|
||||
}
|
||||
if (value === "data-json") {
|
||||
await this.plugin.stencilLibraryManager.switchToLegacyStorage();
|
||||
} else if (this.plugin.stencilLibraryManager.hasLegacyItems()) {
|
||||
await this.plugin.stencilLibraryManager.showMigrationPrompt();
|
||||
} else {
|
||||
this.plugin.settings.libraryStorageMode = "vault";
|
||||
this.plugin.settings.libraryMigrationStatus = "completed";
|
||||
this.plugin.settings.libraryMigrationSnoozeUntil = 0;
|
||||
this.plugin.stencilLibraryManager.invalidate();
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
|
||||
const libraryFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("LIBRARY_FOLDER_NAME"))
|
||||
.setDesc(t("LIBRARY_FOLDER_DESC"));
|
||||
libraryFolderSetting.addText((text) => {
|
||||
text
|
||||
.setValue(this.plugin.settings.libraryFolderPath)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.libraryFolderPath = value;
|
||||
this.plugin.stencilLibraryManager.invalidate();
|
||||
this.applySettingsUpdate(true);
|
||||
});
|
||||
this.addVaultPathSupport(libraryFolderSetting, text, "folder", {
|
||||
optional: this.plugin.settings.libraryStorageMode === "data-json",
|
||||
createFolder: this.plugin.settings.libraryStorageMode === "vault",
|
||||
validate: this.plugin.settings.libraryStorageMode === "vault",
|
||||
});
|
||||
});
|
||||
libraryFolderSetting.setDisabled(
|
||||
this.plugin.settings.libraryStorageMode === "data-json",
|
||||
);
|
||||
|
||||
const libraryFileSetting = new Setting(detailsEl)
|
||||
.setName(t("LIBRARY_FILE_NAME"))
|
||||
.setDesc(t("LIBRARY_FILE_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.folder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.folder = value;
|
||||
this.applySettingsUpdate();
|
||||
.setValue(this.plugin.settings.libraryFileName)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.libraryFileName = value;
|
||||
this.plugin.stencilLibraryManager.invalidate();
|
||||
this.applySettingsUpdate(true);
|
||||
}),
|
||||
);
|
||||
libraryFileSetting.setDisabled(
|
||||
this.plugin.settings.libraryStorageMode === "data-json",
|
||||
);
|
||||
|
||||
if (
|
||||
this.plugin.settings.libraryStorageMode === "data-json" &&
|
||||
this.plugin.settings.libraryMigrationStatus !== "opted-out" &&
|
||||
this.plugin.stencilLibraryManager.hasLegacyItems()
|
||||
) {
|
||||
new Setting(detailsEl)
|
||||
.setName(t("LIBRARY_MIGRATE_NOW"))
|
||||
.setDesc(t("LIBRARY_MIGRATE_NOW_DESC"))
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setCta()
|
||||
.setButtonText(t("LIBRARY_MIGRATION_MIGRATE"))
|
||||
.onClick(async () => {
|
||||
await this.plugin.stencilLibraryManager.showMigrationPrompt();
|
||||
this.display();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("FOLDER_EMBED_NAME"))
|
||||
@@ -1567,58 +1698,69 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const cropFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("CROP_FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("CROP_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("CROP_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.cropFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropFolder = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("CROP_FOLDER_DESC")));
|
||||
cropFolderSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("CROP_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.cropFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropFolder = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(cropFolderSetting, text, "folder", {
|
||||
optional: true,
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
const annotateFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("ANNOTATE_FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.annotateFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotateFolder = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC")));
|
||||
annotateFolderSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.annotateFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotateFolder = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(annotateFolderSetting, text, "folder", {
|
||||
optional: true,
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
const templateFileSetting = new Setting(detailsEl)
|
||||
.setName(t("TEMPLATE_NAME"))
|
||||
.setDesc(fragWithHTML(t("TEMPLATE_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("TEMPLATE_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.templateFilePath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.templateFilePath = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("TEMPLATE_DESC")));
|
||||
templateFileSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("TEMPLATE_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.templateFilePath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.templateFilePath = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(templateFileSetting, text, "file", {
|
||||
optional: true,
|
||||
extensions: ["md", "excalidraw"],
|
||||
});
|
||||
});
|
||||
addYouTubeThumbnail(detailsEl, "jgUpYznHP9A", 216);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const scriptFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("SCRIPT_FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.scriptFolderPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.scriptFolderPath = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC")));
|
||||
scriptFolderSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.scriptFolderPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.scriptFolderPath = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(scriptFolderSetting, text, "folder");
|
||||
});
|
||||
|
||||
// ------------------------------------------------
|
||||
// Saving
|
||||
@@ -4008,28 +4150,27 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const markdownFontSetting = new Setting(detailsEl)
|
||||
.setName(t("MD_DEFAULT_FONT_NAME"))
|
||||
.setDesc(fragWithHTML(t("MD_DEFAULT_FONT_DESC")))
|
||||
.addDropdown((d: DropdownComponent) => {
|
||||
//I do not know why Lilita One and Nunito do not work. The font string is there, but it is not rendered
|
||||
d.addOption("Virgil", "Virgil");
|
||||
d.addOption("Cascadia", "Cascadia");
|
||||
d.addOption("Excalifont", "Excalifont");
|
||||
d.addOption("Comic Shanns", "Comic Shanns");
|
||||
d.addOption("Liberation Sans", "Liberation Sans");
|
||||
getSelectableFontFiles(
|
||||
this.app,
|
||||
this.plugin.settings.fontAssetsPath,
|
||||
).forEach((file) => {
|
||||
d.addOption(file.path, file.name);
|
||||
});
|
||||
d.setValue(this.plugin.settings.mdFont).onChange((value) => {
|
||||
.setDesc(fragWithHTML(t("MD_DEFAULT_FONT_DESC")));
|
||||
this.fontPickers.push(
|
||||
new FontPickerComponent(
|
||||
markdownFontSetting.controlEl,
|
||||
this.app,
|
||||
() =>
|
||||
getSelectableFontOptions(
|
||||
this.app,
|
||||
this.plugin.settings.fontAssetsPath,
|
||||
),
|
||||
)
|
||||
.setAriaLabel(t("MD_DEFAULT_FONT_NAME"))
|
||||
.setValue(this.plugin.settings.mdFont)
|
||||
.onChange((value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
this.plugin.settings.mdFont = value;
|
||||
this.applySettingsUpdate(true);
|
||||
});
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("MD_DEFAULT_COLOR_NAME"))
|
||||
@@ -4175,26 +4316,29 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const fourthFontSetting = new Setting(detailsEl)
|
||||
.setName(t("FOURTH_FONT_NAME"))
|
||||
.setDesc(fragWithHTML(t("FOURTH_FONT_DESC")))
|
||||
.addDropdown((d: DropdownComponent) => {
|
||||
d.addOption("Virgil", "Virgil");
|
||||
getSelectableFontFiles(
|
||||
this.app,
|
||||
this.plugin.settings.fontAssetsPath,
|
||||
).forEach((file) => {
|
||||
d.addOption(file.path, file.name);
|
||||
});
|
||||
d.setValue(this.plugin.settings.experimantalFourthFont).onChange(
|
||||
(value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
this.plugin.settings.experimantalFourthFont = value;
|
||||
this.applySettingsUpdate(true);
|
||||
void this.plugin.initializeFonts();
|
||||
},
|
||||
);
|
||||
});
|
||||
.setDesc(fragWithHTML(t("FOURTH_FONT_DESC")));
|
||||
this.fontPickers.push(
|
||||
new FontPickerComponent(
|
||||
fourthFontSetting.controlEl,
|
||||
this.app,
|
||||
() =>
|
||||
getSelectableFontOptions(
|
||||
this.app,
|
||||
this.plugin.settings.fontAssetsPath,
|
||||
["Virgil"],
|
||||
),
|
||||
)
|
||||
.setAriaLabel(t("FOURTH_FONT_NAME"))
|
||||
.setValue(this.plugin.settings.experimantalFourthFont)
|
||||
.onChange((value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
this.plugin.settings.experimantalFourthFont = value;
|
||||
this.applySettingsUpdate(true);
|
||||
void this.plugin.initializeFonts();
|
||||
}),
|
||||
);
|
||||
|
||||
detailsEl = fontsDetailsEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
@@ -4205,18 +4349,21 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
const cjkdescdiv = detailsEl.createDiv({ cls: "setting-item-description" });
|
||||
setSanitizedHtml(cjkdescdiv, t("OFFLINE_CJK_DESC"));
|
||||
|
||||
new Setting(detailsEl)
|
||||
const cjkAssetsFolderSetting = new Setting(detailsEl)
|
||||
.setName(t("CJK_ASSETS_FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.fontAssetsPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.fontAssetsPath = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC")));
|
||||
cjkAssetsFolderSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.fontAssetsPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.fontAssetsPath = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(cjkAssetsFolderSetting, text, "folder", {
|
||||
optional: true,
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("LOAD_CHINESE_FONTS_NAME"))
|
||||
@@ -4279,18 +4426,22 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
const latexPreambleSetting = new Setting(detailsEl)
|
||||
.setName(t("LATEX_PREAMBLE_NAME"))
|
||||
.setDesc(fragWithHTML(t("LATEX_PREAMBLE_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: preamble.sty")
|
||||
.setValue(this.plugin.settings.latexPreambleLocation)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.latexPreambleLocation = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
.setDesc(fragWithHTML(t("LATEX_PREAMBLE_DESC")));
|
||||
latexPreambleSetting.addText((text) => {
|
||||
text
|
||||
.setPlaceholder("e.g.: preamble.sty")
|
||||
.setValue(this.plugin.settings.latexPreambleLocation)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.latexPreambleLocation = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(latexPreambleSetting, text, "file", {
|
||||
optional: true,
|
||||
extensions: ["sty"],
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("FILETYPE_NAME"))
|
||||
@@ -4466,9 +4617,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
return Boolean(this.app.vault.getAbstractFileByPath(startupPath));
|
||||
};
|
||||
new Setting(detailsEl)
|
||||
const startupScriptSetting = new Setting(detailsEl)
|
||||
.setName(t("STARTUP_SCRIPT_NAME"))
|
||||
.setDesc(fragWithHTML(t("STARTUP_SCRIPT_DESC")))
|
||||
.setDesc(fragWithHTML(t("STARTUP_SCRIPT_DESC")));
|
||||
startupScriptSetting
|
||||
.addText((text) => {
|
||||
startupScriptPathText = text;
|
||||
text
|
||||
@@ -4482,6 +4634,12 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
this.addVaultPathSupport(startupScriptSetting, text, "file", {
|
||||
optional: true,
|
||||
extensions: ["md"],
|
||||
resolvePath: (value) =>
|
||||
value && !value.endsWith(".md") ? `${value}.md` : value,
|
||||
});
|
||||
})
|
||||
.addButton((button) => {
|
||||
startupScriptButton = button;
|
||||
|
||||
+51
-11
@@ -44,6 +44,41 @@ export default {
|
||||
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
|
||||
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (Logseq compatibility)",
|
||||
DOWNLOAD_LIBRARY: "Export stencil library as an *.excalidrawlib file",
|
||||
LIBRARY_MIGRATION_TITLE: "Move your Excalidraw library into the vault",
|
||||
LIBRARY_MIGRATION_DESC:
|
||||
"Excalidraw can store your library in a dedicated vault file instead of data.json. This keeps plugin settings smaller and makes saving more stable. Your existing items will be merged into the selected local library file; downloaded *.excalidrawlib files placed in the same folder will also be loaded. Choose Later to hide this message until tomorrow.",
|
||||
LIBRARY_MIGRATION_SYNC_WARNING:
|
||||
'To sync library files with Obsidian Sync, enable "Sync all other types" in Obsidian Sync settings.',
|
||||
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Keep using data.json",
|
||||
LIBRARY_MIGRATION_LATER: "Later",
|
||||
LIBRARY_MIGRATION_MIGRATE: "Move library",
|
||||
LIBRARY_MIGRATION_SUCCESS: "Excalidraw library moved into the vault.",
|
||||
LIBRARY_MIGRATION_FAILED:
|
||||
"The library could not be moved. Your original data.json library was kept unchanged.",
|
||||
LIBRARY_FILE_READ_ERROR: "Could not read Excalidraw library file: {PATH}",
|
||||
LIBRARY_STORAGE_NAME: "Library storage",
|
||||
LIBRARY_STORAGE_DESC:
|
||||
"Vault files provide more stable saving because the stencil library is kept out of data.json.",
|
||||
LIBRARY_STORAGE_VAULT: "Vault folder (recommended)",
|
||||
LIBRARY_STORAGE_DATA_JSON: "Plugin data.json (legacy)",
|
||||
LIBRARY_FOLDER_NAME: "Library folder",
|
||||
LIBRARY_FOLDER_DESC:
|
||||
'Folder for local-library.excalidrawlib and downloaded library files. Library files use the .excalidrawlib extension. To see them in Obsidian\'s file explorer, enable "Show all file types" in Obsidian settings.',
|
||||
LIBRARY_FILE_NAME: "Local library file name",
|
||||
LIBRARY_FILE_DESC:
|
||||
"Name of the editable local library file. The .excalidrawlib extension is added automatically.",
|
||||
LIBRARY_MIGRATE_NOW: "Move library now",
|
||||
LIBRARY_MIGRATE_NOW_DESC:
|
||||
"Move the existing data.json library into the configured vault file.",
|
||||
LIBRARY_PATH_MISSING: "This path does not currently exist in the vault.",
|
||||
CREATE_FOLDER: "Create folder",
|
||||
CREATE_FOLDER_CONFIRM: "Do you want to create the folder <b>{PATH}</b>?",
|
||||
CREATE_FOLDER_NEVER_MIND: "Never mind",
|
||||
CREATE_FOLDER_YES: "Yes",
|
||||
CREATE_FOLDER_SUCCESS: "Created folder: {PATH}",
|
||||
CREATE_FOLDER_FAILED: "Could not create folder: {PATH}",
|
||||
CREATE_FOLDER_PATH_IS_FILE:
|
||||
"The folder cannot be created because a file already exists at: {PATH}",
|
||||
OPEN_SIDEPANEL: "Open Excalidraw Sidepanel",
|
||||
OPEN_EXISTING_NEW_PANE: "Open existing drawing - IN A NEW PANE",
|
||||
OPEN_EXISTING_ACTIVE_PANE:
|
||||
@@ -102,26 +137,26 @@ export default {
|
||||
MARKDOWN_IMAGE_APPEARANCE: "Appearance",
|
||||
MARKDOWN_IMAGE_WIDTH: "Width",
|
||||
MARKDOWN_IMAGE_WIDTH_DESC: "Markdown flow width in canvas units",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING: "Bottom padding",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
|
||||
"Extra space below the rendered Markdown, in pixels",
|
||||
MARKDOWN_IMAGE_FONT: "Font",
|
||||
MARKDOWN_IMAGE_FONT_COLOR: "Font color",
|
||||
MARKDOWN_IMAGE_BORDER: "Border",
|
||||
MARKDOWN_IMAGE_BORDER_COLOR: "Border color",
|
||||
MARKDOWN_IMAGE_CSS: "CSS",
|
||||
MARKDOWN_IMAGE_CSS_DESC: "CSS rules applied only to this Markdown image.",
|
||||
MARKDOWN_IMAGE_CSS_DESC:
|
||||
"CSS for this Markdown image only. Copy the SVG below and ask your preferred LLM for the CSS you need.",
|
||||
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
|
||||
"If a rule has no effect, add !important to the declaration.",
|
||||
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
|
||||
"To inspect the generated markup, open Developer Console ({shortcut}) and run the command available from the copy button.",
|
||||
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
|
||||
"On desktop, you can inspect the generated markup in Developer Console and run the command available from the copy button.",
|
||||
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "CSS editor for this Markdown image",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
|
||||
"CSS editor for transcluded Markdown",
|
||||
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
|
||||
"Insert a commented CSS boilerplate",
|
||||
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
|
||||
"Copy the generated Markdown SVG console command",
|
||||
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Console command copied",
|
||||
MARKDOWN_IMAGE_COPY_SVG: "Copy the current Markdown image SVG",
|
||||
MARKDOWN_IMAGE_SVG_COPIED: "Markdown image SVG copied",
|
||||
MARKDOWN_IMAGE_SVG_COPY_ERROR: "Could not copy the Markdown image SVG",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
|
||||
"Use a different style for transclusions",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
|
||||
@@ -154,7 +189,10 @@ export default {
|
||||
"Could not change the Markdown image source",
|
||||
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Could not create a local Markdown copy",
|
||||
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extract Markdown image to note",
|
||||
MARKDOWN_IMAGE_EXTRACT_PATH: "Path to the new Markdown note",
|
||||
FILE_AND_FOLDER_SELECTOR_FOLDER: "Folder",
|
||||
FILE_AND_FOLDER_SELECTOR_FILENAME: "File name",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Export to Vault",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT: "Export",
|
||||
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown image.md",
|
||||
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Could not create Markdown note",
|
||||
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Unknown error",
|
||||
@@ -176,6 +214,10 @@ export default {
|
||||
"A local Markdown image can contain only one level 1 heading when converted to an embeddable. It must be the first content and its name must be unique in the drawing.",
|
||||
MARKDOWN_IMAGE_SECTION_NAME: "Name the back-of-note section",
|
||||
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "Enter a unique section name",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
|
||||
"Delete the Markdown text stored for this image? The image will be removed from the scene either way.",
|
||||
MARKDOWN_IMAGE_KEEP_TEXT: "Keep Markdown text",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT: "Delete Markdown text",
|
||||
INSERT_PDF: "Insert PDF file from vault",
|
||||
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert last active PDF page as image",
|
||||
UNIVERSAL_ADD_FILE: "Insert ANY file",
|
||||
@@ -252,8 +294,6 @@ export default {
|
||||
"Inverted Mode: Default arrow binding is now disabled. Use CTRL/CMD to temporarily enable binding when needed.",
|
||||
ARROW_BINDING_NORMAL_MODE:
|
||||
"Normal Mode: Arrow binding is now enabled. Use CTRL/CMD to temporarily disable binding when needed.",
|
||||
EXPORT_FILENAME_PROMPT: "Please provide filename",
|
||||
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "filename, leave blank to cancel action",
|
||||
WARNING_SERIOUS_ERROR:
|
||||
"WARNING: Excalidraw ran into an unknown problem!\n\n" +
|
||||
"There is a risk that your most recent changes cannot be saved.\n\n" +
|
||||
|
||||
+52
-12
@@ -44,6 +44,41 @@ export default {
|
||||
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (compatibilidad con Logseq)",
|
||||
DOWNLOAD_LIBRARY:
|
||||
"Exportar librería de plantillas como archivo *.excalidrawlib",
|
||||
LIBRARY_MIGRATION_TITLE: "Mover la biblioteca de Excalidraw a la bóveda",
|
||||
LIBRARY_MIGRATION_DESC:
|
||||
"Excalidraw puede guardar la biblioteca en un archivo de la bóveda en lugar de data.json. Esto hace más estable el guardado. Los elementos existentes se combinarán con el archivo local seleccionado y también se cargarán los archivos *.excalidrawlib copiados en la misma carpeta. Elige «Más tarde» para ocultar este mensaje hasta mañana.",
|
||||
LIBRARY_MIGRATION_SYNC_WARNING:
|
||||
'Para sincronizar las bibliotecas con Obsidian Sync, activa "Sincronizar todos los demás tipos" en los ajustes de Sync.',
|
||||
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Seguir usando data.json",
|
||||
LIBRARY_MIGRATION_LATER: "Más tarde",
|
||||
LIBRARY_MIGRATION_MIGRATE: "Mover biblioteca",
|
||||
LIBRARY_MIGRATION_SUCCESS: "La biblioteca de Excalidraw se movió a la bóveda.",
|
||||
LIBRARY_MIGRATION_FAILED:
|
||||
"No se pudo mover la biblioteca. La biblioteca original de data.json no se modificó.",
|
||||
LIBRARY_FILE_READ_ERROR: "No se pudo leer la biblioteca: {PATH}",
|
||||
LIBRARY_STORAGE_NAME: "Almacenamiento de la biblioteca",
|
||||
LIBRARY_STORAGE_DESC:
|
||||
"Los archivos de la bóveda ofrecen un guardado más estable al mantener la biblioteca fuera de data.json.",
|
||||
LIBRARY_STORAGE_VAULT: "Carpeta de la bóveda (recomendado)",
|
||||
LIBRARY_STORAGE_DATA_JSON: "data.json del complemento (heredado)",
|
||||
LIBRARY_FOLDER_NAME: "Carpeta de bibliotecas",
|
||||
LIBRARY_FOLDER_DESC:
|
||||
"Carpeta para la biblioteca local y los archivos descargados. Los archivos de biblioteca usan la extensión .excalidrawlib. Para verlos en el explorador de archivos de Obsidian, activa «Mostrar todos los tipos de archivo» en los ajustes de Obsidian.",
|
||||
LIBRARY_FILE_NAME: "Nombre del archivo de biblioteca local",
|
||||
LIBRARY_FILE_DESC:
|
||||
"Nombre de la biblioteca local editable. La extensión se añade automáticamente.",
|
||||
LIBRARY_MIGRATE_NOW: "Mover la biblioteca ahora",
|
||||
LIBRARY_MIGRATE_NOW_DESC:
|
||||
"Mover la biblioteca existente de data.json al archivo configurado en la bóveda.",
|
||||
LIBRARY_PATH_MISSING: "Esta ruta no existe actualmente en la bóveda.",
|
||||
CREATE_FOLDER: "Crear carpeta",
|
||||
CREATE_FOLDER_CONFIRM: "¿Quieres crear la carpeta <b>{PATH}</b>?",
|
||||
CREATE_FOLDER_NEVER_MIND: "No importa",
|
||||
CREATE_FOLDER_YES: "Sí",
|
||||
CREATE_FOLDER_SUCCESS: "Carpeta creada: {PATH}",
|
||||
CREATE_FOLDER_FAILED: "No se pudo crear la carpeta: {PATH}",
|
||||
CREATE_FOLDER_PATH_IS_FILE:
|
||||
"No se puede crear la carpeta porque ya existe un archivo en: {PATH}",
|
||||
OPEN_EXISTING_NEW_PANE: "Abrir bosquejo existente - EN UN PANEL NUEVO",
|
||||
OPEN_EXISTING_ACTIVE_PANE:
|
||||
"Abrir bosquejo existente - EN EL PANEL ACTIVO ACTUAL",
|
||||
@@ -103,26 +138,27 @@ export default {
|
||||
MARKDOWN_IMAGE_APPEARANCE: "Apariencia",
|
||||
MARKDOWN_IMAGE_WIDTH: "Ancho",
|
||||
MARKDOWN_IMAGE_WIDTH_DESC: "Ancho del flujo Markdown en unidades del lienzo",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING: "Relleno inferior",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
|
||||
"Espacio adicional debajo del Markdown renderizado, en píxeles",
|
||||
MARKDOWN_IMAGE_FONT: "Fuente",
|
||||
MARKDOWN_IMAGE_FONT_COLOR: "Color de fuente",
|
||||
MARKDOWN_IMAGE_BORDER: "Borde",
|
||||
MARKDOWN_IMAGE_BORDER_COLOR: "Color del borde",
|
||||
MARKDOWN_IMAGE_CSS: "CSS",
|
||||
MARKDOWN_IMAGE_CSS_DESC: "Reglas CSS aplicadas solo a esta imagen Markdown.",
|
||||
MARKDOWN_IMAGE_CSS_DESC:
|
||||
"CSS solo para esta imagen Markdown. Copia el SVG de abajo y pide a tu LLM preferido el CSS que necesitas.",
|
||||
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
|
||||
"Si una regla no tiene efecto, añade !important a la declaración.",
|
||||
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
|
||||
"Para inspeccionar el marcado generado, abre la consola de desarrollo ({shortcut}) y ejecuta el comando disponible en el botón de copia.",
|
||||
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
|
||||
"En un equipo de escritorio puedes inspeccionar el marcado generado en la consola de desarrollo y ejecutar el comando disponible en el botón de copia.",
|
||||
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Editor CSS para esta imagen Markdown",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
|
||||
"Editor CSS para Markdown transcluido",
|
||||
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
|
||||
"Insertar una plantilla CSS comentada",
|
||||
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
|
||||
"Copiar el comando de consola del SVG Markdown generado",
|
||||
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Comando de consola copiado",
|
||||
MARKDOWN_IMAGE_COPY_SVG: "Copiar el SVG de la imagen Markdown actual",
|
||||
MARKDOWN_IMAGE_SVG_COPIED: "SVG de la imagen Markdown copiado",
|
||||
MARKDOWN_IMAGE_SVG_COPY_ERROR:
|
||||
"No se pudo copiar el SVG de la imagen Markdown",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
|
||||
"Usar un estilo diferente para las transclusiones",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
|
||||
@@ -153,7 +189,10 @@ export default {
|
||||
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "No se pudo cambiar la fuente de la imagen Markdown",
|
||||
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "No se pudo crear una copia Markdown local",
|
||||
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extraer imagen Markdown a una nota",
|
||||
MARKDOWN_IMAGE_EXTRACT_PATH: "Ruta de la nueva nota Markdown",
|
||||
FILE_AND_FOLDER_SELECTOR_FOLDER: "Carpeta",
|
||||
FILE_AND_FOLDER_SELECTOR_FILENAME: "Nombre del archivo",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Exportar a la bóveda",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT: "Exportar",
|
||||
MARKDOWN_IMAGE_DEFAULT_NOTE: "Imagen Markdown.md",
|
||||
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "No se pudo crear la nota Markdown",
|
||||
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Error desconocido",
|
||||
@@ -174,6 +213,10 @@ export default {
|
||||
MARKDOWN_IMAGE_SECTION_NAME: "Nombre de la sección al final de la nota",
|
||||
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER:
|
||||
"Introduce un nombre de sección único",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
|
||||
"¿Eliminar el texto Markdown guardado para esta imagen? La imagen se eliminará de la escena en cualquier caso.",
|
||||
MARKDOWN_IMAGE_KEEP_TEXT: "Conservar texto Markdown",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT: "Eliminar texto Markdown",
|
||||
INSERT_PDF: "Insertar archivo PDF desde la bóveda",
|
||||
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE:
|
||||
"Insertar última página PDF activa como imagen",
|
||||
@@ -241,9 +284,6 @@ export default {
|
||||
"Modo Invertido: La vinculación de flechas predeterminada está ahora deshabilitada. Usa CTRL/CMD para habilitar temporalmente la vinculación cuando sea necesario.",
|
||||
ARROW_BINDING_NORMAL_MODE:
|
||||
"Modo Normal: La vinculación de flechas está ahora habilitada. Usa CTRL/CMD para deshabilitar temporalmente la vinculación cuando sea necesario.",
|
||||
EXPORT_FILENAME_PROMPT: "Por favor, ingresa el nombre de archivo",
|
||||
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
|
||||
"nombre de archivo, dejar en blanco para cancelar la acción",
|
||||
WARNING_SERIOUS_ERROR:
|
||||
"ADVERTENCIA: ¡Excalidraw encontró un problema desconocido!\n\n" +
|
||||
"Existe el riesgo de que tus cambios más recientes no se puedan guardar.\n\n" +
|
||||
|
||||
+51
-12
@@ -39,6 +39,41 @@ export default {
|
||||
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
|
||||
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (совместимость с Logseq)",
|
||||
DOWNLOAD_LIBRARY: "Экспорт библиотеки трафаретов в файл *.excalidrawlib",
|
||||
LIBRARY_MIGRATION_TITLE: "Перенести библиотеку Excalidraw в хранилище",
|
||||
LIBRARY_MIGRATION_DESC:
|
||||
"Excalidraw может хранить библиотеку в отдельном файле хранилища вместо data.json. Это делает сохранение стабильнее. Существующие элементы будут объединены с выбранным локальным файлом; файлы *.excalidrawlib в той же папке также будут загружены. Выберите «Позже», чтобы скрыть это сообщение до завтра.",
|
||||
LIBRARY_MIGRATION_SYNC_WARNING:
|
||||
'Для синхронизации файлов библиотеки включите «Синхронизировать все остальные типы» в настройках Obsidian Sync.',
|
||||
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Оставить в data.json",
|
||||
LIBRARY_MIGRATION_LATER: "Позже",
|
||||
LIBRARY_MIGRATION_MIGRATE: "Перенести библиотеку",
|
||||
LIBRARY_MIGRATION_SUCCESS: "Библиотека Excalidraw перенесена в хранилище.",
|
||||
LIBRARY_MIGRATION_FAILED:
|
||||
"Не удалось перенести библиотеку. Исходная библиотека data.json не изменена.",
|
||||
LIBRARY_FILE_READ_ERROR: "Не удалось прочитать файл библиотеки: {PATH}",
|
||||
LIBRARY_STORAGE_NAME: "Хранилище библиотеки",
|
||||
LIBRARY_STORAGE_DESC:
|
||||
"Файлы хранилища делают сохранение стабильнее, поскольку библиотека находится вне data.json.",
|
||||
LIBRARY_STORAGE_VAULT: "Папка хранилища (рекомендуется)",
|
||||
LIBRARY_STORAGE_DATA_JSON: "data.json плагина (устаревшее)",
|
||||
LIBRARY_FOLDER_NAME: "Папка библиотеки",
|
||||
LIBRARY_FOLDER_DESC:
|
||||
"Папка для локальной библиотеки и загруженных файлов. Файлы библиотек имеют расширение .excalidrawlib. Чтобы видеть их в проводнике файлов Obsidian, включите «Показывать все типы файлов» в настройках Obsidian.",
|
||||
LIBRARY_FILE_NAME: "Имя файла локальной библиотеки",
|
||||
LIBRARY_FILE_DESC:
|
||||
"Имя редактируемого файла локальной библиотеки. Расширение добавляется автоматически.",
|
||||
LIBRARY_MIGRATE_NOW: "Перенести библиотеку сейчас",
|
||||
LIBRARY_MIGRATE_NOW_DESC:
|
||||
"Перенести существующую библиотеку data.json в настроенный файл хранилища.",
|
||||
LIBRARY_PATH_MISSING: "Этот путь сейчас не существует в хранилище.",
|
||||
CREATE_FOLDER: "Создать папку",
|
||||
CREATE_FOLDER_CONFIRM: "Создать папку <b>{PATH}</b>?",
|
||||
CREATE_FOLDER_NEVER_MIND: "Не надо",
|
||||
CREATE_FOLDER_YES: "Да",
|
||||
CREATE_FOLDER_SUCCESS: "Папка создана: {PATH}",
|
||||
CREATE_FOLDER_FAILED: "Не удалось создать папку: {PATH}",
|
||||
CREATE_FOLDER_PATH_IS_FILE:
|
||||
"Невозможно создать папку: по этому пути уже существует файл: {PATH}",
|
||||
OPEN_EXISTING_NEW_PANE: "Открыть существующий чертеж - В НОВОЙ ПАНЕЛИ",
|
||||
OPEN_EXISTING_ACTIVE_PANE:
|
||||
"Открыть существующий чертеж - В ТЕКУЩЕЙ АКТИВНОЙ ПАНЕЛИ",
|
||||
@@ -94,27 +129,27 @@ export default {
|
||||
MARKDOWN_IMAGE_APPEARANCE: "Оформление",
|
||||
MARKDOWN_IMAGE_WIDTH: "Ширина",
|
||||
MARKDOWN_IMAGE_WIDTH_DESC: "Ширина потока Markdown в единицах холста",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING: "Нижний отступ",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
|
||||
"Дополнительное пространство под отрисованным Markdown в пикселях",
|
||||
MARKDOWN_IMAGE_FONT: "Шрифт",
|
||||
MARKDOWN_IMAGE_FONT_COLOR: "Цвет шрифта",
|
||||
MARKDOWN_IMAGE_BORDER: "Рамка",
|
||||
MARKDOWN_IMAGE_BORDER_COLOR: "Цвет рамки",
|
||||
MARKDOWN_IMAGE_CSS: "CSS",
|
||||
MARKDOWN_IMAGE_CSS_DESC:
|
||||
"Правила CSS применяются только к этому Markdown-изображению.",
|
||||
"CSS только для этого Markdown-изображения. Скопируйте SVG ниже и попросите предпочитаемую LLM подобрать нужный CSS.",
|
||||
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
|
||||
"Если правило не действует, добавьте !important к объявлению.",
|
||||
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
|
||||
"Чтобы проверить созданную разметку, откройте консоль разработчика ({shortcut}) и выполните команду, доступную по кнопке копирования.",
|
||||
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
|
||||
"На компьютере созданную разметку можно проверить в консоли разработчика и выполнить команду, доступную по кнопке копирования.",
|
||||
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Редактор CSS для этого Markdown-изображения",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
|
||||
"Редактор CSS для встроенного Markdown",
|
||||
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
|
||||
"Вставить шаблон CSS с комментариями",
|
||||
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
|
||||
"Копировать консольную команду для созданного Markdown SVG",
|
||||
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Консольная команда скопирована",
|
||||
MARKDOWN_IMAGE_COPY_SVG: "Копировать SVG текущего Markdown-изображения",
|
||||
MARKDOWN_IMAGE_SVG_COPIED: "SVG Markdown-изображения скопирован",
|
||||
MARKDOWN_IMAGE_SVG_COPY_ERROR:
|
||||
"Не удалось скопировать SVG Markdown-изображения",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
|
||||
"Использовать отдельный стиль для встраиваний",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
|
||||
@@ -145,7 +180,10 @@ export default {
|
||||
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "Не удалось изменить источник Markdown-изображения",
|
||||
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Не удалось создать локальную копию Markdown",
|
||||
MARKDOWN_IMAGE_EXTRACT_TITLE: "Извлечь Markdown-изображение в заметку",
|
||||
MARKDOWN_IMAGE_EXTRACT_PATH: "Путь к новой Markdown-заметке",
|
||||
FILE_AND_FOLDER_SELECTOR_FOLDER: "Папка",
|
||||
FILE_AND_FOLDER_SELECTOR_FILENAME: "Имя файла",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Экспорт в хранилище",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT: "Экспортировать",
|
||||
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown-изображение.md",
|
||||
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Не удалось создать Markdown-заметку",
|
||||
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Неизвестная ошибка",
|
||||
@@ -169,6 +207,10 @@ export default {
|
||||
MARKDOWN_IMAGE_SECTION_NAME: "Название раздела в конце заметки",
|
||||
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER:
|
||||
"Введите уникальное название раздела",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
|
||||
"Удалить текст Markdown, сохранённый для этого изображения? Само изображение будет удалено со сцены в любом случае.",
|
||||
MARKDOWN_IMAGE_KEEP_TEXT: "Сохранить текст Markdown",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT: "Удалить текст Markdown",
|
||||
INSERT_PDF: "Вставить PDF-файл из хранилища",
|
||||
UNIVERSAL_ADD_FILE: "Вставка ЛЮБОГО файла",
|
||||
// Compatibility keys consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
|
||||
@@ -243,9 +285,6 @@ export default {
|
||||
"Инвертированный режим: Привязка стрелок по умолчанию теперь отключена. Используйте CTRL/CMD, чтобы временно включить привязку, когда это необходимо.",
|
||||
ARROW_BINDING_NORMAL_MODE:
|
||||
"Обычный режим: Привязка стрелок теперь включена. Используйте CTRL/CMD, чтобы временно отключить привязку при необходимости.",
|
||||
EXPORT_FILENAME_PROMPT: "Пожалуйста, укажите имя файла",
|
||||
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
|
||||
"имя файла, оставьте пустым, чтобы отменить действие",
|
||||
WARNING_SERIOUS_ERROR:
|
||||
"ПРЕДУПРЕЖДЕНИЕ: Excalidraw столкнулся с неизвестной проблемой!\n\n" +
|
||||
"Есть риск, что последние изменения не будут сохранены.\n\n" +
|
||||
|
||||
+46
-10
@@ -36,6 +36,36 @@ export default {
|
||||
CONVERT_FILE_KEEP_EXT: "转换:*.excalidraw => *.excalidraw.md",
|
||||
CONVERT_FILE_REPLACE_EXT: "转换:*.excalidraw => *.md (兼容 Logseq)",
|
||||
DOWNLOAD_LIBRARY: "导出 stencil 库为 *.excalidrawlib 文件",
|
||||
LIBRARY_MIGRATION_TITLE: "将 Excalidraw 素材库移入仓库",
|
||||
LIBRARY_MIGRATION_DESC:
|
||||
"Excalidraw 可将素材库保存为独立的仓库文件,而不是放在 data.json 中,从而提升保存稳定性。现有素材会与所选本地素材库文件合并;放入同一文件夹的 *.excalidrawlib 文件也会自动加载。选择“稍后”可将此消息隐藏到明天。",
|
||||
LIBRARY_MIGRATION_SYNC_WARNING:
|
||||
"若要通过 Obsidian Sync 同步素材库文件,请在同步设置中启用“同步所有其他文件类型”。",
|
||||
LIBRARY_MIGRATION_KEEP_DATA_JSON: "继续使用 data.json",
|
||||
LIBRARY_MIGRATION_LATER: "稍后",
|
||||
LIBRARY_MIGRATION_MIGRATE: "移动素材库",
|
||||
LIBRARY_MIGRATION_SUCCESS: "Excalidraw 素材库已移入仓库。",
|
||||
LIBRARY_MIGRATION_FAILED: "无法移动素材库。原 data.json 素材库保持不变。",
|
||||
LIBRARY_FILE_READ_ERROR: "无法读取 Excalidraw 素材库文件:{PATH}",
|
||||
LIBRARY_STORAGE_NAME: "素材库存储位置",
|
||||
LIBRARY_STORAGE_DESC: "将素材库移出 data.json 并使用仓库文件可提升保存稳定性。",
|
||||
LIBRARY_STORAGE_VAULT: "仓库文件夹(推荐)",
|
||||
LIBRARY_STORAGE_DATA_JSON: "插件 data.json(旧方式)",
|
||||
LIBRARY_FOLDER_NAME: "素材库文件夹",
|
||||
LIBRARY_FOLDER_DESC:
|
||||
"用于存放本地素材库和下载的素材库文件。素材库文件使用 .excalidrawlib 扩展名。要在 Obsidian 文件列表中查看这些文件,请在 Obsidian 设置中启用“显示所有文件类型”。",
|
||||
LIBRARY_FILE_NAME: "本地素材库文件名",
|
||||
LIBRARY_FILE_DESC: "可编辑本地素材库的名称。扩展名会自动添加。",
|
||||
LIBRARY_MIGRATE_NOW: "立即移动素材库",
|
||||
LIBRARY_MIGRATE_NOW_DESC: "将 data.json 中的现有素材库移到设定的仓库文件。",
|
||||
LIBRARY_PATH_MISSING: "此路径目前不存在于仓库中。",
|
||||
CREATE_FOLDER: "创建文件夹",
|
||||
CREATE_FOLDER_CONFIRM: "是否创建文件夹 <b>{PATH}</b>?",
|
||||
CREATE_FOLDER_NEVER_MIND: "暂不创建",
|
||||
CREATE_FOLDER_YES: "是",
|
||||
CREATE_FOLDER_SUCCESS: "已创建文件夹:{PATH}",
|
||||
CREATE_FOLDER_FAILED: "无法创建文件夹:{PATH}",
|
||||
CREATE_FOLDER_PATH_IS_FILE: "无法创建文件夹,该路径已有文件:{PATH}",
|
||||
OPEN_SIDEPANEL: "打开 Excalidraw 侧边面板",
|
||||
OPEN_EXISTING_NEW_PANE: "打开已有的绘图 - 于新面板",
|
||||
OPEN_EXISTING_ACTIVE_PANE: "打开已有的绘图 - 于当前面板",
|
||||
@@ -87,24 +117,25 @@ export default {
|
||||
MARKDOWN_IMAGE_APPEARANCE: "外观",
|
||||
MARKDOWN_IMAGE_WIDTH: "宽度",
|
||||
MARKDOWN_IMAGE_WIDTH_DESC: "以画布单位表示的 Markdown 排版宽度",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING: "底部内边距",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
|
||||
"渲染后的 Markdown 下方额外空间(像素)",
|
||||
MARKDOWN_IMAGE_FONT: "字体",
|
||||
MARKDOWN_IMAGE_FONT_COLOR: "字体颜色",
|
||||
MARKDOWN_IMAGE_BORDER: "边框",
|
||||
MARKDOWN_IMAGE_BORDER_COLOR: "边框颜色",
|
||||
MARKDOWN_IMAGE_CSS: "CSS",
|
||||
MARKDOWN_IMAGE_CSS_DESC: "仅应用于此 Markdown 图像的 CSS 规则。",
|
||||
MARKDOWN_IMAGE_CSS_DESC:
|
||||
"CSS 仅应用于此 Markdown 图像。复制下方的 SVG,让你选择的 LLM 生成所需的 CSS。",
|
||||
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
|
||||
"如果规则没有效果,请在声明中添加 !important。",
|
||||
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
|
||||
"要检查生成的标记,请打开开发者控制台({shortcut}),然后运行复制按钮提供的命令。",
|
||||
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
|
||||
"在桌面设备上,可在开发者控制台中检查生成的标记,并运行复制按钮提供的命令。",
|
||||
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 图像的 CSS 编辑器",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
|
||||
"嵌入 Markdown 的 CSS 编辑器",
|
||||
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE: "插入带注释的 CSS 模板",
|
||||
MARKDOWN_IMAGE_COPY_CSS_COMMAND: "复制生成的 Markdown SVG 控制台命令",
|
||||
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "控制台命令已复制",
|
||||
MARKDOWN_IMAGE_COPY_SVG: "复制当前 Markdown 图像的 SVG",
|
||||
MARKDOWN_IMAGE_SVG_COPIED: "已复制 Markdown 图像 SVG",
|
||||
MARKDOWN_IMAGE_SVG_COPY_ERROR: "无法复制 Markdown 图像 SVG",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE: "为嵌入内容使用不同样式",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
|
||||
"显示嵌入 Markdown 的独立外观设置。",
|
||||
@@ -132,7 +163,10 @@ export default {
|
||||
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "无法更改 Markdown 图像来源",
|
||||
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "无法创建本地 Markdown 副本",
|
||||
MARKDOWN_IMAGE_EXTRACT_TITLE: "将 Markdown 图像提取到笔记",
|
||||
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 笔记的路径",
|
||||
FILE_AND_FOLDER_SELECTOR_FOLDER: "文件夹",
|
||||
FILE_AND_FOLDER_SELECTOR_FILENAME: "文件名",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "导出到仓库",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT: "导出",
|
||||
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 图像.md",
|
||||
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "无法创建 Markdown 笔记",
|
||||
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知错误",
|
||||
@@ -151,6 +185,10 @@ export default {
|
||||
"本地 Markdown 图像转换为嵌入内容时只能包含一个一级标题。该标题必须是首个内容,且名称在绘图中必须唯一。",
|
||||
MARKDOWN_IMAGE_SECTION_NAME: "命名笔记末尾的章节",
|
||||
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "输入唯一的章节名称",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
|
||||
"是否删除为此图像保存的 Markdown 文本?无论如何,该图像都会从场景中移除。",
|
||||
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文本",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT: "删除 Markdown 文本",
|
||||
INSERT_PDF: "以图像形式嵌入 PDF 到当前绘图中",
|
||||
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以图像形式嵌入最后激活的 PDF 页面",
|
||||
UNIVERSAL_ADD_FILE: "嵌入文件 / Insert ANY file",
|
||||
@@ -219,8 +257,6 @@ export default {
|
||||
"反转模式:默认方向按键已禁用。需要时请使用 Ctrl/CMD 临时启用。",
|
||||
ARROW_BINDING_NORMAL_MODE:
|
||||
"正常模式:方向键已启用。需要时请使用 Ctrl/CMD 临时禁用。",
|
||||
EXPORT_FILENAME_PROMPT: "请提供文件名",
|
||||
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "请输入文件名,留空以取消操作",
|
||||
WARNING_SERIOUS_ERROR:
|
||||
"警告:Excalidraw 遇到了未知的问题!\n\n" +
|
||||
"您最近的更改可能无法保存。\n\n" +
|
||||
|
||||
+46
-10
@@ -36,6 +36,36 @@ export default {
|
||||
CONVERT_FILE_KEEP_EXT: "轉換:*.excalidraw => *.excalidraw.md",
|
||||
CONVERT_FILE_REPLACE_EXT: "轉換:*.excalidraw => *.md (相容 Logseq)",
|
||||
DOWNLOAD_LIBRARY: "匯出 stencil 庫為 *.excalidrawlib 檔案",
|
||||
LIBRARY_MIGRATION_TITLE: "將 Excalidraw 素材庫移入儲存庫",
|
||||
LIBRARY_MIGRATION_DESC:
|
||||
"Excalidraw 可將素材庫儲存為獨立的儲存庫檔案,而不是放在 data.json 中,讓儲存更穩定。現有素材會與所選本機素材庫檔案合併;放入同一資料夾的 *.excalidrawlib 檔案也會載入。選擇「稍後」可將此訊息隱藏到明天。",
|
||||
LIBRARY_MIGRATION_SYNC_WARNING:
|
||||
"若要透過 Obsidian Sync 同步素材庫檔案,請在同步設定中啟用「同步所有其他檔案類型」。",
|
||||
LIBRARY_MIGRATION_KEEP_DATA_JSON: "繼續使用 data.json",
|
||||
LIBRARY_MIGRATION_LATER: "稍後",
|
||||
LIBRARY_MIGRATION_MIGRATE: "移動素材庫",
|
||||
LIBRARY_MIGRATION_SUCCESS: "Excalidraw 素材庫已移入儲存庫。",
|
||||
LIBRARY_MIGRATION_FAILED: "無法移動素材庫。原 data.json 素材庫保持不變。",
|
||||
LIBRARY_FILE_READ_ERROR: "無法讀取 Excalidraw 素材庫檔案:{PATH}",
|
||||
LIBRARY_STORAGE_NAME: "素材庫儲存位置",
|
||||
LIBRARY_STORAGE_DESC: "將素材庫移出 data.json 並使用儲存庫檔案可提升穩定性。",
|
||||
LIBRARY_STORAGE_VAULT: "儲存庫資料夾(建議)",
|
||||
LIBRARY_STORAGE_DATA_JSON: "外掛 data.json(舊方式)",
|
||||
LIBRARY_FOLDER_NAME: "素材庫資料夾",
|
||||
LIBRARY_FOLDER_DESC:
|
||||
"用於存放本機素材庫和下載的素材庫檔案。素材庫檔案使用 .excalidrawlib 副檔名。要在 Obsidian 檔案列表中查看這些檔案,請在 Obsidian 設定中啟用「顯示所有檔案類型」。",
|
||||
LIBRARY_FILE_NAME: "本機素材庫檔名",
|
||||
LIBRARY_FILE_DESC: "可編輯本機素材庫的名稱。副檔名會自動加入。",
|
||||
LIBRARY_MIGRATE_NOW: "立即移動素材庫",
|
||||
LIBRARY_MIGRATE_NOW_DESC: "將 data.json 中的現有素材庫移到設定的儲存庫檔案。",
|
||||
LIBRARY_PATH_MISSING: "此路徑目前不存在於儲存庫中。",
|
||||
CREATE_FOLDER: "建立資料夾",
|
||||
CREATE_FOLDER_CONFIRM: "是否建立資料夾 <b>{PATH}</b>?",
|
||||
CREATE_FOLDER_NEVER_MIND: "暫不建立",
|
||||
CREATE_FOLDER_YES: "是",
|
||||
CREATE_FOLDER_SUCCESS: "已建立資料夾:{PATH}",
|
||||
CREATE_FOLDER_FAILED: "無法建立資料夾:{PATH}",
|
||||
CREATE_FOLDER_PATH_IS_FILE: "無法建立資料夾,該路徑已有檔案:{PATH}",
|
||||
OPEN_SIDEPANEL: "開啟 Excalidraw 側邊面板",
|
||||
OPEN_EXISTING_NEW_PANE: "開啟已有的繪圖 - 於新面板",
|
||||
OPEN_EXISTING_ACTIVE_PANE: "開啟已有的繪圖 - 於當前面板",
|
||||
@@ -87,24 +117,25 @@ export default {
|
||||
MARKDOWN_IMAGE_APPEARANCE: "外觀",
|
||||
MARKDOWN_IMAGE_WIDTH: "寬度",
|
||||
MARKDOWN_IMAGE_WIDTH_DESC: "以畫布單位表示的 Markdown 排版寬度",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING: "底部內距",
|
||||
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
|
||||
"算繪後的 Markdown 下方額外空間(像素)",
|
||||
MARKDOWN_IMAGE_FONT: "字型",
|
||||
MARKDOWN_IMAGE_FONT_COLOR: "字型顏色",
|
||||
MARKDOWN_IMAGE_BORDER: "邊框",
|
||||
MARKDOWN_IMAGE_BORDER_COLOR: "邊框顏色",
|
||||
MARKDOWN_IMAGE_CSS: "CSS",
|
||||
MARKDOWN_IMAGE_CSS_DESC: "僅套用於此 Markdown 圖像的 CSS 規則。",
|
||||
MARKDOWN_IMAGE_CSS_DESC:
|
||||
"CSS 僅套用於此 Markdown 圖像。複製下方的 SVG,讓你選擇的 LLM 產生所需的 CSS。",
|
||||
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
|
||||
"如果規則沒有作用,請在宣告中加入 !important。",
|
||||
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
|
||||
"若要檢查產生的標記,請開啟開發者主控台({shortcut}),然後執行複製按鈕提供的命令。",
|
||||
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
|
||||
"在桌面裝置上,可在開發者主控台中檢查產生的標記,並執行複製按鈕提供的命令。",
|
||||
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 圖像的 CSS 編輯器",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
|
||||
"嵌入 Markdown 的 CSS 編輯器",
|
||||
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE: "插入含註解的 CSS 範本",
|
||||
MARKDOWN_IMAGE_COPY_CSS_COMMAND: "複製產生的 Markdown SVG 主控台命令",
|
||||
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "主控台命令已複製",
|
||||
MARKDOWN_IMAGE_COPY_SVG: "複製目前 Markdown 圖像的 SVG",
|
||||
MARKDOWN_IMAGE_SVG_COPIED: "已複製 Markdown 圖像 SVG",
|
||||
MARKDOWN_IMAGE_SVG_COPY_ERROR: "無法複製 Markdown 圖像 SVG",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE: "為嵌入內容使用不同樣式",
|
||||
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
|
||||
"顯示嵌入 Markdown 的獨立外觀設定。",
|
||||
@@ -132,7 +163,10 @@ export default {
|
||||
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "無法變更 Markdown 圖像來源",
|
||||
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "無法建立本機 Markdown 副本",
|
||||
MARKDOWN_IMAGE_EXTRACT_TITLE: "將 Markdown 圖像擷取到筆記",
|
||||
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 筆記的路徑",
|
||||
FILE_AND_FOLDER_SELECTOR_FOLDER: "資料夾",
|
||||
FILE_AND_FOLDER_SELECTOR_FILENAME: "檔案名稱",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "匯出到儲存庫",
|
||||
FILE_AND_FOLDER_SELECTOR_EXPORT: "匯出",
|
||||
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 圖像.md",
|
||||
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "無法建立 Markdown 筆記",
|
||||
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知錯誤",
|
||||
@@ -151,6 +185,10 @@ export default {
|
||||
"本機 Markdown 圖像轉換為嵌入內容時只能包含一個一級標題。該標題必須是首個內容,且名稱在繪圖中必須唯一。",
|
||||
MARKDOWN_IMAGE_SECTION_NAME: "命名筆記末尾的章節",
|
||||
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "輸入唯一的章節名稱",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
|
||||
"是否刪除為此圖像儲存的 Markdown 文字?無論如何,該圖像都會從場景中移除。",
|
||||
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文字",
|
||||
MARKDOWN_IMAGE_DELETE_TEXT: "刪除 Markdown 文字",
|
||||
INSERT_PDF: "以影像形式嵌入 PDF 到當前繪圖中",
|
||||
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以影像形式嵌入最後啟用的 PDF 頁面",
|
||||
UNIVERSAL_ADD_FILE: "嵌入檔案 / Insert ANY file",
|
||||
@@ -219,8 +257,6 @@ export default {
|
||||
"反轉模式:預設方向按鍵已停用。需要時請使用 Ctrl/CMD 臨時啟用。",
|
||||
ARROW_BINDING_NORMAL_MODE:
|
||||
"正常模式:方向鍵已啟用。需要時請使用 Ctrl/CMD 臨時停用。",
|
||||
EXPORT_FILENAME_PROMPT: "請提供檔名",
|
||||
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "請輸入檔名,留空以取消操作",
|
||||
WARNING_SERIOUS_ERROR:
|
||||
"警告:Excalidraw 遇到了未知的問題!\n\n" +
|
||||
"您最近的更改可能無法儲存。\n\n" +
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Notice, normalizePath } from "obsidian";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { MultiOptionConfirmationPrompt } from "./Prompt";
|
||||
|
||||
/** Confirms and creates a missing vault folder without overwriting files. */
|
||||
export const confirmAndCreateFolder = async (
|
||||
plugin: ExcalidrawPlugin,
|
||||
requestedPath: string,
|
||||
): Promise<boolean> => {
|
||||
const path = normalizePath(requestedPath.trim());
|
||||
if (!path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (plugin.app.vault.getFolderByPath(path)) {
|
||||
return true;
|
||||
}
|
||||
if (plugin.app.vault.getFileByPath(path)) {
|
||||
new Notice(t("CREATE_FOLDER_PATH_IS_FILE").replace("{PATH}", path), 6000);
|
||||
return false;
|
||||
}
|
||||
|
||||
const confirmed = await new MultiOptionConfirmationPrompt<boolean | null>(
|
||||
plugin,
|
||||
t("CREATE_FOLDER_CONFIRM").replace("{PATH}", path),
|
||||
new Map<string, boolean | null>([
|
||||
[t("CREATE_FOLDER_NEVER_MIND"), false],
|
||||
[t("CREATE_FOLDER_YES"), true],
|
||||
]),
|
||||
t("CREATE_FOLDER_YES"),
|
||||
).waitForClose;
|
||||
if (confirmed !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await plugin.app.vault.createFolder(path);
|
||||
new Notice(t("CREATE_FOLDER_SUCCESS").replace("{PATH}", path));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`Could not create folder '${path}'`, error);
|
||||
new Notice(t("CREATE_FOLDER_FAILED").replace("{PATH}", path), 6000);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
import { Modal, Setting, type App, type ButtonComponent } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
|
||||
|
||||
/** Folder and filename selected in a {@link FileAndFolderSelectorModal}. */
|
||||
export type FileAndFolderSelection = {
|
||||
folderPath: string;
|
||||
fileName: string;
|
||||
};
|
||||
|
||||
/** Labels and initial values for a {@link FileAndFolderSelectorModal}. */
|
||||
export type FileAndFolderSelectorOptions = FileAndFolderSelection & {
|
||||
title: string;
|
||||
folderLabel: string;
|
||||
fileNameLabel: string;
|
||||
submitButtonText: string;
|
||||
};
|
||||
|
||||
/** Prompts for a Vault folder and filename. */
|
||||
export class FileAndFolderSelectorModal extends Modal {
|
||||
private resolvePromise: (
|
||||
selection: FileAndFolderSelection | null,
|
||||
) => void;
|
||||
private result: FileAndFolderSelection | null = null;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
private readonly options: FileAndFolderSelectorOptions,
|
||||
) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
/** Opens the modal and resolves with the selection or null when cancelled. */
|
||||
public start(): Promise<FileAndFolderSelection | null> {
|
||||
const result = new Promise<FileAndFolderSelection | null>((resolve) => {
|
||||
this.resolvePromise = resolve;
|
||||
});
|
||||
this.open();
|
||||
return result;
|
||||
}
|
||||
|
||||
public onOpen(): void {
|
||||
this.titleEl.setText(this.options.title);
|
||||
this.contentEl.addClass("excalidraw-file-and-folder-selector");
|
||||
|
||||
let folderPath = this.options.folderPath;
|
||||
let fileName = this.options.fileName;
|
||||
let submitButton: ButtonComponent | null = null;
|
||||
const updateSubmitButton = (): void => {
|
||||
submitButton?.setDisabled(fileName.trim().length === 0);
|
||||
};
|
||||
|
||||
const folderSetting = new Setting(this.contentEl)
|
||||
.setClass("excalidraw-file-and-folder-selector__field")
|
||||
.setName(this.options.folderLabel)
|
||||
.addText((text) => {
|
||||
text.setValue(folderPath).onChange((value) => {
|
||||
folderPath = value.trim();
|
||||
});
|
||||
new VaultPathSuggest(this.app, text.inputEl, "folder");
|
||||
});
|
||||
folderSetting.controlEl.addClass("excalidraw-folder-path-control");
|
||||
|
||||
let fileNameInput: HTMLInputElement | null = null;
|
||||
new Setting(this.contentEl)
|
||||
.setClass("excalidraw-file-and-folder-selector__field")
|
||||
.setName(this.options.fileNameLabel)
|
||||
.addText((text) => {
|
||||
fileNameInput = text.inputEl;
|
||||
text.setValue(fileName).onChange((value) => {
|
||||
fileName = value;
|
||||
updateSubmitButton();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.onClick(() => this.close()),
|
||||
)
|
||||
.addButton((button) => {
|
||||
submitButton = button;
|
||||
button
|
||||
.setCta()
|
||||
.setButtonText(this.options.submitButtonText)
|
||||
.onClick(() => {
|
||||
this.result = {
|
||||
folderPath,
|
||||
fileName: fileName.trim(),
|
||||
};
|
||||
this.close();
|
||||
});
|
||||
updateSubmitButton();
|
||||
});
|
||||
|
||||
this.containerEl.ownerDocument.defaultView?.setTimeout(
|
||||
() => fileNameInput?.focus(),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
public onClose(): void {
|
||||
this.contentEl.empty();
|
||||
this.resolvePromise?.(this.result);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { FuzzySuggestModal, TFile } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { getEA } from "src/core";
|
||||
import { UniversalInsertFileModal } from "./UniversalInsertFileModal";
|
||||
|
||||
export class InsertMDDialog extends FuzzySuggestModal<TFile> {
|
||||
public plugin: ExcalidrawPlugin;
|
||||
@@ -40,12 +40,11 @@ export class InsertMDDialog extends FuzzySuggestModal<TFile> {
|
||||
}
|
||||
|
||||
onChooseItem(item: TFile): void {
|
||||
const ea = getEA(this.view);
|
||||
void (async () => {
|
||||
await ea.addImage(0, 0, item);
|
||||
await ea.addElementsToView(true, false, true);
|
||||
ea.destroy();
|
||||
})();
|
||||
new UniversalInsertFileModal(this.plugin, this.view).open(
|
||||
item,
|
||||
this.view.currentPosition,
|
||||
"image",
|
||||
);
|
||||
}
|
||||
|
||||
public start(view: ExcalidrawView) {
|
||||
|
||||
+24
-254
@@ -17,18 +17,36 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
|
||||
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
// ${getYouTubeDiv("p9MBFxUoOXQ")}
|
||||
"2.26.0": `
|
||||
## New
|
||||
- Added editable Markdown images. Their source can be stored locally as back-of-the-card markdown content in the drawing or linked to an external Markdown note, heading, or block, including an Excalidraw Markdown file. Edit content and appearance in the Excalidraw sidepanel or use the action menu on a selected Markdown image; the editor supports standard Obsidian Markdown shortcuts and refreshes the image when focus leaves the editor. Markdown images participate in normal canvas layering and image export. You can duplicate local Markdown images, convert interactive embeddables into images and back in the embeddable/image menu in the top left of the selected element, and control dark-mode image inversion from the context menu.
|
||||
- Stencil libraries can now be stored as vault files instead of \`data.json\`, improving plugin settings stability. Existing users are offered a safe, merge-first migration. To sync libraries, enable **Sync all other types** in Obsidian Sync. To view library files, enable **Show all file types** in Obsidian settings.
|
||||
- Added editable Markdown images.
|
||||
- Store content locally (back-of-the-card) or link to a Markdown note, heading, or block.
|
||||
- Edit content and appearance from the Excalidraw side panel.
|
||||
- Supports canvas layering and image export.
|
||||
- Dragging a Markdown note as an image lets you choose a heading (when available) and insert it as either an editable Markdown image or embeddable.
|
||||
- Local Markdown image copies share the same source. Use **Duplicate selected image** to create an independent image and Markdown body. You can also convert between images and embeddables from the selected element's menu.
|
||||
- Image-reference embeds now support an optional \`padding=N\` parameter, e.g.: \`![[drawing#^area=xyz,padding=10]]\` [#2850](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2850) 🙏[@Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov)
|
||||
- Added the Voronoi diagram script. 🙏[@FreeCutter](${URLs.GITHUB_COM}/FreeCutter) [#2845](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2845)
|
||||
- Dragging a single external GIF with the **Import external file** action now lets you import it as either an image or an embeddable. [#2848](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2848)
|
||||
- Folder and file path settings now provide vault suggestions, warn about missing paths, and can create missing folders after confirmation.
|
||||
|
||||
## New and fixed from Excalidraw.com
|
||||
- New: flowchart (CTRL/CMD+arrow keys) now intelligently routes new shapes to avoid overlap of flowchart children [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
|
||||
- New Draw To Shape feature: Draw a shape freehand, and Excalidraw will automatically convert it to a perfect shape. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
|
||||
- Fixed: Dragged arrow endpoint ignore grid and angle locks [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
|
||||
- New: Double-click to toggle arrowhead [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
|
||||
- New: Flowchart (CTRL/CMD+Arrow) now intelligently routes new shapes to avoid overlapping child nodes. [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
|
||||
- New: Draw To Shape automatically converts freehand drawings into perfect shapes. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
|
||||
- Fixed: Dragged arrow endpoints now respect grid and angle locks. [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
|
||||
- New: Double-click an arrow to toggle its arrowhead. [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
|
||||
|
||||
## Fixed
|
||||
- Custom freedraw pens now remain selected after temporarily switching to the eraser or another tool, and are restored when returning to freedraw. [#2859](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2859)
|
||||
- Added configurable bottom padding for Markdown images to prevent clipped final lines or borders.
|
||||
- Markdown image font selectors now preview each font and refresh the vault font list whenever opened.
|
||||
- Empty Markdown image font colors now normalize to black when the editor opens or the color field loses focus. CSS controls can also copy the generated SVG for inspection.
|
||||
- Dragging an external video or other non-image file with the **Import external file** action now offers the same use, overwrite, or import options as images when a matching vault file already exists. [#2851](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2851) 🙏[@WolfExplode](${URLs.GITHUB_COM}/WolfExplode)
|
||||
|
||||
## Excalidraw Automate Breaking Change
|
||||
- Excalidraw component API has discontinued \`api.scrollToContent(target?, opts?)\` and replaced it with \`api.setViewport(opts | null)\`. You'll need to update MindMap Builder and Comic Strip Director scripts. If you have your own scripts using this API function you'll need to update them accordingly. For more information read the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking)
|
||||
- The Excalidraw API has replaced \`api.scrollToContent(target?, opts?)\` with \`api.setViewport(opts | null)\`. Update the MindMap Builder and Comic Strip Director scripts, along with any custom scripts using the old API. See the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking) for details.
|
||||
`,
|
||||
"2.25.3": `
|
||||
Minor maintenance release with two important fixes.
|
||||
@@ -420,253 +438,5 @@ async addImage(
|
||||
anchor: boolean = true,
|
||||
): Promise<string>;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.22.3": `
|
||||
|
||||
Feeling overwhelmed by Excalidraw's endless features?
|
||||
|
||||
It's not just a drawing tool. Inside Obsidian, it becomes a thinking tool.
|
||||
To unlock linking, embedding, and referencing, you need a mindset shift.
|
||||
|
||||
**Join Excalidraw Mastery** to make that shift.
|
||||
Courses, live Q&As, and deep dives to help you move into true 4D Visual PKM. 👉 https://community.sketch-your-mind.com/em
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG}" style="width:50%"></a>
|
||||
</div>
|
||||
|
||||
Excalidraw Mastery is part of the **Sketch Your Mind Community**—a space for visual thinkers.
|
||||
Share your work. Ask questions. Learn from others. 👉 https://community.sketch-your-mind.com
|
||||
|
||||
Curious about the philosophy behind it?
|
||||
|
||||
${getYouTubeDiv("TnwRlaIdhSU")}
|
||||
|
||||
`,
|
||||
"2.22.1": `
|
||||
## New
|
||||
- Added a command palette action to switch all currently open Excalidraw drawings to view mode.
|
||||
- While this temporary mode is enabled, any Excalidraw drawing opened afterward will also open in view mode.
|
||||
- This is useful when presenting multiple drawings and you want to avoid accidentally moving elements, and when you don't want the tools to be in the way.
|
||||
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2688), [#2652](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2652), [#798](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/798)
|
||||
- Look for ""Extra bottom padding for phone controls" in the plugin settings.
|
||||
|
||||
## Fixed
|
||||
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2739)
|
||||
- image sizing issue when embedding image type "SVG Image" to markdown
|
||||
- copying a nested image fragment in Excalidraw and pasting to markdown lost the image block reference
|
||||
- modifier keys conflicted with Excalidraw alt-select (lasso) behavior
|
||||
`,
|
||||
"2.22.0": `
|
||||
## Fixed
|
||||
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
|
||||
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/11018)
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10979)
|
||||
- Added support for Mermaid state diagrams [#11031](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11031)
|
||||
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10760)
|
||||
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11053)
|
||||
|
||||
## New
|
||||
- Added support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embeddable element in Excalidraw. At the moment, changing the canvas theme between dark and light mode does not automatically re-render embedded sheets. To apply the theme change, close and reopen the drawing. This will likely be improved in a future update.
|
||||
`,
|
||||
"2.21.3": `
|
||||
## Fixed
|
||||
- Caret color for link editor, text elemnts in dark mode, color picker input element.
|
||||
- Link click behavior modifier keys setting in plugin settings now enforces CTRL/CMD for link clicks and improves on clarity of setting UI by adding a header row
|
||||
- Link click conbinations that included ALT/OPT did not work because they trigger lasso selection in Excalidraw. This is now fixed, if you CTRL+ALT click a link it will navigate while retaining the lasso select feature when pressing ALT/OPT.
|
||||
- Copying an image block embed (e.g. \`![[drawing#^frame=my_frame]]\`) from the excalidraw scene and pasting it to markdown no longer loses the frame reference
|
||||
- Embed "SVG Image" to markdown should size correctly now when setting a percentage \`![[drawing|50%]]\` where 50% is relative to the width of the markdown note.
|
||||
|
||||
`,
|
||||
"2.21.2": `
|
||||
## Fixed
|
||||
- The new ExcalidrawAutomate function \`parseText()\` broke if the text was a transcluded image or PDF document, causing downstream paste issues in MindMap Builder.
|
||||
- Custom pen sloppiness not being saved to a template drawing [#2715](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2715) 🙏[@sreedharsreeram](${URLs.GITHUB_COM_SREEDHARSREERAM})
|
||||
|
||||
`,
|
||||
"2.21.1": `
|
||||
## Fixed
|
||||
- Drawing and editor fails to initialize in a new window [#2713](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2713)
|
||||
- Duplicate selected image with a different image ID command palette action did not duplicate cropped PDF images.
|
||||
- Memory leak issue with PDF import as images.
|
||||
|
||||
## New
|
||||
- Put caret at pointer position when clicking on selected text element [#10970](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10970)
|
||||
|
||||
`,
|
||||
"2.21.0": `
|
||||
## New
|
||||
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
- Inline link suggester supports new triggers \`
|
||||
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10906)
|
||||
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
|
||||
## Fixed
|
||||
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2685)
|
||||
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2704)
|
||||
|
||||
## MindMap Builder
|
||||
- Fixed navigation (arrow keys) scoping and recognition
|
||||
- Added new feature to paste images and single Excalidraw elements like container with text, text element, or image element directly as a map leaf (using the MindMap Builder default paste shortcut: ALT/OPT+V)
|
||||
- Added new action to toggle a markdown link between markdown embeddable and link as text. Default shortcut is ALT/OPT+E.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Parses text using the target view's ExcalidrawData parser.
|
||||
*
|
||||
* This reuses ExcalidrawData parsing logic directly, including transclusion
|
||||
* resolution, link bracket rendering, and link/url prefixes based on the
|
||||
* target file's frontmatter.
|
||||
*
|
||||
* @param {string} text - Raw text to parse.
|
||||
* @returns {Promise<string | undefined>} Parsed text, or undefined when input/view is unavailable.
|
||||
*/
|
||||
public async parseText (text: string): Promise<string | undefined>;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.20.6": `
|
||||
${getYouTubeDiv("g-BiyQ7TJTM")}
|
||||
|
||||
## New
|
||||
- Inline suggester now supports searching for tags in addition to files. Trigger with "#".
|
||||
- In Mindmap Builder
|
||||
- Added Up-Facing, Down-Facing, and Up-Down maps
|
||||
- Added submaps. You can now promote any node to be a new mindmap root (a sub-map). Sub-maps can have different layout settings such as different growth strategies, different colors, etc.
|
||||
- Added experimental MindMap Builder API, accessible via \`window.MindMapBuilderAPI\`. See [MindMap Builder API documentation](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPT_DOCS_MINDMAPBUILDERAPI_MD}) for more. Essentially, the API allows mindmaps to be created using the Obsidian CLI.
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Allow clicking on links and embeds with laser tool [#10797](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10797)
|
||||
- Improved paste text to diagram with more options and support for more data [#10824](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10824)
|
||||
|
||||
try copy/pasting this into Excalidraw:
|
||||
\`\`\`
|
||||
skill, junior, medior, senior
|
||||
business_analysis, 2, 6, 9
|
||||
business_writing, 3, 7, 9
|
||||
stakeholder_mgmt, 1, 6, 10
|
||||
\`\`\`
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
- Added \`skipScriptRestore(scriptName?: string): boolean\` function to the API. This allows scripts to queue a one-time skip marker so sidepanel persisted restoration will not re-run the script. Intended for startup race conditions where a script is started from the Command Palette/hotkey before the sidepanel has opened. If scriptName is omitted, the function uses ea.activeScript.
|
||||
|
||||
## Fixed
|
||||
- Significant performance improvement of MindMap Builder and all other scripts modifying elements in large scenes containing thousands of elements.
|
||||
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10832) [#10831](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10831) [#10816](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10816)
|
||||
- Hide MindMap Builder and other floating tools when creating a screenshot
|
||||
`,
|
||||
"2.20.5": `
|
||||
## Fixed
|
||||
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2673)
|
||||
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2670)
|
||||
|
||||
## New
|
||||
- Added "Toggle Full Screen" button to toolbar right next to the "Obsidian menu", and the "Insert Any File" button.
|
||||
`,
|
||||
"2.20.4": `
|
||||
## Fixed
|
||||
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2665)
|
||||
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/10772)
|
||||
- Fixed regression that removed LaTeX scaling. [#2668](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2668) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1})
|
||||
- Corrected malformed frame embeds when using marker frames.
|
||||
- Context menu options **“Do not invert image(s) in dark mode”** and **“Invert image(s) in dark mode”** now properly cascade when drawings are nested as images inside other drawings.
|
||||
- Improved performance of the [MindMap Builder script](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}).
|
||||
|
||||
## New
|
||||
- [Deconstruct Selected Elements script](${getYouTubeUrl("HRtaaD34Zzg")}) now includes a folder selection option, allowing you to choose the destination folder for the generated image.
|
||||
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10611)
|
||||
|
||||
`,
|
||||
"2.20.3": `
|
||||
## Fixed
|
||||
- Hover preview when hovering an element with a link in the scene was unreliable
|
||||
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2660)
|
||||
|
||||
## New
|
||||
- Added default keymap to latex editor [#2655](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2655) 🙏[superle3](${URLs.GITHUB_COM_SUPERLE3})
|
||||
`,
|
||||
"2.20.2": `
|
||||
## New from Excalidraw.com
|
||||
- Arrow focus indicator [#10613](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10613)
|
||||
|
||||
## Fixed
|
||||
- Experimental file type display now also works in Obsidian Mobile. (Reported on Discord)
|
||||
- Text to Mermaid stores chat history locally (i.e. not synchronized between devices).
|
||||
- Image positioning in crop editor [#2589](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2589), [#10726](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10726)
|
||||
|
||||
## MindMap Builder
|
||||
- Implemented better undo support (effective only for the very last MindMap Builder action). Additionally, CMD/CTRL+Z and CTRL+Y, CMD+SHIFT+Z now work when the MindMap input window is focused.
|
||||
- Fixed: Double character input issue (IME Composition Error) when creating nodes [#2647](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2647)
|
||||
- Fixed: More robust error handling when the MindMap is corrupted or invalid.
|
||||
- Updated Excalidraw Writing Machine to support document generation from MindMaps. Writing Machine will honor the branch order. Requires update of the Writing Machine Script.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
- \`getBoundTextElement()\` now also accepts an \`ExcalidrawElement[]\` (2-element selection: container + text) in addition to a single element.
|
||||
- \`addElementsToView()\` extended with \`captureUpdate\` parameter (default: "IMMEDIATELY"). When set to false, the addition of elements will not be recorded in the view's history.
|
||||
|
||||
\`\`\`ts
|
||||
async addElementsToView(
|
||||
repositionToCursor: boolean = false,
|
||||
save: boolean = true,
|
||||
newElementsOnTop: boolean = false,
|
||||
shouldRestoreElements: boolean = false,
|
||||
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
|
||||
): Promise<boolean>
|
||||
\`\`\`
|
||||
`,
|
||||
"2.20.1": `
|
||||
## Fixed
|
||||
- Fixed Experimental file type display, available under miscellaneous settings. (Reported on Discord)
|
||||
- Fixed image inversion in dark mode on iOS devices. [#2636](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2636)
|
||||
- Fixed UI Mode switching on tablets was unreliable.
|
||||
|
||||
## New/Fixed in MindMap Builder
|
||||
- **Connector Ontology**: Added support for labeling connection lines. A secondary input field (accessible via Shift+Tab) is now available in both docked and floating modes. Labels are preserved during copy/paste operations using inline Dataview syntax (e.g., link ontology:: node content).
|
||||
- **Connector Styling**: Introduced configuration settings for branch thickness and scaling strategies, allowing a choice between Hierarchical (tapering width by depth) or Uniform connector widths.
|
||||
- **Smart Resume**: The Focus and Zoom actions now target the most recently active node if no current selection is made. This automatically focuses the input field, allowing you to quickly resume mapping from where you left off.
|
||||
- **Radial Fill Sweep**: Added a "Fill Sweep Angle" option for Radial layouts. When enabled, nodes are distributed evenly across the full configured arc range, even when there are only a few nodes. (Visible only when Growth Strategy is set to "Radial").
|
||||
- **Radial Navigation**: Updated Level 1 node navigation in Radial maps to follow visual vertical alignment instead of rotational order. Up/Down keys now consistently move the selection visually up or down on both sides of the circle, matching the behavior of Right-Left layouts.
|
||||
- **Fixed**:
|
||||
- Sidepanel opens on activation of MindMap Builder even in floating mode. Requires update of both Excalidraw and the MindMap Builder script.
|
||||
- **Node Reordering**: Overhauled the logic for moving nodes via CMD/CTRL+Arrow to resolve unpredictability; nodes now move consistently to the intended locations.
|
||||
- **iOS Navigation**: Resolved an issue where using the Tab key to cycle focus between components in the floating input window did not work reliably on iOS.
|
||||
- **Boundary Layering**: Fixed an issue where sub-branch boundaries were placed above text elements when pasting a map; they now correctly render on the layer below the text.
|
||||
- **Layout Stability**: Fixed an issue where the viewport would shift unexpectedly when pasting multiple elements onto an existing node in large scenes.
|
||||
|
||||
> [!Tip]- Learn MindMap Builder
|
||||
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
|
||||
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
|
||||
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
|
||||
|
||||
`,
|
||||
"2.20.0": `
|
||||
${getYouTubeDiv("5G9QF-u9w0Q")}
|
||||
|
||||
> [!Tip]- Learn MindMap Builder
|
||||
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
|
||||
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
|
||||
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
|
||||
|
||||
## Scripts
|
||||
- Moved [Shade Master](${getYouTubeUrl("ISuORbVKyhQ")}) to use the new Excalidraw Sidepanel API (just like MindMap Builder).
|
||||
|
||||
## New
|
||||
- Dark theme from Excalidraw.com [#10578](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10578) (including correct emoji rendering in dark mode 😍).
|
||||
- New image context-menu option (right-click an image) to control whether that image inverts in dark mode
|
||||
- Default behavior: SVG-based images (including LaTeX, Mermaid, and nested Excalidraw images) invert in dark mode; bitmap images (PNG/JPG) do not.
|
||||
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10530)
|
||||
- Breaking change: the legacy “force SVG” option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw, it will be; otherwise, an SVG will be used.
|
||||
- Moved the Shade Master script to use the new Sidepanel (just like MindMap Builder).
|
||||
|
||||
## Fixed
|
||||
- In full-screen mode on phones, a large area at the top of the screen was left unused. Also fixed an issue where the Obsidian Mobile navigation bar could overlap the Excalidraw toolbar.
|
||||
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2625)
|
||||
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2578)
|
||||
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
|
||||
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
|
||||
`,
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import { Modal, normalizePath, Setting, TextComponent } from "obsidian";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
|
||||
import type { StencilLibraryMigrationChoice } from "src/types/stencilLibraryTypes";
|
||||
import { setElementHidden } from "src/utils/htmlUtils";
|
||||
import { confirmAndCreateFolder } from "./CreateFolderPrompt";
|
||||
|
||||
export type StencilLibraryMigrationResult = {
|
||||
choice: StencilLibraryMigrationChoice;
|
||||
folderPath: string;
|
||||
fileName: string;
|
||||
};
|
||||
|
||||
/** Explains and configures the one-time stencil-library storage migration. */
|
||||
export class StencilLibraryMigrationPrompt extends Modal {
|
||||
private resolvePromise: (result: StencilLibraryMigrationResult) => void;
|
||||
private result: StencilLibraryMigrationResult;
|
||||
|
||||
constructor(private readonly plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
this.result = {
|
||||
choice: "later",
|
||||
folderPath: plugin.settings.libraryFolderPath,
|
||||
fileName: plugin.settings.libraryFileName,
|
||||
};
|
||||
}
|
||||
|
||||
public start(): Promise<StencilLibraryMigrationResult> {
|
||||
const result = new Promise<StencilLibraryMigrationResult>((resolve) => {
|
||||
this.resolvePromise = resolve;
|
||||
});
|
||||
this.open();
|
||||
return result;
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.titleEl.setText(t("LIBRARY_MIGRATION_TITLE"));
|
||||
this.contentEl.createEl("p", { text: t("LIBRARY_MIGRATION_DESC") });
|
||||
this.contentEl.createEl("p", {
|
||||
cls: "mod-warning",
|
||||
text: t("LIBRARY_MIGRATION_SYNC_WARNING"),
|
||||
});
|
||||
|
||||
let folderText: TextComponent | null = null;
|
||||
let createFolderButtonEl: HTMLButtonElement | null = null;
|
||||
const folderSetting = new Setting(this.contentEl)
|
||||
.setName(t("LIBRARY_FOLDER_NAME"))
|
||||
.setDesc(t("LIBRARY_FOLDER_DESC"));
|
||||
const updateCreateFolderButton = (): void => {
|
||||
const path = folderText?.getValue().trim() ?? "";
|
||||
const folderExists = path
|
||||
? Boolean(this.app.vault.getFolderByPath(normalizePath(path)))
|
||||
: false;
|
||||
if (createFolderButtonEl) {
|
||||
setElementHidden(createFolderButtonEl, !path || folderExists);
|
||||
}
|
||||
};
|
||||
folderSetting
|
||||
.addText((text: TextComponent) => {
|
||||
folderText = text;
|
||||
text.setValue(this.result.folderPath).onChange((value) => {
|
||||
this.result.folderPath = value;
|
||||
updateCreateFolderButton();
|
||||
});
|
||||
new VaultPathSuggest(this.app, text.inputEl, "folder");
|
||||
text.inputEl.addEventListener("input", updateCreateFolderButton);
|
||||
window.setTimeout(updateCreateFolderButton, 0);
|
||||
})
|
||||
.addButton((button) => {
|
||||
createFolderButtonEl = button.buttonEl;
|
||||
setElementHidden(button.buttonEl, true);
|
||||
button.setButtonText(t("CREATE_FOLDER")).onClick(async () => {
|
||||
await confirmAndCreateFolder(this.plugin, this.result.folderPath);
|
||||
updateCreateFolderButton();
|
||||
});
|
||||
});
|
||||
folderSetting.controlEl.addClass("excalidraw-folder-path-control");
|
||||
const createFolderRow = folderSetting.controlEl.createDiv({
|
||||
cls: "excalidraw-folder-create-row",
|
||||
});
|
||||
createFolderRow.appendChild(createFolderButtonEl);
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("LIBRARY_FILE_NAME"))
|
||||
.setDesc(t("LIBRARY_FILE_DESC"))
|
||||
.addText((text) =>
|
||||
text.setValue(this.result.fileName).onChange((value) => {
|
||||
this.result.fileName = value;
|
||||
}),
|
||||
);
|
||||
|
||||
const buttons = new Setting(this.contentEl);
|
||||
buttons.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("LIBRARY_MIGRATION_KEEP_DATA_JSON"))
|
||||
.onClick(() => {
|
||||
this.result.choice = "keep-data-json";
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
buttons.addButton((button) =>
|
||||
button.setButtonText(t("LIBRARY_MIGRATION_LATER")).onClick(() => {
|
||||
this.result.choice = "later";
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
buttons.addButton((button) =>
|
||||
button
|
||||
.setCta()
|
||||
.setButtonText(t("LIBRARY_MIGRATION_MIGRATE"))
|
||||
.onClick(() => {
|
||||
this.result.choice = "migrate";
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
// Closing via the title-bar button or Escape intentionally keeps the
|
||||
// default "later" choice and applies the same one-day snooze.
|
||||
this.contentEl.empty();
|
||||
this.resolvePromise?.(this.result);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
viewportCoordsToSceneCoords,
|
||||
MAX_IMAGE_SIZE,
|
||||
ANIMATED_IMAGE_TYPES,
|
||||
MD_EX_SECTIONS,
|
||||
} from "src/constants/constants";
|
||||
import {
|
||||
insertEmbeddableToView,
|
||||
@@ -17,14 +16,21 @@ import {
|
||||
} from "src/utils/excalidrawViewUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { InsertPDFModal } from "./InsertPDFModal";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cleanSectionHeading } from "src/utils/pathUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
import {
|
||||
getMarkdownHeadingSubpaths,
|
||||
type MarkdownHeadingSubpath,
|
||||
} from "src/shared/Suggesters/markdownSubpathSuggester";
|
||||
import { insertMarkdownImage } from "src/shared/MarkdownImage";
|
||||
import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
|
||||
|
||||
export type UniversalInsertFileAction = "image" | "embeddable";
|
||||
|
||||
export class UniversalInsertFileModal extends Modal {
|
||||
private center: { x: number; y: number } = { x: 0, y: 0 };
|
||||
private file: TFile;
|
||||
private preferredAction: UniversalInsertFileAction | null = null;
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
@@ -72,9 +78,14 @@ export class UniversalInsertFileModal extends Modal {
|
||||
|
||||
private onKeyDown: (evt: KeyboardEvent) => void;
|
||||
|
||||
open(file?: TFile, center?: { x: number; y: number }) {
|
||||
open(
|
||||
file?: TFile,
|
||||
center?: { x: number; y: number },
|
||||
preferredAction?: UniversalInsertFileAction,
|
||||
) {
|
||||
this.file = file;
|
||||
this.center = center ?? this.center;
|
||||
this.preferredAction = preferredAction ?? null;
|
||||
super.open();
|
||||
}
|
||||
|
||||
@@ -95,6 +106,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
let actionPDF: ButtonComponent;
|
||||
let anchorTo100: boolean = false;
|
||||
let file = this.file;
|
||||
let fileSections: MarkdownHeadingSubpath[] = [];
|
||||
|
||||
const updateForm = async () => {
|
||||
const ea = this.plugin.ea;
|
||||
@@ -110,38 +122,26 @@ export class UniversalInsertFileModal extends Modal {
|
||||
const isPDF = file && file.extension === "pdf";
|
||||
const isExcalidraw = file && ea.isExcalidrawFile(file);
|
||||
|
||||
const sections =
|
||||
file && file.extension === "md"
|
||||
? (
|
||||
await this.plugin.app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
file,
|
||||
)
|
||||
).blocks
|
||||
.filter(
|
||||
(b: { display: string; node?: { type: string } }) =>
|
||||
b.display && b.node?.type === "heading",
|
||||
)
|
||||
.filter(
|
||||
(b: { display: string; node?: { type: string } }) =>
|
||||
!isExcalidraw || !MD_EX_SECTIONS.includes(b.display),
|
||||
)
|
||||
: null;
|
||||
fileSections =
|
||||
file?.extension === "md"
|
||||
? await getMarkdownHeadingSubpaths(
|
||||
this.app,
|
||||
file,
|
||||
Boolean(isExcalidraw),
|
||||
)
|
||||
: [];
|
||||
|
||||
if (isMarkdown || (isExcalidraw && sections?.length > 0)) {
|
||||
while (sectionPicker.selectEl.options.length > 0) {
|
||||
sectionPicker.selectEl.remove(0);
|
||||
}
|
||||
if (isMarkdown || (isExcalidraw && fileSections.length > 0)) {
|
||||
showElement(sectionPickerSetting.settingEl);
|
||||
showElement(sectionPicker.selectEl);
|
||||
while (sectionPicker.selectEl.options.length > 0) {
|
||||
sectionPicker.selectEl.remove(0);
|
||||
if (!isSelf) {
|
||||
sectionPicker.addOption("", t("SHOW_ENTIRE_FILE"));
|
||||
}
|
||||
if (!isExcalidraw) {
|
||||
sectionPicker.addOption("", "");
|
||||
}
|
||||
sections.forEach((b: { display: string; node?: { type: string } }) => {
|
||||
sectionPicker.addOption(
|
||||
`#${cleanSectionHeading(b.display)}`,
|
||||
b.display,
|
||||
);
|
||||
fileSections.forEach((section) => {
|
||||
sectionPicker.addOption(section.subpath, section.display);
|
||||
});
|
||||
} else {
|
||||
hideElement(sectionPickerSetting.settingEl);
|
||||
@@ -154,7 +154,10 @@ export class UniversalInsertFileModal extends Modal {
|
||||
hideElement(sizeToggleSetting.settingEl);
|
||||
}
|
||||
|
||||
if (!isSelf && (isImage || file?.extension === "md")) {
|
||||
if (
|
||||
(!isSelf && (isImage || file?.extension === "md")) ||
|
||||
(isSelf && isExcalidraw && fileSections.length > 0)
|
||||
) {
|
||||
showElement(actionImage.buttonEl);
|
||||
} else {
|
||||
hideElement(actionImage.buttonEl);
|
||||
@@ -163,7 +166,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
if (
|
||||
isIFrame ||
|
||||
isAnimatedImage ||
|
||||
(isExcalidraw && sections?.length > 0)
|
||||
(isExcalidraw && (!isSelf || fileSections.length > 0))
|
||||
) {
|
||||
showElement(actionIFrame.buttonEl);
|
||||
} else {
|
||||
@@ -177,20 +180,11 @@ export class UniversalInsertFileModal extends Modal {
|
||||
}
|
||||
};
|
||||
|
||||
const sections = (
|
||||
await this.plugin.app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
this.view.file,
|
||||
)
|
||||
).blocks
|
||||
.filter(
|
||||
(b: { display: string; node?: { type: string } }) =>
|
||||
b.display && b.node?.type === "heading",
|
||||
)
|
||||
.filter(
|
||||
(b: { display: string; node?: { type: string } }) =>
|
||||
!MD_EX_SECTIONS.includes(b.display),
|
||||
);
|
||||
const currentFileSections = await getMarkdownHeadingSubpaths(
|
||||
this.app,
|
||||
this.view.file,
|
||||
true,
|
||||
);
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
setStyle(search.inputEl, { width: "100%" });
|
||||
@@ -199,7 +193,9 @@ export class UniversalInsertFileModal extends Modal {
|
||||
search,
|
||||
this.app.vault
|
||||
.getFiles()
|
||||
.filter((f: TFile) => sections?.length > 0 || f !== this.view.file),
|
||||
.filter(
|
||||
(f: TFile) => currentFileSections.length > 0 || f !== this.view.file,
|
||||
),
|
||||
this.plugin,
|
||||
);
|
||||
search.onChange(() => {
|
||||
@@ -225,13 +221,16 @@ export class UniversalInsertFileModal extends Modal {
|
||||
|
||||
new Setting(ce)
|
||||
.addButton((button) => {
|
||||
if (this.preferredAction === "embeddable") {
|
||||
button.setCta();
|
||||
}
|
||||
button.setButtonText(t("UIFM_BTN_EMBEDDABLE")).onClick(async () => {
|
||||
const path = this.app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
this.view.file.path,
|
||||
file.extension === "md",
|
||||
);
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
const ea = getEA(this.view);
|
||||
ea.selectElementsInView([
|
||||
await insertEmbeddableToView(
|
||||
ea,
|
||||
@@ -255,24 +254,39 @@ export class UniversalInsertFileModal extends Modal {
|
||||
actionPDF = button;
|
||||
})
|
||||
.addButton((button) => {
|
||||
if (this.preferredAction === "image") {
|
||||
button.setCta();
|
||||
}
|
||||
button.setButtonText(t("UIFM_BTN_IMAGE")).onClick(async () => {
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
const isMarkdown =
|
||||
file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
ea.selectElementsInView([
|
||||
await insertImageToView(
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
isMarkdown &&
|
||||
sectionPicker.selectEl.value &&
|
||||
sectionPicker.selectEl.value !== ""
|
||||
? `${file.path}${sectionPicker.selectEl.value}`
|
||||
file &&
|
||||
file.extension === "md" &&
|
||||
!this.plugin.isExcalidrawFile(file);
|
||||
const section = sectionPicker.selectEl.value;
|
||||
if (isMarkdown || (file?.extension === "md" && section)) {
|
||||
await insertMarkdownImage(
|
||||
this.view,
|
||||
section
|
||||
? new EmbeddedFile(
|
||||
this.plugin,
|
||||
this.view.file.path,
|
||||
`${file.path}${section}`,
|
||||
)
|
||||
: file,
|
||||
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
|
||||
),
|
||||
]);
|
||||
ea.destroy();
|
||||
this.center,
|
||||
);
|
||||
} else {
|
||||
const ea = getEA(this.view);
|
||||
ea.selectElementsInView([
|
||||
await insertImageToView(
|
||||
ea,
|
||||
this.center,
|
||||
file,
|
||||
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
|
||||
),
|
||||
]);
|
||||
ea.destroy();
|
||||
}
|
||||
this.close();
|
||||
});
|
||||
actionImage = button;
|
||||
|
||||
@@ -89,7 +89,7 @@ declare const deliberateFetch: (
|
||||
payload: RequestInfo | URL,
|
||||
init?: RequestInit,
|
||||
) => Promise<Response>;
|
||||
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLStyleElement;
|
||||
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
|
||||
declare const mainDocument: Document;
|
||||
//An ugly workaround for the following situation.
|
||||
//File A is a markdown file that has an embedded Excalidraw file B
|
||||
@@ -115,6 +115,88 @@ type MarkdownRenderOverrides = {
|
||||
isTransclusion?: boolean;
|
||||
};
|
||||
|
||||
const waitForMarkdownPostProcessors = (
|
||||
container: HTMLElement,
|
||||
): Promise<void> => {
|
||||
if (
|
||||
!container.querySelector(
|
||||
".mermaid, .dataview, [class*='block-language-']",
|
||||
)
|
||||
) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const minimumWait = 250;
|
||||
const quietPeriod = 150;
|
||||
const maximumWait = 2000;
|
||||
let minimumElapsed = false;
|
||||
let quietElapsed = false;
|
||||
let quietTimer: number | null = null;
|
||||
let minimumTimer: number | null = null;
|
||||
let maximumTimer: number | null = null;
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
quietElapsed = false;
|
||||
if (quietTimer !== null) {
|
||||
window.clearTimeout(quietTimer);
|
||||
}
|
||||
quietTimer = window.setTimeout(() => {
|
||||
quietElapsed = true;
|
||||
finishIfReady();
|
||||
}, quietPeriod);
|
||||
});
|
||||
const cleanup = () => {
|
||||
observer.disconnect();
|
||||
[quietTimer, minimumTimer, maximumTimer].forEach((timer) => {
|
||||
if (timer !== null) {
|
||||
window.clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
};
|
||||
const finish = () => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const finishIfReady = () => {
|
||||
if (minimumElapsed && quietElapsed) {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
|
||||
observer.observe(container, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
characterData: true,
|
||||
});
|
||||
quietTimer = window.setTimeout(() => {
|
||||
quietElapsed = true;
|
||||
finishIfReady();
|
||||
}, quietPeriod);
|
||||
minimumTimer = window.setTimeout(() => {
|
||||
minimumElapsed = true;
|
||||
finishIfReady();
|
||||
}, minimumWait);
|
||||
maximumTimer = window.setTimeout(finish, maximumWait);
|
||||
});
|
||||
};
|
||||
|
||||
const snapshotRenderedCanvases = (container: HTMLElement): void => {
|
||||
container.querySelectorAll("canvas").forEach((canvas) => {
|
||||
try {
|
||||
const image = deliberateCreateElement(canvas.ownerDocument, "img") as HTMLImageElement;
|
||||
image.src = canvas.toDataURL("image/png");
|
||||
image.width = canvas.width;
|
||||
image.height = canvas.height;
|
||||
image.alt = canvas.getAttribute("aria-label") ?? "Rendered chart";
|
||||
canvas.replaceWith(image);
|
||||
} catch {
|
||||
// Tainted or WebGL canvases cannot always be exported; retain the canvas.
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getTransclusionRenderSettings = (
|
||||
render: MarkdownImageRenderSettings,
|
||||
): MarkdownImageRenderSettings =>
|
||||
@@ -978,6 +1060,7 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency,
|
||||
emitPolicy = "all",
|
||||
onDeferredValidationCandidates,
|
||||
sceneElements,
|
||||
}: {
|
||||
excalidrawData: ExcalidrawData;
|
||||
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
|
||||
@@ -989,13 +1072,16 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency?: number;
|
||||
emitPolicy?: LoadSceneEmitPolicy;
|
||||
onDeferredValidationCandidates?: (fileIds: Set<FileId>) => void;
|
||||
sceneElements?: readonly ExcalidrawElement[];
|
||||
}) {
|
||||
if (depth > 7) {
|
||||
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
|
||||
return;
|
||||
}
|
||||
const entries = Array.from(excalidrawData.getFileEntries());
|
||||
const markdownImageElements = excalidrawData.scene.elements.filter(
|
||||
const markdownImageElements = (
|
||||
sceneElements ?? excalidrawData.scene.elements
|
||||
).filter(
|
||||
(element: ExcalidrawElement) =>
|
||||
element.type === "image" &&
|
||||
Boolean(element.customData?.[MARKDOWN_IMAGE_CUSTOM_DATA_KEY]),
|
||||
@@ -1777,7 +1863,7 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
//4.
|
||||
//create document div - this will be the contents of the foreign object
|
||||
const mdDIV = createDiv();
|
||||
let mdDIV = createDiv();
|
||||
mdDIV.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
|
||||
mdDIV.setAttribute(
|
||||
"class",
|
||||
@@ -1790,10 +1876,27 @@ export class EmbeddedFilesLoader {
|
||||
overflow: "auto",
|
||||
display: "block",
|
||||
color: fontColor && fontColor !== "" ? fontColor : "initial",
|
||||
paddingBottom:
|
||||
overrides && !overrides.isTransclusion
|
||||
? `${overrides.render.paddingBottom}px`
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const renderHost = mainDocument.body.createDiv();
|
||||
renderHost.setAttribute("aria-hidden", "true");
|
||||
setStyle(renderHost, {
|
||||
position: "fixed",
|
||||
left: "-100000px",
|
||||
top: "0",
|
||||
width: `${linkParts.width}px`,
|
||||
opacity: "0",
|
||||
pointerEvents: "none",
|
||||
zIndex: "-1",
|
||||
});
|
||||
renderHost.appendChild(mdDIV);
|
||||
const renderComponent = new Component();
|
||||
renderComponent.load();
|
||||
let renderedDIV: HTMLDivElement | null = null;
|
||||
try {
|
||||
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
|
||||
await MarkdownRenderer.render(
|
||||
@@ -1803,8 +1906,15 @@ export class EmbeddedFilesLoader {
|
||||
file.path,
|
||||
renderComponent,
|
||||
);
|
||||
await waitForMarkdownPostProcessors(mdDIV);
|
||||
snapshotRenderedCanvases(mdDIV);
|
||||
renderedDIV = mdDIV.cloneNode(true) as HTMLDivElement;
|
||||
} finally {
|
||||
renderComponent.unload();
|
||||
renderHost.remove();
|
||||
}
|
||||
if (renderedDIV) {
|
||||
mdDIV = renderedDIV;
|
||||
}
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
@@ -1961,14 +2071,14 @@ export class EmbeddedFilesLoader {
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
if (style) {
|
||||
// Obsidian style.css does not good in this case, yet the code scanner enforces it
|
||||
const styleEl = deliberateCreateElement(iframeDoc, "style");
|
||||
const styleEl = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(styleEl, style);
|
||||
iframeDoc.head.appendChild(styleEl);
|
||||
}
|
||||
// Inject the MathJax CHTML stylesheet into the iframe so that mjx-* custom elements
|
||||
// are styled correctly when measuring scroll height and computing inline styles.
|
||||
if (mjxCHtmlStyleContent) {
|
||||
const mjxStyleEl = deliberateCreateElement(iframeDoc, "style");
|
||||
const mjxStyleEl = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(mjxStyleEl, mjxCHtmlStyleContent);
|
||||
iframeDoc.head.appendChild(mjxStyleEl);
|
||||
}
|
||||
|
||||
@@ -368,6 +368,35 @@ export function parseMarkdownImages(data: string): Map<FileId, MarkdownImageData
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a local Markdown-image block's marker comments while preserving its
|
||||
* Markdown body and surrounding document content exactly.
|
||||
*
|
||||
* @param data - Complete Excalidraw Markdown document.
|
||||
* @param fileId - File ID identifying the local Markdown-image block.
|
||||
* @param markdown - Optional current in-memory body to preserve instead of a
|
||||
* potentially stale body from the document.
|
||||
* @returns The document with the matching marker comments removed.
|
||||
*/
|
||||
export function unwrapMarkdownImageBlock(
|
||||
data: string,
|
||||
fileId: FileId,
|
||||
markdown?: string,
|
||||
): string {
|
||||
const blocks = getMarkdownImageBlocks(data).filter(
|
||||
(block) => block.fileId === fileId,
|
||||
);
|
||||
let updated = data;
|
||||
for (let index = blocks.length - 1; index >= 0; index--) {
|
||||
const block = blocks[index];
|
||||
updated =
|
||||
updated.slice(0, block.start) +
|
||||
(markdown ?? updated.slice(block.bodyStart, block.bodyEnd)) +
|
||||
updated.slice(block.end);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
const serializeMarkdownImageBlock = (
|
||||
fileId: FileId,
|
||||
markdown: string,
|
||||
@@ -2004,7 +2033,9 @@ export class ExcalidrawData {
|
||||
return dirty;
|
||||
}
|
||||
|
||||
//assing new fileId to duplicate equation and markdown files
|
||||
// Assign new fileIds where duplicate image references require independent
|
||||
// backing data. Local Markdown images deliberately keep a shared fileId;
|
||||
// the explicit "Duplicate selected image" action creates an independent ID.
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/601
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/593
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/297
|
||||
@@ -2030,6 +2061,9 @@ export class ExcalidrawData {
|
||||
if (mermaid) {
|
||||
return;
|
||||
}
|
||||
if (markdownImage) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (getMermaidText(images[idx])) {
|
||||
this.setMermaid(fileId, {
|
||||
@@ -2039,7 +2073,7 @@ export class ExcalidrawData {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!embeddedFile && !equation && !mermaid && !markdownImage) {
|
||||
if (!embeddedFile && !equation && !mermaid) {
|
||||
//processing freshly pasted images from likely anotehr instance of excalidraw (e.g. Excalidraw.com, or another Obsidian instance)
|
||||
return;
|
||||
}
|
||||
@@ -2070,9 +2104,6 @@ export class ExcalidrawData {
|
||||
isLoaded: false,
|
||||
});
|
||||
}
|
||||
if (markdownImage) {
|
||||
this.setMarkdownImage(newId as FileId, { ...markdownImage });
|
||||
}
|
||||
}
|
||||
processedIds.add(fileId);
|
||||
});
|
||||
@@ -2722,7 +2753,7 @@ export const getTransclusion = async (
|
||||
if (!para) {
|
||||
return { contents: linkParts.original.trim(), lineNum: 0 };
|
||||
}
|
||||
if (["blockquote"].includes(para.type)) {
|
||||
if (para.type === "blockquote" && para.children?.[0]) {
|
||||
para = para.children[0];
|
||||
} //blockquotes are special, they have one child, which has the paragraph
|
||||
const startPos = para.position.start.offset;
|
||||
@@ -2739,38 +2770,46 @@ export const getTransclusion = async (
|
||||
}
|
||||
|
||||
const headings = blocks.filter(
|
||||
(block: MarkdownBlockCacheEntry) => block.display.search(/^#+\s/) === 0,
|
||||
(block: MarkdownBlockCacheEntry) =>
|
||||
block.node.type === "heading" &&
|
||||
block.display.search(/^#+\s/) === 0 &&
|
||||
Boolean(block.node.children?.[0]?.position?.start),
|
||||
); // startsWith("#"));
|
||||
let startPos: number = null;
|
||||
let lineNum: number = 0;
|
||||
let endPos: number = null;
|
||||
let depth: number = 1;
|
||||
for (let i = 0; i < headings.length; i++) {
|
||||
if (startPos && !endPos) {
|
||||
if (startPos !== null) {
|
||||
let j = i;
|
||||
while (j < headings.length && headings[j].node.depth > depth) {
|
||||
while (
|
||||
j < headings.length &&
|
||||
(headings[j].node.depth ?? 1) > depth
|
||||
) {
|
||||
j++;
|
||||
}
|
||||
if (j === headings.length && headings[j - 1].node.depth > depth) {
|
||||
if (j === headings.length) {
|
||||
return {
|
||||
leadingHashes: `${"#".repeat(depth)} `,
|
||||
contents: contents.substring(startPos).trim(),
|
||||
lineNum,
|
||||
};
|
||||
}
|
||||
endPos = headings[j].node.position.start.offset - 1;
|
||||
const endPos = headings[j].node.position.start.offset - 1;
|
||||
return {
|
||||
leadingHashes: `${"#".repeat(depth)} `,
|
||||
contents: contents.substring(startPos, endPos).trim(),
|
||||
lineNum,
|
||||
};
|
||||
}
|
||||
const c = headings[i].node.children[0];
|
||||
const c = headings[i].node.children?.[0];
|
||||
if (!c) {
|
||||
continue;
|
||||
}
|
||||
const dataHeading = headings[i].node.data?.hProperties?.dataHeading;
|
||||
const cc = c?.children;
|
||||
//const refNoSpace = linkParts.ref.replaceAll(" ","");
|
||||
if (
|
||||
!startPos &&
|
||||
startPos === null &&
|
||||
(cleanBlockRef(c?.value) === linkParts.ref ||
|
||||
cleanBlockRef(c?.title) === linkParts.ref ||
|
||||
cleanBlockRef(dataHeading) === linkParts.ref ||
|
||||
@@ -2780,12 +2819,12 @@ export const getTransclusion = async (
|
||||
cleanSectionHeading(dataHeading) === linkParts.ref ||
|
||||
(cc ? cleanSectionHeading(cc[0]?.value) === linkParts.ref : false))
|
||||
) {
|
||||
startPos = headings[i].node.children[0]?.position.start.offset; //
|
||||
depth = headings[i].node.depth;
|
||||
lineNum = headings[i].node.children[0]?.position.start.line; //
|
||||
startPos = c.position.start.offset;
|
||||
depth = headings[i].node.depth ?? 1;
|
||||
lineNum = c.position.start.line;
|
||||
}
|
||||
}
|
||||
if (startPos) {
|
||||
if (startPos !== null) {
|
||||
return {
|
||||
leadingHashes: `${"#".repeat(depth)} `,
|
||||
contents: contents.substring(startPos).trim(),
|
||||
|
||||
@@ -47,7 +47,9 @@ const getKey = (key: ImageKey): string =>
|
||||
: key.previewImageType === PreviewImageType.PNG
|
||||
? 0
|
||||
: 2
|
||||
}#${key.scale}${key.isTransparent ? "#t" : ""}`; //key.isSVG ? 1 : 0
|
||||
}#${key.scale}${key.isTransparent ? "#t" : ""}${
|
||||
key.padding === undefined ? "" : `#p${key.padding}`
|
||||
}`; //key.isSVG ? 1 : 0
|
||||
|
||||
class ImageCache {
|
||||
private dbName: string;
|
||||
|
||||
+78
-42
@@ -1,4 +1,5 @@
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { TFile } from "obsidian";
|
||||
import type {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawEmbeddableElement,
|
||||
@@ -115,25 +116,46 @@ export function setMarkdownImageCustomData(
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolves the current local fragment or external Markdown transclusion. */
|
||||
/** Resolves a Markdown image element or Markdown file to its renderable source. */
|
||||
export async function getMarkdownImageSource(
|
||||
view: ExcalidrawView,
|
||||
element: ExcalidrawImageElement,
|
||||
source: ExcalidrawImageElement | TFile | EmbeddedFile,
|
||||
): Promise<MarkdownImageSourceData | null> {
|
||||
const customData = getMarkdownImageCustomData(element);
|
||||
let sourceFile: TFile | null;
|
||||
let suppliedEmbeddedFile: EmbeddedFile | null;
|
||||
let element: ExcalidrawImageElement | null;
|
||||
if (source instanceof TFile) {
|
||||
sourceFile = source;
|
||||
suppliedEmbeddedFile = null;
|
||||
element = null;
|
||||
} else if (source instanceof EmbeddedFile) {
|
||||
sourceFile = null;
|
||||
suppliedEmbeddedFile = source;
|
||||
element = null;
|
||||
} else {
|
||||
sourceFile = null;
|
||||
suppliedEmbeddedFile = null;
|
||||
element = source;
|
||||
}
|
||||
const customData = element ? getMarkdownImageCustomData(element) : null;
|
||||
const preferredSource = customData?.source;
|
||||
const local =
|
||||
preferredSource === "external"
|
||||
!element || preferredSource === "external"
|
||||
? undefined
|
||||
: view.excalidrawData.getMarkdownImage(element.fileId);
|
||||
if (local !== undefined) {
|
||||
return { markdown: local.markdown, source: "local" };
|
||||
}
|
||||
const embeddedFile = view.excalidrawData.getFile(element.fileId);
|
||||
const embeddedFile = element
|
||||
? view.excalidrawData.getFile(element.fileId)
|
||||
: (suppliedEmbeddedFile ??
|
||||
new EmbeddedFile(view.plugin, view.file.path, sourceFile.path));
|
||||
if (
|
||||
!embeddedFile?.file ||
|
||||
embeddedFile.file.extension.toLowerCase() !== "md" ||
|
||||
(view.plugin.isExcalidrawFile(embeddedFile.file) && !customData)
|
||||
(view.plugin.isExcalidrawFile(embeddedFile.file) &&
|
||||
!customData &&
|
||||
!suppliedEmbeddedFile?.linkParts.ref)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -188,6 +210,28 @@ const setRenderedMarkdownImageFile = (
|
||||
};
|
||||
};
|
||||
|
||||
const setMarkdownImageSource = (
|
||||
view: ExcalidrawView,
|
||||
fileId: FileId,
|
||||
sourceData: MarkdownImageSourceData,
|
||||
): void => {
|
||||
if (sourceData.source === "local") {
|
||||
view.excalidrawData.setMarkdownImage(fileId, {
|
||||
markdown: sourceData.markdown,
|
||||
});
|
||||
} else if (sourceData.embeddedFile) {
|
||||
view.excalidrawData.setFile(fileId, sourceData.embeddedFile);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteMarkdownImageSource = (
|
||||
view: ExcalidrawView,
|
||||
fileId: FileId,
|
||||
): void => {
|
||||
view.excalidrawData.deleteMarkdownImage(fileId, true);
|
||||
view.excalidrawData.deleteFile(fileId);
|
||||
};
|
||||
|
||||
const getEmbeddableLinkTarget = (link: string): string | null => {
|
||||
const result = REGEX_LINK.getRes(link).next();
|
||||
if (result.value) {
|
||||
@@ -273,20 +317,13 @@ export async function convertEmbeddableElementToMarkdownImage(
|
||||
render,
|
||||
);
|
||||
setRenderedMarkdownImageFile(ea, fileId, rendered);
|
||||
if (sourceData.source === "local") {
|
||||
view.excalidrawData.setMarkdownImage(fileId, {
|
||||
markdown: sourceData.markdown,
|
||||
});
|
||||
} else if (sourceData.embeddedFile) {
|
||||
view.excalidrawData.setFile(fileId, sourceData.embeddedFile);
|
||||
}
|
||||
setMarkdownImageSource(view, fileId, sourceData);
|
||||
let committed = false;
|
||||
try {
|
||||
committed = await commitElements(ea);
|
||||
} finally {
|
||||
if (!committed) {
|
||||
view.excalidrawData.deleteMarkdownImage(fileId, true);
|
||||
view.excalidrawData.deleteFile(fileId);
|
||||
deleteMarkdownImageSource(view, fileId);
|
||||
}
|
||||
}
|
||||
if (!committed) {
|
||||
@@ -379,24 +416,37 @@ export function getLevelOneMarkdownHeadings(
|
||||
return headings;
|
||||
}
|
||||
|
||||
/** Inserts a new local editable Markdown image without adding wrapper content. */
|
||||
/** Inserts an editable Markdown image from local text or a linked Markdown note. */
|
||||
export async function insertMarkdownImage(
|
||||
view: ExcalidrawView,
|
||||
markdown: string = "",
|
||||
): Promise<string | null> {
|
||||
source: string | TFile | EmbeddedFile = "",
|
||||
position: { x: number; y: number } = view.currentPosition,
|
||||
): Promise<ExcalidrawImageElement | null> {
|
||||
if (!view.excalidrawAPI || !view.file) {
|
||||
return null;
|
||||
}
|
||||
const sourceData =
|
||||
typeof source === "string"
|
||||
? { markdown: source, source: "local" as const }
|
||||
: await getMarkdownImageSource(view, source);
|
||||
if (!sourceData) {
|
||||
return null;
|
||||
}
|
||||
const render = getMarkdownImageRenderSettings(view.plugin);
|
||||
const rendered = await renderMarkdown(view, markdown, render);
|
||||
const rendered = await renderMarkdown(
|
||||
view,
|
||||
sourceData.markdown,
|
||||
render,
|
||||
sourceData.embeddedFile?.file ?? view.file,
|
||||
);
|
||||
if (!rendered.dataURL || rendered.size.height <= 0) {
|
||||
return null;
|
||||
}
|
||||
const ea = getEA(view);
|
||||
const fileId = fileid() as FileId;
|
||||
const id = await ea.addImage(
|
||||
view.currentPosition.x,
|
||||
view.currentPosition.y,
|
||||
position.x,
|
||||
position.y,
|
||||
rendered.dataURL,
|
||||
false,
|
||||
false,
|
||||
@@ -406,42 +456,28 @@ export async function insertMarkdownImage(
|
||||
return null;
|
||||
}
|
||||
const element = ea.getElement(id) as Mutable<ExcalidrawImageElement>;
|
||||
const generatedFileId = element.fileId;
|
||||
const image = ea.imagesDict[generatedFileId];
|
||||
delete ea.imagesDict[generatedFileId];
|
||||
delete ea.imagesDict[element.fileId];
|
||||
element.fileId = fileId;
|
||||
element.width = render.width;
|
||||
element.height = rendered.size.height;
|
||||
element.crop = null;
|
||||
setMarkdownImageCustomData(element, "local", render);
|
||||
ea.imagesDict[fileId] = {
|
||||
...image,
|
||||
id: fileId,
|
||||
dataURL: rendered.dataURL,
|
||||
mimeType: "image/svg+xml",
|
||||
size: rendered.size,
|
||||
hasSVGwithBitmap: rendered.hasSVGwithBitmap,
|
||||
};
|
||||
view.excalidrawData.setMarkdownImage(fileId, { markdown });
|
||||
setMarkdownImageCustomData(element, sourceData.source, render);
|
||||
setRenderedMarkdownImageFile(ea, fileId, rendered);
|
||||
setMarkdownImageSource(view, fileId, sourceData);
|
||||
let committed = false;
|
||||
try {
|
||||
committed = await commitElements(ea, true);
|
||||
} finally {
|
||||
if (!committed) {
|
||||
view.excalidrawData.deleteMarkdownImage(fileId, true);
|
||||
deleteMarkdownImageSource(view, fileId);
|
||||
}
|
||||
}
|
||||
if (!committed) {
|
||||
return null;
|
||||
}
|
||||
view.setDirty();
|
||||
const inserted = view
|
||||
.getViewElements()
|
||||
.find((candidate) => candidate.id === id);
|
||||
if (inserted) {
|
||||
view.excalidrawAPI.selectElements([inserted]);
|
||||
}
|
||||
return id;
|
||||
view.excalidrawAPI.selectElements([element]);
|
||||
return element;
|
||||
}
|
||||
|
||||
/** Duplicates a local Markdown image with independent element and file IDs. */
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
TFolder,
|
||||
} from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
|
||||
export class FolderSuggestionModal extends SuggestionModal<TFolder> {
|
||||
text: TextComponent;
|
||||
cache: CachedMetadata;
|
||||
folders: TFolder[];
|
||||
folder: TFolder;
|
||||
private handleGetFolder: () => void;
|
||||
|
||||
constructor(app: App, input: TextComponent, items: TFolder[]) {
|
||||
super(app, input.inputEl, items);
|
||||
this.folders = [...items];
|
||||
this.text = input;
|
||||
|
||||
// Pre-bind the handler
|
||||
this.handleGetFolder = () => this.getFolder();
|
||||
this.inputEl.addEventListener("input", this.handleGetFolder);
|
||||
}
|
||||
getFolder() {
|
||||
const v = this.inputEl.value;
|
||||
const folder = this.app.vault.getAbstractFileByPath(v);
|
||||
if (folder == this.folder) {
|
||||
return;
|
||||
}
|
||||
if (!(folder instanceof TFolder)) {
|
||||
return;
|
||||
}
|
||||
this.folder = folder;
|
||||
|
||||
this.onInputChanged();
|
||||
}
|
||||
close(): void {
|
||||
this.inputEl.removeEventListener("input", this.handleGetFolder);
|
||||
super.close();
|
||||
}
|
||||
getItemText(item: TFolder) {
|
||||
return item.path;
|
||||
}
|
||||
onChooseItem(item: TFolder) {
|
||||
this.text.setValue(item.path);
|
||||
this.folder = item;
|
||||
}
|
||||
selectSuggestion({ item }: FuzzyMatch<TFolder>) {
|
||||
const link = item.path;
|
||||
|
||||
this.text.setValue(link);
|
||||
this.onClose();
|
||||
|
||||
this.close();
|
||||
}
|
||||
renderSuggestion(result: FuzzyMatch<TFolder>, el: HTMLElement) {
|
||||
const { item, match: matches } = result || {};
|
||||
const content = el.createDiv({
|
||||
cls: "suggestion-content",
|
||||
});
|
||||
if (!item) {
|
||||
content.setText(this.emptyStateText);
|
||||
content.parentElement.addClass("is-selected");
|
||||
return;
|
||||
}
|
||||
|
||||
const pathLength = item.path.length - item.name.length;
|
||||
const matchElements = matches.matches.map(() => {
|
||||
return createSpan("suggestion-highlight");
|
||||
});
|
||||
for (let i = pathLength; i < item.path.length; i++) {
|
||||
const match = matches.matches.find((m) => m[0] === i);
|
||||
if (match) {
|
||||
const element = matchElements[matches.matches.indexOf(match)];
|
||||
content.appendChild(element);
|
||||
element.appendText(item.path.substring(match[0], match[1]));
|
||||
|
||||
i += match[1] - match[0] - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
content.appendText(item.path[i]);
|
||||
}
|
||||
el.createDiv({
|
||||
cls: "suggestion-note",
|
||||
text: item.path,
|
||||
});
|
||||
}
|
||||
|
||||
getItems() {
|
||||
return this.folders;
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
TFile,
|
||||
BlockCache,
|
||||
HeadingCache,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
} from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
|
||||
export class PathSuggestionModal extends SuggestionModal<
|
||||
TFile | BlockCache | HeadingCache
|
||||
> {
|
||||
file: TFile;
|
||||
files: TFile[];
|
||||
text: TextComponent;
|
||||
cache: CachedMetadata;
|
||||
private handleGetFile: () => void;
|
||||
|
||||
constructor(app: App, input: TextComponent, items: TFile[]) {
|
||||
super(app, input.inputEl, items);
|
||||
this.files = [...items];
|
||||
this.text = input;
|
||||
|
||||
// Pre-bind the handler
|
||||
this.handleGetFile = () => this.getFile();
|
||||
this.inputEl.addEventListener("input", this.handleGetFile);
|
||||
}
|
||||
|
||||
getFile() {
|
||||
const v = this.inputEl.value;
|
||||
const file = this.app.metadataCache.getFirstLinkpathDest(
|
||||
v.split(/[\^#]/).shift() || "",
|
||||
"",
|
||||
);
|
||||
if (file == this.file) {
|
||||
return;
|
||||
}
|
||||
this.file = file;
|
||||
if (this.file) {
|
||||
this.cache = this.app.metadataCache.getFileCache(this.file);
|
||||
}
|
||||
this.onInputChanged();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.inputEl.removeEventListener("input", this.handleGetFile);
|
||||
super.close();
|
||||
}
|
||||
|
||||
getItemText(item: TFile | HeadingCache | BlockCache) {
|
||||
if (item instanceof TFile) {
|
||||
return item.path;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(item, "heading")) {
|
||||
return (<HeadingCache>item).heading;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(item, "id")) {
|
||||
return (<BlockCache>item).id;
|
||||
}
|
||||
}
|
||||
|
||||
onChooseItem(item: TFile | HeadingCache | BlockCache) {
|
||||
if (item instanceof TFile) {
|
||||
this.text.setValue(item.basename);
|
||||
this.file = item;
|
||||
this.cache = this.app.metadataCache.getFileCache(this.file);
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "heading")) {
|
||||
this.text.setValue(
|
||||
`${this.file.basename}#${(<HeadingCache>item).heading}`,
|
||||
);
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "id")) {
|
||||
this.text.setValue(`${this.file.basename}^${(<BlockCache>item).id}`);
|
||||
}
|
||||
}
|
||||
|
||||
selectSuggestion({ item }: FuzzyMatch<TFile | BlockCache | HeadingCache>) {
|
||||
let link: string;
|
||||
if (item instanceof TFile) {
|
||||
link = item.basename;
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "heading")) {
|
||||
link = `${this.file.basename}#${(<HeadingCache>item).heading}`;
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "id")) {
|
||||
link = `${this.file.basename}^${(<BlockCache>item).id}`;
|
||||
}
|
||||
|
||||
this.text.setValue(link);
|
||||
this.onClose();
|
||||
|
||||
this.close();
|
||||
}
|
||||
|
||||
renderSuggestion(
|
||||
result: FuzzyMatch<TFile | BlockCache | HeadingCache>,
|
||||
el: HTMLElement,
|
||||
) {
|
||||
const { item, match: matches } = result || {};
|
||||
const content = el.createDiv({
|
||||
cls: "suggestion-content",
|
||||
});
|
||||
if (!item) {
|
||||
content.setText(this.emptyStateText);
|
||||
content.parentElement.addClass("is-selected");
|
||||
return;
|
||||
}
|
||||
|
||||
if (item instanceof TFile) {
|
||||
const pathLength = item.path.length - item.name.length;
|
||||
const matchElements = matches.matches.map(() => {
|
||||
return createSpan("suggestion-highlight");
|
||||
});
|
||||
for (
|
||||
let i = pathLength;
|
||||
i < item.path.length - item.extension.length - 1;
|
||||
i++
|
||||
) {
|
||||
const match = matches.matches.find((m) => m[0] === i);
|
||||
if (match) {
|
||||
const element = matchElements[matches.matches.indexOf(match)];
|
||||
content.appendChild(element);
|
||||
element.appendText(item.path.substring(match[0], match[1]));
|
||||
|
||||
i += match[1] - match[0] - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
content.appendText(item.path[i]);
|
||||
}
|
||||
el.createDiv({
|
||||
cls: "suggestion-note",
|
||||
text: item.path,
|
||||
});
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "heading")) {
|
||||
content.setText((<HeadingCache>item).heading);
|
||||
content.prepend(
|
||||
createSpan({
|
||||
cls: "suggestion-flair",
|
||||
text: `H${(<HeadingCache>item).level}`,
|
||||
}),
|
||||
);
|
||||
} else if (Object.prototype.hasOwnProperty.call(item, "id")) {
|
||||
content.setText((<BlockCache>item).id);
|
||||
}
|
||||
}
|
||||
|
||||
get headings() {
|
||||
if (!this.file) {
|
||||
return [];
|
||||
}
|
||||
if (!this.cache) {
|
||||
this.cache = this.app.metadataCache.getFileCache(this.file);
|
||||
}
|
||||
return this.cache.headings || [];
|
||||
}
|
||||
|
||||
get blocks() {
|
||||
if (!this.file) {
|
||||
return [];
|
||||
}
|
||||
if (!this.cache) {
|
||||
this.cache = this.app.metadataCache.getFileCache(this.file);
|
||||
}
|
||||
return Object.values(this.cache.blocks || {}) || [];
|
||||
}
|
||||
|
||||
getItems() {
|
||||
const v = this.inputEl.value;
|
||||
if (/#/.test(v)) {
|
||||
this.modifyInput = (i) => i.split(/#/).pop();
|
||||
return this.headings;
|
||||
} else if (/\^/.test(v)) {
|
||||
this.modifyInput = (i) => i.split(/\^/).pop();
|
||||
return this.blocks;
|
||||
}
|
||||
return this.files;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
AbstractInputSuggest,
|
||||
App,
|
||||
TAbstractFile,
|
||||
TFolder,
|
||||
} from "obsidian";
|
||||
|
||||
type VaultPathSuggestionKind = "file" | "folder";
|
||||
|
||||
/** Adds reusable Vault-aware completion to settings path inputs. */
|
||||
export class VaultPathSuggest extends AbstractInputSuggest<TAbstractFile> {
|
||||
private readonly candidates: TAbstractFile[];
|
||||
private readonly input: HTMLInputElement;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
inputEl: HTMLInputElement,
|
||||
kind: VaultPathSuggestionKind,
|
||||
extensions?: readonly string[],
|
||||
) {
|
||||
super(app, inputEl);
|
||||
this.input = inputEl;
|
||||
const normalizedExtensions = extensions?.map((extension) =>
|
||||
extension.toLowerCase().replace(/^\./, ""),
|
||||
);
|
||||
this.candidates =
|
||||
kind === "folder"
|
||||
? app.vault
|
||||
.getAllLoadedFiles()
|
||||
.filter((file) => file instanceof TFolder)
|
||||
: app.vault
|
||||
.getFiles()
|
||||
.filter(
|
||||
(file) =>
|
||||
!normalizedExtensions ||
|
||||
normalizedExtensions.includes(file.extension.toLowerCase()),
|
||||
);
|
||||
this.limit = 30;
|
||||
}
|
||||
|
||||
protected getSuggestions(query: string): TAbstractFile[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
if (!normalizedQuery) {
|
||||
return this.candidates.slice(0, this.limit);
|
||||
}
|
||||
const isPathQuery = normalizedQuery.includes("/");
|
||||
return this.candidates
|
||||
.filter((file) => {
|
||||
const path = file.path.toLowerCase();
|
||||
return isPathQuery
|
||||
? path.startsWith(normalizedQuery)
|
||||
: file.name.toLowerCase().startsWith(normalizedQuery) ||
|
||||
path.startsWith(normalizedQuery);
|
||||
})
|
||||
.sort((a, b) => a.path.localeCompare(b.path))
|
||||
.slice(0, this.limit);
|
||||
}
|
||||
|
||||
renderSuggestion(file: TAbstractFile, el: HTMLElement): void {
|
||||
el.createDiv({ text: file.name });
|
||||
if (file.path !== file.name) {
|
||||
el.createDiv({ cls: "suggestion-note", text: file.path });
|
||||
}
|
||||
}
|
||||
|
||||
selectSuggestion(file: TAbstractFile): void {
|
||||
this.setValue(file.path);
|
||||
const inputEl = this.getInputEl();
|
||||
inputEl.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
this.close();
|
||||
}
|
||||
|
||||
private getInputEl(): HTMLInputElement {
|
||||
return this.input;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { App, TFile } from "obsidian";
|
||||
import { resolveSubpath, type App, type TFile } from "obsidian";
|
||||
import { MD_EX_SECTIONS, nanoid } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ScriptEngine } from "src/shared/Scripts";
|
||||
@@ -24,6 +24,41 @@ function isHeadingBlockEntry(entry: BlockCacheEntry): entry is HeadingBlockEntry
|
||||
return Boolean(entry.display && entry.node?.type === "heading");
|
||||
}
|
||||
|
||||
export type MarkdownHeadingSubpath = {
|
||||
display: string;
|
||||
subpath: string;
|
||||
};
|
||||
|
||||
/** Returns link subpaths for user-authored Markdown headings. */
|
||||
export async function getMarkdownHeadingSubpaths(
|
||||
app: App,
|
||||
file: TFile,
|
||||
isExcalidrawFile: boolean,
|
||||
): Promise<MarkdownHeadingSubpath[]> {
|
||||
const sections = (
|
||||
await app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
file,
|
||||
)
|
||||
).blocks
|
||||
.filter(isHeadingBlockEntry)
|
||||
.filter(
|
||||
(entry) =>
|
||||
!isExcalidrawFile || !MD_EX_SECTIONS.includes(entry.display),
|
||||
)
|
||||
.map((entry) => ({
|
||||
display: entry.display,
|
||||
subpath: `#${cleanSectionHeading(entry.display)}`,
|
||||
}));
|
||||
const fileCache = app.metadataCache.getFileCache(file);
|
||||
return fileCache
|
||||
? sections.filter(
|
||||
(section) =>
|
||||
resolveSubpath(fileCache, section.subpath)?.type === "heading",
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
function isParagraphLikeBlockEntry(
|
||||
entry: BlockCacheEntry,
|
||||
): entry is ParagraphLikeBlockEntry {
|
||||
@@ -45,20 +80,12 @@ export async function selectMarkdownHeadingSubpath(
|
||||
isExcalidrawFile: boolean,
|
||||
isCancelled?: () => boolean,
|
||||
): Promise<string | null> {
|
||||
const sections = (
|
||||
await app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
file,
|
||||
)
|
||||
).blocks
|
||||
.filter(isHeadingBlockEntry)
|
||||
.filter(
|
||||
(entry) =>
|
||||
!isExcalidrawFile || !MD_EX_SECTIONS.includes(entry.display),
|
||||
);
|
||||
const values = sections.map(
|
||||
(entry) => `#${cleanSectionHeading(entry.display)}`,
|
||||
const sections = await getMarkdownHeadingSubpaths(
|
||||
app,
|
||||
file,
|
||||
isExcalidrawFile,
|
||||
);
|
||||
const values = sections.map((entry) => entry.subpath);
|
||||
const display = sections.map((entry) => entry.display);
|
||||
if (!isExcalidrawFile) {
|
||||
values.unshift("");
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
import { App, Menu, ValueComponent, type TFile } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import type { SelectableFontOption } from "src/types/fontTypes";
|
||||
import { removeStyle, setStyle } from "src/utils/styleUtils";
|
||||
|
||||
type LoadedPreviewFont = {
|
||||
document: Document;
|
||||
face: FontFace;
|
||||
family: string;
|
||||
modified: number;
|
||||
};
|
||||
|
||||
let fontPickerId = 0;
|
||||
|
||||
const quoteFontFamily = (fontFamily: string): string =>
|
||||
`"${fontFamily.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
||||
|
||||
/**
|
||||
* Obsidian-styled font selector whose options preview their respective faces.
|
||||
*
|
||||
* The option provider is invoked whenever the menu opens, allowing vault font
|
||||
* additions, removals, and renames to appear without maintaining a file cache.
|
||||
* Local font binaries are loaded only for the selected option and visible menu
|
||||
* rows, and are registered in the document that owns the control.
|
||||
*/
|
||||
export class FontPickerComponent extends ValueComponent<string> {
|
||||
public readonly buttonEl: HTMLButtonElement;
|
||||
private readonly labelEl: HTMLSpanElement;
|
||||
private readonly id = ++fontPickerId;
|
||||
private previewFontId = 0;
|
||||
private value = "";
|
||||
private onChanged: (value: string) => void = () => {};
|
||||
private menu: Menu | null = null;
|
||||
private optionObserver: IntersectionObserver | null = null;
|
||||
private readonly loadedPreviewFonts = new Map<string, LoadedPreviewFont>();
|
||||
private readonly handleClick = (): void => this.openMenu();
|
||||
|
||||
public constructor(
|
||||
containerEl: HTMLElement,
|
||||
private readonly app: App,
|
||||
private readonly getOptions: () => SelectableFontOption[],
|
||||
) {
|
||||
super();
|
||||
this.buttonEl = containerEl.createEl("button", {
|
||||
cls: "dropdown excalidraw-font-picker",
|
||||
attr: {
|
||||
type: "button",
|
||||
"aria-haspopup": "menu",
|
||||
"aria-expanded": "false",
|
||||
},
|
||||
});
|
||||
this.labelEl = this.buttonEl.createSpan({
|
||||
cls: "excalidraw-font-picker__label",
|
||||
});
|
||||
this.buttonEl.addEventListener("click", this.handleClick);
|
||||
}
|
||||
|
||||
/** Returns the currently selected font value. */
|
||||
public getValue(): string {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/** Selects a font without invoking the change callback. */
|
||||
public setValue(value: string): this {
|
||||
this.value = value;
|
||||
this.updateTrigger(this.getOptions());
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Registers the callback invoked when the user selects a font. */
|
||||
public onChange(callback: (value: string) => void): this {
|
||||
this.onChanged = callback;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Enables or disables interaction with the picker. */
|
||||
public setDisabled(disabled: boolean): this {
|
||||
this.disabled = disabled;
|
||||
this.buttonEl.disabled = disabled;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets the accessible label on the picker trigger. */
|
||||
public setAriaLabel(label: string): this {
|
||||
this.buttonEl.setAttribute("aria-label", label);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Releases menu, DOM, observer, and document font resources. */
|
||||
public destroy(): void {
|
||||
this.menu?.hide();
|
||||
this.menu = null;
|
||||
this.optionObserver?.disconnect();
|
||||
this.optionObserver = null;
|
||||
this.buttonEl.removeEventListener("click", this.handleClick);
|
||||
for (const loaded of this.loadedPreviewFonts.values()) {
|
||||
loaded.document.fonts.delete(loaded.face);
|
||||
}
|
||||
this.loadedPreviewFonts.clear();
|
||||
this.buttonEl.remove();
|
||||
}
|
||||
|
||||
private openMenu(): void {
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
this.menu?.hide();
|
||||
this.optionObserver?.disconnect();
|
||||
this.optionObserver = null;
|
||||
|
||||
// Deliberately refresh on every open: the vault may have gained, lost, or
|
||||
// renamed a font since this settings page or sidepanel was rendered.
|
||||
const options = this.getOptions();
|
||||
this.prunePreviewFonts(options);
|
||||
this.updateTrigger(options);
|
||||
|
||||
const doc = this.buttonEl.ownerDocument;
|
||||
const localPreviews: Array<{
|
||||
option: SelectableFontOption;
|
||||
element: HTMLSpanElement;
|
||||
}> = [];
|
||||
let firstOptionEl: HTMLSpanElement | null = null;
|
||||
const menu = new Menu().setUseNativeMenu(false);
|
||||
for (const option of options) {
|
||||
menu.addItem((item) => {
|
||||
const title = createFragment();
|
||||
const label = title.createSpan({
|
||||
cls: "excalidraw-font-picker__option",
|
||||
text: option.label,
|
||||
});
|
||||
firstOptionEl ??= label;
|
||||
if (option.fontFile) {
|
||||
localPreviews.push({ option, element: label });
|
||||
} else {
|
||||
this.applyPreview(option, label);
|
||||
}
|
||||
item
|
||||
.setTitle(title)
|
||||
.setChecked(option.value === this.value)
|
||||
.onClick(() => {
|
||||
this.setValue(option.value);
|
||||
this.onChanged(option.value);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
menu.onHide(() => {
|
||||
this.optionObserver?.disconnect();
|
||||
this.optionObserver = null;
|
||||
this.buttonEl.setAttribute("aria-expanded", "false");
|
||||
if (this.menu === menu) {
|
||||
this.menu = null;
|
||||
}
|
||||
});
|
||||
this.menu = menu;
|
||||
this.buttonEl.setAttribute("aria-expanded", "true");
|
||||
const rect = this.buttonEl.getBoundingClientRect();
|
||||
if (!DEVICE.isMobile) {
|
||||
doc.body.classList.add("excalidraw-font-picker-menu-opening");
|
||||
}
|
||||
try {
|
||||
menu.showAtPosition(
|
||||
{ x: rect.left, y: rect.bottom, width: rect.width },
|
||||
doc,
|
||||
);
|
||||
if (!DEVICE.isMobile) {
|
||||
firstOptionEl
|
||||
?.closest<HTMLElement>(".menu")
|
||||
?.classList.add("excalidraw-font-picker-menu--desktop");
|
||||
}
|
||||
} finally {
|
||||
doc.body.classList.remove("excalidraw-font-picker-menu-opening");
|
||||
}
|
||||
this.observeLocalPreviews(localPreviews, doc);
|
||||
}
|
||||
|
||||
private observeLocalPreviews(
|
||||
previews: Array<{
|
||||
option: SelectableFontOption;
|
||||
element: HTMLSpanElement;
|
||||
}>,
|
||||
doc: Document,
|
||||
): void {
|
||||
const ownerWindow = doc.defaultView;
|
||||
if (!ownerWindow?.IntersectionObserver) {
|
||||
previews.forEach(({ option, element }) =>
|
||||
this.applyPreview(option, element),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const optionsByElement = new Map(
|
||||
previews.map(({ option, element }) => [element, option]),
|
||||
);
|
||||
this.optionObserver = new ownerWindow.IntersectionObserver(
|
||||
(entries, observer) => {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isIntersecting) {
|
||||
continue;
|
||||
}
|
||||
const element = entry.target as HTMLSpanElement;
|
||||
const option = optionsByElement.get(element);
|
||||
if (option) {
|
||||
this.applyPreview(option, element);
|
||||
}
|
||||
observer.unobserve(element);
|
||||
}
|
||||
},
|
||||
{ rootMargin: "80px 0px" },
|
||||
);
|
||||
previews.forEach(({ element }) => this.optionObserver?.observe(element));
|
||||
}
|
||||
|
||||
private updateTrigger(options: SelectableFontOption[]): void {
|
||||
const option = options.find((candidate) => candidate.value === this.value);
|
||||
this.labelEl.textContent = option?.label ?? this.value;
|
||||
if (option) {
|
||||
this.applyPreview(option, this.labelEl);
|
||||
} else {
|
||||
removeStyle(this.labelEl, ["fontFamily"]);
|
||||
}
|
||||
}
|
||||
|
||||
private applyPreview(
|
||||
option: SelectableFontOption,
|
||||
element: HTMLElement,
|
||||
): void {
|
||||
const family = option.fontFile
|
||||
? this.ensureLocalPreviewFont(option.fontFile)
|
||||
: option.value;
|
||||
if (!family) {
|
||||
removeStyle(element, ["fontFamily"]);
|
||||
return;
|
||||
}
|
||||
setStyle(element, { fontFamily: quoteFontFamily(family) });
|
||||
}
|
||||
|
||||
private ensureLocalPreviewFont(file: TFile): string | null {
|
||||
const doc = this.buttonEl.ownerDocument;
|
||||
const existing = this.loadedPreviewFonts.get(file.path);
|
||||
if (
|
||||
existing &&
|
||||
existing.document === doc &&
|
||||
existing.modified === file.stat.mtime
|
||||
) {
|
||||
return existing.family;
|
||||
}
|
||||
if (existing) {
|
||||
existing.document.fonts.delete(existing.face);
|
||||
this.loadedPreviewFonts.delete(file.path);
|
||||
}
|
||||
const ownerWindow = doc.defaultView;
|
||||
if (!ownerWindow) {
|
||||
return null;
|
||||
}
|
||||
const FontFaceConstructor: typeof FontFace | undefined = Reflect.get(
|
||||
ownerWindow,
|
||||
"FontFace",
|
||||
);
|
||||
if (!FontFaceConstructor) {
|
||||
return null;
|
||||
}
|
||||
const family = `Excalidraw Font Preview ${this.id} ${++this.previewFontId}`;
|
||||
const resourcePath = this.app.vault.getResourcePath(file);
|
||||
const face = new FontFaceConstructor(
|
||||
family,
|
||||
`url(${JSON.stringify(resourcePath)})`,
|
||||
);
|
||||
doc.fonts.add(face);
|
||||
this.loadedPreviewFonts.set(file.path, {
|
||||
document: doc,
|
||||
face,
|
||||
family,
|
||||
modified: file.stat.mtime,
|
||||
});
|
||||
void face.load().catch((): void => {});
|
||||
return family;
|
||||
}
|
||||
|
||||
private prunePreviewFonts(options: SelectableFontOption[]): void {
|
||||
const currentFiles = new Map(
|
||||
options
|
||||
.filter(
|
||||
(option): option is SelectableFontOption & { fontFile: TFile } =>
|
||||
option.fontFile !== undefined,
|
||||
)
|
||||
.map((option) => [option.fontFile.path, option.fontFile.stat.mtime]),
|
||||
);
|
||||
for (const [path, loaded] of this.loadedPreviewFonts) {
|
||||
if (currentFiles.get(path) === loaded.modified) {
|
||||
continue;
|
||||
}
|
||||
loaded.document.fonts.delete(loaded.face);
|
||||
this.loadedPreviewFonts.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+7
@@ -23,6 +23,8 @@ import {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
DataURL,
|
||||
LibraryItem,
|
||||
LibraryItems_anyVersion,
|
||||
Zoom,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
@@ -108,6 +110,11 @@ declare namespace ExcalidrawLib {
|
||||
},
|
||||
): CombineBrandsIfNeeded<T, OrderedExcalidrawElement>;
|
||||
|
||||
function restoreLibraryItems(
|
||||
libraryItems: LibraryItems_anyVersion | undefined,
|
||||
defaultStatus: LibraryItem["status"],
|
||||
): LibraryItem[];
|
||||
|
||||
function exportToSvg(
|
||||
opts: Omit<ExportOpts, "getDimensions"> & {
|
||||
elements: ExcalidrawElement[];
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
ExcalidrawProps,
|
||||
LibraryItems,
|
||||
SceneData,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import {
|
||||
@@ -78,10 +77,7 @@ export type ExcalidrawLinkOpenEvent = Parameters<
|
||||
NonNullable<ExcalidrawProps["onLinkOpen"]>
|
||||
>[1];
|
||||
|
||||
export type StencilLibraryData = {
|
||||
library?: LibraryItems;
|
||||
libraryItems?: LibraryItems;
|
||||
};
|
||||
export type { StencilLibraryData } from "./stencilLibraryTypes";
|
||||
|
||||
export interface ExcalidrawEphemeralState {
|
||||
rename?: string;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { TFile } from "obsidian";
|
||||
|
||||
/** A selectable font value and the optional vault file used for its preview. */
|
||||
export interface SelectableFontOption {
|
||||
value: string;
|
||||
label: string;
|
||||
fontFile?: TFile;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export type MarkdownImageTransclusionRenderSettings = {
|
||||
|
||||
export type MarkdownImageRenderSettings = {
|
||||
width: number;
|
||||
paddingBottom: number;
|
||||
fontFamily: string;
|
||||
fontColor: string;
|
||||
border: {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type {
|
||||
LibraryItem,
|
||||
LibraryItems,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
export type StencilLibraryStorageMode = "data-json" | "vault";
|
||||
|
||||
export type StencilLibraryMigrationStatus =
|
||||
| "not-required"
|
||||
| "pending"
|
||||
| "later"
|
||||
| "completed"
|
||||
| "opted-out";
|
||||
|
||||
export type StencilLibraryData = {
|
||||
type?: "excalidrawlib";
|
||||
version?: number;
|
||||
source?: string;
|
||||
library?: LibraryItems;
|
||||
libraryItems?: LibraryItems;
|
||||
};
|
||||
|
||||
export type StencilLibraryFileData = Omit<
|
||||
StencilLibraryData,
|
||||
"library" | "libraryItems"
|
||||
> & {
|
||||
libraryItems: LibraryItems;
|
||||
};
|
||||
|
||||
export type StencilLibraryMigrationChoice =
|
||||
| "migrate"
|
||||
| "later"
|
||||
| "keep-data-json";
|
||||
|
||||
export type MutableLibraryItem = LibraryItem & {
|
||||
status: LibraryItem["status"];
|
||||
};
|
||||
@@ -13,6 +13,8 @@ export type FILENAMEPARTS = {
|
||||
sectionref: string;
|
||||
linkpartReference: string;
|
||||
linkpartAlias: string;
|
||||
/** Optional non-negative export padding parsed from an image-reference link. */
|
||||
padding?: number;
|
||||
};
|
||||
|
||||
export enum PreviewImageType {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { TFile, App } from "obsidian";
|
||||
import { FRONTMATTER_KEYS } from "src/constants/constants";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import type { FILENAMEPARTS } from "src/types/utilTypes";
|
||||
import Pool from "es6-promise-pool";
|
||||
import { getDataURL } from "./coreUtils";
|
||||
|
||||
export { getEmbeddedFilenameParts } from "./embeddedFilenameParts";
|
||||
|
||||
export async function getFontDataURL(
|
||||
app: App,
|
||||
fontFileName: string,
|
||||
@@ -167,43 +168,6 @@ export function getExportPadding(
|
||||
return plugin.settings.exportPaddingSVG;
|
||||
}
|
||||
|
||||
export function getEmbeddedFilenameParts(fname: string): FILENAMEPARTS {
|
||||
const parts = fname?.match(
|
||||
/([^#^]*)((#\^)(group=|area=|frame=|clippedframe=|taskbone)?([^|]*)|(#)(group=|area=|frame=|clippedframe=|taskbone)?([^^|]*))(.*)/,
|
||||
);
|
||||
if (!parts) {
|
||||
return {
|
||||
filepath: fname,
|
||||
hasBlockref: false,
|
||||
hasGroupref: false,
|
||||
hasTaskbone: false,
|
||||
hasArearef: false,
|
||||
hasFrameref: false,
|
||||
hasClippedFrameref: false,
|
||||
blockref: "",
|
||||
hasSectionref: false,
|
||||
sectionref: "",
|
||||
linkpartReference: "",
|
||||
linkpartAlias: "",
|
||||
};
|
||||
}
|
||||
return {
|
||||
filepath: parts[1],
|
||||
hasBlockref: Boolean(parts[3]),
|
||||
hasGroupref: parts[4] === "group=" || parts[7] === "group=",
|
||||
hasTaskbone: parts[4] === "taskbone" || parts[7] === "taskbone",
|
||||
hasArearef: parts[4] === "area=" || parts[7] === "area=",
|
||||
hasFrameref: parts[4] === "frame=" || parts[7] === "frame=",
|
||||
hasClippedFrameref:
|
||||
parts[4] === "clippedframe=" || parts[7] === "clippedframe=",
|
||||
blockref: parts[5],
|
||||
hasSectionref: Boolean(parts[6]),
|
||||
sectionref: parts[8],
|
||||
linkpartReference: parts[2],
|
||||
linkpartAlias: parts[9],
|
||||
};
|
||||
}
|
||||
|
||||
export function cropCanvas(
|
||||
srcCanvas: HTMLCanvasElement,
|
||||
crop: { left: number; top: number; width: number; height: number },
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { FILENAMEPARTS } from "src/types/utilTypes";
|
||||
|
||||
const EMBEDDED_FILENAME_PARTS_REGEX =
|
||||
/([^#^]*)((#\^)(group=|area=|frame=|clippedframe=|taskbone)?([^|]*)|(#)(group=|area=|frame=|clippedframe=|taskbone)?([^^|]*))(.*)/;
|
||||
const IMAGE_REFERENCE_PREFIXES = new Set([
|
||||
"group=",
|
||||
"area=",
|
||||
"frame=",
|
||||
"clippedframe=",
|
||||
]);
|
||||
const PADDING_PARAMETER_REGEX = /,padding=(\d+(?:\.\d+)?|\.\d+)$/;
|
||||
|
||||
/**
|
||||
* Splits an embedded-file link into its path, reference, alias, and image-reference metadata.
|
||||
*
|
||||
* Image references may end in a non-negative `,padding=N` parameter. The parameter is
|
||||
* removed from the resolved block or section reference while the original link text is
|
||||
* retained in `linkpartReference` so nested export paths can be parsed again.
|
||||
*/
|
||||
export function getEmbeddedFilenameParts(fname: string): FILENAMEPARTS {
|
||||
// 0 1 23 4 5 6 7 8 9
|
||||
const parts = fname?.match(EMBEDDED_FILENAME_PARTS_REGEX);
|
||||
if (!parts) {
|
||||
return {
|
||||
filepath: fname,
|
||||
hasBlockref: false,
|
||||
hasGroupref: false,
|
||||
hasTaskbone: false,
|
||||
hasArearef: false,
|
||||
hasFrameref: false,
|
||||
hasClippedFrameref: false,
|
||||
blockref: "",
|
||||
hasSectionref: false,
|
||||
sectionref: "",
|
||||
linkpartReference: "",
|
||||
linkpartAlias: "",
|
||||
};
|
||||
}
|
||||
|
||||
const hasBlockref = Boolean(parts[3]);
|
||||
const hasSectionref = Boolean(parts[6]);
|
||||
const prefix = parts[4] ?? parts[7];
|
||||
const rawReference = hasBlockref ? parts[5] : parts[8];
|
||||
const paddingMatch = IMAGE_REFERENCE_PREFIXES.has(prefix)
|
||||
? rawReference?.match(PADDING_PARAMETER_REGEX)
|
||||
: null;
|
||||
const parsedPadding = paddingMatch ? Number(paddingMatch[1]) : undefined;
|
||||
const padding = Number.isFinite(parsedPadding) ? parsedPadding : undefined;
|
||||
const reference =
|
||||
padding === undefined || !paddingMatch
|
||||
? rawReference
|
||||
: rawReference.slice(0, -paddingMatch[0].length);
|
||||
|
||||
return {
|
||||
filepath: parts[1],
|
||||
hasBlockref,
|
||||
hasGroupref: prefix === "group=",
|
||||
hasTaskbone: prefix === "taskbone",
|
||||
hasArearef: prefix === "area=",
|
||||
hasFrameref: prefix === "frame=",
|
||||
hasClippedFrameref: prefix === "clippedframe=",
|
||||
blockref: hasBlockref ? reference : parts[5],
|
||||
hasSectionref,
|
||||
sectionref: hasSectionref ? reference : parts[8],
|
||||
linkpartReference: parts[2],
|
||||
linkpartAlias: parts[9],
|
||||
padding,
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns whether parsed filename parts select an image-reference region. */
|
||||
export function isImagePartRef(parts: FILENAMEPARTS): boolean {
|
||||
return (
|
||||
parts.hasGroupref ||
|
||||
parts.hasArearef ||
|
||||
parts.hasFrameref ||
|
||||
parts.hasClippedFrameref
|
||||
);
|
||||
}
|
||||
@@ -391,7 +391,18 @@ export async function getTemplate(
|
||||
(el: ExcalidrawElement) => el.id === filenameParts.blockref,
|
||||
);
|
||||
if (el) {
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, el);
|
||||
const padding = filenameParts.padding;
|
||||
const areaElement: ExcalidrawElement =
|
||||
padding === undefined
|
||||
? el
|
||||
: {
|
||||
...el,
|
||||
x: el.x - padding,
|
||||
y: el.y - padding,
|
||||
width: el.width + 2 * padding,
|
||||
height: el.height + 2 * padding,
|
||||
};
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, areaElement);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,7 +523,8 @@ export async function createPNG(
|
||||
if (!loader) {
|
||||
loader = new EmbeddedFilesLoader(plugin);
|
||||
}
|
||||
padding = padding ?? plugin.settings.exportPaddingSVG;
|
||||
const filenameParts = getEmbeddedFilenameParts(templatePath);
|
||||
padding = filenameParts.padding ?? padding ?? plugin.settings.exportPaddingSVG;
|
||||
const template = templatePath
|
||||
? await getTemplate(plugin, templatePath, true, loader, depth)
|
||||
: null;
|
||||
@@ -549,10 +561,14 @@ export async function createPNG(
|
||||
exportSettings?.withBackground ?? plugin.settings.exportWithBackground,
|
||||
withTheme: exportSettings?.withTheme ?? plugin.settings.exportWithTheme,
|
||||
isMask: exportSettings?.isMask ?? false,
|
||||
...(exportSettings?.frameRendering
|
||||
? { frameRendering: exportSettings.frameRendering }
|
||||
: {}),
|
||||
},
|
||||
padding,
|
||||
scale,
|
||||
overrideFiles,
|
||||
filenameParts.padding !== undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +664,8 @@ export async function createSVG(
|
||||
if (!loader) {
|
||||
loader = new EmbeddedFilesLoader(plugin);
|
||||
}
|
||||
const filenameParts = getEmbeddedFilenameParts(templatePath);
|
||||
padding = filenameParts.padding ?? padding ?? plugin.settings.exportPaddingSVG;
|
||||
if (typeof exportSettings.skipInliningFonts === "undefined") {
|
||||
exportSettings.skipInliningFonts = !embedFont;
|
||||
}
|
||||
@@ -663,7 +681,6 @@ export async function createSVG(
|
||||
: null;
|
||||
let elements = template?.elements ?? [];
|
||||
elements = elements.concat(automateElements);
|
||||
padding = padding ?? plugin.settings.exportPaddingSVG;
|
||||
const files = imagesDict ?? {};
|
||||
if (template?.files) {
|
||||
Object.values(template.files).forEach((f: BinaryFileData) => {
|
||||
@@ -676,7 +693,6 @@ export async function createSVG(
|
||||
const withTheme =
|
||||
exportSettings?.withTheme ?? plugin.settings.exportWithTheme;
|
||||
|
||||
const filenameParts = getEmbeddedFilenameParts(templatePath);
|
||||
const svg = await getSVG(
|
||||
{
|
||||
//createAndOpenDrawing
|
||||
@@ -715,6 +731,7 @@ export async function createSVG(
|
||||
padding,
|
||||
null,
|
||||
overrideFiles,
|
||||
filenameParts.padding !== undefined,
|
||||
);
|
||||
|
||||
if (withTheme && theme === "dark") {
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import type { App, TFile } from "obsidian";
|
||||
import type { SelectableFontOption } from "src/types/fontTypes";
|
||||
|
||||
const LOCAL_FONT_EXTENSIONS = ["ttf", "woff", "woff2", "otf"];
|
||||
|
||||
export const MARKDOWN_FONT_FAMILIES = [
|
||||
"Virgil",
|
||||
"Cascadia",
|
||||
"Excalifont",
|
||||
"Comic Shanns",
|
||||
"Liberation Sans",
|
||||
] as const;
|
||||
|
||||
/** Returns vault font files that are eligible for user-selectable font lists. */
|
||||
export function getSelectableFontFiles(
|
||||
app: App,
|
||||
@@ -15,3 +24,19 @@ export function getSelectableFontFiles(
|
||||
!file.path.startsWith(fontAssetsPath),
|
||||
);
|
||||
}
|
||||
|
||||
/** Builds a fresh font option list from bundled names and current vault files. */
|
||||
export function getSelectableFontOptions(
|
||||
app: App,
|
||||
fontAssetsPath: string,
|
||||
builtInFonts: readonly string[] = MARKDOWN_FONT_FAMILIES,
|
||||
): SelectableFontOption[] {
|
||||
return [
|
||||
...builtInFonts.map((font) => ({ value: font, label: font })),
|
||||
...getSelectableFontFiles(app, fontAssetsPath).map((fontFile) => ({
|
||||
value: fontFile.path,
|
||||
label: fontFile.name,
|
||||
fontFile,
|
||||
})),
|
||||
];
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { MarkdownImageRenderSettings } from "src/types/markdownImageTypes";
|
||||
|
||||
const normalizeFontColor = (fontColor: string): string =>
|
||||
fontColor.trim() === "" ? "black" : fontColor;
|
||||
|
||||
/** Resolves a complete render configuration from stored values and defaults. */
|
||||
export function resolveMarkdownImageRenderSettings(
|
||||
defaults: MarkdownImageRenderSettings,
|
||||
@@ -9,8 +12,12 @@ export function resolveMarkdownImageRenderSettings(
|
||||
const defaultTransclusion = defaults.transclusion;
|
||||
return {
|
||||
width: stored?.width ?? defaults.width,
|
||||
paddingBottom: Math.min(
|
||||
100,
|
||||
Math.max(0, Math.round(stored?.paddingBottom ?? defaults.paddingBottom)),
|
||||
),
|
||||
fontFamily: stored?.fontFamily ?? defaults.fontFamily,
|
||||
fontColor: stored?.fontColor ?? defaults.fontColor,
|
||||
fontColor: normalizeFontColor(stored?.fontColor ?? defaults.fontColor),
|
||||
border: {
|
||||
enabled: stored?.border?.enabled ?? defaults.border.enabled,
|
||||
color: stored?.border?.color ?? defaults.border.color,
|
||||
@@ -23,7 +30,9 @@ export function resolveMarkdownImageRenderSettings(
|
||||
: defaultTransclusion.enabled,
|
||||
fontFamily:
|
||||
storedTransclusion?.fontFamily ?? defaultTransclusion.fontFamily,
|
||||
fontColor: storedTransclusion?.fontColor ?? defaultTransclusion.fontColor,
|
||||
fontColor: normalizeFontColor(
|
||||
storedTransclusion?.fontColor ?? defaultTransclusion.fontColor,
|
||||
),
|
||||
border: {
|
||||
enabled:
|
||||
storedTransclusion?.border?.enabled ??
|
||||
|
||||
+26
-50
@@ -33,7 +33,6 @@ import {
|
||||
getMimeType,
|
||||
getURLImageExtension,
|
||||
} from "./fileUtils";
|
||||
import { FILENAMEPARTS } from "../types/utilTypes";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import {
|
||||
getExcalidrawViews,
|
||||
@@ -61,6 +60,10 @@ import { URLs } from "src/constants/safeUrls";
|
||||
import { isInstanceOfSVGSVGElement } from "./typechecks";
|
||||
export { errorlog, getDataURL } from "./coreUtils";
|
||||
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
|
||||
export {
|
||||
getEmbeddedFilenameParts,
|
||||
isImagePartRef,
|
||||
} from "./embeddedFilenameParts";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -343,12 +346,19 @@ export async function getBinaryFileFromDataURL(
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports an Excalidraw scene to SVG.
|
||||
*
|
||||
* @param allowFramePadding - Whether clipped frame rendering should honor `padding`.
|
||||
* Defaults to `false` to preserve the legacy zero-padding behavior for clipped frames.
|
||||
*/
|
||||
export async function getSVG<TScene extends SceneForExport>(
|
||||
scene: TScene,
|
||||
exportSettings: ExportSettings,
|
||||
padding: number,
|
||||
srcFile: TFile | null, //if set, will replace markdown links with obsidian links
|
||||
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
|
||||
allowFramePadding: boolean = false,
|
||||
): Promise<SVGSVGElement> {
|
||||
let elements: ExcalidrawElement[] = [...scene.elements];
|
||||
if (elements.some((el) => el.type === "embeddable")) {
|
||||
@@ -396,7 +406,10 @@ export async function getSVG<TScene extends SceneForExport>(
|
||||
: {}),
|
||||
} as AppState,
|
||||
files,
|
||||
exportPadding: exportSettings.frameRendering?.enabled ? 0 : padding,
|
||||
exportPadding:
|
||||
exportSettings.frameRendering?.enabled && !allowFramePadding
|
||||
? 0
|
||||
: padding,
|
||||
exportingFrame: null,
|
||||
renderEmbeddables: true,
|
||||
skipInliningFonts: exportSettings.skipInliningFonts,
|
||||
@@ -430,12 +443,19 @@ export function filterFiles(
|
||||
return filteredFiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports an Excalidraw scene to PNG.
|
||||
*
|
||||
* @param allowFramePadding - Whether clipped frame rendering should honor `padding`.
|
||||
* Defaults to `false` to preserve the legacy zero-padding behavior for clipped frames.
|
||||
*/
|
||||
export async function getPNG<TScene extends SceneForExport>(
|
||||
scene: TScene,
|
||||
exportSettings: ExportSettings,
|
||||
padding: number,
|
||||
scale: number = 1,
|
||||
overrideFiles?: BinaryFiles,
|
||||
allowFramePadding: boolean = false,
|
||||
): Promise<Blob> {
|
||||
try {
|
||||
const baseFiles = scene.files ?? {};
|
||||
@@ -475,7 +495,10 @@ export async function getPNG<TScene extends SceneForExport>(
|
||||
: {}),
|
||||
} as AppState,
|
||||
files: filterFiles(files),
|
||||
exportPadding: exportSettings.frameRendering?.enabled ? 0 : padding,
|
||||
exportPadding:
|
||||
exportSettings.frameRendering?.enabled && !allowFramePadding
|
||||
? 0
|
||||
: padding,
|
||||
mimeType: "image/png",
|
||||
getDimensions: (width: number, height: number) => ({
|
||||
width: width * scale,
|
||||
@@ -987,53 +1010,6 @@ export function isVersionNewerThanOther(
|
||||
);
|
||||
}
|
||||
|
||||
export function getEmbeddedFilenameParts(fname: string): FILENAMEPARTS {
|
||||
// 0 1 23 4 5 6 7 8 9
|
||||
const parts = fname?.match(
|
||||
/([^#^]*)((#\^)(group=|area=|frame=|clippedframe=|taskbone)?([^|]*)|(#)(group=|area=|frame=|clippedframe=|taskbone)?([^^|]*))(.*)/,
|
||||
);
|
||||
if (!parts) {
|
||||
return {
|
||||
filepath: fname,
|
||||
hasBlockref: false,
|
||||
hasGroupref: false,
|
||||
hasTaskbone: false,
|
||||
hasArearef: false,
|
||||
hasFrameref: false,
|
||||
hasClippedFrameref: false,
|
||||
blockref: "",
|
||||
hasSectionref: false,
|
||||
sectionref: "",
|
||||
linkpartReference: "",
|
||||
linkpartAlias: "",
|
||||
};
|
||||
}
|
||||
return {
|
||||
filepath: parts[1],
|
||||
hasBlockref: Boolean(parts[3]),
|
||||
hasGroupref: parts[4] === "group=" || parts[7] === "group=",
|
||||
hasTaskbone: parts[4] === "taskbone" || parts[7] === "taskbone",
|
||||
hasArearef: parts[4] === "area=" || parts[7] === "area=",
|
||||
hasFrameref: parts[4] === "frame=" || parts[7] === "frame=",
|
||||
hasClippedFrameref:
|
||||
parts[4] === "clippedframe=" || parts[7] === "clippedframe=",
|
||||
blockref: parts[5],
|
||||
hasSectionref: Boolean(parts[6]),
|
||||
sectionref: parts[8],
|
||||
linkpartReference: parts[2],
|
||||
linkpartAlias: parts[9],
|
||||
};
|
||||
}
|
||||
|
||||
export function isImagePartRef(parts: FILENAMEPARTS): boolean {
|
||||
return (
|
||||
parts.hasGroupref ||
|
||||
parts.hasArearef ||
|
||||
parts.hasFrameref ||
|
||||
parts.hasClippedFrameref
|
||||
);
|
||||
}
|
||||
|
||||
export function fragWithHTML(html: string) {
|
||||
return createFragment((frag) => frag.appendChild(sanitizedFragment(html)));
|
||||
}
|
||||
|
||||
+374
-122
@@ -79,9 +79,9 @@ import {
|
||||
getExcalidrawMarkdownHeaderSection,
|
||||
parseMarkdownImages,
|
||||
syncMarkdownImagesInHeader,
|
||||
unwrapMarkdownImageBlock,
|
||||
} from "../shared/ExcalidrawData";
|
||||
import {
|
||||
checkAndCreateFolder,
|
||||
createFileAndAwaitMetacacheUpdate,
|
||||
createOrOverwriteFile,
|
||||
download,
|
||||
@@ -142,7 +142,6 @@ import {
|
||||
LaTexPrompt,
|
||||
MultiOptionConfirmationPrompt,
|
||||
NewFileActions,
|
||||
Prompt,
|
||||
linkPrompt,
|
||||
} from "../shared/Dialogs/Prompt";
|
||||
import {
|
||||
@@ -160,6 +159,7 @@ import {
|
||||
convertMarkdownImageElementToEmbeddable,
|
||||
getEmbeddableMarkdownImageSource,
|
||||
getLevelOneMarkdownHeadings,
|
||||
getMarkdownImageCustomData,
|
||||
getMarkdownImageSource,
|
||||
isMarkdownImageElement,
|
||||
} from "../shared/MarkdownImage";
|
||||
@@ -186,6 +186,7 @@ import {
|
||||
SwordColors,
|
||||
} from "../constants/actionIcons";
|
||||
import { ExportDialog } from "../shared/Dialogs/ExportDialog";
|
||||
import { FileAndFolderSelectorModal } from "../shared/Dialogs/FileAndFolderSelectorModal";
|
||||
import { getEA } from "src/core";
|
||||
import {
|
||||
anyModifierKeysPressed,
|
||||
@@ -493,6 +494,17 @@ export default class ExcalidrawView
|
||||
private preventReloadResetTimer: number | null = null;
|
||||
private editingSelfResetTimer: number | null = null;
|
||||
private colorChangeTimer: number | null = null;
|
||||
private markdownImageDeleteCandidateTimer: number | null = null;
|
||||
private markdownImageDeleteCandidates = new Map<
|
||||
ExcalidrawElement["id"],
|
||||
ExcalidrawImageElement
|
||||
>();
|
||||
private markdownImageDeletionQueue: Array<{
|
||||
element: ExcalidrawImageElement;
|
||||
filePath: string;
|
||||
}> = [];
|
||||
private pendingMarkdownImageDeletionIds = new Set<ExcalidrawElement["id"]>();
|
||||
private markdownImageDeletionPrompt: Promise<void> | null = null;
|
||||
private previousSceneVersion = 0;
|
||||
public previousBackgroundColor = "";
|
||||
public previousTheme = "";
|
||||
@@ -604,34 +616,32 @@ export default class ExcalidrawView
|
||||
return;
|
||||
}
|
||||
if (DEVICE.isMobile) {
|
||||
const prompt = new Prompt(
|
||||
this.app,
|
||||
t("EXPORT_FILENAME_PROMPT"),
|
||||
this.file.basename,
|
||||
t("EXPORT_FILENAME_PROMPT_PLACEHOLDER"),
|
||||
const location = await new FileAndFolderSelectorModal(this.app, {
|
||||
title: t("FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE"),
|
||||
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
|
||||
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
|
||||
submitButtonText: t("FILE_AND_FOLDER_SELECTOR_EXPORT"),
|
||||
folderPath: splitFolderAndFilename(this.file.path).folderpath,
|
||||
fileName: `${this.file.basename}.excalidraw`,
|
||||
}).start();
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
const filename = location.fileName.toLowerCase().endsWith(".excalidraw")
|
||||
? location.fileName
|
||||
: `${location.fileName}.excalidraw`;
|
||||
const path = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
location.folderPath,
|
||||
);
|
||||
void prompt.openAndGetValue((filename: string) => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
filename = `${filename}.excalidraw`;
|
||||
const folderpath = splitFolderAndFilename(this.file?.path).folderpath;
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const path = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
const file = await exportImageToFile(
|
||||
this,
|
||||
path,
|
||||
JSON.stringify(this.getScene(), null, "\t"),
|
||||
".excalidraw",
|
||||
);
|
||||
new Notice(`Exported to ${file?.name}`, 6000);
|
||||
})();
|
||||
});
|
||||
const file = await exportImageToFile(
|
||||
this,
|
||||
path,
|
||||
JSON.stringify(this.getScene(), null, "\t"),
|
||||
".excalidraw",
|
||||
);
|
||||
new Notice(`Exported to ${file?.name}`, 6000);
|
||||
return;
|
||||
}
|
||||
download(
|
||||
@@ -750,6 +760,7 @@ export default class ExcalidrawView
|
||||
void (await new Promise<void>((resolve) => {
|
||||
void loader.loadSceneFiles({
|
||||
excalidrawData: this.excalidrawData,
|
||||
sceneElements: this.getViewElements(),
|
||||
addFiles: (
|
||||
files: FileData[],
|
||||
_isDark: boolean,
|
||||
@@ -1132,6 +1143,9 @@ export default class ExcalidrawView
|
||||
if (!this.isLoaded) {
|
||||
return;
|
||||
}
|
||||
if (this.markdownImageDeletionPrompt !== null) {
|
||||
await this.markdownImageDeletionPrompt;
|
||||
}
|
||||
if (
|
||||
!overrideEmbeddableIsEditingSelfDebounce &&
|
||||
this.semaphores.embeddableIsEditingSelf
|
||||
@@ -3016,6 +3030,11 @@ export default class ExcalidrawView
|
||||
window.clearTimeout(this.colorChangeTimer);
|
||||
this.colorChangeTimer = null;
|
||||
}
|
||||
if (this.markdownImageDeleteCandidateTimer) {
|
||||
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
|
||||
this.markdownImageDeleteCandidateTimer = null;
|
||||
this.markdownImageDeleteCandidates.clear();
|
||||
}
|
||||
if (this.semaphores?.wheelTimeout) {
|
||||
window.clearTimeout(this.semaphores.wheelTimeout);
|
||||
this.semaphores.wheelTimeout = null;
|
||||
@@ -3722,6 +3741,7 @@ export default class ExcalidrawView
|
||||
// candidates, run one at a time, and emit only regenerated images.
|
||||
void loader.loadSceneFiles({
|
||||
excalidrawData: this.excalidrawData,
|
||||
sceneElements: this.getViewElements(),
|
||||
addFiles: (
|
||||
files: FileData[],
|
||||
isDark: boolean,
|
||||
@@ -3830,6 +3850,7 @@ export default class ExcalidrawView
|
||||
this.activeLoader = l;
|
||||
void l.loadSceneFiles({
|
||||
excalidrawData: this.excalidrawData,
|
||||
sceneElements: this.getViewElements(),
|
||||
addFiles: (
|
||||
files: FileData[],
|
||||
isDark: boolean,
|
||||
@@ -3935,6 +3956,51 @@ export default class ExcalidrawView
|
||||
const reloadFiles = new Set<FileId>();
|
||||
|
||||
try {
|
||||
const syncMarkdownImageSource = (
|
||||
incomingElement: ExcalidrawImageElement,
|
||||
): boolean => {
|
||||
const customData = getMarkdownImageCustomData(incomingElement);
|
||||
if (!customData) {
|
||||
return false;
|
||||
}
|
||||
if (customData.source === "local") {
|
||||
const incomingSource = inData.getMarkdownImage(
|
||||
incomingElement.fileId,
|
||||
);
|
||||
if (!incomingSource) {
|
||||
return false;
|
||||
}
|
||||
const currentSource = this.excalidrawData.getMarkdownImage(
|
||||
incomingElement.fileId,
|
||||
);
|
||||
if (currentSource?.markdown === incomingSource.markdown) {
|
||||
return false;
|
||||
}
|
||||
this.excalidrawData.setMarkdownImage(
|
||||
incomingElement.fileId,
|
||||
incomingSource,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
const incomingFile = inData.getFile(incomingElement.fileId);
|
||||
if (!incomingFile) {
|
||||
return false;
|
||||
}
|
||||
const currentFile = this.excalidrawData.getFile(
|
||||
incomingElement.fileId,
|
||||
);
|
||||
if (
|
||||
currentFile?.file === incomingFile.file &&
|
||||
currentFile?.hyperlink === incomingFile.hyperlink &&
|
||||
currentFile?.linkParts?.original === incomingFile.linkParts?.original
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
this.excalidrawData.setFile(incomingElement.fileId, incomingFile);
|
||||
return true;
|
||||
};
|
||||
|
||||
const deletedIds = inData.deletedElements.map((el) => el.id);
|
||||
const sceneElements = this.excalidrawAPI
|
||||
.getSceneElementsIncludingDeleted()
|
||||
@@ -3953,7 +4019,10 @@ export default class ExcalidrawView
|
||||
);
|
||||
break;
|
||||
case "image":
|
||||
if (inData.getFile(incomingElement.fileId)) {
|
||||
if (getMarkdownImageCustomData(incomingElement)) {
|
||||
syncMarkdownImageSource(incomingElement);
|
||||
reloadFiles.add(incomingElement.fileId);
|
||||
} else if (inData.getFile(incomingElement.fileId)) {
|
||||
this.excalidrawData.setFile(
|
||||
incomingElement.fileId,
|
||||
inData.getFile(incomingElement.fileId),
|
||||
@@ -4028,6 +4097,15 @@ export default class ExcalidrawView
|
||||
sceneElementIds.splice(parentLayer + 1, 0, incomingElement.id);
|
||||
}
|
||||
} else if (sceneElement && incomingElement.type === "image") {
|
||||
if (getMarkdownImageCustomData(incomingElement)) {
|
||||
if (
|
||||
syncMarkdownImageSource(incomingElement) ||
|
||||
!this.excalidrawAPI.getFiles()[incomingElement.fileId]
|
||||
) {
|
||||
reloadFiles.add(incomingElement.fileId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/632
|
||||
const incomingFile = inData.getFile(incomingElement.fileId);
|
||||
const sceneFile = this.excalidrawData.getFile(
|
||||
@@ -4054,6 +4132,17 @@ export default class ExcalidrawView
|
||||
}
|
||||
},
|
||||
);
|
||||
const loadedFiles = this.excalidrawAPI.getFiles();
|
||||
sceneElements.forEach((element) => {
|
||||
if (
|
||||
element.type === "image" &&
|
||||
getMarkdownImageCustomData(element) &&
|
||||
!loadedFiles[element.fileId]
|
||||
) {
|
||||
syncMarkdownImageSource(element);
|
||||
reloadFiles.add(element.fileId);
|
||||
}
|
||||
});
|
||||
this.previousSceneVersion = this.getSceneVersion(sceneElements);
|
||||
//changing files could result in a race condition for sync. If at the end of sync there are differences
|
||||
//set dirty will trigger an autosave
|
||||
@@ -4508,94 +4597,94 @@ export default class ExcalidrawView
|
||||
if (!textElement) {
|
||||
return;
|
||||
}
|
||||
const prompt = new Prompt(
|
||||
this.app,
|
||||
"Filename",
|
||||
"",
|
||||
"Leave blank to cancel this action",
|
||||
);
|
||||
void prompt.openAndGetValue((filename: string) => {
|
||||
void (async () => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
filename = `${filename}.md`;
|
||||
const folderpath = splitFolderAndFilename(this.file.path).folderpath;
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
const text: string[] = [];
|
||||
if (containerElement && containerElement.link) {
|
||||
text.push(containerElement.link);
|
||||
}
|
||||
text.push(textElement.rawText);
|
||||
const f = await createOrOverwriteFile(this.app, fname, text.join("\n"));
|
||||
if (f) {
|
||||
const ea: ExcalidrawAutomate = getEA(this);
|
||||
const elements = containerElement
|
||||
? [textElement, containerElement]
|
||||
: [textElement];
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.getElements().forEach((el) => (el.isDeleted = true));
|
||||
const [x, y, w, h] = containerElement
|
||||
? [
|
||||
containerElement.x,
|
||||
containerElement.y,
|
||||
containerElement.width,
|
||||
containerElement.height,
|
||||
]
|
||||
: [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE];
|
||||
const id = ea.addEmbeddable(x, y, w, h, undefined, f);
|
||||
if (containerElement) {
|
||||
const props: (keyof ExcalidrawElement)[] = [
|
||||
"backgroundColor",
|
||||
"fillStyle",
|
||||
"roughness",
|
||||
"roundness",
|
||||
"strokeColor",
|
||||
"strokeStyle",
|
||||
"strokeWidth",
|
||||
];
|
||||
props.forEach((prop) => {
|
||||
const element = ea.getElement(id);
|
||||
if (prop in element) {
|
||||
const mutableElement = element as Mutable<ExcalidrawElement>;
|
||||
switch (prop) {
|
||||
case "backgroundColor":
|
||||
mutableElement.backgroundColor =
|
||||
containerElement.backgroundColor;
|
||||
break;
|
||||
case "fillStyle":
|
||||
mutableElement.fillStyle = containerElement.fillStyle;
|
||||
break;
|
||||
case "roughness":
|
||||
mutableElement.roughness = containerElement.roughness;
|
||||
break;
|
||||
case "roundness":
|
||||
mutableElement.roundness = containerElement.roundness;
|
||||
break;
|
||||
case "strokeColor":
|
||||
mutableElement.strokeColor = containerElement.strokeColor;
|
||||
break;
|
||||
case "strokeStyle":
|
||||
mutableElement.strokeStyle = containerElement.strokeStyle;
|
||||
break;
|
||||
case "strokeWidth":
|
||||
mutableElement.strokeWidth = containerElement.strokeWidth;
|
||||
break;
|
||||
}
|
||||
void (async () => {
|
||||
const location = await new FileAndFolderSelectorModal(this.app, {
|
||||
title: t("CONVERT_TO_MARKDOWN"),
|
||||
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
|
||||
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
|
||||
submitButtonText: t("PROMPT_BUTTON_CREATE_MARKDOWN"),
|
||||
folderPath: splitFolderAndFilename(this.file.path).folderpath,
|
||||
fileName: "",
|
||||
}).start();
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
const filename = location.fileName.toLowerCase().endsWith(".md")
|
||||
? location.fileName
|
||||
: `${location.fileName}.md`;
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
location.folderPath,
|
||||
);
|
||||
const text: string[] = [];
|
||||
if (containerElement && containerElement.link) {
|
||||
text.push(containerElement.link);
|
||||
}
|
||||
text.push(textElement.rawText);
|
||||
const f = await createOrOverwriteFile(this.app, fname, text.join("\n"));
|
||||
if (f) {
|
||||
const ea: ExcalidrawAutomate = getEA(this);
|
||||
const elements = containerElement
|
||||
? [textElement, containerElement]
|
||||
: [textElement];
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.getElements().forEach((el) => (el.isDeleted = true));
|
||||
const [x, y, w, h] = containerElement
|
||||
? [
|
||||
containerElement.x,
|
||||
containerElement.y,
|
||||
containerElement.width,
|
||||
containerElement.height,
|
||||
]
|
||||
: [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE];
|
||||
const id = ea.addEmbeddable(x, y, w, h, undefined, f);
|
||||
if (containerElement) {
|
||||
const props: (keyof ExcalidrawElement)[] = [
|
||||
"backgroundColor",
|
||||
"fillStyle",
|
||||
"roughness",
|
||||
"roundness",
|
||||
"strokeColor",
|
||||
"strokeStyle",
|
||||
"strokeWidth",
|
||||
];
|
||||
props.forEach((prop) => {
|
||||
const element = ea.getElement(id);
|
||||
if (prop in element) {
|
||||
const mutableElement = element as Mutable<ExcalidrawElement>;
|
||||
switch (prop) {
|
||||
case "backgroundColor":
|
||||
mutableElement.backgroundColor =
|
||||
containerElement.backgroundColor;
|
||||
break;
|
||||
case "fillStyle":
|
||||
mutableElement.fillStyle = containerElement.fillStyle;
|
||||
break;
|
||||
case "roughness":
|
||||
mutableElement.roughness = containerElement.roughness;
|
||||
break;
|
||||
case "roundness":
|
||||
mutableElement.roundness = containerElement.roundness;
|
||||
break;
|
||||
case "strokeColor":
|
||||
mutableElement.strokeColor = containerElement.strokeColor;
|
||||
break;
|
||||
case "strokeStyle":
|
||||
mutableElement.strokeStyle = containerElement.strokeStyle;
|
||||
break;
|
||||
case "strokeWidth":
|
||||
mutableElement.strokeWidth = containerElement.strokeWidth;
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
ea.getElement(id);
|
||||
await ea.addElementsToView();
|
||||
ea.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
});
|
||||
ea.getElement(id);
|
||||
await ea.addElementsToView();
|
||||
ea.destroy();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async addYouTubeThumbnail(link: string) {
|
||||
@@ -4708,7 +4797,7 @@ export default class ExcalidrawView
|
||||
}
|
||||
|
||||
async getLibrary(): Promise<LibraryItems> {
|
||||
const data = this.plugin.getStencilLibrary() as StencilLibraryData;
|
||||
const data = await this.plugin.getStencilLibrary();
|
||||
return data?.library ? data.library : (data?.libraryItems ?? []);
|
||||
}
|
||||
|
||||
@@ -5569,6 +5658,53 @@ export default class ExcalidrawView
|
||||
this.lastKeyDownPosition = { x: 0, y: 0 };
|
||||
};
|
||||
|
||||
private captureSelectedMarkdownImageDeleteCandidates(): void {
|
||||
this.markdownImageDeleteCandidates.clear();
|
||||
this.getViewSelectedElements()
|
||||
.filter(
|
||||
(element): element is ExcalidrawImageElement =>
|
||||
element.type === "image" &&
|
||||
getMarkdownImageCustomData(element)?.source === "local" &&
|
||||
this.excalidrawData.hasMarkdownImage(element.fileId),
|
||||
)
|
||||
.forEach((element) =>
|
||||
this.markdownImageDeleteCandidates.set(element.id, element),
|
||||
);
|
||||
|
||||
if (this.markdownImageDeleteCandidateTimer) {
|
||||
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
|
||||
}
|
||||
this.markdownImageDeleteCandidateTimer = window.setTimeout(() => {
|
||||
this.markdownImageDeleteCandidates.clear();
|
||||
this.markdownImageDeleteCandidateTimer = null;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
private excalidrawDIVonKeyDownCapture(event: KeyboardEvent): void {
|
||||
const isDeleteKey = event.key === "Backspace" || event.key === "Delete";
|
||||
const isCutShortcut =
|
||||
event.key.toLowerCase() === "x" &&
|
||||
isWinCTRLorMacCMD(event) &&
|
||||
!isSHIFT(event) &&
|
||||
!isWinALTorMacOPT(event) &&
|
||||
!isWinMETAorMacCTRL(event);
|
||||
if (
|
||||
this.semaphores?.viewunload ||
|
||||
(!isDeleteKey && !isCutShortcut)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.captureSelectedMarkdownImageDeleteCandidates();
|
||||
}
|
||||
|
||||
private excalidrawDIVonPointerDownCapture(event: PointerEvent): void {
|
||||
const target = event.target as Element | null;
|
||||
if (!target?.closest('[data-testid="deleteSelectedElements"]')) {
|
||||
return;
|
||||
}
|
||||
this.captureSelectedMarkdownImageDeleteCandidates();
|
||||
}
|
||||
|
||||
private excalidrawDIVonKeyDown(event: KeyboardEvent) {
|
||||
//(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.excalidrawDIVonKeyDown, "ExcalidrawView.excalidrawDIVonKeyDown", event);
|
||||
if (this.semaphores?.viewunload) {
|
||||
@@ -5788,8 +5924,123 @@ export default class ExcalidrawView
|
||||
}
|
||||
}
|
||||
|
||||
private handleDeletedMarkdownImageCandidates(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
): void {
|
||||
if (this.markdownImageDeleteCandidates.size === 0) {
|
||||
return;
|
||||
}
|
||||
const currentElements = new Map(
|
||||
elements.map((element) => [element.id, element]),
|
||||
);
|
||||
this.markdownImageDeleteCandidates.forEach((candidate, elementId) => {
|
||||
const current = currentElements.get(elementId);
|
||||
if (current && !current.isDeleted) {
|
||||
return;
|
||||
}
|
||||
this.markdownImageDeleteCandidates.delete(elementId);
|
||||
this.queueMarkdownImageDeletion(candidate);
|
||||
});
|
||||
if (
|
||||
this.markdownImageDeleteCandidates.size === 0 &&
|
||||
this.markdownImageDeleteCandidateTimer
|
||||
) {
|
||||
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
|
||||
this.markdownImageDeleteCandidateTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private queueMarkdownImageDeletion(element: ExcalidrawImageElement): void {
|
||||
if (!this.file || this.pendingMarkdownImageDeletionIds.has(element.id)) {
|
||||
return;
|
||||
}
|
||||
this.pendingMarkdownImageDeletionIds.add(element.id);
|
||||
this.markdownImageDeletionQueue.push({
|
||||
element,
|
||||
filePath: this.file.path,
|
||||
});
|
||||
if (this.markdownImageDeletionPrompt !== null) {
|
||||
return;
|
||||
}
|
||||
const processing = this.processMarkdownImageDeletionQueue();
|
||||
this.markdownImageDeletionPrompt = processing;
|
||||
void processing.finally(() => {
|
||||
if (this.markdownImageDeletionPrompt === processing) {
|
||||
this.markdownImageDeletionPrompt = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async processMarkdownImageDeletionQueue(): Promise<void> {
|
||||
while (this.markdownImageDeletionQueue.length > 0) {
|
||||
const item = this.markdownImageDeletionQueue.shift();
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
const { element, filePath } = item;
|
||||
try {
|
||||
const viewElements = this.getViewElements();
|
||||
if (
|
||||
!this.file ||
|
||||
this.file.path !== filePath ||
|
||||
viewElements.some((candidate) => candidate.id === element.id) ||
|
||||
viewElements.some(
|
||||
(candidate) =>
|
||||
candidate.id !== element.id &&
|
||||
candidate.type === "image" &&
|
||||
candidate.fileId === element.fileId &&
|
||||
getMarkdownImageCustomData(candidate)?.source === "local",
|
||||
) ||
|
||||
!this.excalidrawData.hasMarkdownImage(element.fileId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const prompt = new MultiOptionConfirmationPrompt<
|
||||
"keep" | "delete" | null
|
||||
>(
|
||||
this.plugin,
|
||||
t("MARKDOWN_IMAGE_DELETE_TEXT_PROMPT"),
|
||||
new Map([
|
||||
[t("MARKDOWN_IMAGE_KEEP_TEXT"), "keep"],
|
||||
[t("MARKDOWN_IMAGE_DELETE_TEXT"), "delete"],
|
||||
]),
|
||||
t("MARKDOWN_IMAGE_KEEP_TEXT"),
|
||||
);
|
||||
const decision = await prompt.waitForClose;
|
||||
if (
|
||||
!this.file ||
|
||||
this.file.path !== filePath ||
|
||||
this.getViewElements().some((candidate) => candidate.id === element.id)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (decision !== "delete") {
|
||||
const markdown = this.excalidrawData.getMarkdownImage(
|
||||
element.fileId,
|
||||
)?.markdown;
|
||||
this.data = unwrapMarkdownImageBlock(
|
||||
this.data,
|
||||
element.fileId,
|
||||
markdown,
|
||||
);
|
||||
}
|
||||
this.excalidrawData.deleteMarkdownImage(element.fileId);
|
||||
this.setDirty();
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "ExcalidrawView.processMarkdownImageDeletionQueue",
|
||||
error,
|
||||
});
|
||||
} finally {
|
||||
this.pendingMarkdownImageDeletionIds.delete(element.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onChange(et: ExcalidrawElement[], st: AppState, files: BinaryFiles) {
|
||||
this.selectedElementActionsMenu?.update(et, st);
|
||||
this.handleDeletedMarkdownImageCandidates(et);
|
||||
if (st.activeTool?.type) {
|
||||
if (st.activeTool.type === "image") {
|
||||
if (
|
||||
@@ -5893,7 +6144,7 @@ export default class ExcalidrawView
|
||||
|
||||
private onLibraryChange(items: LibraryItems) {
|
||||
void (async () => {
|
||||
const lib = {
|
||||
const lib: StencilLibraryData = {
|
||||
type: "excalidrawlib",
|
||||
version: 2,
|
||||
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
|
||||
@@ -6699,13 +6950,11 @@ export default class ExcalidrawView
|
||||
selectCardDialog.start(center);
|
||||
}
|
||||
|
||||
/** Opens the sidepanel editor for a selected image or inserts a new one. */
|
||||
/** Opens an image by ID for editing, or inserts a new Markdown image. */
|
||||
public async openMarkdownImageEditor(elementId?: string): Promise<void> {
|
||||
const selected = elementId
|
||||
? this.getViewElements().find((element) => element.id === elementId)
|
||||
: this.getViewSelectedElements().length === 1
|
||||
? this.getViewSelectedElements()[0]
|
||||
: undefined;
|
||||
: undefined;
|
||||
const image = selected?.type === "image" ? selected : undefined;
|
||||
if (image && !isMarkdownImageElement(this, image)) {
|
||||
new Notice(t("MARKDOWN_IMAGE_SELECT_ERROR"));
|
||||
@@ -8294,6 +8543,9 @@ export default class ExcalidrawView
|
||||
ref: excalidrawWrapperRef,
|
||||
key: "abc",
|
||||
tabIndex: 0,
|
||||
onKeyDownCapture: this.excalidrawDIVonKeyDownCapture.bind(this),
|
||||
onPointerDownCapture:
|
||||
this.excalidrawDIVonPointerDownCapture.bind(this),
|
||||
onKeyDown: this.excalidrawDIVonKeyDown.bind(this),
|
||||
onKeyUp: this.excalidrawDIVonKeyUp.bind(this),
|
||||
onPointerDown: this.onPointerDown.bind(this),
|
||||
|
||||
@@ -303,7 +303,8 @@ export class ObsidianMenu {
|
||||
|
||||
const isPenActive = activePenIndex === index;
|
||||
|
||||
//Reset stroke setting when changing to a different tool
|
||||
// Temporarily restore the base stroke settings outside freedraw while
|
||||
// retaining the active pen so it can be reapplied on return.
|
||||
if (
|
||||
pen.freedrawOnly && // Enforce freedrawOnly so global pens do not auto-reset upon changing tools
|
||||
appState.resetCustomPen &&
|
||||
@@ -311,7 +312,6 @@ export class ObsidianMenu {
|
||||
!this.pendingPenActivation &&
|
||||
isPenActive
|
||||
) {
|
||||
this.activePenIndex = null;
|
||||
window.setTimeout(() =>
|
||||
resetStrokeOptions(
|
||||
appState.resetCustomPen as ResetCustomPenState,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ExcalidrawImperativeAPI,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import {
|
||||
ANIMATED_IMAGE_TYPES,
|
||||
DEVICE,
|
||||
IMAGE_TYPES,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
@@ -37,11 +38,15 @@ import {
|
||||
importFileToVault,
|
||||
} from "src/utils/fileUtils";
|
||||
import { ScriptEngine } from "src/shared/Scripts";
|
||||
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
|
||||
import {
|
||||
UniversalInsertFileModal,
|
||||
type UniversalInsertFileAction,
|
||||
} from "src/shared/Dialogs/UniversalInsertFileModal";
|
||||
import { Position } from "src/types/excalidrawViewTypes";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import { ObsidianDraggable } from "src/types/types";
|
||||
import type React from "react";
|
||||
import { insertMarkdownImage } from "src/shared/MarkdownImage";
|
||||
|
||||
/*
|
||||
static getDropAction(event: DragEvent): string {
|
||||
@@ -105,6 +110,18 @@ export class DropManager {
|
||||
return this.view.file;
|
||||
}
|
||||
|
||||
private openDroppedMarkdownFile(
|
||||
file: TFile,
|
||||
position: Position,
|
||||
action: UniversalInsertFileAction,
|
||||
): void {
|
||||
new UniversalInsertFileModal(this.plugin, this.view).open(
|
||||
file,
|
||||
position,
|
||||
action,
|
||||
);
|
||||
}
|
||||
|
||||
public onDrop(event: React.DragEvent<HTMLDivElement>): boolean {
|
||||
if (this.draginfoDiv) {
|
||||
this.ownerDocument.body.removeChild(this.draginfoDiv);
|
||||
@@ -170,6 +187,18 @@ export class DropManager {
|
||||
new Notice(t("FILENAME_INVALID_CHARS"), 4000);
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
file.extension.toLowerCase() === "md" &&
|
||||
(internalDragAction === "image" ||
|
||||
internalDragAction === "embeddable")
|
||||
) {
|
||||
this.openDroppedMarkdownFile(
|
||||
file,
|
||||
{ ...this.currentPosition },
|
||||
internalDragAction,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
["image", "image-fullsize"].contains(internalDragAction) &&
|
||||
(IMAGE_TYPES.contains(file.extension) ||
|
||||
@@ -219,6 +248,19 @@ export class DropManager {
|
||||
return false;
|
||||
case "files":
|
||||
if (!onDropHook("file", draggable.files, null)) {
|
||||
if (
|
||||
draggable.files.length === 1 &&
|
||||
draggable.files[0].extension.toLowerCase() === "md" &&
|
||||
(internalDragAction === "image" ||
|
||||
internalDragAction === "embeddable")
|
||||
) {
|
||||
this.openDroppedMarkdownFile(
|
||||
draggable.files[0],
|
||||
{ ...this.currentPosition },
|
||||
internalDragAction,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
if (["image", "image-fullsize"].contains(internalDragAction)) {
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
@@ -226,6 +268,22 @@ export class DropManager {
|
||||
let counter: number = 0;
|
||||
const ids: string[] = [];
|
||||
for (const f of draggable.files) {
|
||||
if (
|
||||
internalDragAction === "image" &&
|
||||
f.extension.toLowerCase() === "md" &&
|
||||
!this.plugin.isExcalidrawFile(f)
|
||||
) {
|
||||
const element = await insertMarkdownImage(this.view, f, {
|
||||
x: this.currentPosition.x + counter * 50,
|
||||
y: this.currentPosition.y + counter * 50,
|
||||
});
|
||||
if (element) {
|
||||
ids.push(element.id);
|
||||
counter++;
|
||||
ea.selectElementsInView(ids);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (IMAGE_TYPES.contains(f.extension) || f.extension === "md") {
|
||||
ids.push(
|
||||
await ea.addImage(
|
||||
@@ -402,6 +460,19 @@ export class DropManager {
|
||||
const { x, y } = this.currentPosition;
|
||||
const pos = { x: x + i * 300, y: y + i * 300 };
|
||||
if (link.isInternal) {
|
||||
if (
|
||||
files.length === 1 &&
|
||||
link.file.extension.toLowerCase() === "md"
|
||||
) {
|
||||
this.openDroppedMarkdownFile(
|
||||
link.file,
|
||||
pos,
|
||||
localFileDragAction === "embeddable"
|
||||
? "embeddable"
|
||||
: "image",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (localFileDragAction === "embeddable") {
|
||||
const ea = getEA(this.view);
|
||||
void insertEmbeddableToView(ea, pos, link.file).then(() =>
|
||||
@@ -423,16 +494,38 @@ export class DropManager {
|
||||
} else {
|
||||
const extension = getURLImageExtension(link.url);
|
||||
if (localFileDragAction === "image-import") {
|
||||
if (IMAGE_TYPES.contains(extension)) {
|
||||
if (extension === "excalidraw") {
|
||||
return true; //excalidraw to continue processing
|
||||
} else {
|
||||
void (async () => {
|
||||
const droppedFilename = event.dataTransfer.files[i].name;
|
||||
const fileToImport =
|
||||
await event.dataTransfer.files[i].arrayBuffer();
|
||||
const insertImportedFile = async (file: TFile) => {
|
||||
const isSingleAnimatedRasterImage =
|
||||
files.length === 1 &&
|
||||
ANIMATED_IMAGE_TYPES.contains(
|
||||
file.extension.toLowerCase(),
|
||||
) &&
|
||||
file.extension.toLowerCase() !== "svg";
|
||||
if (isSingleAnimatedRasterImage) {
|
||||
const modal = new UniversalInsertFileModal(
|
||||
this.plugin,
|
||||
this.view,
|
||||
);
|
||||
modal.open(file, pos);
|
||||
return;
|
||||
}
|
||||
const ea = getEA(this.view);
|
||||
await insertImageToView(ea, pos, file);
|
||||
ea.destroy();
|
||||
};
|
||||
const maybeFile = this.app.metadataCache.getFirstLinkpathDest(
|
||||
droppedFilename,
|
||||
this.file.path,
|
||||
);
|
||||
if (maybeFile && maybeFile instanceof TFile) {
|
||||
let file = maybeFile instanceof TFile ? maybeFile : null;
|
||||
if (file) {
|
||||
const action = await ScriptEngine.suggester(
|
||||
this.app,
|
||||
[
|
||||
@@ -442,44 +535,26 @@ export class DropManager {
|
||||
],
|
||||
["Use", "Overwrite", "Import"],
|
||||
`A file with the same name/path already exists in the Vault\n${
|
||||
maybeFile.path
|
||||
file.path
|
||||
}`,
|
||||
);
|
||||
if (action !== "Import") {
|
||||
if (action === "Overwrite") {
|
||||
await this.app.vault.modifyBinary(
|
||||
maybeFile,
|
||||
fileToImport,
|
||||
);
|
||||
}
|
||||
const ea = getEA(this.view);
|
||||
await insertImageToView(ea, pos, maybeFile);
|
||||
ea.destroy();
|
||||
return false;
|
||||
if (action === "Overwrite") {
|
||||
await this.app.vault.modifyBinary(file, fileToImport);
|
||||
} else if (action === "Import") {
|
||||
file = null;
|
||||
}
|
||||
}
|
||||
const file = await importFileToVault(
|
||||
file ??= await importFileToVault(
|
||||
this.app,
|
||||
droppedFilename,
|
||||
fileToImport,
|
||||
this.view.file,
|
||||
this.view,
|
||||
);
|
||||
const ea = getEA(this.view);
|
||||
await insertImageToView(ea, pos, file);
|
||||
ea.destroy();
|
||||
})();
|
||||
} else if (extension === "excalidraw") {
|
||||
return true; //excalidraw to continue processing
|
||||
} else {
|
||||
void (async () => {
|
||||
const file = await importFileToVault(
|
||||
this.app,
|
||||
event.dataTransfer.files[i].name,
|
||||
await event.dataTransfer.files[i].arrayBuffer(),
|
||||
this.view.file,
|
||||
this.view,
|
||||
);
|
||||
if (IMAGE_TYPES.contains(extension)) {
|
||||
await insertImportedFile(file);
|
||||
return;
|
||||
}
|
||||
const modal = new UniversalInsertFileModal(
|
||||
this.plugin,
|
||||
this.view,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ButtonComponent,
|
||||
MarkdownView,
|
||||
Notice,
|
||||
resolveSubpath,
|
||||
Setting,
|
||||
type App,
|
||||
type ColorComponent,
|
||||
@@ -35,15 +36,15 @@ import {
|
||||
} from "src/utils/customEmbeddableUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
|
||||
import { ScriptEngine } from "src/shared/Scripts";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
getNewUniqueFilepath,
|
||||
splitFolderAndFilename,
|
||||
} from "src/utils/fileUtils";
|
||||
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { showColorPicker } from "src/shared/Dialogs/ColorPicker";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { getBinaryFileFromDataURL } from "src/utils/utils";
|
||||
import {
|
||||
COLOR_NAMES,
|
||||
DEVICE,
|
||||
@@ -51,7 +52,8 @@ import {
|
||||
} from "src/constants/constants";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import { getSelectableFontFiles } from "src/utils/fontUtils";
|
||||
import { getSelectableFontOptions } from "src/utils/fontUtils";
|
||||
import { FontPickerComponent } from "src/shared/components/FontPickerComponent";
|
||||
import {
|
||||
selectMarkdownBlockSubpath,
|
||||
selectMarkdownHeadingSubpath,
|
||||
@@ -67,9 +69,8 @@ import {
|
||||
BLOCK_REFERENCE_ICON_ID,
|
||||
BLOCK_REFERENCE_ICON_REGISTRY_SVG,
|
||||
} from "src/constants/blockReferenceIcon";
|
||||
import { FileAndFolderSelectorModal } from "src/shared/Dialogs/FileAndFolderSelectorModal";
|
||||
|
||||
const MARKDOWN_SVG_CONSOLE_COMMAND =
|
||||
"ExcalidrawAutomate.mostRecentMarkdownSVG";
|
||||
let blockReferenceIconRegistered = false;
|
||||
|
||||
type MarkdownImageAppearanceStyle = Pick<
|
||||
@@ -84,7 +85,7 @@ type AppearanceControlsOptions = {
|
||||
cssEditorAria: string;
|
||||
cssBoilerplate: string;
|
||||
cssBoilerplateMarker: string;
|
||||
includeCSSCommand: boolean;
|
||||
includeSVGCopy: boolean;
|
||||
};
|
||||
|
||||
const setBlockReferenceIcon = (button: ButtonComponent): void => {
|
||||
@@ -152,12 +153,19 @@ class MarkdownImageEditorController {
|
||||
private closed = false;
|
||||
private editorChangeRef: EventRef | null = null;
|
||||
private selectionGeneration = 0;
|
||||
private initializing = false;
|
||||
private lastObservedSelectionId: string | null = null;
|
||||
private editorFocusHost: HTMLElement | null = null;
|
||||
private editorFocusInHandler: (() => void) | null = null;
|
||||
private editorFocusOutHandler: ((event: FocusEvent) => void) | null = null;
|
||||
private editorCommandView: MarkdownView | null = null;
|
||||
private previousActiveEditor: MarkdownFileInfo | null = null;
|
||||
private editorCommandRoutingActive = false;
|
||||
private editorCommandScopeActive = false;
|
||||
private focusEditorOnMount = false;
|
||||
private sidepanelRevealComplete = false;
|
||||
private editorFocusStabilizationWindow: Window | null = null;
|
||||
private editorFocusStabilizationFrame: number | null = null;
|
||||
private scenePointerDocument: Document | null = null;
|
||||
private scenePointerDownHandler: ((event: PointerEvent) => void) | null = null;
|
||||
private renderStatusEl: HTMLElement | null = null;
|
||||
@@ -170,6 +178,7 @@ class MarkdownImageEditorController {
|
||||
private ownerAttachmentGeneration = 0;
|
||||
private activeLeafChangeRef: EventRef | null = null;
|
||||
private cssEditors: CSSCodeEditor[] = [];
|
||||
private fontPickers: FontPickerComponent[] = [];
|
||||
private focusOwnerButtonEl: HTMLButtonElement | null = null;
|
||||
private ownerStatusEl: HTMLElement | null = null;
|
||||
private mobileViewPatchCleanup: (() => void) | null = null;
|
||||
@@ -193,47 +202,88 @@ class MarkdownImageEditorController {
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!element) {
|
||||
const id = await insertMarkdownImage(this.view);
|
||||
if (!this.ensureOwnerValid()) {
|
||||
this.initializing = true;
|
||||
this.focusEditorOnMount = true;
|
||||
try {
|
||||
// Establish and reveal the feature tab before inserting a new image. The
|
||||
// insertion renders Markdown asynchronously; leaving the prior script tab
|
||||
// active during that work lets its delayed focus handlers win the race.
|
||||
patchMobileView(this.view);
|
||||
const sidepanel = await this.view.plugin.openSidepanel(false);
|
||||
if (!sidepanel || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!id) {
|
||||
new Notice(t("MARKDOWN_IMAGE_INSERT_ERROR"));
|
||||
this.tab = await sidepanel.createTab({
|
||||
title: t("MARKDOWN_IMAGE_TITLE"),
|
||||
});
|
||||
this.tab.onClose = () => this.close();
|
||||
this.tab.onFocus = (view) => void this.handleSidepanelFocus(view);
|
||||
this.tab.onWindowMigrated = () => void this.rebuildEditor();
|
||||
this.tab.onExcalidrawViewClosed = () => void this.invalidateOwner(false);
|
||||
this.watchActiveExcalidrawView();
|
||||
this.renderPanel();
|
||||
await this.app.workspace.revealLeaf(sidepanel.leaf);
|
||||
if (!this.tab || this.closed || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
element = this.view
|
||||
.getViewElements()
|
||||
.find((candidate) => candidate.id === id) as
|
||||
| ExcalidrawImageElement
|
||||
| undefined;
|
||||
this.sidepanelRevealComplete = true;
|
||||
|
||||
if (!element) {
|
||||
element = await insertMarkdownImage(this.view);
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!element) {
|
||||
new Notice(t("MARKDOWN_IMAGE_INSERT_ERROR"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
this.element = element;
|
||||
this.lastObservedSelectionId = element.id;
|
||||
this.renderSettings = getMarkdownImageRenderSettings(
|
||||
this.view.plugin,
|
||||
element,
|
||||
);
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
this.renderPanel();
|
||||
this.focusEditorIfRequested();
|
||||
return true;
|
||||
} finally {
|
||||
this.initializing = false;
|
||||
}
|
||||
if (!element) {
|
||||
return false;
|
||||
}
|
||||
this.element = element;
|
||||
this.lastObservedSelectionId = element.id;
|
||||
this.renderSettings = getMarkdownImageRenderSettings(
|
||||
this.view.plugin,
|
||||
element,
|
||||
}
|
||||
|
||||
public isEditingElement(
|
||||
view: ExcalidrawView,
|
||||
element: ExcalidrawImageElement,
|
||||
): boolean {
|
||||
return (
|
||||
!this.closed &&
|
||||
this.tab !== null &&
|
||||
this.view === view &&
|
||||
this.element?.id === element.id &&
|
||||
this.isOwnerViewValid()
|
||||
);
|
||||
// Revealing a phone sidebar can coincide with Obsidian registering the
|
||||
// soon-to-be-created detached Markdown leaf as its active editor.
|
||||
patchMobileView(this.view);
|
||||
const sidepanel = await this.view.plugin.openSidepanel(true);
|
||||
if (!sidepanel || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public async revealAndFocus(): Promise<void> {
|
||||
if (!this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.tab = await sidepanel.createTab({ title: t("MARKDOWN_IMAGE_TITLE") });
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
this.tab.onClose = () => this.close();
|
||||
this.tab.onFocus = (view) => void this.handleSidepanelFocus(view);
|
||||
this.tab.onWindowMigrated = () => void this.rebuildEditor();
|
||||
this.tab.onExcalidrawViewClosed = () => void this.invalidateOwner(false);
|
||||
this.watchActiveExcalidrawView();
|
||||
this.renderPanel();
|
||||
this.tab.open(true);
|
||||
return true;
|
||||
const sidepanel = await this.plugin.openSidepanel(false);
|
||||
if (!sidepanel || !this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.focusEditorOnMount = true;
|
||||
this.sidepanelRevealComplete = false;
|
||||
this.tab.open(false);
|
||||
await this.app.workspace.revealLeaf(sidepanel.leaf);
|
||||
if (!this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.sidepanelRevealComplete = true;
|
||||
this.focusEditorIfRequested();
|
||||
}
|
||||
|
||||
private renderPanel(): void {
|
||||
@@ -245,6 +295,7 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
this.removeEditorResizeListener();
|
||||
this.destroyCSSEditors();
|
||||
this.destroyFontPickers();
|
||||
this.focusOwnerButtonEl = null;
|
||||
this.ownerStatusEl = null;
|
||||
this.tab.clear();
|
||||
@@ -359,22 +410,35 @@ class MarkdownImageEditorController {
|
||||
});
|
||||
});
|
||||
|
||||
const developerConsoleHelp = DEVICE.isMobile
|
||||
? t("MARKDOWN_IMAGE_CSS_MOBILE_HELP")
|
||||
: t("MARKDOWN_IMAGE_CSS_DESKTOP_HELP").replace(
|
||||
"{shortcut}",
|
||||
DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i",
|
||||
);
|
||||
new Setting(appearance)
|
||||
.setClass("excalidraw-markdown-image-editor__setting--wide")
|
||||
.setName(t("MARKDOWN_IMAGE_BOTTOM_PADDING"))
|
||||
.setDesc(t("MARKDOWN_IMAGE_BOTTOM_PADDING_DESC"))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 100, 1)
|
||||
.setValue(this.renderSettings.paddingBottom)
|
||||
.setDynamicTooltip()
|
||||
.onChange((paddingBottom) => {
|
||||
if (!this.renderSettings) {
|
||||
return;
|
||||
}
|
||||
this.renderSettings = {
|
||||
...this.renderSettings,
|
||||
paddingBottom,
|
||||
};
|
||||
this.scheduleRender();
|
||||
}),
|
||||
);
|
||||
|
||||
this.renderAppearanceControls(appearance, {
|
||||
scope: "image",
|
||||
cssName: t("MARKDOWN_IMAGE_CSS"),
|
||||
cssDescription: fragWithHTML(
|
||||
`${t("MARKDOWN_IMAGE_CSS_DESC")} ${t("MARKDOWN_IMAGE_CSS_IMPORTANT_HINT")} ${developerConsoleHelp}`,
|
||||
),
|
||||
cssDescription: `${t("MARKDOWN_IMAGE_CSS_DESC")} ${t("MARKDOWN_IMAGE_CSS_IMPORTANT_HINT")}`,
|
||||
cssEditorAria: t("MARKDOWN_IMAGE_CSS_EDITOR_ARIA"),
|
||||
cssBoilerplate: MARKDOWN_IMAGE_CSS_BOILERPLATE,
|
||||
cssBoilerplateMarker: MARKDOWN_IMAGE_CSS_BOILERPLATE_MARKER,
|
||||
includeCSSCommand: true,
|
||||
includeSVGCopy: true,
|
||||
});
|
||||
|
||||
const transclusionToggleSetting = new Setting(content)
|
||||
@@ -422,7 +486,7 @@ class MarkdownImageEditorController {
|
||||
cssEditorAria: t("MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA"),
|
||||
cssBoilerplate: TRANSCLUSION_CSS_BOILERPLATE,
|
||||
cssBoilerplateMarker: TRANSCLUSION_CSS_BOILERPLATE_MARKER,
|
||||
includeCSSCommand: false,
|
||||
includeSVGCopy: false,
|
||||
});
|
||||
|
||||
void this.mountMarkdownView(editorHost);
|
||||
@@ -474,30 +538,24 @@ class MarkdownImageEditorController {
|
||||
return;
|
||||
}
|
||||
|
||||
new Setting(host)
|
||||
const fontSetting = new Setting(host)
|
||||
.setClass("excalidraw-markdown-image-editor__setting--font")
|
||||
.setName(t("MARKDOWN_IMAGE_FONT"))
|
||||
.addDropdown((dropdown) => {
|
||||
for (const font of [
|
||||
"Virgil",
|
||||
"Cascadia",
|
||||
"Excalifont",
|
||||
"Comic Shanns",
|
||||
"Liberation Sans",
|
||||
]) {
|
||||
dropdown.addOption(font, font);
|
||||
}
|
||||
getSelectableFontFiles(
|
||||
.setName(t("MARKDOWN_IMAGE_FONT"));
|
||||
const fontPicker = new FontPickerComponent(
|
||||
fontSetting.controlEl,
|
||||
this.view.app,
|
||||
() =>
|
||||
getSelectableFontOptions(
|
||||
this.view.app,
|
||||
this.view.plugin.settings.fontAssetsPath,
|
||||
).forEach((file) => {
|
||||
dropdown.addOption(file.path, file.name);
|
||||
});
|
||||
dropdown.setValue(style.fontFamily).onChange((fontFamily) => {
|
||||
this.updateAppearanceStyle(options.scope, { fontFamily });
|
||||
void this.view.plugin.initializeFonts();
|
||||
});
|
||||
),
|
||||
)
|
||||
.setAriaLabel(t("MARKDOWN_IMAGE_FONT"))
|
||||
.setValue(style.fontFamily)
|
||||
.onChange((fontFamily) => {
|
||||
this.updateAppearanceStyle(options.scope, { fontFamily });
|
||||
});
|
||||
this.fontPickers.push(fontPicker);
|
||||
|
||||
let fontColorTextEl: HTMLInputElement | null = null;
|
||||
let fontColorPicker: ColorComponent | null = null;
|
||||
@@ -522,6 +580,11 @@ class MarkdownImageEditorController {
|
||||
.addText((text) => {
|
||||
fontColorTextEl = text.inputEl;
|
||||
text.setValue(style.fontColor).onChange(setFontColor);
|
||||
text.inputEl.addEventListener("blur", () => {
|
||||
if (text.inputEl.value.trim() === "") {
|
||||
setFontColor("black");
|
||||
}
|
||||
});
|
||||
})
|
||||
.addColorPicker((picker) => {
|
||||
fontColorPicker = picker;
|
||||
@@ -653,22 +716,49 @@ class MarkdownImageEditorController {
|
||||
"aria-label",
|
||||
t("MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE"),
|
||||
);
|
||||
if (options.includeCSSCommand) {
|
||||
const copyCSSCommandButton = new ButtonComponent(cssActions)
|
||||
if (options.includeSVGCopy) {
|
||||
const copySVGButton = new ButtonComponent(cssActions)
|
||||
.setIcon("clipboard-copy")
|
||||
.setClass("excalidraw-markdown-image-editor__css-action-button")
|
||||
.setTooltip(t("MARKDOWN_IMAGE_COPY_CSS_COMMAND"))
|
||||
.onClick(async () => {
|
||||
await navigator.clipboard.writeText(MARKDOWN_SVG_CONSOLE_COMMAND);
|
||||
new Notice(t("MARKDOWN_IMAGE_CSS_COMMAND_COPIED"));
|
||||
});
|
||||
copyCSSCommandButton.buttonEl.setAttribute(
|
||||
.setTooltip(t("MARKDOWN_IMAGE_COPY_SVG"))
|
||||
.onClick(() => void this.copyCurrentMarkdownSVG());
|
||||
copySVGButton.buttonEl.setAttribute(
|
||||
"aria-label",
|
||||
t("MARKDOWN_IMAGE_COPY_CSS_COMMAND"),
|
||||
t("MARKDOWN_IMAGE_COPY_SVG"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async copyCurrentMarkdownSVG(): Promise<void> {
|
||||
if (!this.ensureOwnerValid() || !this.element?.fileId) {
|
||||
new Notice(t("MARKDOWN_IMAGE_SVG_COPY_ERROR"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const file = this.view.excalidrawAPI?.getFiles()[this.element.fileId];
|
||||
if (!file?.dataURL.startsWith("data:image/svg+xml")) {
|
||||
new Notice(t("MARKDOWN_IMAGE_SVG_COPY_ERROR"));
|
||||
return;
|
||||
}
|
||||
const data = await getBinaryFileFromDataURL(file.dataURL);
|
||||
const clipboard =
|
||||
this.tab?.contentEl.ownerDocument.defaultView?.navigator.clipboard ??
|
||||
navigator.clipboard;
|
||||
if (!data || !clipboard) {
|
||||
new Notice(t("MARKDOWN_IMAGE_SVG_COPY_ERROR"));
|
||||
return;
|
||||
}
|
||||
await clipboard.writeText(new TextDecoder().decode(data));
|
||||
new Notice(t("MARKDOWN_IMAGE_SVG_COPIED"));
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "MarkdownImageEditor.copyCurrentMarkdownSVG",
|
||||
error,
|
||||
});
|
||||
new Notice(t("MARKDOWN_IMAGE_SVG_COPY_ERROR"));
|
||||
}
|
||||
}
|
||||
|
||||
private async saveAppearanceDefaults(): Promise<void> {
|
||||
if (!this.ensureOwnerValid() || !this.renderSettings) {
|
||||
return;
|
||||
@@ -692,6 +782,7 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
this.renderStatusEl = null;
|
||||
this.destroyCSSEditors();
|
||||
this.destroyFontPickers();
|
||||
this.focusOwnerButtonEl = null;
|
||||
this.ownerStatusEl = null;
|
||||
this.tab.clear();
|
||||
@@ -749,6 +840,7 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
this.renderStatusEl = null;
|
||||
this.destroyCSSEditors();
|
||||
this.destroyFontPickers();
|
||||
this.focusOwnerButtonEl = null;
|
||||
this.ownerStatusEl = null;
|
||||
this.tab.clear();
|
||||
@@ -1005,10 +1097,12 @@ class MarkdownImageEditorController {
|
||||
return;
|
||||
}
|
||||
new Setting(host)
|
||||
.setClass("excalidraw-markdown-image-editor__setting--wide")
|
||||
.setName(t("MARKDOWN_IMAGE_EXTRACT_LOCAL"))
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setIcon("file-output")
|
||||
.setClass("excalidraw-markdown-image-editor__compact-button")
|
||||
.setTooltip(t("MARKDOWN_IMAGE_EXTRACT"))
|
||||
.onClick(() => {
|
||||
void this.extractToNote();
|
||||
@@ -1017,6 +1111,7 @@ class MarkdownImageEditorController {
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setIcon("copy-plus")
|
||||
.setClass("excalidraw-markdown-image-editor__compact-button")
|
||||
.setTooltip(t("DUPLICATE_IMAGE"))
|
||||
.onClick(() => {
|
||||
void this.duplicateLocalMarkdownImage();
|
||||
@@ -1241,26 +1336,36 @@ class MarkdownImageEditorController {
|
||||
if (!this.ensureOwnerValid() || !source || source.source !== "local") {
|
||||
return;
|
||||
}
|
||||
let path = await ScriptEngine.inputPrompt(
|
||||
this.view,
|
||||
this.view.plugin,
|
||||
this.view.app,
|
||||
t("MARKDOWN_IMAGE_EXTRACT_TITLE"),
|
||||
t("MARKDOWN_IMAGE_EXTRACT_PATH"),
|
||||
const attachmentLocation = await getAttachmentsFolderAndFilePath(
|
||||
this.app,
|
||||
this.view.file.path,
|
||||
t("MARKDOWN_IMAGE_DEFAULT_NOTE"),
|
||||
);
|
||||
if (!path || !this.ensureOwnerValid()) {
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
if (!path.toLowerCase().endsWith(".md")) {
|
||||
path += ".md";
|
||||
const defaultLocation = splitFolderAndFilename(
|
||||
attachmentLocation.filepath,
|
||||
);
|
||||
const location = await new FileAndFolderSelectorModal(this.app, {
|
||||
title: t("MARKDOWN_IMAGE_EXTRACT_TITLE"),
|
||||
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
|
||||
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
|
||||
submitButtonText: t("MARKDOWN_IMAGE_EXTRACT"),
|
||||
folderPath: defaultLocation.folderpath,
|
||||
fileName: defaultLocation.filename,
|
||||
}).start();
|
||||
if (!location || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { folderpath, filename } = splitFolderAndFilename(path);
|
||||
path = getNewUniqueFilepath(
|
||||
const filename = location.fileName.toLowerCase().endsWith(".md")
|
||||
? location.fileName
|
||||
: `${location.fileName}.md`;
|
||||
const path = getNewUniqueFilepath(
|
||||
this.view.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
location.folderPath,
|
||||
);
|
||||
const file = await createOrOverwriteFile(
|
||||
this.view.app,
|
||||
@@ -1309,7 +1414,7 @@ class MarkdownImageEditorController {
|
||||
elements: readonly ExcalidrawElement[],
|
||||
selectedElementIds: Record<string, boolean>,
|
||||
): void {
|
||||
if (!this.tab || this.closed) {
|
||||
if (!this.tab || this.closed || this.initializing) {
|
||||
return;
|
||||
}
|
||||
if (sourceView !== this.view || !this.isOwnerViewValid()) {
|
||||
@@ -1366,11 +1471,26 @@ class MarkdownImageEditorController {
|
||||
private handleSidepanelFocus(
|
||||
nextView: ExcalidrawView | null,
|
||||
): void {
|
||||
if (nextView) {
|
||||
void this.attachToView(nextView);
|
||||
const ownerIsValid = this.isOwnerViewValid();
|
||||
const nextViewIsActive =
|
||||
nextView !== null &&
|
||||
this.app.workspace.getMostRecentLeaf() === nextView.leaf;
|
||||
if (
|
||||
nextView &&
|
||||
(!ownerIsValid || nextView === this.view || nextViewIsActive)
|
||||
) {
|
||||
void this.attachToView(nextView).then(() => {
|
||||
this.focusEditorIfRequested();
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.ensureOwnerValid();
|
||||
// Focusing the sidepanel makes its own leaf the most recent one. In that
|
||||
// transition, the plugin's last-active Excalidraw leaf can briefly be
|
||||
// stale. Keep the owner established by the active-leaf listener instead
|
||||
// of tearing down a valid editor in favor of the stale view.
|
||||
if (this.ensureOwnerValid()) {
|
||||
this.focusEditorIfRequested();
|
||||
}
|
||||
}
|
||||
|
||||
private async mountMarkdownView(host: HTMLElement): Promise<void> {
|
||||
@@ -1388,6 +1508,9 @@ class MarkdownImageEditorController {
|
||||
host.setText(t("MARKDOWN_IMAGE_SOURCE_UNAVAILABLE"));
|
||||
return;
|
||||
}
|
||||
const ownerView = this.view;
|
||||
const ownerFile = this.ownerFile;
|
||||
const elementFileId = element.fileId;
|
||||
const { leaf, rootSplit } = createLeaf(this.view, host.ownerDocument);
|
||||
this.editorLeaf = leaf;
|
||||
this.editorRoot = rootSplit;
|
||||
@@ -1413,13 +1536,9 @@ class MarkdownImageEditorController {
|
||||
{ history: false },
|
||||
);
|
||||
await leaf.loadIfDeferred();
|
||||
if (ref) {
|
||||
leaf.setEphemeralState({ subpath: ref });
|
||||
}
|
||||
} else {
|
||||
await leaf.openFile(sourceFile, {
|
||||
active: false,
|
||||
...(ref ? { eState: { subpath: ref } } : {}),
|
||||
});
|
||||
}
|
||||
if (
|
||||
@@ -1434,7 +1553,9 @@ class MarkdownImageEditorController {
|
||||
if (leaf.view instanceof MarkdownView) {
|
||||
this.editorView = leaf.view;
|
||||
this.prepareEditorView(host, leaf.view);
|
||||
this.revealExternalSourceSubpath(leaf.view, sourceFile, ref);
|
||||
this.watchEditorChanges();
|
||||
this.focusEditorIfRequested(leaf.view);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1442,18 +1563,23 @@ class MarkdownImageEditorController {
|
||||
const fragmentView = new MarkdownFragmentView(
|
||||
leaf,
|
||||
async (markdown) => {
|
||||
if (!this.element) {
|
||||
return;
|
||||
}
|
||||
if (containsReservedMarkdownImageMarker(markdown)) {
|
||||
new Notice(t("MARKDOWN_IMAGE_RESERVED_MARKER"));
|
||||
return;
|
||||
}
|
||||
this.view.excalidrawData.setMarkdownImage(this.element.fileId, {
|
||||
const excalidrawData = ownerView.excalidrawData;
|
||||
if (
|
||||
!excalidrawData ||
|
||||
excalidrawData.file !== ownerFile ||
|
||||
ownerView.file !== ownerFile
|
||||
) {
|
||||
return;
|
||||
}
|
||||
excalidrawData.setMarkdownImage(elementFileId, {
|
||||
markdown,
|
||||
});
|
||||
this.view.setDirty();
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
ownerView.setDirty();
|
||||
ownerView.setMarkdownImageEditorIsEditing();
|
||||
},
|
||||
);
|
||||
await leaf.open(fragmentView);
|
||||
@@ -1470,6 +1596,30 @@ class MarkdownImageEditorController {
|
||||
this.editorView = fragmentView;
|
||||
this.prepareEditorView(host, fragmentView);
|
||||
this.watchEditorChanges();
|
||||
this.focusEditorIfRequested(fragmentView);
|
||||
}
|
||||
|
||||
private revealExternalSourceSubpath(
|
||||
editorView: MarkdownView,
|
||||
sourceFile: TFile,
|
||||
subpath: string,
|
||||
): void {
|
||||
if (!subpath) {
|
||||
return;
|
||||
}
|
||||
const cache = this.app.metadataCache.getFileCache(sourceFile);
|
||||
const location = cache ? resolveSubpath(cache, subpath) : null;
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
const position = {
|
||||
line: location.start.line,
|
||||
ch: location.start.col,
|
||||
};
|
||||
// A collapsed cursor reveals the referenced content without leaving the
|
||||
// detached MarkdownView in Obsidian's persistent subpath-selection state.
|
||||
editorView.editor.setCursor(position);
|
||||
editorView.editor.scrollIntoView({ from: position, to: position }, true);
|
||||
}
|
||||
|
||||
private prepareEditorView(host: HTMLElement, editorView: MarkdownView): void {
|
||||
@@ -1484,29 +1634,29 @@ class MarkdownImageEditorController {
|
||||
this.editorFocusHost = host;
|
||||
this.editorCommandView = editorView;
|
||||
this.editorFocusInHandler = () => {
|
||||
if (this.app.workspace.activeEditor === editorView) {
|
||||
return;
|
||||
}
|
||||
this.previousActiveEditor = this.app.workspace.activeEditor;
|
||||
this.app.workspace.activeEditor = editorView;
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
};
|
||||
this.editorFocusOutHandler = (event: FocusEvent) => {
|
||||
const nextTarget = event.relatedTarget;
|
||||
this.editorFocusOutHandler = () => {
|
||||
const finishFocusTransition = () => {
|
||||
if (this.editorView !== editorView || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
if (host.contains(host.ownerDocument.activeElement)) {
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
return;
|
||||
}
|
||||
this.restorePreviousActiveEditor();
|
||||
void this.renderCurrentEditor();
|
||||
};
|
||||
const targetWindow = host.ownerDocument.defaultView;
|
||||
if (
|
||||
nextTarget &&
|
||||
targetWindow?.Node &&
|
||||
nextTarget instanceof targetWindow.Node &&
|
||||
host.contains(nextTarget)
|
||||
) {
|
||||
return;
|
||||
if (targetWindow) {
|
||||
targetWindow.setTimeout(finishFocusTransition, 0);
|
||||
} else {
|
||||
finishFocusTransition();
|
||||
}
|
||||
this.restorePreviousActiveEditor();
|
||||
void this.renderCurrentEditor();
|
||||
};
|
||||
host.addEventListener("focusin", this.editorFocusInHandler);
|
||||
host.addEventListener("focusout", this.editorFocusOutHandler);
|
||||
|
||||
const viewContainer = this.view.containerEl;
|
||||
if (!viewContainer) {
|
||||
void this.invalidateOwner(false);
|
||||
@@ -1537,7 +1687,96 @@ class MarkdownImageEditorController {
|
||||
);
|
||||
}
|
||||
|
||||
private activateEditorCommandRouting(editorView: MarkdownView): void {
|
||||
if (!this.editorCommandRoutingActive) {
|
||||
this.previousActiveEditor =
|
||||
this.app.workspace.activeEditor === editorView
|
||||
? null
|
||||
: this.app.workspace.activeEditor;
|
||||
this.editorCommandRoutingActive = true;
|
||||
}
|
||||
if (!this.editorCommandScopeActive && editorView.scope) {
|
||||
this.app.keymap.pushScope(editorView.scope);
|
||||
this.editorCommandScopeActive = true;
|
||||
}
|
||||
this.app.workspace.activeEditor = editorView;
|
||||
}
|
||||
|
||||
private focusEditorIfRequested(
|
||||
editorView: MarkdownView | null = this.editorView,
|
||||
): void {
|
||||
if (
|
||||
!this.focusEditorOnMount ||
|
||||
!this.sidepanelRevealComplete ||
|
||||
!editorView ||
|
||||
!this.tab?.isActiveTab()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (this.editorView !== editorView || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
if (DEVICE.isMobile) {
|
||||
// Activating the detached editor leaf navigates away from Obsidian's
|
||||
// mobile drawer and closes the sidepanel. Establish the active editor
|
||||
// before focusing so the mobile Markdown toolbar initializes with the
|
||||
// keyboard, while keeping the sidepanel leaf visible.
|
||||
return;
|
||||
}
|
||||
this.app.workspace.setActiveLeaf(editorView.leaf, { focus: true });
|
||||
editorView.editor.focus();
|
||||
const targetWindow = editorView.containerEl.ownerDocument.defaultView;
|
||||
this.stabilizeActiveEditor(editorView, targetWindow);
|
||||
}
|
||||
|
||||
private stabilizeActiveEditor(
|
||||
editorView: MarkdownView,
|
||||
targetWindow: Window,
|
||||
): void {
|
||||
this.stopEditorFocusStabilization();
|
||||
this.editorFocusStabilizationWindow = targetWindow;
|
||||
const deadline = targetWindow.performance.now() + 500;
|
||||
const stabilize = () => {
|
||||
if (
|
||||
this.editorView !== editorView ||
|
||||
!this.ensureOwnerValid() ||
|
||||
!this.tab?.isActiveTab() ||
|
||||
!this.editorFocusHost?.contains(
|
||||
editorView.containerEl.ownerDocument.activeElement,
|
||||
)
|
||||
) {
|
||||
this.stopEditorFocusStabilization();
|
||||
return;
|
||||
}
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
if (targetWindow.performance.now() >= deadline) {
|
||||
this.editorFocusStabilizationFrame = null;
|
||||
this.editorFocusStabilizationWindow = null;
|
||||
this.focusEditorOnMount = false;
|
||||
return;
|
||||
}
|
||||
this.editorFocusStabilizationFrame = targetWindow.requestAnimationFrame(
|
||||
stabilize,
|
||||
);
|
||||
};
|
||||
stabilize();
|
||||
}
|
||||
|
||||
private stopEditorFocusStabilization(): void {
|
||||
if (
|
||||
this.editorFocusStabilizationWindow &&
|
||||
this.editorFocusStabilizationFrame !== null
|
||||
) {
|
||||
this.editorFocusStabilizationWindow.cancelAnimationFrame(
|
||||
this.editorFocusStabilizationFrame,
|
||||
);
|
||||
}
|
||||
this.editorFocusStabilizationWindow = null;
|
||||
this.editorFocusStabilizationFrame = null;
|
||||
}
|
||||
|
||||
private removeEditorFocusListener(): void {
|
||||
this.stopEditorFocusStabilization();
|
||||
if (this.editorFocusHost && this.editorFocusInHandler) {
|
||||
this.editorFocusHost.removeEventListener(
|
||||
"focusin",
|
||||
@@ -1567,13 +1806,19 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
|
||||
private restorePreviousActiveEditor(): void {
|
||||
if (this.editorCommandScopeActive && this.editorCommandView?.scope) {
|
||||
this.app.keymap.popScope(this.editorCommandView.scope);
|
||||
}
|
||||
this.editorCommandScopeActive = false;
|
||||
if (
|
||||
this.editorCommandRoutingActive &&
|
||||
this.editorCommandView &&
|
||||
this.app.workspace.activeEditor === this.editorCommandView
|
||||
) {
|
||||
this.app.workspace.activeEditor = this.previousActiveEditor;
|
||||
}
|
||||
this.previousActiveEditor = null;
|
||||
this.editorCommandRoutingActive = false;
|
||||
}
|
||||
|
||||
private setupEditorResize(
|
||||
@@ -1653,6 +1898,13 @@ class MarkdownImageEditorController {
|
||||
this.cssEditors = [];
|
||||
}
|
||||
|
||||
private destroyFontPickers(): void {
|
||||
for (const picker of this.fontPickers) {
|
||||
picker.destroy();
|
||||
}
|
||||
this.fontPickers = [];
|
||||
}
|
||||
|
||||
private watchEditorChanges(): void {
|
||||
if (this.editorChangeRef) {
|
||||
this.app.workspace.offref(this.editorChangeRef);
|
||||
@@ -1710,11 +1962,24 @@ class MarkdownImageEditorController {
|
||||
if (!source || this.closed || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
let renderMarkdown = markdown;
|
||||
if (source.source === "external") {
|
||||
await editorView.save();
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
const refreshedSource = await getMarkdownImageSource(
|
||||
this.view,
|
||||
element,
|
||||
);
|
||||
if (
|
||||
!refreshedSource ||
|
||||
refreshedSource.source !== "external" ||
|
||||
!this.ensureOwnerValid()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
renderMarkdown = refreshedSource.markdown;
|
||||
} else {
|
||||
this.view.excalidrawData.setMarkdownImage(element.fileId, {
|
||||
markdown,
|
||||
@@ -1724,7 +1989,7 @@ class MarkdownImageEditorController {
|
||||
const updated = await updateMarkdownImage(
|
||||
this.view,
|
||||
element,
|
||||
markdown,
|
||||
renderMarkdown,
|
||||
renderSettings,
|
||||
source.source,
|
||||
);
|
||||
@@ -1899,10 +2164,13 @@ class MarkdownImageEditorController {
|
||||
this.app.workspace.offref(this.editorChangeRef);
|
||||
this.editorChangeRef = null;
|
||||
}
|
||||
if (editorView && saveEditor) {
|
||||
await editorView.save();
|
||||
try {
|
||||
if (editorView && saveEditor) {
|
||||
await editorView.save();
|
||||
}
|
||||
} finally {
|
||||
editorLeaf?.detach();
|
||||
}
|
||||
editorLeaf?.detach();
|
||||
}
|
||||
|
||||
private close(): void {
|
||||
@@ -1911,6 +2179,7 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
const canClearOwnerEditing = this.isOwnerIdentityValid();
|
||||
this.closed = true;
|
||||
this.sidepanelRevealComplete = false;
|
||||
if (activeController === this) {
|
||||
activeController = null;
|
||||
}
|
||||
@@ -1922,6 +2191,7 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
this.cancelScheduledRender();
|
||||
this.destroyCSSEditors();
|
||||
this.destroyFontPickers();
|
||||
this.focusOwnerButtonEl = null;
|
||||
this.ownerStatusEl = null;
|
||||
void this.flushAndDetachEditor().finally(() => {
|
||||
@@ -1949,15 +2219,27 @@ export async function openMarkdownImageEditor(
|
||||
view: ExcalidrawView,
|
||||
element?: ExcalidrawImageElement,
|
||||
): Promise<void> {
|
||||
activeController?.dispose();
|
||||
if (element && activeController?.isEditingElement(view, element)) {
|
||||
await activeController.revealAndFocus();
|
||||
return;
|
||||
}
|
||||
const previousController = activeController;
|
||||
const controller = new MarkdownImageEditorController(view);
|
||||
activeController = controller;
|
||||
try {
|
||||
if (!(await controller.open(element))) {
|
||||
controller.dispose();
|
||||
if (activeController === null && previousController) {
|
||||
activeController = previousController;
|
||||
}
|
||||
return;
|
||||
}
|
||||
previousController?.dispose();
|
||||
} catch (error: unknown) {
|
||||
controller.dispose();
|
||||
if (activeController === null && previousController) {
|
||||
activeController = previousController;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
+73
-3
@@ -366,6 +366,40 @@ textarea.excalidraw-wysiwyg {
|
||||
min-width: 10em;
|
||||
}
|
||||
|
||||
.excalidraw-folder-path-control {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.excalidraw-file-and-folder-selector__field {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.excalidraw-file-and-folder-selector__field>.setting-item-control {
|
||||
flex: 1 1 18rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.excalidraw-file-and-folder-selector__field input[type="text"] {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.is-mobile .excalidraw-file-and-folder-selector .setting-item-control {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.excalidraw-folder-create-row {
|
||||
display: flex;
|
||||
flex: 0 0 100%;
|
||||
justify-content: flex-end;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.excalidraw-folder-create-row>button:not(.excalidraw-display-none) {
|
||||
margin-top: var(--size-2-2);
|
||||
}
|
||||
|
||||
.excalidraw-ai-provider-table {
|
||||
margin: auto;
|
||||
width: 80%;
|
||||
@@ -1338,7 +1372,8 @@ End Obsidian Sheets Plus support
|
||||
}
|
||||
|
||||
.excalidraw-markdown-image-editor__source .setting-item-control select,
|
||||
.excalidraw-markdown-image-editor__appearance .setting-item-control select {
|
||||
.excalidraw-markdown-image-editor__appearance .setting-item-control select,
|
||||
.excalidraw-markdown-image-editor__appearance .setting-item-control .excalidraw-font-picker {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -1379,7 +1414,8 @@ End Obsidian Sheets Plus support
|
||||
flex: 0 0 var(--input-height, 32px);
|
||||
}
|
||||
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select {
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
|
||||
width: min(240px, 100%);
|
||||
}
|
||||
|
||||
@@ -1430,7 +1466,8 @@ End Obsidian Sheets Plus support
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select {
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
|
||||
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -1566,4 +1603,37 @@ End Obsidian Sheets Plus support
|
||||
border-radius: var(--radius-m);
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
button.excalidraw-font-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: min(240px, 100%);
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.excalidraw-font-picker__label {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.excalidraw-font-picker__option {
|
||||
display: block;
|
||||
min-width: min(12rem, calc(100vw - 4rem));
|
||||
max-width: calc(100vw - 4rem);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--font-ui-medium);
|
||||
}
|
||||
|
||||
.excalidraw-font-picker-menu-opening .menu,
|
||||
.menu.excalidraw-font-picker-menu--desktop {
|
||||
max-height: min(420px, 60vh);
|
||||
overflow-y: auto;
|
||||
}
|
||||
Reference in new issue
Block a user