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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Adds **Previous / Next / See Also** navigation to your notes through standard fr
|---|---|
| **Inline navigation** | Previous / Next cards rendered at the bottom of each note (Reading & Source view) |
| **Floating side buttons** | Circular or full-height strip buttons inside the document area |
| **See Also list** | Related-note list rendered at the top or bottom of a note |
| **See Also list** | Related-link list rendered at the top or bottom of a note — vault notes and external URLs |
| **Auto backlink** | When you set Prev/Next, the plugin keeps the reciprocal link on the target note in sync |
| **New-note seeding** | Newly created empty notes get the three navigation properties automatically |
| **Edge / tap navigation** | Optional: double-click page margins or tap half the screen on mobile to navigate |
Expand Down
2 changes: 1 addition & 1 deletion README_zh.md → README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
|---|---|
| **内联导航** | 在每篇笔记底部渲染上一篇/下一篇卡片(阅读视图与源码视图均支持) |
| **浮动侧边按钮** | 在文档区域内显示圆形或全高条形的浮动按钮 |
| **相关阅读列表** | 在笔记顶部或底部渲染相关笔记列表 |
| **相关阅读列表** | 在笔记顶部或底部渲染相关链接列表 —— 支持库内笔记与外部网址 |
| **自动反向链接** | 设置上一篇/下一篇后,插件自动在目标笔记中维护反向链接 |
| **新笔记初始化** | 新建的空白笔记自动获得三个导航属性 |
| **边缘/点击导航** | 可选:双击页边距或在移动端点击屏幕半侧进行导航 |
Expand Down
150 changes: 136 additions & 14 deletions src/nav/link-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
import type { App, FrontMatterCache, TFile } from 'obsidian';

import type { ArticleNavigatorSettings } from '../settings';
import type { NavData, NavSnapshot } from '../types';
import type { NavData, NavSnapshot, SeeAlsoTarget } from '../types';

/** `[[Note]]`, `[[Note#Section]]`, `[[Note#Section|Alias]]`. */
const WIKILINK_RE = /^\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|([^\]]*))?\]\]$/;

/** `[Label](destination)` — the destination may be a URL or an in-vault path. */
const MARKDOWN_LINK_RE = /^\[([^\]]*)\]\(([\s\S]*)\)$/;

/** `[Label](url "title")` / `[Label](url 'title')` — captures the bare url. */
const LINK_DESTINATION_TITLE_RE = /^(\S+)\s+(?:"[^"]*"|'[^']*'|\([^)]*\))$/;

/**
* External destinations. Any `scheme://…` (http, obsidian, zotero, …), the
* authority-less schemes people actually write by hand, or a bare `www.` host.
* Requiring `//` keeps note names containing a colon from being mistaken for
* URLs.
*/
const URL_WITH_AUTHORITY_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
const BARE_SCHEME_RE = /^(?:mailto|tel|sms):/i;
const BARE_HOST_RE = /^www\./i;

/** Schemes that must never become a clickable href. */
const UNSAFE_SCHEME_RE = /^(?:javascript|data|vbscript|blob):/i;

interface ParsedEntry {
/** Link path (internal) or URL (external). */
target: string;
/** Explicit display text from an alias or link label, when given. */
display: string | null;
external: boolean;
}

/**
* Parse a frontmatter value into the link's path portion. Accepts plain strings,
Expand All @@ -18,11 +48,81 @@ export function extractLinkPath(value: unknown): string | null {
}
const trimmed = value.trim();
if (!trimmed) return null;
const m = trimmed.match(/^\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]$/);
const m = trimmed.match(WIKILINK_RE);
if (m && m[1]) return m[1].trim();
return trimmed;
}

export function isExternalLink(value: string): boolean {
return (
URL_WITH_AUTHORITY_RE.test(value) ||
BARE_SCHEME_RE.test(value) ||
BARE_HOST_RE.test(value) ||
UNSAFE_SCHEME_RE.test(value)
);
}

/** Strip `<…>` wrappers and CommonMark titles from a markdown link target. */
function extractLinkDestination(raw: string): string {
const dest = raw.trim();
if (dest.startsWith('<') && dest.endsWith('>')) {
return dest.slice(1, -1).trim();
}
const titled = dest.match(LINK_DESTINATION_TITLE_RE);
return titled && titled[1] ? titled[1] : dest;
}

/** Markdown link destinations are percent-encoded; vault paths are not. */
function decodeVaultPath(path: string): string {
try {
return decodeURIComponent(path);
} catch {
return path;
}
}

