add open book command to open any book from local sys (#8632)

* add open book command to open any book from local sys

* no-floating promises

* moved all the loc strings to common loc file

* typos
This commit is contained in:
Maddy
2019-12-18 09:08:52 -08:00
committed by GitHub
parent 30d9e9c141
commit a67e3abb4c
7 changed files with 88 additions and 39 deletions

View File

@@ -171,6 +171,15 @@
"dark": "resources/dark/search_inverse.svg", "dark": "resources/dark/search_inverse.svg",
"light": "resources/light/search.svg" "light": "resources/light/search.svg"
} }
},
{
"command": "notebook.command.openBook",
"title": "%title.openJupyterBook%",
"category": "%books-preview-category%",
"icon": {
"dark": "resources/dark/open_notebook_inverse.svg",
"light": "resources/light/open_notebook.svg"
}
} }
], ],
"languages": [ "languages": [
@@ -312,6 +321,13 @@
"group": "inline" "group": "inline"
} }
], ],
"view/title": [
{
"command": "notebook.command.openBook",
"when": "view == bookTreeView",
"group": "navigation"
}
],
"notebook/toolbar": [ "notebook/toolbar": [
{ {
"command": "jupyter.cmd.managePackages", "command": "jupyter.cmd.managePackages",

View File

@@ -33,5 +33,6 @@
"title.searchJupyterBook": "Search Book", "title.searchJupyterBook": "Search Book",
"title.SavedBooks": "Saved Books", "title.SavedBooks": "Saved Books",
"title.UnsavedBooks": "Unsaved Books", "title.UnsavedBooks": "Unsaved Books",
"title.PreviewLocalizedBook": "Get localized SQL Server 2019 guide" "title.PreviewLocalizedBook": "Get localized SQL Server 2019 guide",
"title.openJupyterBook": "Open Jupyter Book"
} }

View File

@@ -12,11 +12,11 @@ import { maxBookSearchDepth, notebookConfigKey } from '../common/constants';
import * as path from 'path'; import * as path from 'path';
import * as fileServices from 'fs'; import * as fileServices from 'fs';
import * as fs from 'fs-extra'; import * as fs from 'fs-extra';
import * as nls from 'vscode-nls'; import * as loc from '../common/localizedConstants';
import { IJupyterBookToc, IJupyterBookSection } from '../contracts/content'; import { IJupyterBookToc, IJupyterBookSection } from '../contracts/content';
import { isNullOrUndefined } from 'util'; import { isNullOrUndefined } from 'util';
const localize = nls.loadMessageBundle();
const fsPromises = fileServices.promises; const fsPromises = fileServices.promises;
export class BookModel implements azdata.nb.NavigationProvider { export class BookModel implements azdata.nb.NavigationProvider {
@@ -54,9 +54,13 @@ export class BookModel implements azdata.nb.NavigationProvider {
let p = path.join(workspacePath, '**', '_data', 'toc.yml').replace(/\\/g, '/'); let p = path.join(workspacePath, '**', '_data', 'toc.yml').replace(/\\/g, '/');
let tableOfContentPaths = await glob(p, { deep: maxDepth }); let tableOfContentPaths = await glob(p, { deep: maxDepth });
this._tableOfContentPaths = this._tableOfContentPaths.concat(tableOfContentPaths); if (tableOfContentPaths.length > 0) {
let bookOpened: boolean = this._tableOfContentPaths.length > 0; this._tableOfContentPaths = this._tableOfContentPaths.concat(tableOfContentPaths);
vscode.commands.executeCommand('setContext', 'bookOpened', bookOpened); vscode.commands.executeCommand('setContext', 'bookOpened', true);
} else {
vscode.window.showErrorMessage(loc.errBookInitialize);
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }
@@ -168,7 +172,7 @@ export class BookModel implements azdata.nb.NavigationProvider {
); );
notebooks.push(markdown); notebooks.push(markdown);
} else { } else {
let error = localize('missingFileError', "Missing file : {0}", sections[i].title); let error = loc.missingFileError(sections[i].title);
vscode.window.showErrorMessage(error); vscode.window.showErrorMessage(error);
} }
} }
@@ -187,9 +191,9 @@ export class BookModel implements azdata.nb.NavigationProvider {
try { try {
return section.reduce((acc, val) => Array.isArray(val.sections) ? acc.concat(val).concat(this.parseJupyterSections(val.sections)) : acc.concat(val), []); return section.reduce((acc, val) => Array.isArray(val.sections) ? acc.concat(val).concat(this.parseJupyterSections(val.sections)) : acc.concat(val), []);
} catch (error) { } catch (error) {
let err: string = localize('InvalidError.tocFile', "{0}", error); let err: string = loc.invalidTocFileError(error);
if (section.length > 0) { if (section.length > 0) {
err = localize('Invalid toc.yml', "Error: {0} has an incorrect toc.yml file", section[0].title); //need to find a way to get title. err = loc.invalidTocError(section[0].title);
} }
vscode.window.showErrorMessage(err); vscode.window.showErrorMessage(err);
throw err; throw err;

View File

@@ -6,9 +6,8 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import * as nls from 'vscode-nls';
import { IJupyterBookSection, IJupyterBookToc } from '../contracts/content'; import { IJupyterBookSection, IJupyterBookToc } from '../contracts/content';
const localize = nls.loadMessageBundle(); import * as loc from '../common/localizedConstants';
export enum BookTreeItemType { export enum BookTreeItemType {
Book = 'Book', Book = 'Book',
@@ -69,12 +68,12 @@ export class BookTreeItem extends vscode.TreeItem {
private setCommand() { private setCommand() {
if (this.book.type === BookTreeItemType.Notebook) { if (this.book.type === BookTreeItemType.Notebook) {
let pathToNotebook = path.join(this.book.root, 'content', this._uri.concat('.ipynb')); let pathToNotebook = path.join(this.book.root, 'content', this._uri.concat('.ipynb'));
this.command = { command: this.book.isUntitled ? 'bookTreeView.openUntitledNotebook' : 'bookTreeView.openNotebook', title: localize('openNotebookCommand', "Open Notebook"), arguments: [pathToNotebook], }; this.command = { command: this.book.isUntitled ? 'bookTreeView.openUntitledNotebook' : 'bookTreeView.openNotebook', title: loc.openNotebookCommand, arguments: [pathToNotebook], };
} else if (this.book.type === BookTreeItemType.Markdown) { } else if (this.book.type === BookTreeItemType.Markdown) {
let pathToMarkdown = path.join(this.book.root, 'content', this._uri.concat('.md')); let pathToMarkdown = path.join(this.book.root, 'content', this._uri.concat('.md'));
this.command = { command: 'bookTreeView.openMarkdown', title: localize('openMarkdownCommand', "Open Markdown"), arguments: [pathToMarkdown], }; this.command = { command: 'bookTreeView.openMarkdown', title: loc.openMarkdownCommand, arguments: [pathToMarkdown], };
} else if (this.book.type === BookTreeItemType.ExternalLink) { } else if (this.book.type === BookTreeItemType.ExternalLink) {
this.command = { command: 'bookTreeView.openExternalLink', title: localize('openExternalLinkCommand', "Open External Link"), arguments: [this._uri], }; this.command = { command: 'bookTreeView.openExternalLink', title: loc.openExternalLinkCommand, arguments: [this._uri], };
} }
} }

View File

@@ -10,12 +10,10 @@ import * as fs from 'fs-extra';
import { IPrompter, QuestionTypes, IQuestion } from '../prompts/question'; import { IPrompter, QuestionTypes, IQuestion } from '../prompts/question';
import CodeAdapter from '../prompts/adapter'; import CodeAdapter from '../prompts/adapter';
import { BookTreeItem } from './bookTreeItem'; import { BookTreeItem } from './bookTreeItem';
import * as nls from 'vscode-nls';
import { isEditorTitleFree } from '../common/utils'; import { isEditorTitleFree } from '../common/utils';
import { BookModel } from './bookModel'; import { BookModel } from './bookModel';
import { Deferred } from '../common/promise'; import { Deferred } from '../common/promise';
import * as loc from '../common/localizedConstants';
const localize = nls.loadMessageBundle();
export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeItem> { export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeItem> {
@@ -39,7 +37,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
this._openAsUntitled = openAsUntitled; this._openAsUntitled = openAsUntitled;
this._extensionContext = extensionContext; this._extensionContext = extensionContext;
this.books = []; this.books = [];
this.initialize(workspaceFolders.map(a => a.uri.fsPath)); this.initialize(workspaceFolders.map(a => a.uri.fsPath)).catch(e => console.error(e));
this.viewId = view; this.viewId = view;
this.prompter = new CodeAdapter(); this.prompter = new CodeAdapter();
@@ -72,19 +70,17 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
// Check if the book is already open in viewlet. // Check if the book is already open in viewlet.
if (books.length > 0 && books[0].bookItems) { if (books.length > 0 && books[0].bookItems) {
this.currentBook = books[0]; this.currentBook = books[0];
this.showPreviewFile(urlToOpen); await this.showPreviewFile(urlToOpen);
} }
else { else {
await this.initialize([bookPath]); await this.initialize([bookPath]);
let bookViewer = vscode.window.createTreeView(this.viewId, { showCollapseAll: true, treeDataProvider: this }); let bookViewer = vscode.window.createTreeView(this.viewId, { showCollapseAll: true, treeDataProvider: this });
this.currentBook = this.books.filter(book => book.bookPath === bookPath)[0]; this.currentBook = this.books.filter(book => book.bookPath === bookPath)[0];
bookViewer.reveal(this.currentBook.bookItems[0], { expand: vscode.TreeItemCollapsibleState.Expanded, focus: true, select: true }); bookViewer.reveal(this.currentBook.bookItems[0], { expand: vscode.TreeItemCollapsibleState.Expanded, focus: true, select: true });
this.showPreviewFile(urlToOpen); await this.showPreviewFile(urlToOpen);
} }
} catch (e) { } catch (e) {
vscode.window.showErrorMessage(localize('openBookError', "Open book {0} failed: {1}", vscode.window.showErrorMessage(loc.openFileError(bookPath, e instanceof Error ? e.message : e));
bookPath,
e instanceof Error ? e.message : e));
} }
} }
@@ -99,7 +95,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
this.openMarkdown(sectionToOpenMarkdown); this.openMarkdown(sectionToOpenMarkdown);
} }
else if (await fs.pathExists(sectionToOpenNotebook)) { else if (await fs.pathExists(sectionToOpenNotebook)) {
this.openNotebook(sectionToOpenNotebook); await this.openNotebook(sectionToOpenNotebook);
} }
} }
} }
@@ -114,9 +110,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
vscode.window.showTextDocument(doc); vscode.window.showTextDocument(doc);
} }
} catch (e) { } catch (e) {
vscode.window.showErrorMessage(localize('openNotebookError', "Open notebook {0} failed: {1}", vscode.window.showErrorMessage(loc.openNotebookError(resource, e instanceof Error ? e.message : e));
resource,
e instanceof Error ? e.message : e));
} }
} }
@@ -125,9 +119,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
try { try {
vscode.commands.executeCommand('markdown.showPreview', vscode.Uri.file(resource)); vscode.commands.executeCommand('markdown.showPreview', vscode.Uri.file(resource));
} catch (e) { } catch (e) {
vscode.window.showErrorMessage(localize('openMarkdownError', "Open markdown {0} failed: {1}", vscode.window.showErrorMessage(loc.openMarkdownError(resource, e instanceof Error ? e.message : e));
resource,
e instanceof Error ? e.message : e));
} }
}); });
} }
@@ -144,15 +136,13 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
}); });
}); });
} catch (e) { } catch (e) {
vscode.window.showErrorMessage(localize('openUntitledNotebookError', "Open untitled notebook {0} as untitled failed: {1}", vscode.window.showErrorMessage(loc.openUntitledNotebookError(resource, e instanceof Error ? e.message : e));
resource,
e instanceof Error ? e.message : e));
} }
} }
async saveJupyterBooks(): Promise<void> { async saveJupyterBooks(): Promise<void> {
if (this.currentBook.bookPath) { if (this.currentBook.bookPath) {
const allFilesFilter = localize('allFiles', "All Files"); const allFilesFilter = loc.allFiles;
let filter: any = {}; let filter: any = {};
filter[allFilesFilter] = '*'; filter[allFilesFilter] = '*';
let uris = await vscode.window.showOpenDialog({ let uris = await vscode.window.showOpenDialog({
@@ -160,7 +150,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
canSelectFiles: false, canSelectFiles: false,
canSelectMany: false, canSelectMany: false,
canSelectFolders: true, canSelectFolders: true,
openLabel: localize('labelPickFolder', "Pick Folder") openLabel: loc.labelPickFolder
}); });
if (uris && uris.length > 0) { if (uris && uris.length > 0) {
let pickedFolder = uris[0]; let pickedFolder = uris[0];
@@ -200,6 +190,23 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
} }
} }
public async openNewBook(): Promise<void> {
const allFilesFilter = loc.allFiles;
let filter: any = {};
filter[allFilesFilter] = '*';
let uris = await vscode.window.showOpenDialog({
filters: filter,
canSelectFiles: false,
canSelectMany: false,
canSelectFolders: true,
openLabel: loc.labelBookFolder
});
if (uris && uris.length > 0) {
let bookPath = uris[0];
await this.openBook(bookPath.fsPath);
}
}
private runThrottledAction(resource: string, action: () => void) { private runThrottledAction(resource: string, action: () => void) {
const isResourceChange = resource !== this._resource; const isResourceChange = resource !== this._resource;
if (isResourceChange) { if (isResourceChange) {
@@ -230,9 +237,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
try { try {
vscode.env.openExternal(vscode.Uri.parse(resource)); vscode.env.openExternal(vscode.Uri.parse(resource));
} catch (e) { } catch (e) {
vscode.window.showErrorMessage(localize('openExternalLinkError', "Open link {0} failed: {1}", vscode.window.showErrorMessage(loc.openExternalLinkError(resource, e instanceof Error ? e.message : e));
resource,
e instanceof Error ? e.message : e));
} }
} }
@@ -316,7 +321,7 @@ export class BookTreeViewProvider implements vscode.TreeDataProvider<BookTreeIte
private async confirmReplace(): Promise<boolean> { private async confirmReplace(): Promise<boolean> {
return await this.prompter.promptSingle<boolean>(<IQuestion>{ return await this.prompter.promptSingle<boolean>(<IQuestion>{
type: QuestionTypes.confirm, type: QuestionTypes.confirm,
message: localize('confirmReplace', "Folder already exists. Are you sure you want to delete and replace this folder?"), message: loc.confirmReplace,
default: false default: false
}); });
} }

View File

@@ -14,3 +14,26 @@ export const msgNo = localize('msgNo', "No");
// Jupyter Constants /////////////////////////////////////////////////////// // Jupyter Constants ///////////////////////////////////////////////////////
export const msgSampleCodeDataFrame = localize('msgSampleCodeDataFrame', "This sample code loads the file into a data frame and shows the first 10 results."); export const msgSampleCodeDataFrame = localize('msgSampleCodeDataFrame', "This sample code loads the file into a data frame and shows the first 10 results.");
// Book view-let constants
export const allFiles = localize('allFiles', "All Files");
export const labelPickFolder = localize('labelPickFolder', "Pick Folder");
export const labelBookFolder = localize('labelBookFolder', "Select Book");
export const confirmReplace = localize('confirmReplace', "Folder already exists. Are you sure you want to delete and replace this folder?");
export const openNotebookCommand = localize('openNotebookCommand', "Open Notebook");
export const openMarkdownCommand = localize('openMarkdownCommand', "Open Markdown");
export const openExternalLinkCommand = localize('openExternalLinkCommand', "Open External Link");
export const errBookInitialize = localize('bookInitializeFailed', "Book initialize failed: Failed to recognize the structure.");
export function missingFileError(title: string): string { return localize('missingFileError', "Missing file : {0}", title); }
export function invalidTocFileError(error: string): string { return localize('InvalidError.tocFile', "{0}", error); }
export function invalidTocError(title: string): string { return localize('Invalid toc.yml', "Error: {0} has an incorrect toc.yml file", title); }
export function openFileError(path: string, error: string): string { return localize('openBookError', "Open book {0} failed: {1}", path, error); }
export function openNotebookError(resource: string, error: string): string { return localize('openNotebookError', "Open notebook {0} failed: {1}", resource, error); }
export function openMarkdownError(resource: string, error: string): string { return localize('openMarkdownError', "Open markdown {0} failed: {1}", resource, error); }
export function openUntitledNotebookError(resource: string, error: string): string { return localize('openUntitledNotebookError', "Open untitled notebook {0} as untitled failed: {1}", resource, error); }
export function openExternalLinkError(resource: string, error: string): string { return localize('openExternalLinkError', "Open link {0} failed: {1}", resource, error); }

View File

@@ -36,6 +36,7 @@ export async function activate(extensionContext: vscode.ExtensionContext): Promi
extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.saveBook', () => untitledBookTreeViewProvider.saveJupyterBooks())); extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.saveBook', () => untitledBookTreeViewProvider.saveJupyterBooks()));
extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.searchBook', () => bookTreeViewProvider.searchJupyterBooks())); extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.searchBook', () => bookTreeViewProvider.searchJupyterBooks()));
extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.searchUntitledBook', () => untitledBookTreeViewProvider.searchJupyterBooks())); extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.searchUntitledBook', () => untitledBookTreeViewProvider.searchJupyterBooks()));
extensionContext.subscriptions.push(vscode.commands.registerCommand('notebook.command.openBook', () => bookTreeViewProvider.openNewBook()));
extensionContext.subscriptions.push(vscode.commands.registerCommand('_notebook.command.new', (context?: azdata.ConnectedContext) => { extensionContext.subscriptions.push(vscode.commands.registerCommand('_notebook.command.new', (context?: azdata.ConnectedContext) => {
let connectionProfile: azdata.IConnectionProfile = undefined; let connectionProfile: azdata.IConnectionProfile = undefined;