Skip to content

Commit 8270cc0

Browse files
committed
add method to resolve link
1 parent c503f34 commit 8270cc0

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

jsEngine/api/API.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import type { JsFunc } from 'jsEngine/engine/JsExecution';
1010
import type JsEnginePlugin from 'jsEngine/main';
1111
import type { Validators } from 'jsEngine/utils/Validators';
1212
import { validateAPIArgs } from 'jsEngine/utils/Validators';
13-
import type { App, Plugin } from 'obsidian';
13+
import type {App, Plugin, TFile} from 'obsidian';
14+
import { getLinkpath } from 'obsidian';
1415
import * as Obsidian from 'obsidian';
1516
import { z } from 'zod';
1617

@@ -122,4 +123,21 @@ export class API {
122123

123124
return new ReactiveComponent(this, fn, initialArgs);
124125
}
126+
127+
/**
128+
* Gets the target file of a link.
129+
* The link must be a valid wiki link with or without the brackets, so `[[file|foo]]` or `file|foo`.
130+
* If the link is not found, this will return undefined.
131+
*
132+
* @param link the link to get the target file of.
133+
* @param sourcePath the path of the file that contains the link. This is needed to resolve relative links.
134+
*/
135+
public getLinkTarget(link: string, sourcePath: string): TFile | undefined {
136+
validateAPIArgs(z.object({ link: z.string() }), { link });
137+
138+
const linkText = link.startsWith('[[') && link.endsWith(']]') ? link.slice(2, -2) : link;
139+
const linkTarget = getLinkpath(linkText);
140+
141+
return this.app.metadataCache.getFirstLinkpathDest(linkTarget, sourcePath) ?? undefined;
142+
}
125143
}

0 commit comments

Comments
 (0)