Skip to content

Commit

Permalink
feat: adds open in browser
Browse files Browse the repository at this point in the history
  • Loading branch information
Ken Howard committed Dec 13, 2018
1 parent ae0ac6f commit d3666e8
Show file tree
Hide file tree
Showing 10 changed files with 157 additions and 9 deletions.
1 change: 1 addition & 0 deletions __mocks__/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module.exports = {
StatusBarAlignment: {
Left: true
},
Uri: { parse: jest.fn((url: string) => url) },
commands: {
executeCommand: jest.fn()
},
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
"category": "GIST"
},
{
"command": "extension.openCodeBlockInBrowser",
"title": "Open Block In Browser",
"command": "extension.gist.openInBrowser",
"title": "Open Gist In Browser",
"category": "GIST"
},
{
Expand Down
1 change: 1 addition & 0 deletions src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const commandInitializers: CommandInitializer[] = [
gists.create,
gists.open,
gists.openFavorite,
gists.openInBrowser,
gists.updateAccessKey,
profiles.create,
profiles.select,
Expand Down
1 change: 1 addition & 0 deletions src/commands/extension-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ enum GistCommands {
Create = 'extension.gist.create',
Open = 'extension.gist.open',
OpenFavorite = 'extension.gist.openFavorite',
OpenInBrowser = 'extension.gist.openInBrowser',
UpdateAccessKey = 'extension.gist.updateAccessKey'
}

Expand Down
97 changes: 97 additions & 0 deletions src/commands/gists/__tests__/open-in-browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// tslint:disable:no-any no-magic-numbers
import { commands, window } from 'vscode';

import { TMP_DIRECTORY_PREFIX } from '../../../constants';
import { openInBrowser } from '../open-in-browser';

jest.mock('fs');
jest.mock('path');

const getGistsMock = jest.fn(() => [
{
createdAt: new Date(),
description: 'some markdown file',
fileCount: 1,
files: { 'file-one.md': { content: 'test' } },
id: '123',
name: 'gist one',
public: true,
updatedAt: new Date(),
url: 'gist-one-url'
},
{
createdAt: new Date(),
description: 'some markdown file',
fileCount: 1,
files: { 'file-two.md': { content: 'test' } },
id: '123',
name: 'gist two',
public: true,
updatedAt: new Date(),
url: 'gist-two-url'
}
]);
const getGistMock = jest.fn((id: string) => ({
createdAt: new Date(),
description: 'some markdown file',
fileCount: 1,
files: { 'file-one.md': { content: 'test' } },
id,
name: 'test',
public: true,
updatedAt: new Date(),
url: 'test-url'
}));
const utilsMock = jest.genMockFromModule<Utils>('../../../utils');
const errorMock = jest.fn();

const executeCommandSpy = jest.spyOn(commands, 'executeCommand');

describe('open favorite gist', () => {
let openInBrowserFn: CommandFn;
beforeEach(() => {
const gists = { getGists: getGistsMock, getGist: getGistMock };
const insights = { exception: jest.fn() };
const logger = { error: errorMock, info: jest.fn() };
openInBrowserFn = openInBrowser(
{ gists, insights, logger } as any,
utilsMock as any
)[1];
(<any>window).activeTextEditor = undefined;
});
afterEach(() => {
jest.clearAllMocks();
});
test('that a notification is shown when no open documents', async () => {
expect.assertions(1);

const infoSpy = jest.spyOn(utilsMock.notify, 'info');

await openInBrowserFn();
expect(infoSpy.mock.calls.length).toBe(1);
});
test('it opens a browser', async () => {
expect.assertions(2);

(<any>utilsMock.files.extractTextDocumentDetails).mockImplementation(
() => ({ id: '123456789abcdefg', url: 'test-url' })
);

const codeBlock = {
fileName: `${TMP_DIRECTORY_PREFIX}_123456789abcdefg_random_string/test-file-name.md`,
getText: jest.fn(() => 'test-file-content')
};

const editor = {
document: codeBlock,
selection: { isEmpty: true }
};

(<any>window).activeTextEditor = editor;

await openInBrowserFn();

expect(getGistMock).toHaveBeenCalledWith('123456789abcdefg');
expect(executeCommandSpy).toHaveBeenCalledWith('vscode.open', 'test-url');
});
});
1 change: 1 addition & 0 deletions src/commands/gists/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './create';
export * from './open';
export * from './open-favorite';
export * from './open-in-browser';
export * from './update-access-key';
51 changes: 51 additions & 0 deletions src/commands/gists/open-in-browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { commands, Uri, window } from 'vscode';

import { GistCommands } from '../extension-commands';

const openInBrowser: CommandInitializer = (
services: Services,
utils: Utils
): [Command, CommandFn] => {
const { gists, insights, logger } = services;

const command = GistCommands.OpenInBrowser;

const commandFn = async (): Promise<void> => {
const gistName = '';
try {
logger.info(`User Activated ${command}`);

const editor = window.activeTextEditor;

if (!editor) {
utils.notify.info('No open documents');

return;
}

const gistId = utils.files.extractTextDocumentDetails(editor.document).id;

const gist = await gists.getGist(gistId);

commands.executeCommand('vscode.open', Uri.parse(gist.url));

insights.track(command);
} catch (err) {
const error: Error = err as Error;
logger.error(`${command} > ${error && error.message}`);
insights.exception(command, { messsage: error.message });
if (error && error.message === 'Not Found') {
utils.notify.error(
`Could Not Open Gist ${gistName}`,
`Reason: ${error.message}`
);
} else {
utils.notify.error('Unable To Open Gists', error.message);
}
}
};

return [command, commandFn];
};

export { openInBrowser };
6 changes: 0 additions & 6 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,6 @@ export function activate(context: ExtensionContext): void {
});
});

commands.registerCommand(
'extension.openCodeBlockInBrowser',
(): void => {
// intentionally left blank
}
);
commands.registerCommand(
'extension.deleteCodeBlock',
(): void => {
Expand Down
3 changes: 2 additions & 1 deletion src/gists/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ const formatGist = (gist: GistResponse): Gist => ({
day: 'numeric',
month: 'long',
year: 'numeric'
}).format(new Date(gist.updated_at))
}).format(new Date(gist.updated_at)),
url: gist.html_url
});

const formatGists = (gistList: GistsResponse): Gist[] =>
Expand Down
1 change: 1 addition & 0 deletions src/typings/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface Gist {
name: string;
public: boolean;
updatedAt: string;
url: string;
}

interface GistTextDocument {
Expand Down

0 comments on commit d3666e8

Please sign in to comment.