/**
* Parse one See Also entry. Supports `[[Wikilinks]]` (with alias),
* `[Label](url)` markdown links, bare URLs, and plain note names.
*/
function parseSeeAlsoEntry(value: unknown): ParsedEntry | null {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
if (!trimmed) return null;

const wiki = trimmed.match(WIKILINK_RE);
if (wiki && wiki[1]) {
const alias = wiki[2] ? wiki[2].trim() : '';
return {
target: wiki[1].trim(),
display: alias || null,
external: false,
};
}

const md = trimmed.match(MARKDOWN_LINK_RE);
if (md) {
const destination = extractLinkDestination(md[2] ?? '');
if (!destination) return null;
const label = (md[1] ?? '').trim();
const external = isExternalLink(destination);
return {
target: external ? destination : decodeVaultPath(destination),
display: label || null,
external,
};
}

return { target: trimmed, display: null, external: isExternalLink(trimmed) };
}

/** Reject unsafe schemes and give bare `www.` hosts a protocol. */
function toSafeUrl(target: string): string | null {
if (UNSAFE_SCHEME_RE.test(target)) return null;
if (BARE_HOST_RE.test(target)) return `https://${target}`;
return target;
}

export function getFrontmatter(
app: App,
file: TFile,
Expand All @@ -43,29 +143,51 @@ export function resolveLinkedFile(
return app.metadataCache.getFirstLinkpathDest(linkPath, currentFile.path);
}

export function resolveLinkedFiles(
/**
* Resolve the See Also list. Entries pointing outside the vault are kept as
* external URLs instead of being dropped, so a note can mix in-vault notes and
* web links in one list.
*/
export function resolveSeeAlsoTargets(
app: App,
currentFile: TFile,
key: string,
): TFile[] {
): SeeAlsoTarget[] {
const fm = getFrontmatter(app, currentFile);
if (!fm) return [];
const raw = fm[key] as unknown;
if (raw == null) return [];
const values: unknown[] = Array.isArray(raw) ? raw : [raw];

const result: TFile[] = [];
const result: SeeAlsoTarget[] = [];
const seen = new Set<string>();
for (const v of values) {
const linkPath = extractLinkPath(v);
if (!linkPath) continue;
const target = app.metadataCache.getFirstLinkpathDest(
linkPath,
for (const value of values) {
const entry = parseSeeAlsoEntry(value);
if (!entry) continue;

if (entry.external) {
const url = toSafeUrl(entry.target);
if (!url || seen.has(`url:${url}`)) continue;
seen.add(`url:${url}`);
result.push({
kind: 'external',
url,
display: entry.display ?? entry.target,
});
continue;
}

const file = app.metadataCache.getFirstLinkpathDest(
entry.target,
currentFile.path,
);
if (!target || seen.has(target.path)) continue;
seen.add(target.path);
result.push(target);
if (!file || seen.has(`file:${file.path}`)) continue;
seen.add(`file:${file.path}`);
result.push({
kind: 'internal',
file,
display: entry.display ?? file.basename,
});
}
return result;
}
Expand All @@ -78,7 +200,7 @@ export function getNavData(
return {
prevFile: resolveLinkedFile(app, file, settings.previousKey),
nextFile: resolveLinkedFile(app, file, settings.nextKey),
seeAlsoFiles: resolveLinkedFiles(app, file, settings.seeAlsoKey),
seeAlsoTargets: resolveSeeAlsoTargets(app, file, settings.seeAlsoKey),
};
}

Expand Down
10 changes: 9 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import type { TFile } from 'obsidian';

/**
* A resolved See Also entry. Entries either point at a note inside the vault
* or at an external URL; both carry the text to render for the link.
*/
export type SeeAlsoTarget =
| { kind: 'internal'; file: TFile; display: string }
| { kind: 'external'; url: string; display: string };

export interface NavData {
prevFile: TFile | null;
nextFile: TFile | null;
seeAlsoFiles: TFile[];
seeAlsoTargets: SeeAlsoTarget[];
}

export interface NavSnapshot {
Expand Down
69 changes: 51 additions & 18 deletions src/ui/inline-injections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { MarkdownView, TFile } from 'obsidian';

import { INJECTED_CLASS } from '../constants';
import type ArticleNavigatorPlugin from '../main';
import type { NavData } from '../types';
import type { NavData, SeeAlsoTarget } from '../types';

interface InjectionContainer {
el: HTMLElement;
Expand Down Expand Up @@ -48,17 +48,18 @@ export function injectInline(

const showInline = plugin.settings.inlineEnabled;
const showSeeAlso =
plugin.settings.seeAlsoPosition !== 'none' && data.seeAlsoFiles.length > 0;
plugin.settings.seeAlsoPosition !== 'none' &&
data.seeAlsoTargets.length > 0;
const seeAlsoAtTop = plugin.settings.seeAlsoPosition === 'top';

for (const { el: container } of containers) {
if (showSeeAlso && seeAlsoAtTop) {
const el = buildSeeAlsoElement(plugin, data.seeAlsoFiles);
const el = buildSeeAlsoElement(plugin, data.seeAlsoTargets);
el.classList.add('article-nav-seealso-top');
prependAfterPusher(container, el);
}
if (showSeeAlso && !seeAlsoAtTop) {
const el = buildSeeAlsoElement(plugin, data.seeAlsoFiles);
const el = buildSeeAlsoElement(plugin, data.seeAlsoTargets);
el.classList.add('article-nav-seealso-bottom');
appendBeforeBacklinks(container, el);
}
Expand Down Expand Up @@ -128,7 +129,7 @@ function buildInlineLink(

function buildSeeAlsoElement(
plugin: ArticleNavigatorPlugin,
files: TFile[],
targets: SeeAlsoTarget[],
): HTMLElement {
const root = document.createElement('div');
root.classList.add('article-nav-seealso', INJECTED_CLASS);
Expand All @@ -140,27 +141,59 @@ function buildSeeAlsoElement(

const list = document.createElement('ul');
list.classList.add('article-nav-seealso-list');
for (const f of files) {
for (const target of targets) {
const li = document.createElement('li');
const a = document.createElement('a');
a.classList.add('article-nav-seealso-link', 'internal-link');
a.setAttribute('href', '#');
a.setAttribute('data-href', f.path);
a.textContent = f.basename;
a.addEventListener('click', (e) => {
e.preventDefault();
plugin.openFile(f, e);
});
a.addEventListener('mouseover', (e) =>
triggerHoverPreview(plugin, e, f, a),
li.appendChild(
target.kind === 'external'
? buildSeeAlsoExternalLink(target.url, target.display)
: buildSeeAlsoInternalLink(plugin, target.file, target.display),
);
li.appendChild(a);
list.appendChild(li);
}
root.appendChild(list);
return root;
}

function buildSeeAlsoInternalLink(
plugin: ArticleNavigatorPlugin,
file: TFile,
display: string,
): HTMLAnchorElement {
const a = document.createElement('a');
a.classList.add('article-nav-seealso-link', 'internal-link');
a.setAttribute('href', '#');
a.setAttribute('data-href', file.path);
a.textContent = display;
a.addEventListener('click', (e) => {
e.preventDefault();
plugin.openFile(file, e);
});
a.addEventListener('mouseover', (e) =>
triggerHoverPreview(plugin, e, file, a),
);
return a;
}

/**
* Mirrors the markup Obsidian emits for external links in rendered markdown, so
* clicks are handed to the system browser on both desktop and mobile without
* any extra wiring.
*/
function buildSeeAlsoExternalLink(
url: string,
display: string,
): HTMLAnchorElement {
const a = document.createElement('a');
a.classList.add('article-nav-seealso-link', 'external-link');
a.setAttribute('href', url);
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener nofollow');
a.setAttribute('aria-label', url);
a.setAttribute('data-tooltip-position', 'top');
a.textContent = display;
return a;
}

function triggerHoverPreview(
plugin: ArticleNavigatorPlugin,
evt: MouseEvent,
Expand Down
2 changes: 1 addition & 1 deletion src/ui/view-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class ViewManager {
}
if (
this.plugin.settings.seeAlsoPosition !== 'none' &&
data.seeAlsoFiles.length > 0
data.seeAlsoTargets.length > 0
) {
count++;
}
Expand Down
8 changes: 8 additions & 0 deletions styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,14 @@
text-decoration: underline;
}

.article-nav-seealso-link.external-link {
color: var(--link-external-color, var(--link-color));
}

.article-nav-seealso-link.external-link:hover {
color: var(--link-external-color-hover, var(--link-color-hover));
}

/* ===== Confirm modal ===== */

.article-nav-confirm-message {
Expand Down
4 changes: 3 additions & 1 deletion test_vault/.obsidian/app.json
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
{}
{
"settingsPopoutWindow": false
}
4 changes: 2 additions & 2 deletions test_vault/.obsidian/plugins/article-navigator/manifest.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"id": "article-navigator",
"name": "Article Navigator",
"version": "1.0.0",
"version": "1.0.1",
"minAppVersion": "1.4.0",
"description": "Adds Previous / Next / SeeAlso navigation to notes via frontmatter properties. Supports floating buttons or VitePress-style inline navigation.",
"author": "IvanHanloth",
"authorUrl": "https://github.com/IvanHanloth",
"isDesktopOnly": false
}
}
Loading
Loading