Skip to content

Commit

Permalink
Fix standalone path and theme
Browse files Browse the repository at this point in the history
  • Loading branch information
dan-lee committed Aug 19, 2024
1 parent 649f1b6 commit 8712d19
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 22 deletions.
5 changes: 4 additions & 1 deletion packages/zudoku/src/app/demo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createBrowserRouter } from "react-router-dom";
import { Bootstrap } from "zudoku/components";
import type { ZudokuConfig } from "../config/validators/validate.js";
import { openApiPlugin } from "../lib/plugins/openapi/index.js";
import { themeToggle } from "../lib/themeToggle.js";
import "../lib/util/logInit.js";
import "./main.css";
import { getRoutesByConfig } from "./main.js";
Expand All @@ -16,6 +17,8 @@ if (!apiUrl) {
);
}

themeToggle();

logger.info(`API URL: ${apiUrl}`);

const root =
Expand Down Expand Up @@ -51,6 +54,6 @@ const config = {

const routes = getRoutesByConfig(config);
const router = createBrowserRouter(routes, {
basename: "/demo",
basename: window.location.pathname,
});
createRoot(root).render(<Bootstrap router={router} />);
2 changes: 1 addition & 1 deletion packages/zudoku/src/app/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import "virtual:zudoku-theme.css";
import { DevPortal, Layout, RouterError } from "zudoku/components";
import { isNavigationPlugin } from "zudoku/internal";
import { customPagePlugin } from "zudoku/plugins/custom-page";
import { inkeepSearchPlugin } from "zudoku/plugins/search-inkeep";
import type { ZudokuConfig } from "../config/config.js";
import type { ZudokuContextOptions } from "../lib/core/DevPortalContext.js";
import { inkeepSearchPlugin } from "../lib/plugins/search-inkeep/index.js";

export const convertZudokuConfigToOptions = (
config: ZudokuConfig,
Expand Down
5 changes: 4 additions & 1 deletion packages/zudoku/src/app/standalone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createBrowserRouter } from "react-router-dom";
import { Bootstrap } from "zudoku/components";
import type { ZudokuConfig } from "../config/validators/validate.js";
import { openApiPlugin } from "../lib/plugins/openapi/index.js";
import { themeToggle } from "../lib/themeToggle.js";
import "../lib/util/logInit.js";
import "./main.css";
import { getRoutesByConfig } from "./main.js";
Expand All @@ -12,6 +13,8 @@ if (!root) {
throw new Error("No div found with attribute data-api-url");
}

themeToggle();

const apiUrl = root.getAttribute("data-api-url");
const pageTitle = document.getElementsByTagName("title")[0].innerText;
const logoUrl = root.getAttribute("data-logo-url");
Expand Down Expand Up @@ -50,6 +53,6 @@ const config = {

const routes = getRoutesByConfig(config);
const router = createBrowserRouter(routes, {
basename: "/standalone",
basename: window.location.pathname,
});
createRoot(root).render(<Bootstrap router={router} />);
5 changes: 3 additions & 2 deletions packages/zudoku/src/lib/components/navigation/SidebarItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { cva } from "class-variance-authority";
import { ExternalLinkIcon } from "lucide-react";
import { NavLink } from "react-router-dom";
import { NavLink, useSearchParams } from "react-router-dom";

import type { SidebarItem as SidebarItemType } from "../../../config/validators/SidebarSchema.js";
import { cn } from "../../util/cn.js";
Expand Down Expand Up @@ -42,6 +42,7 @@ export const SidebarItem = ({
}) => {
const topNavItem = useTopNavigationItem();
const { activeAnchor } = useViewportAnchor();
const [searchParams] = useSearchParams();

switch (item.type) {
case "category":
Expand Down Expand Up @@ -69,7 +70,7 @@ export const SidebarItem = ({
case "link":
return item.href.startsWith("#") ? (
<AnchorLink
to={item.href}
to={{ hash: item.href, search: searchParams.toString() }}
{...{ [DATA_ANCHOR_ATTR]: item.href.slice(1) }}
className={cn(
"flex gap-2.5 justify-between",
Expand Down
7 changes: 7 additions & 0 deletions packages/zudoku/src/lib/themeToggle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const themeToggle = () => {
const isDarkMode =
localStorage.getItem("theme") === "dark" ||
(!localStorage.getItem("theme") &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", isDarkMode);
};
6 changes: 4 additions & 2 deletions packages/zudoku/src/vite/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { writeFile } from "fs/promises";
import { build as viteBuild } from "vite";
import { createServer as createViteServer, build as viteBuild } from "vite";
import { getViteConfig } from "./config.js";
import { getBuildHtml } from "./html.js";
import { prerender } from "./prerender.js";
Expand Down Expand Up @@ -32,13 +32,15 @@ export async function runBuild(options: { dir: string }) {
o.fileName.endsWith(".css"),
)?.fileName;

const vite = await createViteServer(viteServerConfig);

const html = getBuildHtml({
jsEntry: `/${jsEntry}`,
cssEntry: `/${cssEntry}`,
});

try {
const writtenFiles = await prerender(html, options.dir);
const writtenFiles = await prerender(vite, html, options.dir);

if (writtenFiles.includes("index.html")) {
return;
Expand Down
12 changes: 0 additions & 12 deletions packages/zudoku/src/vite/html.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,10 @@
const themeScript = `if (
localStorage.getItem("theme") === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}`;

export function getDevHtml(jsEntry: string) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--app-helmet-->
<script type="module">${themeScript}</script>
<link rel="preconnect" href="https://cdn.zudoku.dev/">
</head>
<body>
Expand All @@ -41,7 +30,6 @@ export function getBuildHtml({
<script type="module" crossorigin src="${jsEntry}"></script>
<link rel="stylesheet" crossorigin href="${cssEntry}">
<!--app-helmet-->
<script type="module">${themeScript}</script>
<link rel="preconnect" href="https://cdn.zudoku.dev/">
</head>
<body>
Expand Down
17 changes: 17 additions & 0 deletions packages/zudoku/src/vite/plugin-html-transform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Plugin } from "vite";
import { ZudokuPluginOptions } from "../config/config.js";
import { themeToggle } from "../lib/themeToggle.js";

export const viteHtmlTransform = (_config: ZudokuPluginOptions): Plugin => {
return {
name: "zudoku-html-transform",
transformIndexHtml: () => [
{
tag: "script",
attrs: { type: "module" },
injectTo: "head",
children: `(${themeToggle.toString()})();`,
},
],
};
};
2 changes: 2 additions & 0 deletions packages/zudoku/src/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import viteAliasPlugin from "./plugin-component.js";
import viteConfigPlugin from "./plugin-config.js";
import viteCustomCss from "./plugin-custom-css.js";
import viteDocsPlugin from "./plugin-docs.js";
import { viteHtmlTransform } from "./plugin-html-transform.js";
import viteMdxPlugin from "./plugin-mdx.js";
import viteRedirectPlugin from "./plugin-redirect.js";
import { viteSidebarPlugin } from "./plugin-sidebar.js";
Expand All @@ -27,5 +28,6 @@ export default function vitePlugin(
viteAliasPlugin(config),
viteRedirectPlugin(config),
viteCustomCss(config),
viteHtmlTransform(config),
];
}
11 changes: 9 additions & 2 deletions packages/zudoku/src/vite/prerender.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from "node:fs/promises";
import path from "node:path";
import type { ViteDevServer } from "vite";
import {
type getRoutesByConfig,
type render as serverRender,
Expand Down Expand Up @@ -65,7 +66,11 @@ const routesToPaths = (routes: ReturnType<typeof getRoutesByConfig>) => {
return paths;
};

export const prerender = async (html: string, dir: string) => {
export const prerender = async (
vite: ViteDevServer,
html: string,
dir: string,
) => {
// eslint-disable-next-line no-console
console.log("Prerendering...");
const config = await import(
Expand All @@ -88,7 +93,9 @@ export const prerender = async (html: string, dir: string) => {

const response = new FileWritingResponse(path.join(dir, "dist/", filename));

await render({ template: html, request: req, response, config });
const template = await vite.transformIndexHtml(urlPath, html);

await render({ template, request: req, response, config });
await response.isSent();
writtenFiles.push(filename);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/zudoku/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
],
"zudoku/plugins/custom-page": ["src/lib/plugins/custom-page/index.tsx"],
"zudoku/plugins/openapi": ["src/lib/plugins/openapi/index.ts"],
"zudoku/plugins/search-inkeep": ["src/lib/plugins/search-inkeep/index.ts"]
"zudoku/plugins/search-inkeep": [
"src/lib/plugins/search-inkeep/index.tsx"
]
}
},
"exclude": ["node_modules", "dist"],
Expand Down

0 comments on commit 8712d19

Please sign in to comment.