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
fix(share): keep the alt text of images on shared pages
Elian Doran6ba1291af96a
diff --git a/packages/share-theme/src/templates/page.ejs b/packages/share-theme/src/templates/page.ejsindex c866845ea3..9549048f8a 100644--- a/packages/share-theme/src/templates/page.ejs+++ b/packages/share-theme/src/templates/page.ejs@@ -93,9 +93,6 @@<% if (isEmpty && (!note.hasVisibleChildren() && note.type !== "book")) { %><p><%= t("share_page.no-content") %></p><% } else { %>- <%- content = content.replace(/<img /g, `<img alt="${t("share_theme.image_alt")}" loading="lazy" `);- %><%- content %><% } %><%- snippets["content:end"] %>diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 9c87a7fcf2..d3acc5cd5d 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -11,8 +11,8 @@ import * as sanitize from "../services/sanitizer.js";import * as utils from "../services/utils/index.js";import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";import {- anchorHeadings, ensureShareHighlighting, getContent, readShareTemplate, renderCode, renderNoteContent,- type Result+ ensureShareHighlighting, getContent, preparePageContent, readShareTemplate, renderCode,+ renderNoteContent, type Result} from "./content_renderer.js";import type SNote from "./shaca/entities/snote.js";import shaca from "./shaca/shaca.js";@@ -341,6 +341,22 @@ describe("content_renderer", () => {expect(page.querySelector(".navigation .next")?.text).toBe("Second");});+ it("keeps the alt text of an image on the page", () => {+ const shareRootNote = buildShareNote({+ id: shareRoot.SHARE_ROOT_NOTE_ID,+ children: [{+ id: "altPage",+ content: `<p><img src="chart.png" alt="Chart"></p><p><img src="plain.png"></p>`+ }]+ });++ const page = String(renderNoteContent(shareRootNote.getChildNotes()[0]));++ expect(page).not.toMatch(/<img[^>]*\salt=[^>]*\salt=/);+ expect(page).toContain(`<img src="chart.png" alt="Chart" loading="lazy">`);+ expect(page).toMatch(/<img src="plain.png" alt="[^"]+" loading="lazy">/);+ });+it("leaves an include-note section untouched when the referenced note is missing", () => {const note = buildShareNote({id: "missingRefHost",@@ -950,9 +966,9 @@ describe("content_renderer", () => {}});});- describe("anchorHeadings", () => {+ describe("preparePageContent", () => {it("anchors every heading and lists it with its level, text and unique slug", () => {- const { content, headings } = anchorHeadings(trimIndentation`+ const { content, headings } = prepare(trimIndentation`<h1>Intro</h1><p>Text</p><h2 class="x">Q&A <strong>now</strong></h2>@@ -974,10 +990,28 @@ describe("content_renderer", () => {expect(parse(content).querySelectorAll(".toc-anchor")).toHaveLength(4);});- it("returns content without headings as it is", () => {+ it("gives an image without alt text the generic one and lazy loading, keeping its own", () => {+ const { content } = prepare(trimIndentation`+ <p><img src="a.png"></p>+ <p><img src="b.png" alt="Chart" loading="eager"></p>+ <p><img src="c.png" alt=""></p>+ `);++ expect(content).toContain(`<img src="a.png" alt="Image" loading="lazy">`);+ expect(content).toContain(`<img src="b.png" alt="Chart" loading="eager">`);+ const decorative = parse(content).querySelector(`img[src="c.png"]`);+ expect(decorative?.getAttribute("alt")).toBe("");+ expect(decorative?.getAttribute("loading")).toBe("lazy");+ });++ it("returns content without headings or images as it is", () => {const html = `<p>No <b>headings</b> here & there</p>`;- expect(anchorHeadings(html)).toStrictEqual({ content: html, headings: [] });+ expect(prepare(html)).toStrictEqual({ content: html, headings: [] });});++ function prepare(html: string) {+ return preparePageContent(html, { imageAlt: "Image" });+ }});describe("Navigation tree", () => {diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 48c5afd435..887baa744e 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -267,27 +267,38 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)}// Render with the default view otherwise. Custom templates get `content` without the heading- // anchors, which templates derived from an earlier `page.ejs` add themselves.- const { content: anchoredContent, headings } = typeof content === "string"- ? anchorHeadings(content)+ // anchors and image attributes, which templates derived from an earlier `page.ejs` add+ // themselves.+ const { content: pageContent, headings } = typeof content === "string"+ ? preparePageContent(content, { imageAlt: t("share_theme.image_alt") }): { content, headings: [] };- const pageOpts = { ...opts, content: anchoredContent, headings, toc: getTableOfContents(headings) };+ const pageOpts = { ...opts, content: pageContent, headings, toc: getTableOfContents(headings) };return ejs.render(readShareTemplate("page"), pageOpts, {includer: (path) => ({ template: readShareTemplate(path) })});}/**- * Gives every heading of `html` a `#` link to itself, with an ID made from its text that is- * unique on the page, and returns the headings in document order. HTML without headings comes- * back as it is.+ * Prepares the content of a share page for the default template. Every heading gets a `#` link to+ * itself, with an ID made from its text that is unique on the page, and the headings are returned+ * in document order. An image without `alt` gets `imageAlt`, and one without `loading` loads+ * lazily. HTML without headings or images comes back as it is.*/-export function anchorHeadings(html: string): { content: string; headings: PageHeading[] } {- if (!/<h[1-6][\s>]/i.test(html)) {- return { content: html, headings: [] };+export function preparePageContent(html: string, options: { imageAlt: string }) {+ if (!/<(h[1-6]|img)[\s>]/i.test(html)) {+ return { content: html, headings: [] as PageHeading[] };}const document = parse(html, { comment: true });+ for (const image of document.querySelectorAll("img")) {+ if (!image.hasAttribute("alt")) {+ image.setAttribute("alt", options.imageAlt);+ }+ if (!image.hasAttribute("loading")) {+ image.setAttribute("loading", "lazy");+ }+ }+const elements = document.querySelectorAll("h1, h2, h3, h4, h5, h6");const slugs = utils.slugifyHeadings(elements.map((element) => element.innerHTML));const headings = elements.map((element, index) => {