Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/obsidian/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@
"zod": "^3.24.1"
},
"dependencies": {
"@codemirror/view": "^6.38.8",
"date-fns": "^4.1.0",
"nanoid": "^4.0.2",
"react": "catalog:obsidian",
"react-dom": "catalog:obsidian",
"date-fns": "^4.1.0",
"tailwindcss-animate": "^1.0.7",
"tldraw": "3.14.2"
}
}
}
41 changes: 41 additions & 0 deletions apps/obsidian/src/components/GeneralSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ const GeneralSettings = () => {
);
const [canvasAttachmentsFolderPath, setCanvasAttachmentsFolderPath] =
useState<string>(plugin.settings.canvasAttachmentsFolderPath);
const [nodeTagHotkey, setNodeTagHotkey] = useState<string>(
plugin.settings.nodeTagHotkey,
);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

const handleToggleChange = (newValue: boolean) => {
Expand All @@ -179,11 +182,20 @@ const GeneralSettings = () => {
[],
);

const handleNodeTagHotkeyChange = useCallback((newValue: string) => {
// Only allow single character
if (newValue.length <= 1) {
setNodeTagHotkey(newValue);
setHasUnsavedChanges(true);
}
}, []);

const handleSave = async () => {
plugin.settings.showIdsInFrontmatter = showIdsInFrontmatter;
plugin.settings.nodesFolderPath = nodesFolderPath;
plugin.settings.canvasFolderPath = canvasFolderPath;
plugin.settings.canvasAttachmentsFolderPath = canvasAttachmentsFolderPath;
plugin.settings.nodeTagHotkey = nodeTagHotkey || "";
await plugin.saveSettings();
new Notice("General settings saved");
setHasUnsavedChanges(false);
Expand Down Expand Up @@ -262,6 +274,35 @@ const GeneralSettings = () => {
</div>
</div>

<div className="setting-item">
<div className="setting-item-info">
<div className="setting-item-name">Node tag hotkey</div>
<div className="setting-item-description">
Key to press after a space to open the node tags menu. Default:
&quot;\&quot;.
</div>
</div>
<div className="setting-item-control">
<input
type="text"
value={nodeTagHotkey}
onChange={(e) => handleNodeTagHotkeyChange(e.target.value)}
onKeyDown={(e) => {
// Capture the key pressed
if (e.key.length === 1) {
e.preventDefault();
handleNodeTagHotkeyChange(e.key);
} else if (e.key === "Backspace") {
handleNodeTagHotkeyChange("");
}
}}
placeholder="\\"
maxLength={1}
className="setting-item-control"
/>
</div>
</div>

<div className="setting-item">
<button
onClick={() => void handleSave()}
Expand Down
292 changes: 292 additions & 0 deletions apps/obsidian/src/components/NodeTagSuggestModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,292 @@
import { Editor } from "obsidian";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we are mostly creating this from scratch? Are there any existing obsidian components we can tie into without having to re-invent the wheel, cover all edge cases, etc? List items, popovers, etc, etc.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as far as i know there's no official API to create popovers at tooltip position. The popover API they have are the one that takes over the whole screen

import { DiscourseNode } from "~/types";

type NodeTagItem = {
nodeType: DiscourseNode;
tag: string;
};

export class NodeTagSuggestPopover {
private popover: HTMLElement | null = null;
private items: NodeTagItem[] = [];
private selectedIndex = 0;
private keydownHandler: ((e: KeyboardEvent) => void) | null = null;
private clickOutsideHandler: ((e: MouseEvent) => void) | null = null;

constructor(
private editor: Editor,
private nodeTypes: DiscourseNode[],
) {
this.initializeItems();
}

private initializeItems() {
this.items = [];
this.nodeTypes.forEach((nodeType) => {
if (nodeType.tag) {
this.items.push({
nodeType,
tag: nodeType.tag,
});
}
});
}

private getCursorPosition(): { x: number; y: number } | null {
try {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
console.error("No selection found");
return null;
}

const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();

// If the rect has no dimensions (collapsed cursor), try using a temporary span to get cursor position
if (rect.width === 0 && rect.height === 0) {
const span = document.createElement("span");
span.textContent = "\u200B";
range.insertNode(span);
const spanRect = span.getBoundingClientRect();
span.remove();

if (spanRect.width === 0 && spanRect.height === 0) {
console.error("Could not determine cursor position");
return null;
}

return {
x: spanRect.left,
y: spanRect.bottom,
};
}

return {
x: rect.left,
y: rect.bottom,
};
} catch (error) {
console.error("Error getting cursor position:", error);
return null;
}
}

private createPopover(): HTMLElement {
const popover = document.createElement("div");
popover.className =
"node-tag-suggest-popover fixed z-[10000] bg-primary border border-modifier-border rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.15)] max-h-[300px] overflow-y-auto min-w-[200px] max-w-[400px]";

const itemsContainer = document.createElement("div");
itemsContainer.className = "node-tag-items-container";
popover.appendChild(itemsContainer);

this.renderItems(itemsContainer);

return popover;
}

private renderItems(container: HTMLElement) {
container.innerHTML = "";

if (this.items.length === 0) {
const noResults = document.createElement("div");
noResults.className = "p-3 text-center text-muted text-sm";
noResults.textContent = "No node tags available";
container.appendChild(noResults);
return;
}

this.items.forEach((item, index) => {
const itemEl = document.createElement("div");
itemEl.className = `node-tag-item px-3 py-2 cursor-pointer flex items-center gap-2 border-b border-[var(--background-modifier-border-hover)]${
index === this.selectedIndex ? " bg-modifier-hover" : ""
}`;
itemEl.dataset.index = index.toString();

if (item.nodeType.color) {
const colorDot = document.createElement("div");
colorDot.className = `w-3 h-3 rounded-full shrink-0`;
colorDot.style.backgroundColor = item.nodeType.color;
itemEl.appendChild(colorDot);
}

const textContainer = document.createElement("div");
textContainer.className = "flex flex-col gap-0.5 flex-1";

const tagText = document.createElement("div");
tagText.textContent = `#${item.tag}`;
tagText.className = "font-medium text-normal text-sm";

const nodeTypeText = document.createElement("div");
nodeTypeText.textContent = item.nodeType.name;
nodeTypeText.className = "text-xs text-muted";

textContainer.appendChild(tagText);
textContainer.appendChild(nodeTypeText);
itemEl.appendChild(textContainer);

itemEl.addEventListener("mousedown", (e) => {
e.preventDefault();
e.stopPropagation();
this.selectItem(item);
});

itemEl.addEventListener("mouseenter", () => {
this.updateSelectedIndex(index);
});

container.appendChild(itemEl);
});
}

private updateSelectedIndex(newIndex: number) {
if (newIndex === this.selectedIndex) return;

const prevSelected = this.popover?.querySelector(
`.node-tag-item[data-index="${this.selectedIndex}"]`,
) as HTMLElement;
if (prevSelected) {
prevSelected.classList.remove("bg-modifier-hover");
}

this.selectedIndex = newIndex;

const newSelected = this.popover?.querySelector(
`.node-tag-item[data-index="${this.selectedIndex}"]`,
) as HTMLElement;
if (newSelected) {
newSelected.classList.add("bg-modifier-hover");
}
}

private scrollToSelected() {
const selectedEl = this.popover?.querySelector(
`.node-tag-item[data-index="${this.selectedIndex}"]`,
) as HTMLElement;
if (selectedEl) {
selectedEl.scrollIntoView({ block: "nearest", behavior: "smooth" });
}
}

private selectItem(item: NodeTagItem) {
const tagText = `#${item.tag} `;
const cursor = this.editor.getCursor();
this.editor.replaceRange(tagText, cursor, cursor);
const newCursor = {
line: cursor.line,
ch: cursor.ch + tagText.length,
};
this.editor.setCursor(newCursor);
this.close();
}

private setupEventHandlers() {
this.keydownHandler = (e: KeyboardEvent) => {
if (!this.popover) return;

if (e.key === "ArrowDown") {
e.preventDefault();
e.stopPropagation();
const newIndex = Math.min(
this.selectedIndex + 1,
this.items.length - 1,
);
this.updateSelectedIndex(newIndex);
this.scrollToSelected();
} else if (e.key === "ArrowUp") {
e.preventDefault();
e.stopPropagation();
const newIndex = Math.max(this.selectedIndex - 1, 0);
this.updateSelectedIndex(newIndex);
this.scrollToSelected();
} else if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
const selectedItem = this.items[this.selectedIndex];
if (selectedItem) {
this.selectItem(selectedItem);
}
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
this.close();
}
};

this.clickOutsideHandler = (e: MouseEvent) => {
if (
this.popover &&
!this.popover.contains(e.target as Node) &&
!(e.target as HTMLElement).closest(".node-tag-suggest-popover")
) {
this.close();
}
};

document.addEventListener("keydown", this.keydownHandler, true);
document.addEventListener("mousedown", this.clickOutsideHandler, true);
}

private removeEventHandlers() {
if (this.keydownHandler) {
document.removeEventListener("keydown", this.keydownHandler, true);
this.keydownHandler = null;
}
if (this.clickOutsideHandler) {
document.removeEventListener("mousedown", this.clickOutsideHandler, true);
this.clickOutsideHandler = null;
}
}

public open() {
if (this.popover) {
this.close();
}

const position = this.getCursorPosition();
if (!position) {
console.error("Could not get cursor position for popover");
return;
}

this.popover = this.createPopover();
document.body.appendChild(this.popover);

const popoverRect = this.popover.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;

let left = position.x;
let top = position.y + 4;

if (left + popoverRect.width > viewportWidth) {
left = viewportWidth - popoverRect.width - 10;
}
if (left < 10) {
left = 10;
}

if (top + popoverRect.height > viewportHeight) {
// Position above cursor instead
top = position.y - popoverRect.height - 4;
}
if (top < 10) {
top = 10;
}

this.popover.style.left = `${left}px`;
this.popover.style.top = `${top}px`;

this.setupEventHandlers();
}

public close() {
this.removeEventHandlers();
if (this.popover) {
this.popover.remove();
this.popover = null;
}
this.selectedIndex = 0;
}
}
1 change: 1 addition & 0 deletions apps/obsidian/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export const DEFAULT_SETTINGS: Settings = {
nodesFolderPath: "",
canvasFolderPath: "Discourse Canvas",
canvasAttachmentsFolderPath: "attachments",
nodeTagHotkey: "\\",
};
export const FRONTMATTER_KEY = "tldr-dg";
export const TLDATA_DELIMITER_START =
Expand Down
Loading