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);
...@@ -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