Skip to content

Commit bfce221

Browse files
authored
feat: support line anchors in url (conwnet#326)
1 parent 5b5814d commit bfce221

5 files changed

Lines changed: 109 additions & 15 deletions

File tree

‎extensions/github1s/src/extension.ts‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { registerEventListeners } from '@/listeners';
1717
import { PageType } from './router/types';
1818

1919
export async function activate(context: vscode.ExtensionContext) {
20-
const browserUrl = (await await vscode.commands.executeCommand(
20+
const browserUrl = (await vscode.commands.executeCommand(
2121
'github1s.vscode.get-browser-url'
2222
)) as string;
2323

@@ -40,17 +40,37 @@ export async function activate(context: vscode.ExtensionContext) {
4040

4141
// sponsors in Status Bar
4242
showSponsors();
43-
await showGitpod();
43+
showGitpod();
4444

45-
// open corresponding editor if there is a filePath specified in browser url
46-
const { filePath, pageType } = await router.getState();
47-
if (filePath && [PageType.TREE, PageType.BLOB].includes(pageType)) {
45+
// initialize the VSCode's state
46+
initialVSCodeState();
47+
}
48+
49+
// initialize the VSCode's state according to the router url
50+
const initialVSCodeState = async () => {
51+
const routerState = await router.getState();
52+
const { filePath, pageType } = routerState;
53+
const scheme = GitHub1sFileSystemProvider.scheme;
54+
55+
if (filePath && pageType === PageType.TREE) {
4856
vscode.commands.executeCommand(
49-
pageType === PageType.TREE ? 'revealInExplorer' : 'vscode.open',
50-
vscode.Uri.parse('').with({
51-
scheme: GitHub1sFileSystemProvider.scheme,
52-
path: filePath,
53-
})
57+
'revealInExplorer',
58+
vscode.Uri.parse('').with({ scheme, path: filePath })
59+
);
60+
} else if (filePath && pageType === PageType.BLOB) {
61+
const { startLineNumber, endLineNumber } = routerState;
62+
const start = new vscode.Position(startLineNumber - 1, 0);
63+
const end = new vscode.Position(endLineNumber - 1, 999999);
64+
const documentShowOptions: vscode.TextDocumentShowOptions = startLineNumber
65+
? { selection: new vscode.Range(start, end) }
66+
: {};
67+
68+
// TODO: the selection of the opening file may be cleared
69+
// when editor try to restore previous state in the same file
70+
vscode.commands.executeCommand(
71+
'vscode.open',
72+
vscode.Uri.parse('').with({ scheme, path: filePath }),
73+
documentShowOptions
5474
);
5575
} else if (pageType === PageType.PULL_LIST) {
5676
vscode.commands.executeCommand('github1s.views.pull-request-list.focus');
@@ -59,4 +79,4 @@ export async function activate(context: vscode.ExtensionContext) {
5979
} else if ([PageType.PULL, PageType.COMMIT].includes(pageType)) {
6080
vscode.commands.executeCommand('workbench.scm.focus');
6181
}
62-
}
82+
};

‎extensions/github1s/src/helpers/func.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,17 @@ export const throttle = <T extends (...args: any[]) => any>(
4242
};
4343
};
4444

45+
export const debounce = <T extends (...args: any[]) => any>(
46+
func: T,
47+
wait: number
48+
) => {
49+
let timer = null;
50+
return function (...args: Parameters<T>): void {
51+
timer && clearTimeout(timer);
52+
timer = setTimeout(() => func.call(this, ...args), timer);
53+
};
54+
};
55+
4556
// debounce an async func. once an async func canceled, it throws a exception
4657
export const debounceAsyncFunc = <T extends (...args: any[]) => Promise<any>>(
4758
func: T,

‎extensions/github1s/src/listeners/vscode.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { PageType } from '@/router/types';
99
import { setVSCodeContext } from '@/helpers/vscode';
1010
import { getChangedFileFromSourceControl } from '@/commands/editor';
1111
import { GitHub1sFileSystemProvider } from '@/providers/fileSystemProvider';
12+
import { debounce } from '@/helpers/func';
1213

1314
const handleRouterOnActiveEditorChange = async (
1415
editor: vscode.TextEditor | undefined
@@ -33,12 +34,12 @@ const handleRouterOnActiveEditorChange = async (
3334
ref.toUpperCase() === 'HEAD'
3435
? `/${owner}/${repo}`
3536
: `/${owner}/${repo}/tree/${ref}`;
36-
router.history.replace(browserPath);
37+
router.history.replace({ pathname: browserPath, hash: '' });
3738
return;
3839
}
3940

4041
const browserPath = `/${owner}/${repo}/blob/${ref}${activeFileUri.path}`;
41-
router.history.replace(browserPath);
42+
router.history.replace({ pathname: browserPath, hash: '' });
4243
};
4344

4445
// if the `Open Changes` Button should show in editor title
@@ -60,10 +61,51 @@ const handleGutterBlameOpeningContextOnActiveEditorChange = async () => {
6061
return setVSCodeContext('github1s.context.gutterBlameOpening', false);
6162
};
6263

64+
// get the line anchor hash (`#L27-L39`) from the editor.selection
65+
const getAnchorHashFromSelection = (selection: vscode.Selection) => {
66+
const { start, end } = selection;
67+
68+
// the cursor move to somewhere but nothing is selected
69+
if (start.line === end.line && start.character === end.character) {
70+
return '';
71+
}
72+
if (start.line === end.line) {
73+
return `#L${start.line + 1}`;
74+
}
75+
return `#L${start.line + 1}-L${end.line + 1}`;
76+
};
77+
78+
// add the line number anchor when user selection lines in a editor
79+
const handleRouterOnTextEditorSelectionChange = async (
80+
editor: vscode.TextEditor
81+
) => {
82+
const { owner, repo, ref, pageType } = await router.getState();
83+
84+
// only add the line number anchor when pageType is PageType.BLOB
85+
if (pageType !== PageType.BLOB || !editor.selection) {
86+
return;
87+
}
88+
89+
const activeFileUri = editor?.document.uri;
90+
const anchorText = getAnchorHashFromSelection(editor.selection);
91+
const browserPath = `/${owner}/${repo}/blob/${ref}${activeFileUri.path}`;
92+
93+
router.history.replace({ pathname: browserPath, hash: anchorText });
94+
};
95+
6396
export const registerVSCodeEventListeners = () => {
64-
vscode.window.onDidChangeActiveTextEditor(async (editor) => {
97+
vscode.window.onDidChangeActiveTextEditor((editor) => {
6598
handleRouterOnActiveEditorChange(editor);
6699
handleOpenChangesContextOnActiveEditorChange(editor);
67100
handleGutterBlameOpeningContextOnActiveEditorChange();
68101
});
102+
103+
// debounce to update the browser url
104+
const debouncedSelectionChangeRouterHandler = debounce(
105+
handleRouterOnTextEditorSelectionChange,
106+
100
107+
);
108+
vscode.window.onDidChangeTextEditorSelection((event) => {
109+
debouncedSelectionChangeRouterHandler(event.textEditor);
110+
});
69111
};

‎extensions/github1s/src/router/parser/blob.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,27 @@
33
* @author netcon
44
*/
55

6+
import { parsePath } from 'history';
67
import { PageType, RouterState } from '../types';
78
import { parseTreeUrl } from './tree';
89

910
export const parseBlobUrl = async (path: string): Promise<RouterState> => {
1011
const routerState = await parseTreeUrl(path);
12+
const { hash: routerHash } = parsePath(path);
1113

12-
return { ...routerState, pageType: PageType.BLOB };
14+
if (!routerHash) {
15+
return { ...routerState, pageType: PageType.BLOB };
16+
}
17+
18+
// get selected line number range from path which looks like:
19+
// `/conwnet/github1s/blob/HEAD/package.json#L10-L20`
20+
const matches = routerHash.match(/^#L(\d+)(?:-L(\d+))?/);
21+
const [_, startLineNumber = '0', endLineNumber] = matches ? matches : [];
22+
23+
return {
24+
...routerState,
25+
pageType: PageType.BLOB,
26+
startLineNumber: parseInt(startLineNumber, 10),
27+
endLineNumber: parseInt(endLineNumber || startLineNumber, 10),
28+
};
1329
};

‎extensions/github1s/src/router/types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ export interface RouterState {
5252
// current file path
5353
filePath?: string;
5454

55+
// the one-based line numbers specified which lines should focus
56+
// after opening the file, only exists when pageType is `BLOB`
57+
startLineNumber?: number;
58+
endLineNumber?: number;
59+
5560
// only exists when the page type is PULL
5661
pullNumber?: number;
5762

0 commit comments

Comments
 (0)