Commit 7bbb8a60 authored by Robert Knight's avatar Robert Knight

Convert root `<hypothesis-app>` component to Preact

Convert the root `<hypothesis-app>` component to Preact and update the
startup code in `src/sidebar/index.js` to replace the AngularJS app
bootstrap with rendering the `HypothesisApp` component directly using
`render` from Preact.
parent 1d37386a
import { createElement } from 'preact';
import { useEffect, useMemo } from 'preact/hooks';
import propTypes from 'prop-types';
import bridgeEvents from '../../shared/bridge-events'; import bridgeEvents from '../../shared/bridge-events';
import events from '../events';
import serviceConfig from '../service-config'; import serviceConfig from '../service-config';
import useStore from '../store/use-store';
import uiConstants from '../ui-constants'; import uiConstants from '../ui-constants';
import { parseAccountID } from '../util/account-id'; import { parseAccountID } from '../util/account-id';
import isSidebar from '../util/is-sidebar';
import { shouldAutoDisplayTutorial } from '../util/session'; import { shouldAutoDisplayTutorial } from '../util/session';
import { applyTheme } from '../util/theme'; import { applyTheme } from '../util/theme';
import { withServices } from '../util/service-context';
import AnnotationViewerContent from './annotation-viewer-content';
import HelpPanel from './help-panel';
import ShareAnnotationsPanel from './share-annotations-panel';
import SidebarContent from './sidebar-content';
import StreamContent from './stream-content';
import ToastMessages from './toast-messages';
import TopBar from './top-bar';
/** /**
* Return the user's authentication status from their profile. * Return the user's authentication status from their profile.
...@@ -31,102 +43,82 @@ function authStateFromProfile(profile) { ...@@ -31,102 +43,82 @@ function authStateFromProfile(profile) {
} }
} }
// @ngInject /**
function HypothesisAppController( * The root component for the Hypothesis client.
$document, *
$rootScope, * This handles login/logout actions and renders the top navigation bar
$scope, * and content appropriate for the current route.
$window, */
analytics, function HypothesisApp({
store,
auth, auth,
bridge, bridge,
features,
frameSync,
groups,
serviceUrl, serviceUrl,
session,
settings, settings,
toastMessenger session,
) { toastMessenger,
const self = this; }) {
const clearGroups = useStore(store => store.clearGroups);
// This stores information about the current user's authentication status. const closeSidebarPanel = useStore(store => store.closeSidebarPanel);
// When the controller instantiates we do not yet know if the user is const countDrafts = useStore(store => store.countDrafts);
// logged-in or not, so it has an initial status of 'unknown'. This can be const discardAllDrafts = useStore(store => store.discardAllDrafts);
// used by templates to show an intermediate or loading state. const hasFetchedProfile = useStore(store => store.hasFetchedProfile());
this.auth = { status: 'unknown' }; const openSidebarPanel = useStore(store => store.openSidebarPanel);
const profile = useStore(store => store.profile());
this.backgroundStyle = applyTheme(['appBackgroundColor'], settings); const removeAnnotations = useStore(store => store.removeAnnotations);
const route = useStore(store => store.route());
// Check to see if we're in the sidebar, or on a standalone page such as const unsavedAnnotations = useStore(store => store.unsavedAnnotations);
// the stream page or an individual annotation page.
this.isSidebar = isSidebar(); const authState = useMemo(() => {
if (this.isSidebar) { if (!hasFetchedProfile) {
frameSync.connect(); return { status: 'unknown' };
} }
return authStateFromProfile(profile);
}, [hasFetchedProfile, profile]);
// Reload the view when the user switches accounts const backgroundStyle = useMemo(
this.onUserChange = profile => { () => applyTheme(['backgroundColor'], settings),
self.auth = authStateFromProfile(profile); [settings]
if (shouldAutoDisplayTutorial(this.isSidebar, store.profile(), settings)) { );
// Auto-open the tutorial (help) panel
store.openSidebarPanel(uiConstants.PANEL_HELP);
}
};
this.route = () => store.route(); const isSidebar = route === 'sidebar';
$scope.$on(events.USER_CHANGED, function (event, data) { useEffect(() => {
self.onUserChange(data.profile); if (shouldAutoDisplayTutorial(isSidebar, profile, settings)) {
}); openSidebarPanel(uiConstants.PANEL_HELP);
}
session.load().then(profile => { }, [isSidebar, profile, openSidebarPanel, settings]);
self.onUserChange(profile);
});
/** const login = async () => {
* Start the login flow. This will present the user with the login dialog.
*
* @return {Promise<void>} - A Promise that resolves when the login flow
* completes. For non-OAuth logins, always resolves immediately.
*/
this.login = function () {
if (serviceConfig(settings)) { if (serviceConfig(settings)) {
// Let the host page handle the login request // Let the host page handle the login request
bridge.call(bridgeEvents.LOGIN_REQUESTED); bridge.call(bridgeEvents.LOGIN_REQUESTED);
return Promise.resolve(); return;
} }
return auth try {
.login() await auth.login();
.then(() => {
// If the prompt-to-log-in sidebar panel is open, close it closeSidebarPanel(uiConstants.PANEL_LOGIN_PROMPT);
store.closeSidebarPanel(uiConstants.PANEL_LOGIN_PROMPT); clearGroups();
store.clearGroups();
session.reload(); session.reload();
}) } catch (err) {
.catch(err => {
toastMessenger.error(err.message); toastMessenger.error(err.message);
}); }
}; };
this.signUp = function () { const signUp = () => {
analytics.track(analytics.events.SIGN_UP_REQUESTED);
if (serviceConfig(settings)) { if (serviceConfig(settings)) {
// Let the host page handle the signup request // Let the host page handle the signup request
bridge.call(bridgeEvents.SIGNUP_REQUESTED); bridge.call(bridgeEvents.SIGNUP_REQUESTED);
return; return;
} }
$window.open(serviceUrl('signup')); window.open(serviceUrl('signup'));
}; };
// Prompt to discard any unsaved drafts. const promptToLogout = () => {
const promptToLogout = function () {
// TODO - Replace this with a UI which doesn't look terrible. // TODO - Replace this with a UI which doesn't look terrible.
let text = ''; let text = '';
const drafts = store.countDrafts(); const drafts = countDrafts();
if (drafts === 1) { if (drafts === 1) {
text = text =
'You have an unsaved annotation.\n' + 'You have an unsaved annotation.\n' +
...@@ -138,31 +130,73 @@ function HypothesisAppController( ...@@ -138,31 +130,73 @@ function HypothesisAppController(
' unsaved annotations.\n' + ' unsaved annotations.\n' +
'Do you really want to discard these drafts?'; 'Do you really want to discard these drafts?';
} }
return drafts === 0 || $window.confirm(text); return drafts === 0 || window.confirm(text);
}; };
// Log the user out. const logout = () => {
this.logout = function () {
if (!promptToLogout()) { if (!promptToLogout()) {
return; return;
} }
clearGroups();
store.clearGroups(); removeAnnotations(unsavedAnnotations());
store.removeAnnotations(store.unsavedAnnotations()); discardAllDrafts();
store.discardAllDrafts();
if (serviceConfig(settings)) { if (serviceConfig(settings)) {
// Let the host page handle the signup request
bridge.call(bridgeEvents.LOGOUT_REQUESTED); bridge.call(bridgeEvents.LOGOUT_REQUESTED);
return; return;
} }
session.logout(); session.logout();
}; };
return (
<div
className="app-content-wrapper js-thread-list-scroll-root"
style={backgroundStyle}
>
<TopBar
auth={authState}
onLogin={login}
onSignUp={signUp}
onLogout={logout}
isSidebar={isSidebar}
/>
<div className="content">
<ToastMessages />
<HelpPanel auth={authState} />
<ShareAnnotationsPanel />
{route && (
<main>
{route === 'annotation' && <AnnotationViewerContent />}
{route === 'stream' && <StreamContent />}
{route === 'sidebar' && (
<SidebarContent onLogin={login} onSignUp={signUp} />
)}
</main>
)}
</div>
</div>
);
} }
export default { HypothesisApp.propTypes = {
controller: HypothesisAppController, // Injected.
controllerAs: 'vm', auth: propTypes.object,
template: require('../templates/hypothesis-app.html'), bridge: propTypes.object,
serviceUrl: propTypes.func,
settings: propTypes.object,
session: propTypes.object,
toastMessenger: propTypes.object,
}; };
HypothesisApp.injectedProps = [
'auth',
'bridge',
'serviceUrl',
'session',
'settings',
'toastMessenger',
];
export default withServices(HypothesisApp);
import angular from 'angular'; import { mount } from 'enzyme';
import { createElement } from 'preact';
import bridgeEvents from '../../../shared/bridge-events'; import bridgeEvents from '../../../shared/bridge-events';
import events from '../../events'; import mockImportedComponents from '../../../test-util/mock-imported-components';
import { events as analyticsEvents } from '../../services/analytics';
import hypothesisApp from '../hypothesis-app'; import HypothesisApp, { $imports } from '../hypothesis-app';
import { $imports } from '../hypothesis-app';
describe('HypothesisApp', () => {
describe('sidebar.components.hypothesis-app', function () {
let $componentController = null;
let $scope = null;
let $rootScope = null;
let fakeStore = null; let fakeStore = null;
let fakeAnalytics = null;
let fakeAuth = null; let fakeAuth = null;
let fakeBridge = null; let fakeBridge = null;
let fakeFeatures = null;
let fakeFrameSync = null;
let fakeIsSidebar = null;
let fakeServiceConfig = null; let fakeServiceConfig = null;
let fakeSession = null; let fakeSession = null;
let fakeShouldAutoDisplayTutorial = null; let fakeShouldAutoDisplayTutorial = null;
let fakeGroups = null;
let fakeServiceUrl = null; let fakeServiceUrl = null;
let fakeSettings = null; let fakeSettings = null;
let fakeToastMessenger = null; let fakeToastMessenger = null;
let fakeWindow = null;
let sandbox = null;
const createController = function (locals) { const createComponent = (props = {}) => {
locals = locals || {}; return mount(
locals.$scope = $scope; <HypothesisApp
return $componentController('hypothesisApp', locals); auth={fakeAuth}
bridge={fakeBridge}
serviceUrl={fakeServiceUrl}
settings={fakeSettings}
session={fakeSession}
toastMessenger={fakeToastMessenger}
{...props}
/>
);
}; };
beforeEach(function () { beforeEach(() => {
sandbox = sinon.createSandbox(); fakeServiceConfig = sinon.stub();
});
beforeEach(function () {
fakeIsSidebar = sandbox.stub().returns(true);
fakeServiceConfig = sandbox.stub();
fakeShouldAutoDisplayTutorial = sinon.stub().returns(false); fakeShouldAutoDisplayTutorial = sinon.stub().returns(false);
$imports.$mock({
'../util/is-sidebar': fakeIsSidebar,
'../service-config': fakeServiceConfig,
'../util/session': {
shouldAutoDisplayTutorial: fakeShouldAutoDisplayTutorial,
},
});
angular.module('h', []).component('hypothesisApp', hypothesisApp);
});
afterEach(() => {
$imports.$restore();
});
beforeEach(angular.mock.module('h'));
beforeEach(
angular.mock.module(function ($provide) {
fakeStore = { fakeStore = {
tool: 'comment', clearSelectedAnnotations: sinon.spy(),
clearSelectedAnnotations: sandbox.spy(),
clearGroups: sinon.stub(), clearGroups: sinon.stub(),
closeSidebarPanel: sinon.stub(), closeSidebarPanel: sinon.stub(),
openSidebarPanel: sinon.stub(), openSidebarPanel: sinon.stub(),
// draft store // draft store
countDrafts: sandbox.stub().returns(0), countDrafts: sinon.stub().returns(0),
discardAllDrafts: sandbox.stub(), discardAllDrafts: sinon.stub(),
unsavedAnnotations: sandbox.stub().returns([]), unsavedAnnotations: sinon.stub().returns([]),
removeAnnotations: sandbox.stub(), removeAnnotations: sinon.stub(),
hasFetchedProfile: sinon.stub().returns(true),
profile: sinon.stub().returns({ profile: sinon.stub().returns({
userid: null,
preferences: { preferences: {
show_sidebar_tutorial: false, show_sidebar_tutorial: false,
}, },
}), }),
}; route: sinon.stub().returns('sidebar'),
fakeAnalytics = {
track: sandbox.stub(),
events: analyticsEvents,
}; };
fakeAuth = {}; fakeAuth = {};
fakeFeatures = {
fetch: sandbox.spy(),
flagEnabled: sandbox.stub().returns(false),
};
fakeFrameSync = {
connect: sandbox.spy(),
};
fakeSession = { fakeSession = {
load: sandbox.stub().returns(Promise.resolve({ userid: null })), load: sinon.stub().returns(Promise.resolve({ userid: null })),
logout: sandbox.stub(), logout: sinon.stub(),
reload: sandbox.stub().returns(Promise.resolve({ userid: null })), reload: sinon.stub().returns(Promise.resolve({ userid: null })),
};
fakeGroups = {
focus: sandbox.spy(),
};
fakeWindow = {
top: {},
confirm: sandbox.stub(),
open: sandbox.stub(),
}; };
fakeServiceUrl = sinon.stub(); fakeServiceUrl = sinon.stub();
fakeSettings = {}; fakeSettings = {};
fakeBridge = { fakeBridge = {
call: sandbox.stub(), call: sinon.stub(),
}; };
fakeToastMessenger = { fakeToastMessenger = {
error: sandbox.stub(), error: sinon.stub(),
}; };
$provide.value('store', fakeStore); $imports.$mock(mockImportedComponents());
$provide.value('auth', fakeAuth); $imports.$mock({
$provide.value('analytics', fakeAnalytics); '../service-config': fakeServiceConfig,
$provide.value('features', fakeFeatures); '../store/use-store': callback => callback(fakeStore),
$provide.value('frameSync', fakeFrameSync); '../util/session': {
$provide.value('serviceUrl', fakeServiceUrl); shouldAutoDisplayTutorial: fakeShouldAutoDisplayTutorial,
$provide.value('session', fakeSession); },
$provide.value('settings', fakeSettings); });
$provide.value('toastMessenger', fakeToastMessenger); });
$provide.value('bridge', fakeBridge);
$provide.value('groups', fakeGroups);
$provide.value('$window', fakeWindow);
})
);
beforeEach(
angular.mock.inject(function (_$componentController_, _$rootScope_) {
$componentController = _$componentController_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
})
);
afterEach(function () { afterEach(() => {
sandbox.restore(); $imports.$restore();
}); });
it('connects to host frame in the sidebar app', function () { it('does not render content if route is not yet determined', () => {
fakeIsSidebar.returns(true); fakeStore.route.returns(null);
createController(); const wrapper = createComponent();
assert.called(fakeFrameSync.connect); [
'main',
'AnnotationViewerContent',
'StreamContent',
'SidebarContent',
].forEach(contentComponent => {
assert.isFalse(wrapper.exists(contentComponent));
});
}); });
it('does not connect to the host frame in the stream', function () { [
fakeIsSidebar.returns(false); {
createController(); route: 'annotation',
assert.notCalled(fakeFrameSync.connect); contentComponent: 'AnnotationViewerContent',
},
{
route: 'sidebar',
contentComponent: 'SidebarContent',
},
{
route: 'stream',
contentComponent: 'StreamContent',
},
].forEach(({ route, contentComponent }) => {
it('renders app content for route', () => {
fakeStore.route.returns(route);
const wrapper = createComponent();
assert.isTrue(wrapper.find(contentComponent).exists());
});
}); });
describe('auto-opening tutorial', () => { describe('auto-opening tutorial', () => {
it('should open tutorial on profile load when criteria are met', () => { it('should open tutorial on profile load when criteria are met', () => {
fakeShouldAutoDisplayTutorial.returns(true); fakeShouldAutoDisplayTutorial.returns(true);
createController(); createComponent();
return fakeSession.load().then(() => {
assert.calledOnce(fakeStore.openSidebarPanel); assert.calledOnce(fakeStore.openSidebarPanel);
}); });
});
it('should not open tutorial on profile load when criteria are not met', () => { it('should not open tutorial on profile load when criteria are not met', () => {
fakeShouldAutoDisplayTutorial.returns(false); fakeShouldAutoDisplayTutorial.returns(false);
createController(); createComponent();
return fakeSession.load().then(() => { assert.notCalled(fakeStore.openSidebarPanel);
assert.equal(fakeStore.openSidebarPanel.callCount, 0);
});
}); });
}); });
it('auth.status is "unknown" on startup', function () { const getAuthState = wrapper => wrapper.find('TopBar').prop('auth');
const ctrl = createController();
assert.equal(ctrl.auth.status, 'unknown');
});
it('sets auth.status to "logged-out" if userid is null', function () { it('auth state is "unknown" if profile has not yet been fetched', () => {
const ctrl = createController(); fakeStore.hasFetchedProfile.returns(false);
return fakeSession.load().then(function () { const wrapper = createComponent();
assert.equal(ctrl.auth.status, 'logged-out'); assert.equal(getAuthState(wrapper).status, 'unknown');
});
}); });
it('sets auth.status to "logged-in" if userid is non-null', function () { it('auth state is "logged-out" if userid is null', () => {
fakeSession.load = function () { fakeStore.profile.returns({ userid: null });
return Promise.resolve({ userid: 'acct:jim@hypothes.is' }); const wrapper = createComponent();
}; assert.equal(getAuthState(wrapper).status, 'logged-out');
const ctrl = createController();
return fakeSession.load().then(function () {
assert.equal(ctrl.auth.status, 'logged-in');
}); });
it('auth state is "logged-in" if userid is non-null', () => {
fakeStore.profile.returns({ userid: 'acct:jimsmith@hypothes.is' });
const wrapper = createComponent();
assert.equal(getAuthState(wrapper).status, 'logged-in');
}); });
[ [
...@@ -236,123 +192,100 @@ describe('sidebar.components.hypothesis-app', function () { ...@@ -236,123 +192,100 @@ describe('sidebar.components.hypothesis-app', function () {
}, },
}, },
].forEach(({ profile, expectedAuth }) => { ].forEach(({ profile, expectedAuth }) => {
it('sets `auth` properties when profile has loaded', () => { it('sets auth state depending on profile', () => {
fakeSession.load = () => Promise.resolve(profile); fakeStore.profile.returns(profile);
const ctrl = createController(); const wrapper = createComponent();
return fakeSession.load().then(() => { assert.deepEqual(getAuthState(wrapper), expectedAuth);
assert.deepEqual(ctrl.auth, expectedAuth);
});
}); });
}); });
it('updates auth when the logged-in user changes', function () { describe('"Sign up" action', () => {
const ctrl = createController(); const clickSignUp = wrapper => wrapper.find('TopBar').props().onSignUp();
return fakeSession.load().then(function () {
$scope.$broadcast(events.USER_CHANGED, { beforeEach(() => {
profile: { sinon.stub(window, 'open');
userid: 'acct:john@hypothes.is',
},
});
assert.deepEqual(ctrl.auth, {
status: 'logged-in',
displayName: 'john',
userid: 'acct:john@hypothes.is',
username: 'john',
provider: 'hypothes.is',
});
});
}); });
describe('#signUp', function () { afterEach(() => {
it('tracks sign up requests in analytics', function () { window.open.restore();
const ctrl = createController();
ctrl.signUp();
assert.calledWith(
fakeAnalytics.track,
fakeAnalytics.events.SIGN_UP_REQUESTED
);
}); });
context('when using a third-party service', function () { context('when using a third-party service', () => {
beforeEach(function () { beforeEach(() => {
fakeServiceConfig.returns({}); fakeServiceConfig.returns({});
}); });
it('sends SIGNUP_REQUESTED event', function () { it('sends SIGNUP_REQUESTED event', () => {
const ctrl = createController(); const wrapper = createComponent();
ctrl.signUp(); clickSignUp(wrapper);
assert.calledWith(fakeBridge.call, bridgeEvents.SIGNUP_REQUESTED); assert.calledWith(fakeBridge.call, bridgeEvents.SIGNUP_REQUESTED);
}); });
it('does not open a URL directly', function () { it('does not open a URL directly', () => {
const ctrl = createController(); const wrapper = createComponent();
ctrl.signUp(); clickSignUp(wrapper);
assert.notCalled(fakeWindow.open); assert.notCalled(window.open);
}); });
}); });
context('when not using a third-party service', function () { context('when not using a third-party service', () => {
it('opens the signup URL in a new tab', function () { it('opens the signup URL in a new tab', () => {
fakeServiceUrl.withArgs('signup').returns('https://ann.service/signup'); fakeServiceUrl.withArgs('signup').returns('https://ann.service/signup');
const ctrl = createController(); const wrapper = createComponent();
ctrl.signUp(); clickSignUp(wrapper);
assert.calledWith(fakeWindow.open, 'https://ann.service/signup'); assert.calledWith(window.open, 'https://ann.service/signup');
}); });
}); });
}); });
describe('#login()', function () { describe('"Log in" action', () => {
const clickLogIn = wrapper => wrapper.find('TopBar').props().onLogin();
beforeEach(() => { beforeEach(() => {
fakeAuth.login = sinon.stub().returns(Promise.resolve()); fakeAuth.login = sinon.stub().returns(Promise.resolve());
}); });
it('clears groups', () => { it('clears groups', async () => {
const ctrl = createController(); const wrapper = createComponent();
await clickLogIn(wrapper);
return ctrl.login().then(() => {
assert.called(fakeStore.clearGroups); assert.called(fakeStore.clearGroups);
}); });
});
it('initiates the OAuth login flow', () => { it('initiates the OAuth login flow', async () => {
const ctrl = createController(); const wrapper = createComponent();
ctrl.login(); await clickLogIn(wrapper);
assert.called(fakeAuth.login); assert.called(fakeAuth.login);
}); });
it('reloads the session when login completes', () => { it('reloads the session when login completes', async () => {
const ctrl = createController(); const wrapper = createComponent();
return ctrl.login().then(() => { await clickLogIn(wrapper);
assert.called(fakeSession.reload); assert.called(fakeSession.reload);
}); });
});
it('closes the login prompt panel', () => { it('closes the login prompt panel', async () => {
const ctrl = createController(); const wrapper = createComponent();
return ctrl.login().then(() => { await clickLogIn(wrapper);
assert.called(fakeStore.closeSidebarPanel); assert.called(fakeStore.closeSidebarPanel);
}); });
});
it('reports an error if login fails', () => { it('reports an error if login fails', async () => {
fakeAuth.login.returns(Promise.reject(new Error('Login failed'))); fakeAuth.login.returns(Promise.reject(new Error('Login failed')));
const ctrl = createController(); const wrapper = createComponent();
await clickLogIn(wrapper);
return ctrl.login().then(null, () => {
assert.called(fakeToastMessenger.error); assert.called(fakeToastMessenger.error);
}); });
});
it('sends LOGIN_REQUESTED if a third-party service is in use', function () { it('sends LOGIN_REQUESTED if a third-party service is in use', async () => {
// If the client is using a third-party annotation service then clicking // If the client is using a third-party annotation service then clicking
// on a login button should send the LOGIN_REQUESTED event over the bridge // on a login button should send the LOGIN_REQUESTED event over the bridge
// (so that the partner site we're embedded in can do its own login // (so that the partner site we're embedded in can do its own login
// thing). // thing).
fakeServiceConfig.returns({}); fakeServiceConfig.returns({});
const ctrl = createController();
ctrl.login(); const wrapper = createComponent();
await clickLogIn(wrapper);
assert.equal(fakeBridge.call.callCount, 1); assert.equal(fakeBridge.call.callCount, 1);
assert.isTrue( assert.isTrue(
...@@ -361,33 +294,44 @@ describe('sidebar.components.hypothesis-app', function () { ...@@ -361,33 +294,44 @@ describe('sidebar.components.hypothesis-app', function () {
}); });
}); });
describe('#logout()', function () { describe('"Log out" action', () => {
// Tests shared by both of the contexts below. const clickLogOut = wrapper => wrapper.find('TopBar').props().onLogout();
function doSharedTests() {
it('prompts the user if there are drafts', function () {
fakeStore.countDrafts.returns(1);
const ctrl = createController();
ctrl.logout(); beforeEach(() => {
sinon.stub(window, 'confirm');
});
assert.equal(fakeWindow.confirm.callCount, 1); afterEach(() => {
window.confirm.restore();
}); });
it('clears groups', () => { // Tests used by both the first and third-party account scenarios.
const ctrl = createController(); function addCommonLogoutTests() {
// nb. Slightly different messages are shown depending on the draft count.
[1, 2].forEach(draftCount => {
it('prompts the user if there are drafts', () => {
fakeStore.countDrafts.returns(draftCount);
ctrl.logout(); const wrapper = createComponent();
clickLogOut(wrapper);
assert.equal(window.confirm.callCount, 1);
});
});
it('clears groups', () => {
const wrapper = createComponent();
clickLogOut(wrapper);
assert.called(fakeStore.clearGroups); assert.called(fakeStore.clearGroups);
}); });
it('removes unsaved annotations', function () { it('removes unsaved annotations', () => {
fakeStore.unsavedAnnotations = sandbox fakeStore.unsavedAnnotations = sinon
.stub() .stub()
.returns(['draftOne', 'draftTwo', 'draftThree']); .returns(['draftOne', 'draftTwo', 'draftThree']);
const ctrl = createController(); const wrapper = createComponent();
clickLogOut(wrapper);
ctrl.logout();
assert.calledWith(fakeStore.removeAnnotations, [ assert.calledWith(fakeStore.removeAnnotations, [
'draftOne', 'draftOne',
...@@ -396,64 +340,63 @@ describe('sidebar.components.hypothesis-app', function () { ...@@ -396,64 +340,63 @@ describe('sidebar.components.hypothesis-app', function () {
]); ]);
}); });
it('discards drafts', function () { it('discards drafts', () => {
const ctrl = createController(); const wrapper = createComponent();
clickLogOut(wrapper);
ctrl.logout();
assert(fakeStore.discardAllDrafts.calledOnce); assert(fakeStore.discardAllDrafts.calledOnce);
}); });
it('does not remove unsaved annotations if the user cancels the prompt', function () { it('does not remove unsaved annotations if the user cancels the prompt', () => {
const ctrl = createController(); const wrapper = createComponent();
fakeStore.countDrafts.returns(1); fakeStore.countDrafts.returns(1);
$rootScope.$emit = sandbox.stub(); window.confirm.returns(false);
fakeWindow.confirm.returns(false);
ctrl.logout(); clickLogOut(wrapper);
assert.notCalled(fakeStore.removeAnnotations); assert.notCalled(fakeStore.removeAnnotations);
}); });
it('does not discard drafts if the user cancels the prompt', function () { it('does not discard drafts if the user cancels the prompt', () => {
const ctrl = createController(); const wrapper = createComponent();
fakeStore.countDrafts.returns(1); fakeStore.countDrafts.returns(1);
fakeWindow.confirm.returns(false); window.confirm.returns(false);
ctrl.logout(); clickLogOut(wrapper);
assert(fakeStore.discardAllDrafts.notCalled); assert(fakeStore.discardAllDrafts.notCalled);
}); });
it('does not prompt if there are no drafts', function () { it('does not prompt if there are no drafts', () => {
const ctrl = createController(); const wrapper = createComponent();
fakeStore.countDrafts.returns(0); fakeStore.countDrafts.returns(0);
ctrl.logout(); clickLogOut(wrapper);
assert.equal(fakeWindow.confirm.callCount, 0); assert.notCalled(window.confirm);
}); });
} }
context('when no third-party service is in use', function () { context('when no third-party service is in use', () => {
doSharedTests(); addCommonLogoutTests();
it('calls session.logout()', function () { it('calls session.logout()', () => {
const ctrl = createController(); const wrapper = createComponent();
ctrl.logout(); clickLogOut(wrapper);
assert.called(fakeSession.logout); assert.called(fakeSession.logout);
}); });
}); });
context('when a third-party service is in use', function () { context('when a third-party service is in use', () => {
beforeEach('configure a third-party service to be in use', function () { beforeEach('configure a third-party service to be in use', () => {
fakeServiceConfig.returns({}); fakeServiceConfig.returns({});
}); });
doSharedTests(); addCommonLogoutTests();
it('sends LOGOUT_REQUESTED', function () { it('sends LOGOUT_REQUESTED', () => {
createController().logout(); const wrapper = createComponent();
clickLogOut(wrapper);
assert.calledOnce(fakeBridge.call); assert.calledOnce(fakeBridge.call);
assert.calledWithExactly( assert.calledWithExactly(
...@@ -462,18 +405,19 @@ describe('sidebar.components.hypothesis-app', function () { ...@@ -462,18 +405,19 @@ describe('sidebar.components.hypothesis-app', function () {
); );
}); });
it('does not send LOGOUT_REQUESTED if the user cancels the prompt', function () { it('does not send LOGOUT_REQUESTED if the user cancels the prompt', () => {
fakeStore.countDrafts.returns(1); fakeStore.countDrafts.returns(1);
fakeWindow.confirm.returns(false); window.confirm.returns(false);
createController().logout(); const wrapper = createComponent();
clickLogOut(wrapper);
assert.notCalled(fakeBridge.call); assert.notCalled(fakeBridge.call);
}); });
it('does not call session.logout()', function () { it('does not call session.logout()', () => {
createController().logout(); const wrapper = createComponent();
clickLogOut(wrapper);
assert.notCalled(fakeSession.logout); assert.notCalled(fakeSession.logout);
}); });
}); });
......
...@@ -21,19 +21,9 @@ if (appConfig.sentry) { ...@@ -21,19 +21,9 @@ if (appConfig.sentry) {
sentry.init(appConfig.sentry); sentry.init(appConfig.sentry);
} }
// Disable Angular features that are not compatible with CSP.
//
// See https://docs.angularjs.org/api/ng/directive/ngCsp
//
// The `ng-csp` attribute must be set on some HTML element in the document
// _before_ Angular is require'd for the first time.
document.body.setAttribute('ng-csp', '');
// Prevent tab-jacking. // Prevent tab-jacking.
disableOpenerForExternalLinks(document.body); disableOpenerForExternalLinks(document.body);
import angular from 'angular';
// Load polyfill for :focus-visible pseudo-class. // Load polyfill for :focus-visible pseudo-class.
import 'focus-visible'; import 'focus-visible';
...@@ -42,8 +32,6 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -42,8 +32,6 @@ if (process.env.NODE_ENV !== 'production') {
require('preact/debug'); require('preact/debug');
} }
import wrapReactComponent from './util/wrap-react-component';
if (appConfig.googleAnalytics) { if (appConfig.googleAnalytics) {
addAnalytics(appConfig.googleAnalytics); addAnalytics(appConfig.googleAnalytics);
} }
...@@ -100,29 +88,24 @@ function autosave(autosaveService) { ...@@ -100,29 +88,24 @@ function autosave(autosaveService) {
autosaveService.init(); autosaveService.init();
} }
// @ngInject
function setupFrameSync(frameSync) {
if (isSidebar) {
frameSync.connect();
}
}
// Register icons used by the sidebar app (and maybe other assets in future). // Register icons used by the sidebar app (and maybe other assets in future).
import { registerIcons } from '../shared/components/svg-icon'; import { registerIcons } from '../shared/components/svg-icon';
import iconSet from './icons'; import iconSet from './icons';
registerIcons(iconSet); registerIcons(iconSet);
// Preact UI components that are wrapped for use within Angular templates. // The entry point component for the app.
import { createElement, render } from 'preact';
import AnnotationViewerContent from './components/annotation-viewer-content'; import HypothesisApp from './components/hypothesis-app';
import HelpPanel from './components/help-panel'; import { ServiceContext } from './util/service-context';
import LoginPromptPanel from './components/login-prompt-panel';
import ShareAnnotationsPanel from './components/share-annotations-panel';
import SidebarContent from './components/sidebar-content';
import StreamContent from './components/stream-content';
import ThreadList from './components/thread-list';
import ToastMessages from './components/toast-messages';
import TopBar from './components/top-bar';
// Remaining UI components that are still built with Angular.
import hypothesisApp from './components/hypothesis-app';
// Services. // Services.
import bridgeService from '../shared/bridge'; import bridgeService from '../shared/bridge';
import analyticsService from './services/analytics'; import analyticsService from './services/analytics';
...@@ -151,18 +134,13 @@ import unicodeService from './services/unicode'; ...@@ -151,18 +134,13 @@ import unicodeService from './services/unicode';
import viewFilterService from './services/view-filter'; import viewFilterService from './services/view-filter';
// Redux store. // Redux store.
import store from './store'; import store from './store';
// Utilities. // Utilities.
import { Injector } from '../shared/injector'; import { Injector } from '../shared/injector';
import EventEmitter from 'tiny-emitter';
function startAngularApp(config) { function startApp(config) {
// Create dependency injection container for services.
//
// This is a replacement for the use of Angular's dependency injection
// (including its `$injector` service) to construct services with dependencies.
const container = new Injector(); const container = new Injector();
// Register services. // Register services.
...@@ -194,6 +172,15 @@ function startAngularApp(config) { ...@@ -194,6 +172,15 @@ function startAngularApp(config) {
.register('viewFilter', viewFilterService) .register('viewFilter', viewFilterService)
.register('store', store); .register('store', store);
// Register a dummy `$rootScope` pub-sub service for services that still
// use it.
const emitter = new EventEmitter();
const dummyRootScope = {
$on: (event, callback) => emitter.on(event, data => callback({}, data)),
$broadcast: (event, data) => emitter.emit(event, data),
};
container.register('$rootScope', { value: dummyRootScope });
// Register utility values/classes. // Register utility values/classes.
// //
// nb. In many cases these can be replaced by direct imports in the services // nb. In many cases these can be replaced by direct imports in the services
...@@ -203,92 +190,23 @@ function startAngularApp(config) { ...@@ -203,92 +190,23 @@ function startAngularApp(config) {
.register('isSidebar', { value: isSidebar }) .register('isSidebar', { value: isSidebar })
.register('settings', { value: config }); .register('settings', { value: config });
// Register services which only Angular can construct, once Angular has // Initialize services.
// constructed them.
//
// @ngInject
function registerAngularServices($rootScope) {
container.register('$rootScope', { value: $rootScope });
}
// Run initialization logic that uses constructed services.
//
// @ngInject
function initServices() {
container.run(persistDefaults); container.run(persistDefaults);
container.run(autosave); container.run(autosave);
container.run(sendPageView); container.run(sendPageView);
container.run(setupApi); container.run(setupApi);
container.run(setupRoute); container.run(setupRoute);
container.run(startRPCServer); container.run(startRPCServer);
} container.run(setupFrameSync);
const wrapComponent = component => wrapReactComponent(component, container);
angular
.module('h', [])
// The root component for the application
.component('hypothesisApp', hypothesisApp)
// UI components
.component(
'annotationViewerContent',
wrapComponent(AnnotationViewerContent)
)
.component('helpPanel', wrapComponent(HelpPanel))
.component('loginPromptPanel', wrapComponent(LoginPromptPanel))
.component('sidebarContent', wrapComponent(SidebarContent))
.component('shareAnnotationsPanel', wrapComponent(ShareAnnotationsPanel))
.component('streamContent', wrapComponent(StreamContent))
.component('threadList', wrapComponent(ThreadList))
.component('toastMessages', wrapComponent(ToastMessages))
.component('topBar', wrapComponent(TopBar))
// Register services, the store and utilities with Angular, so that
// Angular components can use them.
.service('analytics', () => container.get('analytics'))
.service('api', () => container.get('api'))
.service('auth', () => container.get('auth'))
.service('bridge', () => container.get('bridge'))
.service('features', () => container.get('features'))
.service('frameSync', () => container.get('frameSync'))
.service('groups', () => container.get('groups'))
.service('loadAnnotationsService', () =>
container.get('loadAnnotationsService')
)
.service('rootThread', () => container.get('rootThread'))
.service('searchFilter', () => container.get('searchFilter'))
.service('serviceUrl', () => container.get('serviceUrl'))
.service('session', () => container.get('session'))
.service('streamer', () => container.get('streamer'))
.service('streamFilter', () => container.get('streamFilter'))
.service('toastMessenger', () => container.get('toastMessenger'))
// Redux store
.service('store', () => container.get('store'))
// Utilities
.value('isSidebar', container.get('isSidebar'))
.value('settings', container.get('settings'))
// Make Angular built-ins available to services constructed by `container`.
.run(registerAngularServices)
.run(initServices);
// Work around a check in Angular's $sniffer service that causes it to
// incorrectly determine that Firefox extensions are Chrome Packaged Apps which
// do not support the HTML 5 History API. This results Angular redirecting the
// browser on startup and thus the app fails to load.
// See https://github.com/angular/angular.js/blob/a03b75c6a812fcc2f616fc05c0f1710e03fca8e9/src/ng/sniffer.js#L30
if (window.chrome && !window.chrome.app) {
window.chrome.app = {
dummyAddedByHypothesisClient: true,
};
}
// Render the UI.
const appEl = document.querySelector('hypothesis-app'); const appEl = document.querySelector('hypothesis-app');
angular.bootstrap(appEl, ['h'], { strictDi: true }); render(
<ServiceContext.Provider value={container}>
<HypothesisApp />
</ServiceContext.Provider>,
appEl
);
} }
// Start capturing RPC requests before we start the RPC server (startRPCServer) // Start capturing RPC requests before we start the RPC server (startRPCServer)
...@@ -296,11 +214,10 @@ preStartRPCServer(); ...@@ -296,11 +214,10 @@ preStartRPCServer();
fetchConfig(appConfig) fetchConfig(appConfig)
.then(config => { .then(config => {
startAngularApp(config); startApp(config);
}) })
.catch(err => { .catch(err => {
// Report error. This will be the only notice that the user gets because the // Report error. This will be the only notice that the user gets because the
// sidebar does not currently appear at all if the Angular app fails to // sidebar does not currently appear at all if the app fails to start.
// start.
console.error('Failed to start Hypothesis client: ', err); console.error('Failed to start Hypothesis client: ', err);
}); });
<div class="app-content-wrapper js-thread-list-scroll-root" ng-style="vm.backgroundStyle">
<top-bar
auth="vm.auth"
on-login="vm.login()"
on-sign-up="vm.signUp()"
on-logout="vm.logout()"
is-sidebar="::vm.isSidebar">
</top-bar>
<div class="content">
<toast-messages></toast-messages>
<help-panel auth="vm.auth"></help-panel>
<share-annotations-panel></share-annotations-panel>
<main ng-if="vm.route()">
<annotation-viewer-content ng-if="vm.route() == 'annotation'"></annotation-viewer-content>
<stream-content ng-if="vm.route() == 'stream'"></stream-content>
<sidebar-content ng-if="vm.route() == 'sidebar'" on-login="vm.login()" on-signUp="vm.signUp()"></sidebar-content>
</main>
</div>
</div>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment