Skip to content

Commit

Permalink
Refine naked embed handling
Browse files Browse the repository at this point in the history
  • Loading branch information
mgmeyers committed Dec 31, 2021
1 parent c8b9b8b commit b6a8887
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 12 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-contextual-typography",
"name": "Contextual Typography",
"version": "2.2.3",
"version": "2.2.4",
"minAppVersion": "0.9.22",
"description": "This plugin adds a data-tag-name attribute to all top-level divs in preview mode containing the child's tag name, allowing contextual typography styling.",
"author": "mgmeyers",
Expand Down
55 changes: 44 additions & 11 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,57 @@ function fixMarkdownLinkEmbeds(node: HTMLElement) {
return;
}

let embedChildren: HTMLElement[] = [];

for (let i = 0, len = node.children.length; i < len; i++) {
const child = node.children.item(i);
let containsNakedEmbed = false;
let childNodes: ChildNode[] = [];

node.childNodes.forEach((n) => {
if (n.nodeValue === "\n") return;

switch (n.nodeName) {
case "P": {
if ((n as HTMLElement).children.length === 0) {
return;
} else {
n.childNodes.forEach((pn) => {
if (pn.nodeName !== "BR" && pn.nodeValue !== "\n")
childNodes.push(pn);
});
return;
}
}
case "BR": {
return;
}
}

if (child.classList?.contains("internal-embed")) {
embedChildren.push(child as HTMLElement);
if (
n.nodeType === 1 &&
(n as HTMLElement).classList?.contains("internal-embed")
) {
containsNakedEmbed = true;
}
}

if (!embedChildren.length) return;
childNodes.push(n);
});

node.empty();
if (!containsNakedEmbed) return;

node.empty();
node.createEl("p", {}, (p) => {
embedChildren.forEach((c, i) => {
childNodes.forEach((c, i, arr) => {
p.append(c);
if (i < embedChildren.length - 1) {

const nodeIsEmbed =
c.nodeType === 1 &&
!!(c as HTMLElement).getAttribute("src") &&
i < arr.length - 1;

const nodeIsTextFollowedByEmbed =
c.nodeType === 3 &&
arr[i + 1]?.nodeType === 1 &&
!!(arr[i + 1] as HTMLElement).getAttribute("src");

if (nodeIsEmbed || nodeIsTextFollowedByEmbed) {
p.createEl("br");
}
});
Expand Down

0 comments on commit b6a8887

Please sign in to comment.