Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement SSR langservice #106

Merged
merged 3 commits into from
Jul 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions example-ssr/src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react"
import { Link, Stack } from "../../../src"
import React from "react";
import { Link, Stack } from "../../../src";

export function App() {
const crossedTransitions = ({
Expand All @@ -8,28 +8,30 @@ export function App() {
unmountPreviousPage,
}): Promise<void> => {
return new Promise(async (resolve) => {
const $current = currentPage?.$element
if ($current) $current.style.visibility = "hidden"
const $current = currentPage?.$element;
if ($current) $current.style.visibility = "hidden";
if (previousPage) {
previousPage.playOut()
previousPage.playOut();
}
if (currentPage) {
await currentPage.isReadyPromise()
if ($current) $current.style.visibility = "visible"
await currentPage.playIn()
unmountPreviousPage()
await currentPage.isReadyPromise();
if ($current) $current.style.visibility = "visible";
await currentPage.playIn();
unmountPreviousPage();
}
resolve()
})
}
resolve();
});
};

return (
<div className={"App"}>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link> |{" "} | <Link to="/article/my-article-1">Article 1</Link> |{" "}
<Link to="/contact">Contact</Link>
<Link to={{ name: "Home" }}>Home</Link> |{" "}
<Link to={{ name: "About" }}>About</Link> |{" "}
<Link to={{ name: "Article", params: { slug: "article-1" } }}>Article 1</Link> |{" "}
<Link to={{ name: "Contact" }}>Contact</Link>
</nav>
<Stack manageTransitions={crossedTransitions} />
<Stack manageTransitions={crossedTransitions} />
</div>
)
);
}
20 changes: 16 additions & 4 deletions example-ssr/src/index-server.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
import "isomorphic-unfetch";
import * as React from "react";
import ReactDOMServer from "react-dom/server";
import { routes } from "./routes";
import { App } from "./components/App";
import { Router, TRoute } from "../../src";
import { LangService, Router, TRoute } from "../../src";
import { getNotFoundRoute, getRouteFromUrl } from "../../src/core/matcher";
import { formatRoutes } from "../../src/core/helpers";
import { GlobalDataContext } from "./GlobalDataContext";
import 'isomorphic-unfetch';
import languages from "./languages";

