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 events from '../events';
import serviceConfig from '../service-config';
import useStore from '../store/use-store';
import uiConstants from '../ui-constants';
import { parseAccountID } from '../util/account-id';
import isSidebar from '../util/is-sidebar';
import { shouldAutoDisplayTutorial } from '../util/session';
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.
......@@ -31,102 +43,82 @@ function authStateFromProfile(profile) {
}
}
// @ngInject
function HypothesisAppController(
$document,
$rootScope,
$scope,
$window,
analytics,
store,
/**
* The root component for the Hypothesis client.
*
* This handles login/logout actions and renders the top navigation bar
* and content appropriate for the current route.
*/
function HypothesisApp({
auth,
bridge,
features,
frameSync,
groups,
serviceUrl,
session,
settings,
toastMessenger
) {
const self = this;
// This stores information about the current user's authentication status.
// When the controller instantiates we do not yet know if the user is
// logged-in or not, so it has an initial status of 'unknown'. This can be
// used by templates to show an intermediate or loading state.
this.auth = { status: 'unknown' };
this.backgroundStyle = applyTheme(['appBackgroundColor'], settings);
// Check to see if we're in the sidebar, or on a standalone page such as
// the stream page or an individual annotation page.
this.isSidebar = isSidebar();
if (this.isSidebar) {
frameSync.connect();
session,
toastMessenger,
}) {
const clearGroups = useStore(store => store.clearGroups);
const closeSidebarPanel = useStore(store => store.closeSidebarPanel);
const countDrafts = useStore(store => store.countDrafts);
const discardAllDrafts = useStore(store => store.discardAllDrafts);
const hasFetchedProfile = useStore(store => store.hasFetchedProfile());
const openSidebarPanel = useStore(store => store.openSidebarPanel);
const profile = useStore(store => store.profile());
const removeAnnotations = useStore(store => store.removeAnnotations);
const route = useStore(store => store.route());
const unsavedAnnotations = useStore(store => store.unsavedAnnotations);
const authState = useMemo(() => {
if (!hasFetchedProfile) {
return { status: 'unknown' };
}
return authStateFromProfile(profile);
}, [hasFetchedProfile, profile]);
// Reload the view when the user switches accounts
this.onUserChange = profile => {
self.auth = authStateFromProfile(profile);
if (shouldAutoDisplayTutorial(this.isSidebar, store.profile(), settings)) {
// Auto-open the tutorial (help) panel
store.openSidebarPanel(uiConstants.PANEL_HELP);
}
};
const backgroundStyle = useMemo(
() => applyTheme(['backgroundColor'], settings),
[settings]
);
this.route = () => store.route();
const isSidebar = route === 'sidebar';
$scope.$on(events.USER_CHANGED, function (event, data) {
self.onUserChange(data.profile);
});
session.load().then(profile => {
self.onUserChange(profile);
});
useEffect(() => {
if (shouldAutoDisplayTutorial(isSidebar, profile, settings)) {
openSidebarPanel(uiConstants.PANEL_HELP);
}
}, [isSidebar, profile, openSidebarPanel, settings]);
/**
* 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 () {
const login = async () => {
if (serviceConfig(settings)) {
// Let the host page handle the login request
bridge.call(bridgeEvents.LOGIN_REQUESTED);
return Promise.resolve();
return;
}
return auth
.login()
.then(() => {
// If the prompt-to-log-in sidebar panel is open, close it
store.closeSidebarPanel(uiConstants.PANEL_LOGIN_PROMPT);
store.clearGroups();
try {
await auth.login();
closeSidebarPanel(uiConstants.PANEL_LOGIN_PROMPT);
clearGroups();
session.reload();
})
.catch(err => {
} catch (err) {
toastMessenger.error(err.message);
});
}
};
this.signUp = function () {
analytics.track(analytics.events.SIGN_UP_REQUESTED);
const signUp = () => {
if (serviceConfig(settings)) {
// Let the host page handle the signup request
bridge.call(bridgeEvents.SIGNUP_REQUESTED);
return;
}
$window.open(serviceUrl('signup'));
window.open(serviceUrl('signup'));
};
// Prompt to discard any unsaved drafts.
const promptToLogout = function () {
const promptToLogout = () => {
// TODO - Replace this with a UI which doesn't look terrible.
let text = '';
const drafts = store.countDrafts();
const drafts = countDrafts();
if (drafts === 1) {
text =
'You have an unsaved annotation.\n' +
......@@ -138,31 +130,73 @@ function HypothesisAppController(
' unsaved annotations.\n' +
'Do you really want to discard these drafts?';
}
return drafts === 0 || $window.confirm(text);
return drafts === 0 || window.confirm(text);
};
// Log the user out.
this.logout = function () {
const logout = () => {
if (!promptToLogout()) {
return;
}
store.clearGroups();
store.removeAnnotations(store.unsavedAnnotations());
store.discardAllDrafts();
clearGroups();
removeAnnotations(unsavedAnnotations());
discardAllDrafts();
if (serviceConfig(settings)) {
// Let the host page handle the signup request
bridge.call(bridgeEvents.LOGOUT_REQUESTED);
return;
}
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 {
controller: HypothesisAppController,
controllerAs: 'vm',
template: require('../templates/hypothesis-app.html'),
HypothesisApp.propTypes = {
// Injected.
auth: propTypes.object,
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) {
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.
disableOpenerForExternalLinks(document.body);
import angular from 'angular';
// Load polyfill for :focus-visible pseudo-class.
import 'focus-visible';
......@@ -42,8 +32,6 @@ if (process.env.NODE_ENV !== 'production') {
require('preact/debug');
}
import wrapReactComponent from './util/wrap-react-component';
if (appConfig.googleAnalytics) {
addAnalytics(appConfig.googleAnalytics);
}
......@@ -100,29 +88,24 @@ function autosave(autosaveService) {
autosaveService.init();
}
// @ngInject
function setupFrameSync(frameSync) {
if (isSidebar) {
frameSync.connect();
}
}
// Register icons used by the sidebar app (and maybe other assets in future).
import { registerIcons } from '../shared/components/svg-icon';
import iconSet from './icons';
registerIcons(iconSet);
// Preact UI components that are wrapped for use within Angular templates.
import AnnotationViewerContent from './components/annotation-viewer-content';
import HelpPanel from './components/help-panel';
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';
// The entry point component for the app.
import { createElement, render } from 'preact';
import HypothesisApp from './components/hypothesis-app';
import { ServiceContext } from './util/service-context';
// Services.
import bridgeService from '../shared/bridge';
import analyticsService from './services/analytics';
......@@ -151,18 +134,13 @@ import unicodeService from './services/unicode';
import viewFilterService from './services/view-filter';
// Redux store.
import store from './store';
// Utilities.
import { Injector } from '../shared/injector';
import EventEmitter from 'tiny-emitter';
function startAngularApp(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.
function startApp(config) {
const container = new Injector();
// Register services.
......@@ -194,6 +172,15 @@ function startAngularApp(config) {
.register('viewFilter', viewFilterService)
.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.
//
// nb. In many cases these can be replaced by direct imports in the services
......@@ -203,92 +190,23 @@ function startAngularApp(config) {
.register('isSidebar', { value: isSidebar })
.register('settings', { value: config });
// Register services which only Angular can construct, once Angular has
// constructed them.
//
// @ngInject
function registerAngularServices($rootScope) {
container.register('$rootScope', { value: $rootScope });
}
// Run initialization logic that uses constructed services.
//
// @ngInject
function initServices() {
// Initialize services.
container.run(persistDefaults);
container.run(autosave);
container.run(sendPageView);
container.run(setupApi);
container.run(setupRoute);
container.run(startRPCServer);
}
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,
};
}
container.run(setupFrameSync);
// Render the UI.
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)
......@@ -296,11 +214,10 @@ preStartRPCServer();
fetchConfig(appConfig)
.then(config => {
startAngularApp(config);
startApp(config);
})
.catch(err => {
// 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
// start.
// sidebar does not currently appear at all if the app fails to start.
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