Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(share-theme): let each script import its own stylesheet
Elian Doran3a21bf34f754
diff --git a/apps/server/src/types.d.ts b/apps/server/src/types.d.tsindex 7d0f442bf4..ffd492727a 100644--- a/apps/server/src/types.d.ts+++ b/apps/server/src/types.d.ts@@ -19,11 +19,6 @@ declare module "@triliumnext/share-theme/*.ejs" {export default content;}-declare module "@triliumnext/share-theme/styles.css" {- const content: string;- export default content;-}-declare module "archiver" {import { Transform } from "stream";import { ZlibOptions } from "zlib";diff --git a/apps/standalone/e2e/share.spec.ts b/apps/standalone/e2e/share.spec.tsindex 8c25661b20..6a4b964ac7 100644--- a/apps/standalone/e2e/share.spec.ts+++ b/apps/standalone/e2e/share.spec.ts@@ -35,7 +35,7 @@ test("renders a published note, its tree and the share theme", async ({ context// The theme's stylesheet is copied into the build rather than answered by a route, so a missing// copy step would leave the page unstyled instead of failing outright.- const stylesStatus = await share.evaluate(async () => (await fetch("/share/assets/styles.css")).status);+ const stylesStatus = await share.evaluate(async () => (await fetch("/share/assets/scripts.css")).status);expect(stylesStatus).toBe(200);});diff --git a/docs/Developer Guide/Developer Guide/Concepts/Share.md b/docs/Developer Guide/Developer Guide/Concepts/Share.mdindex 701621077c..1f3b7b1931 100644--- a/docs/Developer Guide/Developer Guide/Concepts/Share.md+++ b/docs/Developer Guide/Developer Guide/Concepts/Share.md@@ -5,7 +5,9 @@ The share theme represents the layout, styles and scripts behind the Share notes* The theme resides in `packages/share-theme`.* The HTML is defined in `src/templates` using EJS templating.-* The `src/scripts` and `src/styles` subdirectories house the rest of the theme.+* `src/page` holds the parts of the page around the note (layout, header, navigation tree, theme switch, search, table of contents, footer) and `src/content` the styles and scripts for the note's own content (math, Mermaid, link embeds, adaptive colors). A script imports its own stylesheet, which sits next to it under the same name: `toc.ts` imports `./toc.css`.+* `src/index.ts` is the single entry point. It sets every script up and imports the stylesheets that have no script; the order of its imports is the order of the bundled stylesheet.+* The build emits `dist/scripts.js` and `dist/scripts.css`, the only stylesheet a shared page loads (`#shareOmitDefaultCss` drops it).## Building the share theme@@ -13,7 +15,7 @@ The share theme represents the layout, styles and scripts behind the Share notes* Alternatively, use `pnpm dev` to watch for changes.* `pnpm dist` is the same build, minified. It is what the app builds run, so a release ships the minified assets while local development keeps readable ones.-Both scripts clear `dist` first, since esbuild writes into it without removing what an earlier build left there — a minified release build would otherwise be copied alongside the unminified files `pnpm install` produces. A `--module=` build (`build-scripts`, `build-styles`) builds one entry point and deliberately does not clear, so it leaves the other's output alone.+Both scripts clear `dist` first, since esbuild writes into it without removing what an earlier build left there — a minified release build would otherwise be copied alongside the unminified files `pnpm install` produces.## Where the code livesdiff --git a/packages/share-theme/README.md b/packages/share-theme/README.mdindex 6b38724acf..7957c60eb5 100644--- a/packages/share-theme/README.md+++ b/packages/share-theme/README.md@@ -3,7 +3,7 @@The default theme for [shared notes](../../docs/User%20Guide/User%20Guide/Advanced%20Usage/Sharing.md) and for the static HTML export. It started as the theme of [trilium.rocks](https://trilium.rocks) by [Zerebos](https://github.com/zerebos).- `src/templates/` — the EJS templates. `packages/trilium-core/src/share/content_renderer.ts` renders them on the server; a note can replace `page.ejs` with its own through `~shareTemplate`.-- `src/page/` — the parts of the page around the note (layout, header, navigation tree, search, table of contents, footer), and `src/content/` — the styles and enhancements for the note's own content (math, Mermaid, link embeds, adaptive colors). A part's script and stylesheet share a name and a folder: `toc.ts`, `toc.css`.-- `src/index.ts` and `src/index.css` — the two entry points. `index.ts` sets every script up; `index.css` imports every stylesheet, and its order is the cascade order.+- `src/page/` — the parts of the page around the note (layout, header, navigation tree, search, table of contents, footer), and `src/content/` — the styles and enhancements for the note's own content (math, Mermaid, link embeds, adaptive colors). A script imports its own stylesheet, which shares its name and folder: `toc.ts` imports `./toc.css`.+- `src/index.ts` — the entry point. It sets every script up and imports the stylesheets that have no script; the order of its imports is the cascade order.-`pnpm --filter share-theme build` bundles them into `dist/` (`scripts.js`, `styles.css`, and `scripts.css` for the third-party styles `index.ts` imports), which the server, desktop, standalone and static-export builds copy. `pnpm install` runs it, but no `*:start` script does, so rebuild after changing a script or style (or run `pnpm --filter share-theme dev` to watch).+`pnpm --filter share-theme build` bundles them into `dist/scripts.js` and `dist/scripts.css`, which the server, desktop, standalone and static-export builds copy. `pnpm install` runs it, but no `*:start` script does, so rebuild after changing a script or style (or run `pnpm --filter share-theme dev` to watch).diff --git a/packages/share-theme/package.json b/packages/share-theme/package.jsonindex 0d5943b386..e91b71bb05 100644--- a/packages/share-theme/package.json+++ b/packages/share-theme/package.json@@ -6,8 +6,6 @@"scripts": {"dev": "esrun scripts/build.ts -- --watch","build": "esrun scripts/build.ts",- "build-scripts": "esrun scripts/build.ts -- --module=scripts",- "build-styles": "esrun scripts/build.ts -- --module=styles","dist": "esrun scripts/build.ts -- --minify","test": "vitest run"},diff --git a/packages/share-theme/scripts/build.ts b/packages/share-theme/scripts/build.tsindex 390496e310..3a553005f5 100644--- a/packages/share-theme/scripts/build.ts+++ b/packages/share-theme/scripts/build.ts@@ -6,38 +6,11 @@ import { createRequire } from "node:module";import { pathToFileURL } from "node:url";import * as sass from "sass";-const rootDir = path.dirname(process.env.npm_package_json!);--const modules = ["scripts", "styles"];-const entryPoints: {in: string, out: string}[] = [];--function makeEntry(mod: string) {- let entrypoint: string;- switch (mod) {- case "styles":- entrypoint = "index.css";- break;- case "scripts":- entrypoint = "index.ts";- break;- default:- throw new Error(`Unknown module type ${mod}.`);- }-- return {- "in": path.join(rootDir, "src", entrypoint),- "out": mod- };+const packageJson = process.env.npm_package_json;+if (!packageJson) {+ throw new Error("Run the build through pnpm, which sets npm_package_json.");}--const modulesRequested = process.argv.filter(a => a.startsWith("--module="));-for (const mod of modulesRequested) {- const module = mod?.replace("--module=", "") ?? "";- if (modules.includes(module)) entryPoints.push(makeEntry(module));-}--if (!entryPoints.length) for (const mod of modules) entryPoints.push(makeEntry(mod));-+const rootDir = path.dirname(packageJson);// Sass resolves relative paths on its own; bare specifiers such as// "katex/src/styles/katex.scss" go through Node.@@ -71,14 +44,11 @@ async function runBuild(watch: boolean) {// esbuild leaves its outdir as it found it, and every `pnpm install` writes an unminified// build there, so a minified release build would land beside those files and both sets would- // be copied into the app. A partial build must not clean: `--module=` builds one of the two- // entry points and would otherwise delete the other's output.- if (!modulesRequested.length) {- rmSync(outDir, { recursive: true, force: true });- }+ // be copied into the app.+ rmSync(outDir, { recursive: true, force: true });const opts: esbuild.BuildOptions = {- entryPoints: entryPoints,+ entryPoints: [ { in: path.join(rootDir, "src", "index.ts"), out: "scripts" } ],bundle: true,splitting: true,outdir: outDir,diff --git a/packages/share-theme/src/content/favicon_contrast.ts b/packages/share-theme/src/content/favicon_contrast.tsdeleted file mode 100644index 7169517b66..0000000000--- a/packages/share-theme/src/content/favicon_contrast.ts+++ /dev/null@@ -1,39 +0,0 @@-import {- classifyFaviconContrast,- faviconContrastClass,- measureFaviconVisibility-} from "@triliumnext/commons/src/lib/favicon_contrast.js";--/**- * Corrects link-preview favicons that would be invisible against the page.- *- * A site draws its icon for one background, usually its own: GitHub's is a black octocat on nothing,- * which disappears on the dark theme, and a mark drawn white for a dark header disappears on the- * light one. Each icon's own pixels are measured (the shared logic lives in commons, so the app and- * the shared page reach the same verdict about the same picture) and the answer is left on the- * element as a class for `link_embed.css` to act on — which is what lets the visitor's theme switch- * correct the icons with nothing measured again.- */-export default function setupFaviconContrast() {- for (const favicon of document.querySelectorAll<HTMLImageElement>("img.link-embed-mention-favicon")) {- // A picture already in the browser's cache is complete before this runs and will never fire- // `load`; one still arriving has to be waited for.- if (favicon.complete) {- classify(favicon);- } else {- favicon.addEventListener("load", () => classify(favicon), { once: true });- }- }-}--function classify(favicon: HTMLImageElement) {- const visibility = measureFaviconVisibility(favicon);- if (!visibility) {- return;- }-- const contrastClass = faviconContrastClass(classifyFaviconContrast(visibility));- if (contrastClass) {- favicon.classList.add(contrastClass);- }-}diff --git a/packages/share-theme/src/content/link_embed.ts b/packages/share-theme/src/content/link_embed.tsnew file mode 100644index 0000000000..dce99b5aad--- /dev/null+++ b/packages/share-theme/src/content/link_embed.ts@@ -0,0 +1,74 @@+import {+ classifyFaviconContrast,+ faviconContrastClass,+ measureFaviconVisibility+} from "@triliumnext/commons/src/lib/favicon_contrast.js";+import "./link_embed.css";++export default function setupLinkEmbeds() {+ setupVideoFacades();+ setupFaviconContrast();+}++/**+ * Click-to-play for the link-preview video embeds.+ *+ * The shared page ships only the thumbnail stored in the note (see the share content renderer), so+ * reading a page that contains a video does not tell YouTube that the visitor read it. The player is+ * loaded here, on the visitor's own click — which doubles as the play command, hence `autoplay=1`.+ */+function setupVideoFacades() {+ const facades = document.querySelectorAll<HTMLButtonElement>(".link-embed-video-facade[data-video-id]");++ for (const facade of facades) {+ facade.addEventListener("click", () => {+ const videoId = facade.dataset.videoId;+ const container = facade.parentElement;+ if (!videoId || !container) {+ return;+ }++ const iframe = document.createElement("iframe");+ iframe.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(videoId)}?rel=0&autoplay=1`;+ iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";+ iframe.referrerPolicy = "strict-origin-when-cross-origin";+ iframe.allowFullscreen = true;++ container.replaceChildren(iframe);+ });+ }+}++/**+ * Corrects link-preview favicons that would be invisible against the page.+ *+ * A site draws its icon for one background, usually its own: GitHub's is a black octocat on nothing,+ * which disappears on the dark theme, and a mark drawn white for a dark header disappears on the+ * light one. Each icon's own pixels are measured (the shared logic lives in commons, so the app and+ * the shared page reach the same verdict about the same picture) and the answer is left on the+ * element as a class for `link_embed.css` to act on — which is what lets the visitor's theme switch+ * correct the icons with nothing measured again.+ */+function setupFaviconContrast() {+ for (const favicon of document.querySelectorAll<HTMLImageElement>("img.link-embed-mention-favicon")) {+ // A picture already in the browser's cache is complete before this runs and will never fire+ // `load`; one still arriving has to be waited for.+ if (favicon.complete) {+ classifyFavicon(favicon);+ } else {+ favicon.addEventListener("load", () => classifyFavicon(favicon), { once: true });+ }+ }+}++function classifyFavicon(favicon: HTMLImageElement) {+ const visibility = measureFaviconVisibility(favicon);+ if (!visibility) {+ return;+ }++ const contrastClass = faviconContrastClass(classifyFaviconContrast(visibility));+ if (contrastClass) {+ favicon.classList.add(contrastClass);+ }+}diff --git a/packages/share-theme/src/content/video_facade.ts b/packages/share-theme/src/content/video_facade.tsdeleted file mode 100644index f87f053c44..0000000000--- a/packages/share-theme/src/content/video_facade.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * Click-to-play for the link-preview video embeds.- *- * The shared page ships only the thumbnail stored in the note (see the share content renderer), so- * reading a page that contains a video does not tell YouTube that the visitor read it. The player is- * loaded here, on the visitor's own click — which doubles as the play command, hence `autoplay=1`.- */-export default function setupVideoFacades() {- const facades = document.querySelectorAll<HTMLButtonElement>(".link-embed-video-facade[data-video-id]");-- for (const facade of facades) {- facade.addEventListener("click", () => {- const videoId = facade.dataset.videoId;- const container = facade.parentElement;- if (!videoId || !container) {- return;- }-- const iframe = document.createElement("iframe");- iframe.src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(videoId)}?rel=0&autoplay=1`;- iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";- iframe.referrerPolicy = "strict-origin-when-cross-origin";- iframe.allowFullscreen = true;-- container.replaceChildren(iframe);- });- }-}diff --git a/packages/share-theme/src/index.css b/packages/share-theme/src/index.cssdeleted file mode 100644index 0460fc75ed..0000000000--- a/packages/share-theme/src/index.css+++ /dev/null@@ -1,17 +0,0 @@-@import "./base.css";--@import "./page/layout.css";-@import "./page/header.css";-@import "./page/navigation.css";-@import "./page/theme_switch.css";-@import "./page/search.css";-@import "./page/toc.css";-@import "./page/child_links.css";-@import "./page/footer.css";--@import "./content/content.css";-@import "./content/footnotes.css";-@import "./content/external_links.css";-@import "./content/task_states.css";-@import "./content/adaptive_colors.css";-@import "./content/link_embed.css";diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex c352973cec..c3401f7666 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -1,14 +1,23 @@-import setupToC from "./page/toc.js";-import setupExpanders from "./page/navigation.js";+// The order of these imports is the order of the bundled stylesheet: a module's CSS is emitted+// where the module is first imported.+import "./base.css";import setupLayout from "./page/layout.js";-import setupSearch from "./page/search.js";+import "./page/header.css";+import setupExpanders from "./page/navigation.js";import setupThemeSelector from "./page/theme_switch.js";-import setupMermaid from "./content/mermaid.js";+import setupSearch from "./page/search.js";+import setupToC from "./page/toc.js";+import "./page/child_links.css";+import "./page/footer.css";+import "./content/content.css";+import "./content/footnotes.css";+import "./content/external_links.css";+import "./content/task_states.css";+import "./content/adaptive_colors.css";+import setupLinkEmbeds from "./content/link_embed.js";import setupMath from "./content/math.js";-import setupVideoFacades from "./content/video_facade.js";-import setupFaviconContrast from "./content/favicon_contrast.js";+import setupMermaid from "./content/mermaid.js";import api from "./api.js";-// These go to `scripts.css`, which the page loads after `styles.css` (built from `index.css`).import "highlight.js/styles/default.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";import "@triliumnext/ckeditor5/src/theme/tabs.css";@@ -35,8 +44,7 @@ $try(setupSearch);function setupTextNote() {$try(setupMermaid);$try(setupMath);- $try(setupVideoFacades);- $try(setupFaviconContrast);+ $try(setupLinkEmbeds);$try(setupTabs);}diff --git a/packages/share-theme/src/page/layout.ts b/packages/share-theme/src/page/layout.tsindex 7029a4001c..de063f2da6 100644--- a/packages/share-theme/src/page/layout.ts+++ b/packages/share-theme/src/page/layout.ts@@ -1,3 +1,5 @@+import "./layout.css";+const MOBILE_BREAKPOINT = 768; // 48emexport default function setupLayout() {diff --git a/packages/share-theme/src/page/navigation.ts b/packages/share-theme/src/page/navigation.tsindex 71a007cdf4..1066c3e4ba 100644--- a/packages/share-theme/src/page/navigation.ts+++ b/packages/share-theme/src/page/navigation.ts@@ -1,3 +1,5 @@+import "./navigation.css";+export default function setupExpanders() {const expanders = document.querySelectorAll("#menu .submenu-item .collapse-button");for (const expander of expanders) {diff --git a/packages/share-theme/src/page/search.ts b/packages/share-theme/src/page/search.tsindex 432027432a..41bb3c4879 100644--- a/packages/share-theme/src/page/search.ts+++ b/packages/share-theme/src/page/search.ts@@ -2,6 +2,7 @@ import debounce from "../common/debounce.js";import parents from "../common/parents.js";import parseHTML from "../common/parsehtml.js";import type { default as Fuse, FuseResultMatch } from "fuse.js";+import "./search.css";let fuseInstance: Fuse<SearchResult> | null = null;diff --git a/packages/share-theme/src/page/theme_switch.ts b/packages/share-theme/src/page/theme_switch.tsindex 466a042a73..56e6c25aaf 100644--- a/packages/share-theme/src/page/theme_switch.ts+++ b/packages/share-theme/src/page/theme_switch.ts@@ -1,3 +1,5 @@+import "./theme_switch.css";+const themeRootEl = document.documentElement;/**diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.tsindex e1d89db287..b6a3c9a178 100644--- a/packages/share-theme/src/page/toc.ts+++ b/packages/share-theme/src/page/toc.ts@@ -1,6 +1,7 @@import { revealTab } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";import { closeMobileMenus } from "./layout.js";+import "./toc.css";/*** The ToC is now generated in the page template sodiff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 4aa6d42aaa..49facd38de 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -120,10 +120,7 @@ export function renderNoteForExport(note: BNote, parentBranch: BBranch, basePathreturn renderNoteContentInternal(note, {subRoot,rootNoteId: parentBranch.noteId,- cssToLoad: [- `${basePath}assets/styles.css`,- `${basePath}assets/scripts.css`,- ],+ cssToLoad: [ `${basePath}assets/scripts.css` ],jsToLoad,logoUrl: `${basePath}icon-color.svg`,faviconUrl: `${basePath}favicon.ico`,@@ -157,7 +154,6 @@ export function renderNoteContent(note: SNote, canAccessEmbed?: CanAccessEmbed)// Determine CSS to load.const cssToLoad: string[] = [];if (!note.isLabelTruthy("shareOmitDefaultCss")) {- cssToLoad.push(`assets/styles.css`);cssToLoad.push(`assets/scripts.css`);}for (const cssRelation of note.getRelations("shareCss")) {