export async function render(url) {
/**
* 1. savoir quel composant je dois rendre dans mon router
*/
const langService = new LangService({
staticLocation: url,
languages,
});

const matchingRoute = getRouteFromUrl({
pUrl: url,
pBase: "/",
pRoutes: formatRoutes(routes),
pRoutes: formatRoutes(routes, null, langService),
});

const notFoundRoute = getNotFoundRoute(routes);
if (!matchingRoute && !notFoundRoute) {
console.error("matchingRoute not found & 'notFoundRoute' not found, return.");
Expand Down Expand Up @@ -52,7 +59,12 @@ export async function render(url) {
*/
return {
renderToString: ReactDOMServer.renderToString(
<Router routes={routes} staticLocation={url} initialStaticProps={SSR_STATIC_PROPS}>
<Router
routes={routes}
staticLocation={url}
initialStaticProps={SSR_STATIC_PROPS}
langService={langService}
>
{/* Provide Global data */}
<GlobalDataContext.Provider value={{ globalData: GLOBAL_DATA }}>
<App />
Expand Down
8 changes: 7 additions & 1 deletion example-ssr/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import { App } from "./components/App";
import { routes } from "./routes";
import { createBrowserHistory } from "history";
import "./index.css";
import { Router } from "../../src";
import { LangService, Router } from "../../src";
import { GlobalDataContext } from "./GlobalDataContext";
import languages from "./languages";

const langService = new LangService({
languages,
});

/**
* Client side
Expand All @@ -16,6 +21,7 @@ const root = hydrateRoot(
routes={routes}
history={createBrowserHistory()}
initialStaticProps={window["__SSR_STATIC_PROPS__"]}
langService={langService}
>
<GlobalDataContext.Provider value={{ globalData: window["__GLOBAL_DATA__"] }}>
<App />
Expand Down
1 change: 1 addition & 0 deletions example-ssr/src/languages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default [{ key: "fr" }, { key: "en" }]
29 changes: 14 additions & 15 deletions example-ssr/src/pages/HomePage.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import React, {useState, useRef, useEffect, useContext} from "react"
import { useStack } from "../../../src"
import { transitionsHelper } from "../helpers/transitionsHelper"
import {GlobalDataContext} from "../GlobalDataContext";
import React, { useState, useRef, useEffect, useContext } from "react";
import { useStack } from "../../../src";
import { transitionsHelper } from "../helpers/transitionsHelper";
import { GlobalDataContext } from "../GlobalDataContext";

const componentName = "HomePage"
const componentName = "HomePage";
function HomePage(props, handleRef) {
const rootRef = useRef(null)
const [n, setN] = useState(0)
const {globalData} = useContext(GlobalDataContext)

console.log('HOME props ', props)
console.log("Global data", globalData)
const rootRef = useRef(null);
const [n, setN] = useState(0);
const { globalData } = useContext(GlobalDataContext);

useStack({
componentName,
handleRef,
rootRef,
playIn: () => transitionsHelper(rootRef.current, true, { x: -50 }, { x: 0 }),
playOut: () => transitionsHelper(rootRef.current, false, { x: -0 }, { x: 50 }),
})
});

return (
<div className={componentName} ref={rootRef}>
Expand All @@ -28,9 +25,11 @@ function HomePage(props, handleRef) {
HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME HOME
<br />
<button onClick={() => setN(n + 1)}>+ {n}</button>
{globalData.users.map((user,i) => <p key={i}>{user.name}</p>)}
{globalData.users.map((user, i) => (
<p key={i}>{user.name}</p>
))}
</div>
)
);
}

export default React.forwardRef(HomePage)
export default React.forwardRef(HomePage);
27 changes: 19 additions & 8 deletions src/components/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import debug from "@wbe/debug";
import { BrowserHistory, HashHistory, MemoryHistory } from "history";
import { Match } from "path-to-regexp";
import React from "react";
import { formatRoutes } from "../core/helpers";
import { formatRoutes, isSSR } from "../core/helpers";
import { getNotFoundRoute, getRouteFromUrl } from "../core/matcher";
import { Routers } from "../core/Routers";
import LangService from "../core/LangService";
Expand Down Expand Up @@ -125,10 +125,18 @@ function Router(props: {
* const { routes } = useRouter();
* return current Router instance routes list, not all routes given to the first instance.
*/
const routes = React.useMemo(
() => formatRoutes(props.routes, props.middlewares, langService, props.id),
[props.routes, langService, props.middlewares, props.id]
);
const routes = React.useMemo(() => {
const routesList = formatRoutes(
props.routes,
props.middlewares,
langService,
props.id
);

// if is first instance, register result in Routers
if (!Routers.routes) Routers.routes = routesList;
return routesList;
}, [props.routes, langService, props.middlewares, props.id]);

/**
* 2. base
Expand Down Expand Up @@ -252,7 +260,7 @@ function Router(props: {

// if no newRoute, do not continue
if (!newRoute) return;

if (props.initialStaticProps) {
const cache = staticPropsCache();

Expand All @@ -262,10 +270,13 @@ function Router(props: {
// first route visited (server & client)
const isFirstRouteVisited = newRoute.name === props.initialStaticProps.name;

// In SSR context, we have to manage getStaticProps route properties from server and client
if (isFirstRouteVisited) {
Object.assign(newRoute.props, props.initialStaticProps.props);
if (newRoute.props) {
Object.assign(newRoute.props, props.initialStaticProps?.props ?? {});
}
if (!dataFromCache) {
cache.set(newRoute.fullUrl, props.initialStaticProps.props);
cache.set(newRoute.fullUrl, props.initialStaticProps?.props ?? {});
}
}
// if NOT first route (client)
Expand Down
30 changes: 24 additions & 6 deletions src/core/LangService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Routers } from "../core/Routers";
import { Routers } from "./Routers";
import {
compileUrl,
createUrl,
joinPaths,
removeLastCharFromString,
} from "../core/helpers";
import debug from "@wbe/debug";
getLangPathByLang,
isSSR,
} from "./helpers";
import { TRoute } from "../components/Router";
import { getLangPathByLang } from "../core/helpers";
import debug from "@wbe/debug";

const log = debug(`router:LangService`);

Expand Down Expand Up @@ -48,27 +49,36 @@ class LangService<TLang = any> {
*/
public base: string;

/**
* Static Location used for SSR context
*/
public staticLocation: string;

/**
* Init languages service
* @param languages
* @param showDefaultLangInUrl
* @param base
* @param staticLocation
*/
public constructor({
languages,
showDefaultLangInUrl = true,
base = "/",
staticLocation,
}: {
languages: TLanguage<TLang>[];
showDefaultLangInUrl?: boolean;
base?: string;
staticLocation?: string;
}) {
if (languages?.length === 0) {
throw new Error("ERROR, no language is set.");
}
this.languages = languages;
// remove extract / at the end, if exist
this.base = removeLastCharFromString(base, "/", true);
this.staticLocation = staticLocation;
this.defaultLang = this.getDefaultLang(languages);
this.currentLang = this.getLangFromUrl() || this.defaultLang;
this.showDefaultLangInUrl = showDefaultLangInUrl;
Expand Down Expand Up @@ -232,7 +242,12 @@ class LangService<TLang = any> {
routes: TRoute[],
showLangInUrl = this.showLangInUrl()
): TRoute[] {
if (!this.isInit) return routes;
if (routes?.some((el) => !!el.langPath)) {
log(
"Routes have already been formatted by 'addLangParamToRoutes()', return routes."
);
return routes;
}

/**
* Add :lang param on path
Expand Down Expand Up @@ -308,7 +323,9 @@ class LangService<TLang = any> {
* Get current language from URL
* @param pathname
*/
protected getLangFromUrl(pathname = window.location.pathname): TLanguage<TLang> {
protected getLangFromUrl(
pathname = this.staticLocation ?? window.location.pathname
): TLanguage<TLang> {
let pathnameWithoutBase = pathname.replace(this.base, "/");
const firstPart = joinPaths([pathnameWithoutBase]).split("/")[1];

Expand All @@ -335,6 +352,7 @@ class LangService<TLang = any> {
* @protected
*/
protected reloadOrRefresh(newUrl: string, forcePageReload = true): void {
if (isSSR()) return;
forcePageReload ? window?.open(newUrl, "_self") : Routers.history.push(newUrl);
}
}
Expand Down
22 changes: 16 additions & 6 deletions src/core/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export function getSubRouterRoutes(
* openRoute push a route in history
* the Stack component will render the new route
* @param args can be string or TOpenRouteParams object
* @param availablesRoutes
* @param history
*/
export function openRoute(args: string | TOpenRouteParams, history = Routers?.history) {
const url = typeof args === "string" ? args : createUrl(args);
Expand All @@ -169,16 +169,19 @@ export function formatRoutes(
console.error(id, "props.routes is missing or empty, return.");
return;
}

// For each instances
let routesList = patchMissingRootRoute(routes);

// Only for first instance
if (!Routers.routes) {
// subRouter instances shouldn't inquired middlewares and LangService
if (middlewares) {
routesList = applyMiddlewares(routesList, middlewares);
if (langService) routesList = langService.addLangParamToRoutes(routesList);
Routers.routes = routesList;
}
log(id, "routesList", routesList);
// Only for first instance
if (langService) {
routesList = langService.addLangParamToRoutes(routesList);
}

return routesList;
}

Expand Down Expand Up @@ -507,3 +510,10 @@ export function removeBaseToUrl(path: string, base: string): string {
let baseStartIndex = path.indexOf(base);
return baseStartIndex == 0 ? path.substr(base.length, path.length) : path;
}

/**
* Check if we are in SRR context
*/
export function isSSR() {
return !(typeof window != "undefined" && window.document);
}