From b2372a96e25120b218a210b656900ac1a7aa07d0 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Thu, 14 Apr 2022 01:19:27 -0400 Subject: [PATCH 1/9] Add react-router --- package-lock.json | 17 +++++++ package.json | 1 + src/components/HistoryRouter.tsx | 22 ++++++++ src/components/Page.tsx | 50 +++++++++++++++++++ src/components/appRouter.js | 4 +- src/components/pages/SearchPage.tsx | 42 ---------------- src/components/search/LiveTVSearchResults.tsx | 4 +- src/components/search/SearchResults.tsx | 4 +- src/components/search/SearchSuggestions.tsx | 2 +- src/components/viewManager/viewManager.js | 9 ++++ src/controllers/search.html | 2 - src/index.html | 1 + src/routes/index.tsx | 16 ++++++ src/routes/search.tsx | 40 +++++++++++++++ src/scripts/routes.js | 6 --- src/scripts/site.js | 15 +++++- 16 files changed, 176 insertions(+), 59 deletions(-) create mode 100644 src/components/HistoryRouter.tsx create mode 100644 src/components/Page.tsx delete mode 100644 src/components/pages/SearchPage.tsx delete mode 100644 src/controllers/search.html create mode 100644 src/routes/index.tsx create mode 100644 src/routes/search.tsx diff --git a/package-lock.json b/package-lock.json index 765cfd27cd..50dd570d6f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10760,6 +10760,23 @@ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", "dev": true }, + "react-router": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.3.0.tgz", + "integrity": "sha512-7Wh1DzVQ+tlFjkeo+ujvjSqSJmkt1+8JO+T5xklPlgrh70y7ogx75ODRW0ThWhY7S+6yEDks8TYrtQe/aoboBQ==", + "requires": { + "history": "^5.2.0" + } + }, + "react-router-dom": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.3.0.tgz", + "integrity": "sha512-uaJj7LKytRxZNQV8+RbzJWnJ8K2nPsOOEuX7aQstlMZKQT0164C+X2w6bnkqU3sjtLvpd5ojrezAyfZ1+0sStw==", + "requires": { + "history": "^5.2.0", + "react-router": "6.3.0" + } + }, "read-file-stdin": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/read-file-stdin/-/read-file-stdin-0.2.1.tgz", diff --git a/package.json b/package.json index 8c14b329f1..022483d232 100644 --- a/package.json +++ b/package.json @@ -96,6 +96,7 @@ "pdfjs-dist": "2.12.313", "react": "17.0.2", "react-dom": "17.0.2", + "react-router-dom": "6.3.0", "resize-observer-polyfill": "1.5.1", "screenfull": "6.0.0", "sortablejs": "1.14.0", diff --git a/src/components/HistoryRouter.tsx b/src/components/HistoryRouter.tsx new file mode 100644 index 0000000000..d789944e03 --- /dev/null +++ b/src/components/HistoryRouter.tsx @@ -0,0 +1,22 @@ +import React, { useLayoutEffect } from 'react'; +import { HistoryRouterProps, Router } from 'react-router-dom'; + +export function HistoryRouter({ basename, children, history }: HistoryRouterProps) { + const [state, setState] = React.useState({ + action: history.action, + location: history.location + }); + + useLayoutEffect(() => history.listen(setState), [history]); + + return ( + + ); +} diff --git a/src/components/Page.tsx b/src/components/Page.tsx new file mode 100644 index 0000000000..7772e495cd --- /dev/null +++ b/src/components/Page.tsx @@ -0,0 +1,50 @@ +import React, { FunctionComponent, useEffect, useRef } from 'react'; + +import viewManager from './viewManager/viewManager'; + +type PageProps = { + title?: string +}; + +/** + * Page component that handles hiding active non-react views, triggering the required events for + * navigation and appRouter state updates, and setting the correct classes and data attributes. + */ +const Page: FunctionComponent = ({ children, title }) => { + const element = useRef(null); + + useEffect(() => { + // hide active non-react views + viewManager.hideView(); + }, []); + + useEffect(() => { + const event = { + bubbles: true, + cancelable: false, + detail: { + isRestored: false + } + }; + // pagebeforeshow - hides tabs on tabless pages in libraryMenu + element.current?.dispatchEvent(new CustomEvent('pagebeforeshow', event)); + // viewshow - updates state of appRouter + element.current?.dispatchEvent(new CustomEvent('viewshow', event)); + // pageshow - updates header/navigation in libraryMenu + element.current?.dispatchEvent(new CustomEvent('pageshow', event)); + }, [ element ]); + + return ( +
+ {children} +
+ ); +}; + +export default Page; diff --git a/src/components/appRouter.js b/src/components/appRouter.js index 3b5f356653..7cad70394a 100644 --- a/src/components/appRouter.js +++ b/src/components/appRouter.js @@ -122,7 +122,7 @@ class AppRouter { isBack: action === Action.Pop }); } else { - console.warn('[appRouter] "%s" route not found', normalizedPath, location); + console.info('[appRouter] "%s" route not found', normalizedPath, location); } } @@ -139,7 +139,7 @@ class AppRouter { Events.on(apiClient, 'requestfail', this.onRequestFail); }); - ServerConnections.connect().then(result => { + return ServerConnections.connect().then(result => { this.firstConnectionResult = result; // Handle the initial route diff --git a/src/components/pages/SearchPage.tsx b/src/components/pages/SearchPage.tsx deleted file mode 100644 index a63d450e8e..0000000000 --- a/src/components/pages/SearchPage.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import React, { FunctionComponent, useState } from 'react'; - -import SearchFields from '../search/SearchFields'; -import SearchResults from '../search/SearchResults'; -import SearchSuggestions from '../search/SearchSuggestions'; -import LiveTVSearchResults from '../search/LiveTVSearchResults'; - -type SearchProps = { - serverId?: string, - parentId?: string, - collectionType?: string -}; - -const SearchPage: FunctionComponent = ({ serverId, parentId, collectionType }: SearchProps) => { - const [ query, setQuery ] = useState(); - - return ( - <> - - {!query && - - } - - - - ); -}; - -export default SearchPage; diff --git a/src/components/search/LiveTVSearchResults.tsx b/src/components/search/LiveTVSearchResults.tsx index 67378bc138..b79a24c3be 100644 --- a/src/components/search/LiveTVSearchResults.tsx +++ b/src/components/search/LiveTVSearchResults.tsx @@ -21,8 +21,8 @@ const CARD_OPTIONS = { type LiveTVSearchResultsProps = { serverId?: string; - parentId?: string; - collectionType?: string; + parentId?: string | null; + collectionType?: string | null; query?: string; } diff --git a/src/components/search/SearchResults.tsx b/src/components/search/SearchResults.tsx index 9f6d30a708..a54e568a3c 100644 --- a/src/components/search/SearchResults.tsx +++ b/src/components/search/SearchResults.tsx @@ -9,8 +9,8 @@ import SearchResultsRow from './SearchResultsRow'; type SearchResultsProps = { serverId?: string; - parentId?: string; - collectionType?: string; + parentId?: string | null; + collectionType?: string | null; query?: string; } diff --git a/src/components/search/SearchSuggestions.tsx b/src/components/search/SearchSuggestions.tsx index fee361a162..abc24eb7f6 100644 --- a/src/components/search/SearchSuggestions.tsx +++ b/src/components/search/SearchSuggestions.tsx @@ -22,7 +22,7 @@ const createSuggestionLink = ({ name, href }: { name: string, href: string }) => type SearchSuggestionsProps = { serverId?: string; - parentId?: string; + parentId?: string | null; } const SearchSuggestions: FunctionComponent = ({ serverId = window.ApiClient.serverId(), parentId }: SearchSuggestionsProps) => { diff --git a/src/components/viewManager/viewManager.js b/src/components/viewManager/viewManager.js index 501bd928ae..5073cccf8c 100644 --- a/src/components/viewManager/viewManager.js +++ b/src/components/viewManager/viewManager.js @@ -147,6 +147,15 @@ class ViewManager { }); } + hideView() { + if (currentView) { + dispatchViewEvent(currentView, null, 'viewbeforehide'); + dispatchViewEvent(currentView, null, 'viewhide'); + currentView.classList.add('hide'); + currentView = null; + } + } + tryRestoreView(options, onViewChanging) { if (options.cancel) { return Promise.reject({ cancelled: true }); diff --git a/src/controllers/search.html b/src/controllers/search.html deleted file mode 100644 index e6fa92c0fc..0000000000 --- a/src/controllers/search.html +++ /dev/null @@ -1,2 +0,0 @@ -
-
diff --git a/src/index.html b/src/index.html index f6a4a956c8..d77378d3f8 100644 --- a/src/index.html +++ b/src/index.html @@ -158,6 +158,7 @@
+
diff --git a/src/routes/index.tsx b/src/routes/index.tsx new file mode 100644 index 0000000000..31cb06b8c2 --- /dev/null +++ b/src/routes/index.tsx @@ -0,0 +1,16 @@ +import React from 'react'; +import { Route, Routes } from 'react-router-dom'; + +import SearchPage from './search'; + +const AppRoutes = () => ( + + + } /> + {/* Suppress warnings for unhandled routes */} + + + +); + +export default AppRoutes; diff --git a/src/routes/search.tsx b/src/routes/search.tsx new file mode 100644 index 0000000000..864af6141e --- /dev/null +++ b/src/routes/search.tsx @@ -0,0 +1,40 @@ +import React, { FunctionComponent, useState } from 'react'; +import { useSearchParams } from 'react-router-dom'; + +import Page from '../components/Page'; +import SearchFields from '../components/search/SearchFields'; +import SearchResults from '../components/search/SearchResults'; +import SearchSuggestions from '../components/search/SearchSuggestions'; +import LiveTVSearchResults from '../components/search/LiveTVSearchResults'; +import globalize from '../scripts/globalize'; + +const SearchPage: FunctionComponent = () => { + const [ query, setQuery ] = useState(); + const [ searchParams ] = useSearchParams(); + + return ( + + + {!query && + + } + + + + ); +}; + +export default SearchPage; diff --git a/src/scripts/routes.js b/src/scripts/routes.js index a96ab7a30d..e1f7cd8a3b 100644 --- a/src/scripts/routes.js +++ b/src/scripts/routes.js @@ -308,12 +308,6 @@ import { appRouter } from '../components/appRouter'; type: 'home' }); - defineRoute({ - alias: '/search.html', - path: 'search.html', - pageComponent: 'SearchPage' - }); - defineRoute({ alias: '/list.html', path: 'list.html', diff --git a/src/scripts/site.js b/src/scripts/site.js index bfe40d5045..edf2dab2cd 100644 --- a/src/scripts/site.js +++ b/src/scripts/site.js @@ -7,6 +7,8 @@ import 'classlist.js'; import 'whatwg-fetch'; import 'resize-observer-polyfill'; import '../assets/css/site.scss'; +import React from 'react'; +import * as ReactDOM from 'react-dom'; import { Events } from 'jellyfin-apiclient'; import ServerConnections from '../components/ServerConnections'; import globalize from './globalize'; @@ -18,7 +20,7 @@ import { appHost } from '../components/apphost'; import { getPlugins } from './settings/webSettings'; import { pluginManager } from '../components/pluginManager'; import packageManager from '../components/packageManager'; -import { appRouter } from '../components/appRouter'; +import { appRouter, history } from '../components/appRouter'; import '../elements/emby-button/emby-button'; import './autoThemes'; import './libraryMenu'; @@ -40,6 +42,8 @@ import SyncPlayHtmlVideoPlayer from '../components/syncPlay/ui/players/HtmlVideo import SyncPlayHtmlAudioPlayer from '../components/syncPlay/ui/players/HtmlAudioPlayer'; import { currentSettings } from './settings/userSettings'; import taskButton from './taskbutton'; +import { HistoryRouter } from '../components/HistoryRouter.tsx'; +import AppRoutes from '../routes/index.tsx'; function loadCoreDictionary() { const languages = ['af', 'ar', 'be-by', 'bg-bg', 'bn_bd', 'ca', 'cs', 'cy', 'da', 'de', 'el', 'en-gb', 'en-us', 'eo', 'es', 'es-419', 'es-ar', 'es_do', 'es-mx', 'et', 'fa', 'fi', 'fil', 'fr', 'fr-ca', 'gl', 'gsw', 'he', 'hi-in', 'hr', 'hu', 'id', 'it', 'ja', 'kk', 'ko', 'lt-lt', 'lv', 'mr', 'ms', 'nb', 'nl', 'nn', 'pl', 'pr', 'pt', 'pt-br', 'pt-pt', 'ro', 'ru', 'sk', 'sl-si', 'sq', 'sv', 'ta', 'th', 'tr', 'uk', 'ur_pk', 'vi', 'zh-cn', 'zh-hk', 'zh-tw']; @@ -167,7 +171,14 @@ async function onAppReady() { ServerConnections.currentApiClient()?.ensureWebSocket(); }); - appRouter.start(); + await appRouter.start(); + + ReactDOM.render( + + + , + document.getElementById('reactRoot') + ); if (!browser.tv && !browser.xboxOne && !browser.ps4) { import('../components/nowPlayingBar/nowPlayingBar'); From 1aeb90d323d3c3c943c388cbc0d36b521cafb18e Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Fri, 22 Apr 2022 14:27:28 -0400 Subject: [PATCH 2/9] Add authentication/connection checks for react-router routes --- src/components/ConnectedRoute.tsx | 162 ++++++++++++++++++++++++++++++ src/routes/index.tsx | 10 +- 2 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 src/components/ConnectedRoute.tsx diff --git a/src/components/ConnectedRoute.tsx b/src/components/ConnectedRoute.tsx new file mode 100644 index 0000000000..ce5f639eba --- /dev/null +++ b/src/components/ConnectedRoute.tsx @@ -0,0 +1,162 @@ +import React, { FunctionComponent, useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import globalize from '../scripts/globalize'; + +import alert from './alert'; +import { appRouter } from './appRouter'; +import loading from './loading/loading'; +import ServerConnections from './ServerConnections'; + +enum Routes { + Home = '/home.html', + Login = '/login.html', + SelectServer = '/selectserver.html', + StartWizard = '/wizardstart.html' +} + +// TODO: This should probably be in the SDK +enum ConnectionState { + SignedIn = 'SignedIn', + ServerSignIn = 'ServerSignIn', + ServerSelection = 'ServerSelection', + ServerUpdateNeeded = 'ServerUpdateNeeded' +} + +type ConnectedRouteProps = { + isAdminRoute?: boolean, + isUserRoute?: boolean, + roles?: string[] +}; + +const ConnectedRoute: FunctionComponent = ({ + children, + isAdminRoute = false, + isUserRoute = true +}) => { + const navigate = useNavigate(); + + const [ isLoading, setIsLoading ] = useState(true); + + useEffect(() => { + const bounce = async (connectionResponse: any) => { + switch (connectionResponse.State) { + case ConnectionState.SignedIn: + // Already logged in, bounce to the home page + console.debug('[ConnectedRoute] already logged in, redirecting to home'); + navigate(Routes.Home); + return; + case ConnectionState.ServerSignIn: + // Bounce to the login page + console.debug('[ConnectedRoute] not logged in, redirecting to login page'); + navigate(Routes.Login, { + state: { + serverid: connectionResponse.ApiClient.serverId() + } + }); + return; + case ConnectionState.ServerSelection: + // Bounce to select server page + console.debug('[ConnectedRoute] redirecting to select server page'); + navigate(Routes.SelectServer); + return; + case ConnectionState.ServerUpdateNeeded: + // Show update needed message and bounce to select server page + try { + await alert({ + text: globalize.translate('ServerUpdateNeeded', 'https://github.com/jellyfin/jellyfin'), + html: globalize.translate('ServerUpdateNeeded', 'https://github.com/jellyfin/jellyfin') + }); + } catch (ex) { + console.warn('[ConnectedRoute] failed to show alert', ex); + } + console.debug('[ConnectedRoute] server update required, redirecting to select server page'); + navigate(Routes.SelectServer); + return; + } + + console.warn('[ConnectedRoute] unhandled connection state', connectionResponse.State); + }; + + const validateConnection = async () => { + // Check connection status on initial page load + const firstConnection = appRouter.firstConnectionResult; + appRouter.firstConnectionResult = null; + + if (firstConnection && firstConnection.State !== ConnectionState.SignedIn) { + if (firstConnection.State === ConnectionState.ServerSignIn) { + // Verify the wizard is complete + try { + const infoResponse = await fetch(`${firstConnection.ApiClient.serverAddress()}/System/Info/Public`); + if (!infoResponse.ok) { + throw new Error('Public system info request failed'); + } + const systemInfo = await infoResponse.json(); + if (!systemInfo.StartupWizardCompleted) { + // Bounce to the wizard + console.info('[ConnectedRoute] startup wizard is not complete, redirecting there'); + navigate(Routes.StartWizard); + return; + } + } catch (ex) { + console.error('[ConnectedRoute] checking wizard status failed', ex); + } + } + + // Bounce to the correct page in the login flow + bounce(firstConnection); + return; + } + + // TODO: should exiting the app be handled here? + + const client = ServerConnections.currentApiClient(); + + // If this is a user route, ensure a user is logged in + if ((isAdminRoute || isUserRoute) && !client?.isLoggedIn()) { + try { + console.warn('[ConnectedRoute] unauthenticated user attempted to access user route'); + bounce(await ServerConnections.connect()); + } catch (ex) { + console.warn('[ConnectedRoute] error bouncing from user route', ex); + } + return; + } + + // If this is an admin route, ensure the user has access + if (isAdminRoute) { + try { + const user = await client.getCurrentUser(); + if (!user.Policy.IsAdministrator) { + console.warn('[ConnectedRoute] normal user attempted to access admin route'); + bounce(await ServerConnections.connect()); + return; + } + } catch (ex) { + console.warn('[ConnectedRoute] error bouncing from admin route', ex); + return; + } + } + + setIsLoading(false); + }; + + loading.show(); + validateConnection(); + }, [ isAdminRoute, isUserRoute, navigate ]); + + useEffect(() => { + if (!isLoading) { + loading.hide(); + } + }, [ isLoading ]); + + if (isLoading) { + return null; + } + + return ( + <>{children} + ); +}; + +export default ConnectedRoute; diff --git a/src/routes/index.tsx b/src/routes/index.tsx index 31cb06b8c2..49c8e52a49 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -1,12 +1,20 @@ import React from 'react'; import { Route, Routes } from 'react-router-dom'; +import ConnectedRoute from '../components/ConnectedRoute'; import SearchPage from './search'; const AppRoutes = () => ( - } /> + + + + } + /> {/* Suppress warnings for unhandled routes */} From 05dbeff4733f3f6bf180ceb0d00012e8d86649f5 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Sat, 23 Apr 2022 01:42:42 -0400 Subject: [PATCH 3/9] Fix hashbang route handling for react-router --- src/components/HistoryRouter.tsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/components/HistoryRouter.tsx b/src/components/HistoryRouter.tsx index d789944e03..9b0e64f60a 100644 --- a/src/components/HistoryRouter.tsx +++ b/src/components/HistoryRouter.tsx @@ -1,5 +1,8 @@ import React, { useLayoutEffect } from 'react'; import { HistoryRouterProps, Router } from 'react-router-dom'; +import { Update } from 'history'; + +const normalizePath = (pathname: string) => pathname.replace(/^!/, ''); export function HistoryRouter({ basename, children, history }: HistoryRouterProps) { const [state, setState] = React.useState({ @@ -7,14 +10,27 @@ export function HistoryRouter({ basename, children, history }: HistoryRouterProp location: history.location }); - useLayoutEffect(() => history.listen(setState), [history]); + useLayoutEffect(() => { + const onHistoryChange = (update: Update) => { + if (update.location.pathname.startsWith('!')) { + history.replace(normalizePath(update.location.pathname), update.location.state); + } else { + setState(update); + } + }; + + history.listen(onHistoryChange); + }, [ history ]); return ( From 2e49d2db8b0eb008f9b4adb139c7f3e6bec9003b Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Mon, 25 Apr 2022 12:38:10 -0400 Subject: [PATCH 4/9] Rename ConnectedRoute component --- ...nectedRoute.tsx => ConnectionRequired.tsx} | 65 ++++++++++--------- src/components/HistoryRouter.tsx | 10 +++ src/routes/index.tsx | 6 +- 3 files changed, 48 insertions(+), 33 deletions(-) rename src/components/{ConnectedRoute.tsx => ConnectionRequired.tsx} (66%) diff --git a/src/components/ConnectedRoute.tsx b/src/components/ConnectionRequired.tsx similarity index 66% rename from src/components/ConnectedRoute.tsx rename to src/components/ConnectionRequired.tsx index ce5f639eba..1d127e2e89 100644 --- a/src/components/ConnectedRoute.tsx +++ b/src/components/ConnectionRequired.tsx @@ -1,13 +1,13 @@ import React, { FunctionComponent, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import globalize from '../scripts/globalize'; import alert from './alert'; import { appRouter } from './appRouter'; import loading from './loading/loading'; import ServerConnections from './ServerConnections'; +import globalize from '../scripts/globalize'; -enum Routes { +enum BounceRoutes { Home = '/home.html', Login = '/login.html', SelectServer = '/selectserver.html', @@ -22,33 +22,38 @@ enum ConnectionState { ServerUpdateNeeded = 'ServerUpdateNeeded' } -type ConnectedRouteProps = { - isAdminRoute?: boolean, - isUserRoute?: boolean, - roles?: string[] +type ConnectionRequiredProps = { + isAdminRequired?: boolean, + isUserRequired?: boolean }; -const ConnectedRoute: FunctionComponent = ({ +/** + * A component that ensures a server connection has been established. + * Additional parameters exist to verify a user or admin have authenticated. + * If a condition fails, this component will navigate to the appropriate page. + */ +const ConnectionRequired: FunctionComponent = ({ children, - isAdminRoute = false, - isUserRoute = true + isAdminRequired = false, + isUserRequired = true }) => { const navigate = useNavigate(); const [ isLoading, setIsLoading ] = useState(true); useEffect(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const bounce = async (connectionResponse: any) => { switch (connectionResponse.State) { case ConnectionState.SignedIn: // Already logged in, bounce to the home page - console.debug('[ConnectedRoute] already logged in, redirecting to home'); - navigate(Routes.Home); + console.debug('[ConnectionRequired] already logged in, redirecting to home'); + navigate(BounceRoutes.Home); return; case ConnectionState.ServerSignIn: // Bounce to the login page - console.debug('[ConnectedRoute] not logged in, redirecting to login page'); - navigate(Routes.Login, { + console.debug('[ConnectionRequired] not logged in, redirecting to login page'); + navigate(BounceRoutes.Login, { state: { serverid: connectionResponse.ApiClient.serverId() } @@ -56,8 +61,8 @@ const ConnectedRoute: FunctionComponent = ({ return; case ConnectionState.ServerSelection: // Bounce to select server page - console.debug('[ConnectedRoute] redirecting to select server page'); - navigate(Routes.SelectServer); + console.debug('[ConnectionRequired] redirecting to select server page'); + navigate(BounceRoutes.SelectServer); return; case ConnectionState.ServerUpdateNeeded: // Show update needed message and bounce to select server page @@ -67,14 +72,14 @@ const ConnectedRoute: FunctionComponent = ({ html: globalize.translate('ServerUpdateNeeded', 'https://github.com/jellyfin/jellyfin') }); } catch (ex) { - console.warn('[ConnectedRoute] failed to show alert', ex); + console.warn('[ConnectionRequired] failed to show alert', ex); } - console.debug('[ConnectedRoute] server update required, redirecting to select server page'); - navigate(Routes.SelectServer); + console.debug('[ConnectionRequired] server update required, redirecting to select server page'); + navigate(BounceRoutes.SelectServer); return; } - console.warn('[ConnectedRoute] unhandled connection state', connectionResponse.State); + console.warn('[ConnectionRequired] unhandled connection state', connectionResponse.State); }; const validateConnection = async () => { @@ -93,12 +98,12 @@ const ConnectedRoute: FunctionComponent = ({ const systemInfo = await infoResponse.json(); if (!systemInfo.StartupWizardCompleted) { // Bounce to the wizard - console.info('[ConnectedRoute] startup wizard is not complete, redirecting there'); - navigate(Routes.StartWizard); + console.info('[ConnectionRequired] startup wizard is not complete, redirecting there'); + navigate(BounceRoutes.StartWizard); return; } } catch (ex) { - console.error('[ConnectedRoute] checking wizard status failed', ex); + console.error('[ConnectionRequired] checking wizard status failed', ex); } } @@ -112,27 +117,27 @@ const ConnectedRoute: FunctionComponent = ({ const client = ServerConnections.currentApiClient(); // If this is a user route, ensure a user is logged in - if ((isAdminRoute || isUserRoute) && !client?.isLoggedIn()) { + if ((isAdminRequired || isUserRequired) && !client?.isLoggedIn()) { try { - console.warn('[ConnectedRoute] unauthenticated user attempted to access user route'); + console.warn('[ConnectionRequired] unauthenticated user attempted to access user route'); bounce(await ServerConnections.connect()); } catch (ex) { - console.warn('[ConnectedRoute] error bouncing from user route', ex); + console.warn('[ConnectionRequired] error bouncing from user route', ex); } return; } // If this is an admin route, ensure the user has access - if (isAdminRoute) { + if (isAdminRequired) { try { const user = await client.getCurrentUser(); if (!user.Policy.IsAdministrator) { - console.warn('[ConnectedRoute] normal user attempted to access admin route'); + console.warn('[ConnectionRequired] normal user attempted to access admin route'); bounce(await ServerConnections.connect()); return; } } catch (ex) { - console.warn('[ConnectedRoute] error bouncing from admin route', ex); + console.warn('[ConnectionRequired] error bouncing from admin route', ex); return; } } @@ -142,7 +147,7 @@ const ConnectedRoute: FunctionComponent = ({ loading.show(); validateConnection(); - }, [ isAdminRoute, isUserRoute, navigate ]); + }, [ isAdminRequired, isUserRequired, navigate ]); useEffect(() => { if (!isLoading) { @@ -159,4 +164,4 @@ const ConnectedRoute: FunctionComponent = ({ ); }; -export default ConnectedRoute; +export default ConnectionRequired; diff --git a/src/components/HistoryRouter.tsx b/src/components/HistoryRouter.tsx index 9b0e64f60a..68577dc1d5 100644 --- a/src/components/HistoryRouter.tsx +++ b/src/components/HistoryRouter.tsx @@ -2,8 +2,16 @@ import React, { useLayoutEffect } from 'react'; import { HistoryRouterProps, Router } from 'react-router-dom'; import { Update } from 'history'; +/** Strips leading "!" from paths */ const normalizePath = (pathname: string) => pathname.replace(/^!/, ''); +/** + * A slightly customized version of the HistoryRouter from react-router-dom. + * We need to use HistoryRouter to have a shared history state between react-router and appRouter, but it does not seem + * to be properly exported in the upstream package. + * We also needed some customizations to handle #! routes. + * Refs: https://github.com/remix-run/react-router/blob/v6.3.0/packages/react-router-dom/index.tsx#L222 + */ export function HistoryRouter({ basename, children, history }: HistoryRouterProps) { const [state, setState] = React.useState({ action: history.action, @@ -13,6 +21,7 @@ export function HistoryRouter({ basename, children, history }: HistoryRouterProp useLayoutEffect(() => { const onHistoryChange = (update: Update) => { if (update.location.pathname.startsWith('!')) { + // When the location changes, we need to check for #! paths and replace the location with the "!" stripped history.replace(normalizePath(update.location.pathname), update.location.state); } else { setState(update); @@ -29,6 +38,7 @@ export function HistoryRouter({ basename, children, history }: HistoryRouterProp children={children} location={{ ...state.location, + // The original location does not get replaced with the normalized version, so we need to strip it here pathname: normalizePath(state.location.pathname) }} navigationType={state.action} diff --git a/src/routes/index.tsx b/src/routes/index.tsx index 49c8e52a49..3cc4896874 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Route, Routes } from 'react-router-dom'; -import ConnectedRoute from '../components/ConnectedRoute'; +import ConnectionRequired from '../components/ConnectionRequired'; import SearchPage from './search'; const AppRoutes = () => ( @@ -10,9 +10,9 @@ const AppRoutes = () => ( + - + } /> {/* Suppress warnings for unhandled routes */} From ceb10e2877e86c76e471f0db3c9d5ec469fa00d7 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Mon, 25 Apr 2022 12:53:33 -0400 Subject: [PATCH 5/9] Update current route state for unhandled routes in app router --- src/components/appRouter.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/components/appRouter.js b/src/components/appRouter.js index 7cad70394a..cab40043b1 100644 --- a/src/components/appRouter.js +++ b/src/components/appRouter.js @@ -123,6 +123,10 @@ class AppRouter { }); } else { console.info('[appRouter] "%s" route not found', normalizedPath, location); + this.currentRouteInfo = { + route: {}, + path: normalizedPath + location.search + }; } } From b349d8953475efd106cee83eae8da7e9d74a0c8a Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Tue, 14 Jun 2022 12:48:49 -0400 Subject: [PATCH 6/9] Add options to Page props --- src/components/Page.tsx | 16 +++++++++++----- src/routes/search.tsx | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/components/Page.tsx b/src/components/Page.tsx index 7772e495cd..399c1a55c1 100644 --- a/src/components/Page.tsx +++ b/src/components/Page.tsx @@ -1,16 +1,22 @@ -import React, { FunctionComponent, useEffect, useRef } from 'react'; +import React, { FunctionComponent, HTMLAttributes, useEffect, useRef } from 'react'; import viewManager from './viewManager/viewManager'; type PageProps = { - title?: string + title?: string, + isBackButtonEnabled?: boolean }; /** * Page component that handles hiding active non-react views, triggering the required events for * navigation and appRouter state updates, and setting the correct classes and data attributes. */ -const Page: FunctionComponent = ({ children, title }) => { +const Page: FunctionComponent> = ({ + children, + className = '', + title, + isBackButtonEnabled = true +}) => { const element = useRef(null); useEffect(() => { @@ -38,9 +44,9 @@ const Page: FunctionComponent = ({ children, title }) => {
{children}
diff --git a/src/routes/search.tsx b/src/routes/search.tsx index 864af6141e..cd50e9e0b6 100644 --- a/src/routes/search.tsx +++ b/src/routes/search.tsx @@ -13,7 +13,7 @@ const SearchPage: FunctionComponent = () => { const [ searchParams ] = useSearchParams(); return ( - + {!query && Date: Wed, 15 Jun 2022 10:53:13 -0400 Subject: [PATCH 7/9] Use babel transform for react-router --- webpack.common.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack.common.js b/webpack.common.js index fb0db8f0a5..8d6d702bf6 100644 --- a/webpack.common.js +++ b/webpack.common.js @@ -96,7 +96,7 @@ module.exports = { }, { test: /\.(js|jsx)$/, - exclude: /node_modules[\\/](?!@uupaa[\\/]dynamic-import-polyfill|blurhash|date-fns|epubjs|flv.js|libarchive.js|marked|screenfull)/, + exclude: /node_modules[\\/](?!@uupaa[\\/]dynamic-import-polyfill|blurhash|date-fns|epubjs|flv.js|libarchive.js|marked|react-router|screenfull)/, use: [{ loader: 'babel-loader' }] From 5b5784a448264a10c0f418576d276de28075424c Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Fri, 17 Jun 2022 02:31:13 -0400 Subject: [PATCH 8/9] Fix review issues --- src/components/ConnectionRequired.tsx | 6 ++++-- src/components/HistoryRouter.tsx | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/components/ConnectionRequired.tsx b/src/components/ConnectionRequired.tsx index 1d127e2e89..7ec089af50 100644 --- a/src/components/ConnectionRequired.tsx +++ b/src/components/ConnectionRequired.tsx @@ -96,7 +96,7 @@ const ConnectionRequired: FunctionComponent = ({ throw new Error('Public system info request failed'); } const systemInfo = await infoResponse.json(); - if (!systemInfo.StartupWizardCompleted) { + if (!systemInfo?.StartupWizardCompleted) { // Bounce to the wizard console.info('[ConnectionRequired] startup wizard is not complete, redirecting there'); navigate(BounceRoutes.StartWizard); @@ -104,6 +104,7 @@ const ConnectionRequired: FunctionComponent = ({ } } catch (ex) { console.error('[ConnectionRequired] checking wizard status failed', ex); + return; } } @@ -112,7 +113,8 @@ const ConnectionRequired: FunctionComponent = ({ return; } - // TODO: should exiting the app be handled here? + // TODO: appRouter will call appHost.exit() if navigating back when you are already at the default route. + // This case will need to be handled elsewhere before appRouter can be killed. const client = ServerConnections.currentApiClient(); diff --git a/src/components/HistoryRouter.tsx b/src/components/HistoryRouter.tsx index 68577dc1d5..21e1efe0fe 100644 --- a/src/components/HistoryRouter.tsx +++ b/src/components/HistoryRouter.tsx @@ -13,7 +13,7 @@ const normalizePath = (pathname: string) => pathname.replace(/^!/, ''); * Refs: https://github.com/remix-run/react-router/blob/v6.3.0/packages/react-router-dom/index.tsx#L222 */ export function HistoryRouter({ basename, children, history }: HistoryRouterProps) { - const [state, setState] = React.useState({ + const [state, setState] = React.useState({ action: history.action, location: history.location }); From e2a6f08822e97d47539a6dd280dc4cc636df6884 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Mon, 27 Jun 2022 11:49:56 -0400 Subject: [PATCH 9/9] Fix Page component compatibility issues --- src/components/Page.tsx | 23 ++++++++++++++++++----- src/routes/search.tsx | 6 +++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/components/Page.tsx b/src/components/Page.tsx index 399c1a55c1..be1253740f 100644 --- a/src/components/Page.tsx +++ b/src/components/Page.tsx @@ -3,8 +3,11 @@ import React, { FunctionComponent, HTMLAttributes, useEffect, useRef } from 'rea import viewManager from './viewManager/viewManager'; type PageProps = { + id: string, // id is required for libraryMenu title?: string, - isBackButtonEnabled?: boolean + isBackButtonEnabled?: boolean, + isNowPlayingBarEnabled?: boolean, + isThemeMediaSupported?: boolean }; /** @@ -13,9 +16,12 @@ type PageProps = { */ const Page: FunctionComponent> = ({ children, + id, className = '', title, - isBackButtonEnabled = true + isBackButtonEnabled = true, + isNowPlayingBarEnabled = true, + isThemeMediaSupported = false }) => { const element = useRef(null); @@ -29,20 +35,27 @@ const Page: FunctionComponent> = ({ bubbles: true, cancelable: false, detail: { - isRestored: false + isRestored: false, + options: { + enableMediaControl: isNowPlayingBarEnabled, + supportsThemeMedia: isThemeMediaSupported + } } }; - // pagebeforeshow - hides tabs on tabless pages in libraryMenu + // viewbeforeshow - switches between the admin dashboard and standard themes + element.current?.dispatchEvent(new CustomEvent('viewbeforeshow', event)); + // pagebeforeshow - hides tabs on tables pages in libraryMenu element.current?.dispatchEvent(new CustomEvent('pagebeforeshow', event)); // viewshow - updates state of appRouter element.current?.dispatchEvent(new CustomEvent('viewshow', event)); // pageshow - updates header/navigation in libraryMenu element.current?.dispatchEvent(new CustomEvent('pageshow', event)); - }, [ element ]); + }, [ element, isNowPlayingBarEnabled, isThemeMediaSupported ]); return (
{ const [ searchParams ] = useSearchParams(); return ( - + {!query &&