|
1 | | -import { Uri, workspace } from 'vscode'; |
| 1 | +import { NotebookCell, NotebookDocument, Uri, workspace } from 'vscode'; |
2 | 2 | import { isWindows } from '../../managers/common/utils'; |
3 | 3 |
|
4 | 4 | export function checkUri(scope?: Uri | Uri[] | string): Uri | Uri[] | string | undefined { |
| 5 | + if (!scope) { |
| 6 | + return undefined; |
| 7 | + } |
| 8 | + |
| 9 | + if (Array.isArray(scope)) { |
| 10 | + return scope.map((item) => checkUri(item) as Uri); |
| 11 | + } |
| 12 | + |
5 | 13 | if (scope instanceof Uri) { |
6 | 14 | if (scope.scheme === 'vscode-notebook-cell') { |
7 | | - workspace.notebookDocuments.find((doc) => { |
8 | | - if (doc.uri.toString() === scope.toString()) { |
9 | | - return doc; |
10 | | - } |
| 15 | + // If the scope is a cell Uri, we need to find the notebook document it belongs to. |
| 16 | + const matchingDoc = workspace.notebookDocuments.find((doc) => { |
| 17 | + const cell = findCell(scope, doc); |
| 18 | + return cell !== undefined; |
11 | 19 | }); |
12 | | - return scope; |
| 20 | + // If we find a matching notebook document, return the Uri of the cell. |
| 21 | + return matchingDoc ? matchingDoc.uri : scope; |
13 | 22 | } |
14 | 23 | } |
15 | | - if (Array.isArray(scope)) { |
16 | | - return scope.map((item) => { |
17 | | - return checkUri(item) as Uri; |
18 | | - }); |
19 | | - } |
20 | 24 | return scope; |
21 | 25 | } |
22 | 26 |
|
| 27 | +/** |
| 28 | + * Find a notebook document by cell Uri. |
| 29 | + */ |
| 30 | +export function findCell(cellUri: Uri, notebook: NotebookDocument): NotebookCell | undefined { |
| 31 | + // Fragment is not unique to a notebook, hence ensure we compare the path as well. |
| 32 | + const index = notebook |
| 33 | + .getCells() |
| 34 | + .findIndex( |
| 35 | + (cell) => |
| 36 | + isEqual(cell.document.uri, cellUri) || |
| 37 | + (cell.document.uri.fragment === cellUri.fragment && cell.document.uri.path === cellUri.path), |
| 38 | + ); |
| 39 | + if (index !== -1) { |
| 40 | + return notebook.getCells()[index]; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +function isEqual(a: Uri, b: Uri): boolean { |
| 45 | + return a.toString() === b.toString(); |
| 46 | +} |
| 47 | + |
23 | 48 | export function normalizePath(path: string): string { |
24 | 49 | const path1 = path.replace(/\\/g, '/'); |
25 | 50 | if (isWindows()) { |
|
0 commit comments