Skip to content

Commit

Permalink
feat(vscodePlugin): open web link and open file link (#922)
Browse files Browse the repository at this point in the history
* feat(vscodePlugin): open web  link and open file link

* feat: open of local files

* chore: remove `console.log`
  • Loading branch information
RSS1102 authored Oct 11, 2024
1 parent 91778f3 commit 796b087
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
26 changes: 26 additions & 0 deletions vscodePlugin/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,32 @@ const initCherryPanelEvent = () => {
}
});
break;
case 'open-url': {
if (data === 'href-invalid') {
vscode.window.showErrorMessage('link is not valid, please check it.');
return;
}
// http/https协议的链接,直接打开
if (/^(http|https):\/\//.test(data)) {
vscode.env.openExternal(vscode.Uri.parse(data));
return;
}
// 本地绝对路径,打开文件(绝对路径需要解码)
const decodedData = decodeURIComponent(data);
if (path.isAbsolute(decodedData)) {
const decodedDataPath = vscode.Uri.file(decodedData);
vscode.commands.executeCommand('vscode.open', decodedDataPath, { preview: true });
return;
}
// 以#开头的锚点不处理
if (data.startsWith('#')) {
return;
}
// 本地相对路径,打开文件
const uri = vscode.Uri.file(path.join(targetDocument.document.uri.fsPath, '..', data));
vscode.commands.executeCommand('vscode.open', uri, { preview: true });
break;
}
}
});
cherryPanel?.onDidDispose(() => {
Expand Down
29 changes: 29 additions & 0 deletions vscodePlugin/web-resources/scripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,22 @@ function changeTheme(theme) {
)} theme__${theme}`;
}

/** 处理 a 链接跳转问题 */
const onClickLink = (target) => {
// 这里不能直接使用 target.href,因为本地相对文件地址会被vscode转成`webview://`协议
const href = target.attributes?.href.value;
if (!href) {
vscode.postMessage({
type: 'open-url',
data: 'href-invalid',
});
};
vscode.postMessage({
type: 'open-url',
data: href,
});
};

const basicConfig = {
id: 'markdown',
externals: {
Expand Down Expand Up @@ -307,6 +323,19 @@ const basicConfig = {
src: path.join(basePath, srcValue),
};
},
onClickPreview: (e) => {
const { target } = e;
switch (target?.nodeName) {
case 'SPAN':
if (target?.parentElement?.nodeName === 'A') {
onClickLink(target?.parentElement);
}
break;
case 'A':
onClickLink(target);
break;
};
},
},
};

Expand Down

0 comments on commit 796b087

Please sign in to comment.