From 14706bba51ff879ca6bf1072dffe96f882d020ff Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Fri, 20 Nov 2026 21:05:30 +1100 Subject: [PATCH 01/24] slideshow option when 1 image --- src/slideshow/slideshowPane.js | 2 +- test/unit/slideshowPane.test.ts | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/slideshow/slideshowPane.js b/src/slideshow/slideshowPane.js index 9b46f0ab..40336d16 100644 --- a/src/slideshow/slideshowPane.js +++ b/src/slideshow/slideshowPane.js @@ -27,7 +27,7 @@ export const slideshowPane = { const store = context.session.store if (solidLogicSingleton.resource.isContainer(subject)) { const images = getImageContents(subject, store) - return new Set(images.map(image => image.uri)).size > 1 ? 'Slideshow' : null + return images.length > 0 ? 'Slideshow' : null } return null }, diff --git a/test/unit/slideshowPane.test.ts b/test/unit/slideshowPane.test.ts index 0b2bd448..ea07ce8f 100644 --- a/test/unit/slideshowPane.test.ts +++ b/test/unit/slideshowPane.test.ts @@ -24,9 +24,25 @@ function contextFor (contents: Array<{ uri: string, image?: boolean }>) { } describe('slideshow pane', () => { - it('requires at least two images', () => { + it('offers Slideshow for a container with one image', () => { const { subject, context } = contextFor([{ uri: 'one.png', image: true }]) + expect(slideshowPane.label(subject as any, context)).toBe('Slideshow') + }) + + it.each([ + { contents: [] }, + { contents: [{ uri: 'notes.txt', image: false }] } + ])('does not offer Slideshow without images: $contents', ({ contents }) => { + const { subject, context } = contextFor(contents) + + expect(slideshowPane.label(subject as any, context)).toBeNull() + }) + + it('does not offer Slideshow for an individual image resource', () => { + const { subject, context } = contextFor([{ uri: 'one.png', image: true }]) + resource.isContainer.mockReturnValueOnce(false) + expect(slideshowPane.label(subject as any, context)).toBeNull() }) From c9515c2023c109aa52527b46cfba3f78f1d0e5ed Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Fri, 20 Nov 2026 21:08:31 +1100 Subject: [PATCH 02/24] move human readable and make iframe component --- .../iframe-preview/IframePreview.styles.css | 23 + .../iframe-preview/IframePreview.ts | 166 +++ src/components/iframe-preview/index.ts | 4 + src/{ => humanReadable}/humanReadablePane.css | 26 +- src/humanReadable/index.ts | 510 ++++++++ src/humanReadable/markdown.ts | 19 + src/humanReadable/previewBridge.ts | 403 +++++++ src/humanReadable/previewFrame.ts | 12 + src/humanReadable/previewHelpers.ts | 25 + src/humanReadablePane.ts | 1072 ----------------- src/mainPage/index.ts | 4 +- src/registerPanes.js | 2 +- test/unit/humanReadablePane.test.ts | 204 +++- 13 files changed, 1336 insertions(+), 1134 deletions(-) create mode 100644 src/components/iframe-preview/IframePreview.styles.css create mode 100644 src/components/iframe-preview/IframePreview.ts create mode 100644 src/components/iframe-preview/index.ts rename src/{ => humanReadable}/humanReadablePane.css (88%) create mode 100644 src/humanReadable/index.ts create mode 100644 src/humanReadable/markdown.ts create mode 100644 src/humanReadable/previewBridge.ts create mode 100644 src/humanReadable/previewFrame.ts create mode 100644 src/humanReadable/previewHelpers.ts delete mode 100644 src/humanReadablePane.ts diff --git a/src/components/iframe-preview/IframePreview.styles.css b/src/components/iframe-preview/IframePreview.styles.css new file mode 100644 index 00000000..b129d73e --- /dev/null +++ b/src/components/iframe-preview/IframePreview.styles.css @@ -0,0 +1,23 @@ +:host { + display: flex; + flex: 1 1 0%; + min-height: 0; + min-width: 0; +} + +.editor-card, +.human-readable-pane__container--iframe { + display: flex; + flex: 1 1 0%; + flex-direction: column; + min-height: 0; + min-width: 0; +} + +.human-readable-pane__frame--iframe { + flex: 1 1 0%; + width: 100%; + min-height: 0; + box-sizing: border-box; + border: 1px solid var(--solid-ui-color-slate-200, #E2E8F0); +} diff --git a/src/components/iframe-preview/IframePreview.ts b/src/components/iframe-preview/IframePreview.ts new file mode 100644 index 00000000..73ff2aac --- /dev/null +++ b/src/components/iframe-preview/IframePreview.ts @@ -0,0 +1,166 @@ +import { html, nothing } from 'lit' +import { property, state } from 'lit/decorators.js' +import { customElement, WebComponent } from 'solid-ui' +import type { LiveStore, NamedNode } from 'rdflib' +import { + documentTitle, + HTML_PREVIEW_SANDBOX, + IFRAME_PREVIEW_FRAME_NAME, + resourceFilename +} from '../../humanReadable/previewHelpers' +import styles from './IframePreview.styles.css' +import 'solid-ui/components/error-state' + +@customElement('solid-panes-iframe-preview') +export default class IframePreview extends WebComponent { + static styles = styles + + @property({ attribute: false }) + accessor store: LiveStore | undefined = undefined + + @property({ attribute: false }) + accessor subject: NamedNode | undefined = undefined + + @state() + private accessor contentType: string | null = null + + @state() + private accessor content: string | undefined = undefined + + @state() + private accessor errorMessage = '' + + @state() + private accessor dokieliHtml = false + + @state() + private accessor fetchedTitle = '' + + @property({ attribute: false }) + accessor rememberHtmlType: ((uri: string, isDokieli: boolean) => void) | undefined + + @property({ attribute: false }) + accessor withBaseHref: ((html: string, uri: string) => string) | undefined + + @property({ attribute: false }) + accessor isDokieliHtml: ((html: string) => boolean) | undefined + + @property({ attribute: false }) + accessor mountDokieliBridge: + ((frame: HTMLIFrameElement, uri: string, html: string) => () => void) | undefined + + private objectUrl: string | undefined + private removeDokieliBridge = () => {} + private rawHtml: string | undefined + private fetchGeneration = 0 + + private get previewTitle (): string { + return this.fetchedTitle || (this.subject?.uri ? resourceFilename(this.subject.uri) : 'preview') + } + + private dismissError = (): void => { + this.errorMessage = '' + } + + private clearPreview (): void { + this.removeDokieliBridge() + this.removeDokieliBridge = () => {} + if (this.objectUrl) { + URL.revokeObjectURL(this.objectUrl) + this.objectUrl = undefined + } + this.content = undefined + this.contentType = null + this.rawHtml = undefined + this.fetchedTitle = '' + this.dokieliHtml = false + this.errorMessage = '' + } + + private async fetchDocument (): Promise { + const generation = ++this.fetchGeneration + const { subject, store } = this + this.clearPreview() + if (!subject || !store) return + + const isCurrent = () => this.isConnected && + generation === this.fetchGeneration && this.subject === subject && this.store === store + + try { + const response = await store.fetcher._fetch(subject.uri) + if (!response.ok) throw new Error(`HTTP ${response.status}`) + const contentType = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? null + const isHtml = contentType === 'text/html' || contentType === 'application/xhtml+xml' + + if (isHtml) { + const htmlContent = await response.text() + if (!isCurrent()) return + this.dokieliHtml = this.isDokieliHtml?.(htmlContent) ?? false + this.rememberHtmlType?.(subject.uri, this.dokieliHtml) + this.rawHtml = htmlContent + this.fetchedTitle = documentTitle(htmlContent, subject.uri) + this.contentType = contentType + this.content = this.withBaseHref?.(htmlContent, subject.uri) ?? htmlContent + } else { + const blob = await response.blob() + if (!isCurrent()) return + this.objectUrl = URL.createObjectURL(blob) + this.contentType = contentType + this.content = this.objectUrl + } + } catch (error) { + if (isCurrent()) { + this.errorMessage = error instanceof Error ? error.message : String(error) + } + } + } + + connectedCallback (): void { + super.connectedCallback() + if (this.hasUpdated) this.fetchDocument() + } + + protected updated (changed: Map): void { + super.updated(changed) + if (changed.has('subject') || changed.has('store')) { + this.fetchDocument() + } else if (changed.has('content') && this.dokieliHtml && this.rawHtml && this.subject) { + const frame = this.renderRoot.querySelector('iframe') + if (frame && this.mountDokieliBridge) { + this.removeDokieliBridge() + this.removeDokieliBridge = this.mountDokieliBridge(frame, this.subject.uri, this.rawHtml) + } + } + } + + disconnectedCallback (): void { + ++this.fetchGeneration + this.clearPreview() + super.disconnectedCallback() + } + + render () { + const isHtml = this.contentType === 'text/html' || this.contentType === 'application/xhtml+xml' + return html` +
+
+ +
+ ${this.errorMessage + ? html`` + : nothing} +
+ ` + } +} diff --git a/src/components/iframe-preview/index.ts b/src/components/iframe-preview/index.ts new file mode 100644 index 00000000..79258d61 --- /dev/null +++ b/src/components/iframe-preview/index.ts @@ -0,0 +1,4 @@ +import IframePreview from './IframePreview' + +export { IframePreview } +export default IframePreview \ No newline at end of file diff --git a/src/humanReadablePane.css b/src/humanReadable/humanReadablePane.css similarity index 88% rename from src/humanReadablePane.css rename to src/humanReadable/humanReadablePane.css index c4c82adc..02fb53fc 100644 --- a/src/humanReadablePane.css +++ b/src/humanReadable/humanReadablePane.css @@ -68,7 +68,7 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { flex: 1 1 0%; height: 100%; min-height: 0; - overflow: visible; + overflow: hidden; } .human-readable-pane__container--iframe { @@ -76,12 +76,13 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { display: flex; flex-direction: column; min-height: 0; + overflow: hidden; } .human-readable-pane__container--iframe > .human-readable-pane__frame--iframe { - flex: 1 1 auto; - height: 480px; - min-height: 288px; + flex: 1 1 0%; + height: 100%; + min-height: 0; resize: none; } @@ -91,6 +92,23 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { max-height: none; } +.human-readable-pane--document { + overflow: hidden; +} + +.human-readable-pane--document > .human-readable-pane__container { + overflow: hidden; +} + +.human-readable-pane--document > .human-readable-pane__container > .human-readable-pane__frame--markdown, +.human-readable-pane--document > .human-readable-pane__container > .human-readable-pane__frame--plain-text { + flex: 1 1 0%; + height: 100%; + min-height: 0; + max-height: none; + overflow: auto; +} + .human-readable-pane__frame--markdown { overflow-wrap: anywhere; word-break: break-word; diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts new file mode 100644 index 00000000..ce1f829c --- /dev/null +++ b/src/humanReadable/index.ts @@ -0,0 +1,510 @@ +/* Human-readable Pane + ** + ** This outline pane contains the document contents for an HTML document + ** This is for peeking at a page, because the user might not want to leave the data browser. + */ +import { icons, ns } from 'solid-ui' +import { Util } from 'rdflib' +import { authn } from 'solid-logic' +import type { DataBrowserContext, RenderEnvironment } from 'pane-registry' +import type { NamedNode } from 'rdflib' +import './humanReadablePane.css' +import { createPreviewBridge } from './previewBridge' +import { configurePreviewFrame } from './previewFrame' +import { renderMarkdownContent } from './markdown' +import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' +import type IframePreview from '../components/iframe-preview' +import '../components/iframe-preview' + +export { IFRAME_PREVIEW_FRAME_NAME } from './previewHelpers' + +function viewerWebId (): string | null { + try { + return authn.currentUser()?.value ?? null + } catch { + return null + } +} + +// Helper function to check if a URI has a markdown file extension +type DokieliCacheValue = 'dokieli' | 'html' + +type HumanReadableIcon = string | Promise + +type HumanReadablePaneDefinition = { + icon: (subject: NamedNode, context: DataBrowserContext) => HumanReadableIcon + name: string + label: (subject: NamedNode, context: DataBrowserContext) => 'Webpage' | 'View' | null + render: (subject: NamedNode, context: DataBrowserContext) => HTMLDivElement +} + +const isMarkdownFile = (uri?: string | null): boolean => { + if (!uri) return false + const path = uri.split('?')[0].split('#')[0] // Remove query string and fragment + return /\.(md|markdown|mdown|mkd|mkdn)$/i.test(path) +} + +const isJsonFile = (uri?: string | null): boolean => { + if (!uri) return false + const path = uri.split('?')[0].split('#')[0] + return /\.json$/i.test(path) +} + +// Cache for dokieli detection results (keyed by subject URI) +const dokieliCache = new Map() + +const isDokieliHtml = (text: string): boolean => + text.includes('` + const cleanHtml = options.stripPreviewBridgeScripts(html) ?? html + return options.withBaseHref(cleanHtml, uri).replace(/]*)?>/i, match => `${match}${bridge}`) +} diff --git a/src/humanReadable/previewFrame.ts b/src/humanReadable/previewFrame.ts new file mode 100644 index 00000000..4020c2a0 --- /dev/null +++ b/src/humanReadable/previewFrame.ts @@ -0,0 +1,12 @@ +export function configurePreviewFrame ( + frame: HTMLElement, + modifier: 'markdown' | 'plain-text' | 'iframe', + lines?: number +): void { + frame.className = '' + frame.classList.add('human-readable-pane__frame') + frame.classList.add(`human-readable-pane__frame--${modifier}`) + if (lines !== undefined) { + frame.style.setProperty('--human-readable-pane-height', `${lines * 16}px`) + } +} diff --git a/src/humanReadable/previewHelpers.ts b/src/humanReadable/previewHelpers.ts new file mode 100644 index 00000000..90d0a258 --- /dev/null +++ b/src/humanReadable/previewHelpers.ts @@ -0,0 +1,25 @@ +export const IFRAME_PREVIEW_FRAME_NAME = 'solidos-iframe-preview' +export const HTML_PREVIEW_SANDBOX = 'allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals' + +export function escapeAttribute (value: string): string { + return value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') +} + +export function resourceFilename (uri: string): string { + const encodedFilename = uri.split('/').pop() || uri + try { + return decodeURIComponent(encodedFilename) + } catch { + return encodedFilename + } +} + +export function documentTitle (html: string, uri: string): string { + const fallback = resourceFilename(uri) + try { + const title = new DOMParser().parseFromString(html, 'text/html').querySelector('title')?.textContent?.trim() + return title || fallback + } catch { + return fallback + } +} diff --git a/src/humanReadablePane.ts b/src/humanReadablePane.ts deleted file mode 100644 index 0c2eba4a..00000000 --- a/src/humanReadablePane.ts +++ /dev/null @@ -1,1072 +0,0 @@ -/* Human-readable Pane - ** - ** This outline pane contains the document contents for an HTML document - ** This is for peeking at a page, because the user might not want to leave the data browser. - */ -import { icons, ns } from 'solid-ui' -import { Util } from 'rdflib' -import { authn } from 'solid-logic' -import { marked } from 'marked' -import DOMPurify from 'dompurify' -import type { DataBrowserContext, RenderEnvironment } from 'pane-registry' -import type { NamedNode } from 'rdflib' -import './humanReadablePane.css' - -function viewerWebId (): string | null { - try { - return authn.currentUser()?.value ?? null - } catch { - return null - } -} - -// Helper function to check if a URI has a markdown file extension -type DokieliCacheValue = 'dokieli' | 'html' - -type HumanReadableIcon = string | Promise - -type HumanReadablePaneDefinition = { - icon: (subject: NamedNode, context: DataBrowserContext) => HumanReadableIcon - name: string - label: (subject: NamedNode, context: DataBrowserContext) => 'Webpage' | 'View' | null - render: (subject: NamedNode, context: DataBrowserContext) => HTMLDivElement -} - -const isMarkdownFile = (uri?: string | null): boolean => { - if (!uri) return false - const path = uri.split('?')[0].split('#')[0] // Remove query string and fragment - return /\.(md|markdown|mdown|mkd|mkdn)$/i.test(path) -} - -const isJsonFile = (uri?: string | null): boolean => { - if (!uri) return false - const path = uri.split('?')[0].split('#')[0] - return /\.json$/i.test(path) -} - -// Cache for dokieli detection results (keyed by subject URI) -const dokieliCache = new Map() - -function applyFrameClasses ( - frame: HTMLElement, - modifier: 'markdown' | 'plain-text' | 'iframe', - lines?: number -): void { - frame.className = '' - frame.classList.add('human-readable-pane__frame') - frame.classList.add(`human-readable-pane__frame--${modifier}`) - if (lines !== undefined) { - frame.style.setProperty('--human-readable-pane-height', `${lines * 16}px`) - } -} - -// window.name of preview iframes; initMainPage refuses to boot SolidOS inside such a frame. -export const HUMAN_READABLE_PREVIEW_FRAME_NAME = 'solidos-human-readable-preview' - -// Scripts may run but get an opaque origin, so previewed pages cannot reach the SolidOS session. -const HTML_PREVIEW_SANDBOX = 'allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals' - -const isDokieliHtml = (text: string): boolean => - text.includes('` - const withScript = html.replace(/<\/body\s*>/i, `${script}$&`) - return withScript === html ? `${html}${script}` : withScript -} - -function resourceFilename (uri: string): string { - const encodedFilename = uri.split('/').pop() || uri - try { - return decodeURIComponent(encodedFilename) - } catch { - return encodedFilename - } -} - -function documentTitle (html: string, uri: string): string { - const fallback = resourceFilename(uri) - try { - const title = new DOMParser().parseFromString(html, 'text/html').querySelector('title')?.textContent?.trim() - return title || fallback - } catch { - return fallback - } -} - -type PreviewRequest = { - type: 'solidos-preview-request' - nonce: string - id: string - url: string - method: string - headers?: Record - body?: string -} - -type PreviewResponse = { - type: 'solidos-preview-response' - nonce: string - id: string - ok: boolean - status: number - headers: Array<[string, string]> - body: string - error?: string -} - -const PREVIEW_REQUEST_TYPE = 'solidos-preview-request' -const PREVIEW_RESPONSE_TYPE = 'solidos-preview-response' -const PREVIEW_BRIDGE_ATTRIBUTE = 'data-solidos-preview-bridge' -const PREVIEW_READ_METHODS = new Set(['GET', 'HEAD']) -const PREVIEW_WRITE_METHODS = new Set(['PUT', 'PATCH', 'DELETE']) - -function stripPreviewBridgeScripts (html: string | undefined): string | undefined { - if (typeof html !== 'string' || !html.includes(PREVIEW_REQUEST_TYPE)) return html - - const parsed = new DOMParser().parseFromString(html, 'text/html') - let removed = false - for (const script of parsed.querySelectorAll('script')) { - const source = script.textContent || '' - const isPreviewBridge = script.hasAttribute(PREVIEW_BRIDGE_ATTRIBUTE) || - ( - source.includes(PREVIEW_REQUEST_TYPE) && - source.includes(PREVIEW_RESPONSE_TYPE) && - source.includes('const pending = new Map()') - ) - if (isPreviewBridge) { - script.remove() - removed = true - } - } - if (!removed) return html - - const doctype = html.match(/]*>/i)?.[0] - return `${doctype ? `${doctype}\n` : ''}${parsed.documentElement.outerHTML}` -} - -function isSrcdocUrl (url: string): boolean { - return url === 'about:srcdoc' || /^file:\/\/srcdoc\/?(?:[?#].*)?$/i.test(url) -} - -export function previewRequestUrl (url: string, documentUri: string): string { - const resolvedUrl = new URL(url, documentUri).href - return isSrcdocUrl(resolvedUrl) ? documentUri : resolvedUrl -} - -function profileDocumentUrl (webId: string | null | undefined): string | undefined { - if (!webId) return undefined - try { - const url = new URL(webId) - url.hash = '' - return url.href - } catch { - return undefined - } -} - -export function isAllowedPreviewRequest ( - url: string, - method: string, - documentUri: string, - webId: string | null = null -): boolean { - let resolvedUrl: URL - let expectedUrl: URL - try { - resolvedUrl = new URL(previewRequestUrl(url, documentUri)) - expectedUrl = new URL(documentUri) - } catch { - return false - } - - if (resolvedUrl.origin !== expectedUrl.origin) { - return false - } - - const normalizedMethod = method.toUpperCase() - const requestedDocument = new URL(resolvedUrl.href) - requestedDocument.hash = '' - const expectedDocument = new URL(expectedUrl.href) - expectedDocument.hash = '' - const isPreviewDocument = requestedDocument.href === expectedDocument.href - const isExactPreviewDocument = resolvedUrl.href === expectedUrl.href - // Path-based pods keep the viewer profile below the pod path, e.g. /alice/profile/card. - const isApprovedProfileResource = resolvedUrl.pathname === '/profile/card' || - requestedDocument.href === profileDocumentUrl(webId) - return ( - PREVIEW_READ_METHODS.has(normalizedMethod) && - (isPreviewDocument || isApprovedProfileResource) - ) || (isExactPreviewDocument && PREVIEW_WRITE_METHODS.has(normalizedMethod)) -} - -function createPreviewBridge (html: string, uri: string, nonce: string, webId: string | null = null): string { - const bridge = `` - const cleanHtml = stripPreviewBridgeScripts(html) ?? html - return withBaseHref(cleanHtml, uri).replace(/]*)?>/i, match => `${match}${bridge}`) -} - -function mountDokieliBridge ( - frame: HTMLIFrameElement, - uri: string, - html: string, - authenticatedFetch: (url: string, init?: RequestInit) => Promise, - webId: string | null = null -): void { - const ownerWindow = frame.ownerDocument.defaultView - if (!ownerWindow) return - - const randomValues = new Uint32Array(4) - ownerWindow.crypto.getRandomValues(randomValues) - const nonce = Array.from(randomValues, value => value.toString(16)).join('-') - const expectedUri = new URL(uri).href - const listener = (event: MessageEvent) => { - const request = event.data - if ( - event.source !== frame.contentWindow || - !request || - request.type !== PREVIEW_REQUEST_TYPE || - request.nonce !== nonce - ) return - - const respond = (response: PreviewResponse) => { - frame.contentWindow?.postMessage(response, '*') - } - - // Always settle authenticated bridge requests. Dropping a denied request - // leaves the preview awaiting it forever (Dokieli then never leaves Loading…). - if (!isAllowedPreviewRequest(request.url, request.method, expectedUri, webId)) { - respond({ - type: PREVIEW_RESPONSE_TYPE, - nonce, - id: request.id, - ok: false, - status: 403, - headers: [], - body: '', - error: 'Request not permitted by the SolidOS preview' - }) - return - } - const requestUrl = previewRequestUrl(request.url, expectedUri) - - authenticatedFetch(requestUrl, { - method: request.method, - headers: request.headers, - body: PREVIEW_READ_METHODS.has(request.method) - ? undefined - : stripPreviewBridgeScripts(request.body) - }).then(async response => { - respond({ - type: PREVIEW_RESPONSE_TYPE, - nonce, - id: request.id, - ok: response.ok, - status: response.status, - headers: Array.from(response.headers.entries()), - body: await response.text() - }) - }).catch(error => { - respond({ - type: PREVIEW_RESPONSE_TYPE, - nonce, - id: request.id, - ok: false, - status: 0, - headers: [], - body: '', - error: error instanceof Error ? error.message : String(error) - }) - }) - } - - ownerWindow.addEventListener('message', listener) - frame.setAttribute('sandbox', HTML_PREVIEW_SANDBOX) - frame.srcdoc = createPreviewBridge(html, expectedUri, nonce, webId) -} - -function installPreviewAutoSize ( - frame: HTMLIFrameElement, - ownerWindow: Window -): () => void { - const onMessage = (event: MessageEvent<{ type?: string, height?: number }>) => { - const message = event.data - if ( - event.source !== frame.contentWindow || - message?.type !== 'solidos-preview-size' || - typeof message.height !== 'number' || - !Number.isFinite(message.height) - ) return - frame.style.height = `${Math.max(1, Math.ceil(message.height))}px` - frame.style.flexShrink = '0' - } - ownerWindow.addEventListener('message', onMessage) - return () => ownerWindow.removeEventListener('message', onMessage) -} - -const humanReadablePane: HumanReadablePaneDefinition = { - icon: function (subject: NamedNode, context: DataBrowserContext): HumanReadableIcon { - // Markdown files detected by extension - if (subject && isMarkdownFile(subject.uri)) { - return icons.iconBase + 'markdown.svg' - } - - // Dokieli files detected by content check - if (subject) { - const kb = context.session.store - - // Check cache from previous detection - const cachedResult = dokieliCache.get(subject.uri) - if (cachedResult === 'dokieli') { - return icons.iconBase + 'dokieli-logo.png' - } else if (cachedResult === 'html') { - return icons.originalIconBase + 'tango/22-text-x-generic.png' - } - - // Check if content already fetched (synchronous) - const responseText = kb.fetcher.getHeader(subject.doc(), 'content') - if (responseText && responseText.length > 0) { - const text = responseText[0] - const isDokieli = text.includes('

Dok

' - const authenticatedFetch = vi.fn().mockResolvedValue(new Response('ok')) + const authenticatedFetch = vi.fn().mockImplementation((_url, init) => + Promise.resolve(init ? new Response('ok') : htmlResponse(html))) const subject = { uri: dokieliUri, doc: () => subject } const store = { fetcher: { getHeader: vi.fn().mockReturnValue(['text/html']), - webOperation: vi.fn().mockResolvedValue({ responseText: html }), _fetch: authenticatedFetch } } const pane = humanReadablePane.render(subject as any, { dom: document, session: { store } } as any) document.body.appendChild(pane) - const frame = pane.querySelector('iframe')! try { - await flush() + await waitForSrcdoc(pane, 'solidos-preview-request') + const frame = getFrame(pane)! + // jsdom does not create browsing contexts for iframes in shadow roots. + Object.defineProperty(frame, 'contentWindow', { configurable: true, value: window }) + authenticatedFetch.mockClear() expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals') expect(frame.srcdoc).toContain('solidos-preview-request') expect(frame.srcdoc).toContain('dokieli.js') @@ -269,7 +294,7 @@ describe('human readable pane iframe rendering', () => { body: 'saved from file srcdoc' }) authenticatedFetch.mockClear() - const postToPreview = vi.spyOn(frame.contentWindow!, 'postMessage') + const postToPreview = vi.spyOn(window, 'postMessage') window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { @@ -289,19 +314,31 @@ describe('human readable pane iframe rendering', () => { ok: false, status: 403 }), '*') + pane.remove() + window.dispatchEvent(new MessageEvent('message', { + source: window, + data: { + type: 'solidos-preview-request', + nonce: frame.srcdoc.match(/const nonce = "([^"]+)"/)?.[1], + id: 'after-removal', + url: dokieliUri, + method: 'PUT', + body: 'x' + } + })) + await flush() + expect(authenticatedFetch).not.toHaveBeenCalled() } finally { pane.remove() } }) it('keeps cross-origin Dokieli documents in the isolated preview', async () => { - const webOperation = vi.fn().mockResolvedValue({ - responseText: '' - }) - const pane = renderWith('text/html', { webOperation }) - await flush() + const fetch = vi.fn().mockResolvedValue(htmlResponse('')) + const pane = renderWith('text/html', { _fetch: fetch }) + await waitForSrcdoc(pane, 'dokieli.js') - const frame = pane.querySelector('iframe')! + const frame = getFrame(pane)! expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals') expect(frame.srcdoc).toContain('dokieli.js') }) @@ -311,9 +348,9 @@ describe('human readable pane iframe rendering', () => { headers: { 'content-type': 'text/html; charset=utf-8' } }) const pane = renderWith('image/png', { _fetch: vi.fn().mockResolvedValue(response) }) - await flush() + await waitForSrcdoc(pane, 'compromised') - const frame = pane.querySelector('iframe')! + const frame = getFrame(pane)! expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals') expect(frame.src).toBe('') expect(frame.srcdoc).toContain('compromised') @@ -325,9 +362,9 @@ describe('human readable pane iframe rendering', () => { headers: { 'content-type': 'application/pdf' } }) const pane = renderWith('application/octet-stream', { _fetch: vi.fn().mockResolvedValue(response) }) - await flush() + await vi.waitFor(() => expect(getFrame(pane)?.src).toBe('blob:https://pod.example/resource')) - const frame = pane.querySelector('iframe')! + const frame = getFrame(pane)! expect(frame.getAttribute('sandbox')).toBeNull() expect(frame.src).toBe('blob:https://pod.example/resource') expect(createObjectURL).toHaveBeenCalled() @@ -340,20 +377,21 @@ describe('human readable pane iframe rendering', () => { headers: { 'content-type': 'image/svg+xml' } }) const pane = renderWith('image/svg+xml', { _fetch: vi.fn().mockResolvedValue(response) }) - await flush() + await vi.waitFor(() => expect(createObjectURL).toHaveBeenCalled()) - expect(pane.querySelector('iframe')?.getAttribute('sandbox')) + expect(getFrame(pane)?.getAttribute('sandbox')) .toBe('allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals') createObjectURL.mockRestore() }) - it('revokes a blob URL when the preview is removed before fetching completes', async () => { + it('does not create a blob URL when the preview is removed before fetching completes', async () => { let resolveResponse!: (response: Response) => void const responsePromise = new Promise(resolve => { resolveResponse = resolve }) const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:https://pod.example/resource') const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) - const pane = renderWith('application/pdf', { _fetch: vi.fn().mockReturnValue(responsePromise) }) - document.body.appendChild(pane) + const fetch = vi.fn().mockReturnValue(responsePromise) + const pane = renderWith('application/pdf', { _fetch: fetch }) + await vi.waitFor(() => expect(fetch).toHaveBeenCalled()) pane.remove() resolveResponse(new Response('pdf', { headers: { 'content-type': 'application/pdf' } @@ -361,24 +399,77 @@ describe('human readable pane iframe rendering', () => { await flush() await flush() - expect(createObjectURL).toHaveBeenCalled() + expect(createObjectURL).not.toHaveBeenCalled() + expect(revokeObjectURL).not.toHaveBeenCalled() + createObjectURL.mockRestore() + revokeObjectURL.mockRestore() + }) + + it('revokes an active blob URL when the preview is removed', async () => { + const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:https://pod.example/resource') + const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) + const pane = renderWith('application/pdf', { + _fetch: vi.fn().mockResolvedValue(new Response('pdf', { headers: { 'content-type': 'application/pdf' } })) + }) + await vi.waitFor(() => expect(getFrame(pane)?.src).toBe('blob:https://pod.example/resource')) + pane.remove() expect(revokeObjectURL).toHaveBeenCalledWith('blob:https://pod.example/resource') createObjectURL.mockRestore() revokeObjectURL.mockRestore() }) - it('shows an error instead of the resource URL when the fetch fails', async () => { - const webOperation = vi.fn().mockRejectedValue(new Error('401')) - vi.spyOn(console, 'error').mockImplementation(() => {}) - const pane = renderWith('text/html', { webOperation }) + it('loads a changed subject and ignores the earlier response', async () => { + let resolveFirst!: (response: Response) => void + const firstResponse = new Promise(resolve => { resolveFirst = resolve }) + const fetch = vi.fn() + .mockReturnValueOnce(firstResponse) + .mockResolvedValueOnce(htmlResponse('

New document

')) + const pane = renderWith('text/html', { _fetch: fetch }) + await vi.waitFor(() => expect(fetch).toHaveBeenCalledWith(uri)) + + const preview = pane.querySelector('solid-panes-iframe-preview') as IframePreview + const nextUri = 'https://pod.example/docs/next.html' + preview.subject = sym(nextUri) + await waitForSrcdoc(pane, 'New document') + expect(fetch).toHaveBeenCalledWith(nextUri) + + resolveFirst(htmlResponse('

Stale document

')) + await flush() + expect(getFrame(pane)?.srcdoc).toContain('New document') + expect(getFrame(pane)?.srcdoc).not.toContain('Stale document') + }) + + it.each(['text/html', 'application/octet-stream'])('does not attach a late Dokieli bridge after a %s preview is removed', async contentType => { + let resolveResponse!: (response: Response) => void + const responsePromise = new Promise(resolve => { resolveResponse = resolve }) + const fetch = vi.fn().mockReturnValue(responsePromise) + const pane = renderWith(contentType, { + _fetch: fetch + }) + await vi.waitFor(() => expect(fetch).toHaveBeenCalled()) + const frame = getFrame(pane)! + pane.remove() + const addListener = vi.spyOn(window, 'addEventListener') + const html = '' + resolveResponse(htmlResponse(html)) await flush() + expect(frame.srcdoc).toBe('') + expect(addListener).not.toHaveBeenCalledWith('message', expect.any(Function)) + addListener.mockRestore() + }) + + it('shows an error instead of the resource URL when the fetch fails', async () => { + const fetch = vi.fn().mockRejectedValue(new Error('401')) + const pane = renderWith('text/html', { _fetch: fetch }) + const preview = pane.querySelector('solid-panes-iframe-preview')! + await vi.waitFor(() => expect(preview.shadowRoot?.querySelector('solid-ui-error-state')).not.toBeNull()) - const frame = pane.querySelector('iframe')! + const frame = getFrame(pane)! expect(frame.getAttribute('src')).toBeNull() - expect(frame.srcdoc).toContain('Error loading content') + expect(preview.shadowRoot?.querySelector('solid-ui-error-state')).toHaveProperty('message', '401') }) - it('falls back to the encoded filename when it is not valid UTF-8', () => { + it('falls back to the encoded filename when it is not valid UTF-8', async () => { const invalidUri = 'https://pod.example/docs/file%FF.pdf' const subject = { uri: invalidUri, doc: () => subject } const store = { @@ -390,8 +481,10 @@ describe('human readable pane iframe rendering', () => { } } const pane = humanReadablePane.render(subject as any, { dom: document, session: { store } } as any) + document.body.appendChild(pane) + await vi.waitFor(() => expect(getFrame(pane)?.title).toBe('file%FF.pdf')) - expect(pane.querySelector('iframe')?.title).toBe('file%FF.pdf') + expect(getFrame(pane)?.title).toBe('file%FF.pdf') }) it('gives Dokieli the signed-in viewer as a bridged session', async () => { @@ -403,14 +496,14 @@ describe('human readable pane iframe rendering', () => { const store = { fetcher: { getHeader: vi.fn().mockReturnValue(['text/html']), - webOperation: vi.fn().mockResolvedValue({ responseText: html }), - _fetch: vi.fn() + _fetch: vi.fn().mockImplementation(() => Promise.resolve(htmlResponse(html))) } } try { const pane = humanReadablePane.render(subject as any, { dom: document, session: { store } } as any) - await flush() - const srcdoc = pane.querySelector('iframe')!.srcdoc + document.body.appendChild(pane) + await waitForSrcdoc(pane, 'const viewerWebId') + const srcdoc = getFrame(pane)!.srcdoc expect(srcdoc).toContain(`const viewerWebId = ${JSON.stringify(webId)}`) expect(srcdoc).toContain('if (bridgedSession) config.Session = bridgedSession') expect(srcdoc).toContain('Object.defineProperty(config, \'DocumentURL\'') @@ -418,8 +511,9 @@ describe('human readable pane iframe rendering', () => { spy.mockReturnValue(null) const loggedOut = humanReadablePane.render(subject as any, { dom: document, session: { store } } as any) - await flush() - expect(loggedOut.querySelector('iframe')!.srcdoc).toContain('const viewerWebId = null') + document.body.appendChild(loggedOut) + await waitForSrcdoc(loggedOut, 'const viewerWebId') + expect(getFrame(loggedOut)!.srcdoc).toContain('const viewerWebId = null') } finally { spy.mockRestore() } From 00f11df9851c339b2b4868196386c16a245d0c6b Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 06:25:34 +1100 Subject: [PATCH 03/24] link in tab, open in solidos --- src/mainPage/index.ts | 3 ++- test/unit/humanReadablePane.test.ts | 24 ++++++++++++++++++++++++ test/unit/mainPage/index.test.ts | 18 ++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/mainPage/index.ts b/src/mainPage/index.ts index 9b78f3af..11ae4b6f 100644 --- a/src/mainPage/index.ts +++ b/src/mainPage/index.ts @@ -56,7 +56,8 @@ export async function initMainPage ( return } ensureMainContent() - uri = uri || window.location.href + const requestedUri = new URL(window.location.href).searchParams.get('uri') + uri = requestedUri || uri || window.location.href const subject: NamedNode = typeof uri === 'string' ? store.sym(uri) : uri // A reload shows what the URL is, whatever the history entry last displayed through the navbar // or the account menu: the profile on a profile page, otherwise the resource or container itself. diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index da966b14..77ff6045 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -120,6 +120,23 @@ describe('isAllowedPreviewRequest', () => { }) describe('human readable pane iframe rendering', () => { + it.each(['text/markdown', 'text/markdown; charset=utf-8', 'text/markdown; charset=UTF-8; format=flowed'])( + 'renders Markdown from content type %s without a Markdown filename', + async contentType => { + const webOperation = vi.fn().mockResolvedValue({ responseText: '# Markdown heading' }) + const store = { fetcher: { getHeader: vi.fn().mockReturnValue([contentType]) }, findTypeURIs: vi.fn().mockReturnValue({}) } + expect(humanReadablePane.label(sym(uri), { session: { store } } as any)).toBe('View') + const pane = renderWith(contentType, { webOperation }) + + await vi.waitFor(() => { + expect(pane.querySelector('.human-readable-pane__frame--markdown h1')?.textContent) + .toBe('Markdown heading') + }) + expect(pane.querySelector('.human-readable-pane__frame--plain-text')).toBeNull() + expect(getFrame(pane)).toBeNull() + } + ) + it('renders JSON as readable text', async () => { const webOperation = vi.fn().mockResolvedValue({ responseText: '{\n "enabled": true\n}' }) const pane = renderWith('application/json', { webOperation }) @@ -467,6 +484,13 @@ describe('human readable pane iframe rendering', () => { const frame = getFrame(pane)! expect(frame.getAttribute('src')).toBeNull() expect(preview.shadowRoot?.querySelector('solid-ui-error-state')).toHaveProperty('message', '401') + + preview.shadowRoot?.querySelector('solid-ui-error-state')?.dispatchEvent(new CustomEvent('close', { + bubbles: true, + composed: true + })) + await flush() + expect(preview.shadowRoot?.querySelector('solid-ui-error-state')).toBeNull() }) it('falls back to the encoded filename when it is not valid UTF-8', async () => { diff --git a/test/unit/mainPage/index.test.ts b/test/unit/mainPage/index.test.ts index 7778b4f9..2fcc2912 100644 --- a/test/unit/mainPage/index.test.ts +++ b/test/unit/mainPage/index.test.ts @@ -148,6 +148,24 @@ describe('main page load', () => { expect(GotoSubject.mock.calls[0][2]).toBeUndefined() expect(window.history.state).toEqual({}) }) + + it('loads the resource requested by a SolidOS deep link', async () => { + const GotoSubject = setup({}, false) + const resourceUri = 'https://pod.example/docs/readme.md' + window.history.replaceState({}, '', `/?uri=${encodeURIComponent(resourceUri)}`) + + await initMainPage(store) + + expect(GotoSubject).toHaveBeenCalledWith( + store.sym(resourceUri), + true, + undefined, + true, + undefined, + undefined, + expect.anything() + ) + }) }) describe('browser navigation without a reload', () => { From 663b898955c47659fd78dfab8dfb44716e6a2000 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 11:46:58 +1100 Subject: [PATCH 04/24] pdf new design and web component --- package-lock.json | 311 +++++++++++++++--- package.json | 1 + src/components/pdf-viewer/PdfViewer.ts | 224 +++++++++++++ .../pdf-viewer/PdfViewier.styles.css | 207 ++++++++++++ src/components/pdf-viewer/index.ts | 4 + src/components/pdf-viewer/pdfJs.ts | 3 + src/humanReadable/index.ts | 12 +- test/unit/humanReadablePane.test.ts | 39 ++- 8 files changed, 739 insertions(+), 62 deletions(-) create mode 100644 src/components/pdf-viewer/PdfViewer.ts create mode 100644 src/components/pdf-viewer/PdfViewier.styles.css create mode 100644 src/components/pdf-viewer/index.ts create mode 100644 src/components/pdf-viewer/pdfJs.ts diff --git a/package-lock.json b/package-lock.json index 1f6ab9d8..b3a29148 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,6 +22,7 @@ "meeting-pane": "4.1.1-0", "mime-types": "^3.0.2", "pane-registry": "5.1.2-0", + "pdfjs-dist": "^6.5.438", "profile-pane": "4.1.1-0", "rdflib": "2.4.1", "solid-logic": "6.2.1-0", @@ -3081,6 +3082,256 @@ "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", "license": "MIT" }, + "node_modules/@napi-rs/canvas": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.1.1.tgz", + "integrity": "sha512-UyNspnx0rXclATMOBXiWgy1xtWUSUDm4UOO6+YO8xzyVKaZRpvK+SlJSCtRoSI9J/mEqklJiPYtroN1B+hgLXg==", + "license": "MIT", + "optional": true, + "workspaces": [ + "e2e/*" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@napi-rs/canvas-android-arm64": "1.1.1", + "@napi-rs/canvas-darwin-arm64": "1.1.1", + "@napi-rs/canvas-darwin-x64": "1.1.1", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.1.1", + "@napi-rs/canvas-linux-arm64-gnu": "1.1.1", + "@napi-rs/canvas-linux-arm64-musl": "1.1.1", + "@napi-rs/canvas-linux-riscv64-gnu": "1.1.1", + "@napi-rs/canvas-linux-x64-gnu": "1.1.1", + "@napi-rs/canvas-linux-x64-musl": "1.1.1", + "@napi-rs/canvas-win32-arm64-msvc": "1.1.1", + "@napi-rs/canvas-win32-x64-msvc": "1.1.1" + } + }, + "node_modules/@napi-rs/canvas-android-arm64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.1.1.tgz", + "integrity": "sha512-rSEp3y+/YXw6TxSx4/NHSAFxumZrkMoXy2WiVqpKGT8oF5GHOUDzTKj45e5cvzophX4iFaxwKs3+/gNkJ7FmzQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-arm64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.1.1.tgz", + "integrity": "sha512-NrPTZWpu0ywOGdp9JBDi46gABUzDJK6IzlP7cOEwaAuVVFM8KRakUWk12RK3YQ/Ea5FrNVTWUFTmkXVk4RfHqg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-x64": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.1.1.tgz", + "integrity": "sha512-p3DOT8VBfu8cR3SVBUs6cEzJmzwOUQkNfo1S4nKLgeKDsSlvn2oZsRaa9m0lfMccn1WbwtgKCEpJXmHhp++Zrg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.1.1.tgz", + "integrity": "sha512-YWGJfMa8TtEhsHd/kDiyBFwT/dAbRQiXwsm0tDev4H5cJiyOk08CC83JihrwnUsePGjIvxC8/8g/zqKKuqjpQA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.1.1.tgz", + "integrity": "sha512-q1HBkNmB9mc6SF6uSz2492qSgsB46MqS+n3bPbPCE0kUXmWAPkH9vDADeawbhepQYn8RhlV2V/P5u6nykFXbuQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-musl": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.1.1.tgz", + "integrity": "sha512-aF4RkTp2T45fERFPCIqbxeKVhvhHuXeyyk5/jdJ+N0tGLZy4NvMkIrBWt6GOCmAQ7H0G3M/O03hAsc4Li52q4A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.1.1.tgz", + "integrity": "sha512-rCU4Xo5h0AQFEaa9dNr7Kxbk4gke9Uyi/I6ZXuBGYPSNWxYmWRS6DkrxaSKUJyCgA7c8l6lZBYfx/FtbJo3fMA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-gnu": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.1.1.tgz", + "integrity": "sha512-7bZfDI9lxKqj9wJRHiSQBimCRanxDGHYE7TugnOmFJ9ScpgFSsLHFQtOH9wvmbQvBwv5nBuDBGJlG0+7iGkN+w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-musl": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.1.1.tgz", + "integrity": "sha512-xaFof2p0aO7C7ziMCLeueve09PVEKYCebljLTL3nyxoaRsYpEnBrUBP1aVpfD1Nk464dc7/wPV23fkHdOBie2g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-arm64-msvc": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.1.1.tgz", + "integrity": "sha512-wOLX/WRwWr0xGj2hnDf/t3tZfPlzzL9rGPsO1UnYSuNbRzwas/hC8JXnuhaEs8eCw+J+W4zxOJiVF4RxkvcMfw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-x64-msvc": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.1.1.tgz", + "integrity": "sha512-6Ge1AF1SVO+Ypjaw9IPcApm95krR3GQ32HgVqlIckbN/WqUlWYS0hnb8ZIdu3e0IbutbJgd8D2qSeb2/Cdpbdw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", @@ -3308,9 +3559,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3329,9 +3577,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3350,9 +3595,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3371,9 +3613,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3392,9 +3631,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3413,9 +3649,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -7821,9 +8054,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7845,9 +8075,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7869,9 +8096,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7893,9 +8117,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -8849,6 +9070,18 @@ "dev": true, "license": "MIT" }, + "node_modules/pdfjs-dist": { + "version": "6.5.438", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", + "integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==", + "license": "Apache-2.0", + "engines": { + "node": ">=22.13.0 || >=24" + }, + "optionalDependencies": { + "@napi-rs/canvas": "^1.0.13" + } + }, "node_modules/peowly": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/peowly/-/peowly-1.3.3.tgz", @@ -10919,9 +11152,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10939,9 +11169,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -10959,9 +11186,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10979,9 +11203,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10999,9 +11220,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -11019,9 +11237,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/package.json b/package.json index b7bf4c65..57dc886e 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "meeting-pane": "4.1.1-0", "mime-types": "^3.0.2", "pane-registry": "5.1.2-0", + "pdfjs-dist": "^6.5.438", "profile-pane": "4.1.1-0", "rdflib": "2.4.1", "solid-logic": "6.2.1-0", diff --git a/src/components/pdf-viewer/PdfViewer.ts b/src/components/pdf-viewer/PdfViewer.ts new file mode 100644 index 00000000..8bbc03ec --- /dev/null +++ b/src/components/pdf-viewer/PdfViewer.ts @@ -0,0 +1,224 @@ +import { html, nothing, TemplateResult } from 'lit' +import { property, state } from 'lit/decorators.js' +import { customElement, WebComponent } from 'solid-ui' +import type { LiveStore, NamedNode } from 'rdflib' +import { resourceFilename } from '../../humanReadable/previewHelpers' +import 'solid-ui/components/error-state' +import styles from './PdfViewier.styles.css' + +type PdfJsModule = typeof import('pdfjs-dist') +type PdfDocument = Awaited['promise']> +let pdfJsModulePromise: Promise | undefined + +function loadPdfJs (): Promise { + if (!pdfJsModulePromise) { + pdfJsModulePromise = import('./pdfJs').then(module => module.default) + } + return pdfJsModulePromise +} + +@customElement('solid-panes-pdf-viewer') +export default class PdfViewer extends WebComponent { + static styles = styles + + @property({ attribute: false }) + accessor store: LiveStore | undefined = undefined + + @property({ attribute: false }) + accessor subject: NamedNode | undefined = undefined + + @state() + private accessor errorMessage = '' + + protected pdfJs: PdfJsModule | undefined + protected pdfData: ArrayBuffer | undefined + private pdfDocument: PdfDocument | undefined + private pdfLoadingTask: ReturnType | undefined + private fetchGeneration = 0 + + @state() + private accessor pageCount = 0 + + @state() + private accessor currentPage = 1 + + private get previewTitle (): string { + return this.subject?.uri ? resourceFilename(this.subject.uri) : 'PDF preview' + } + + private dismissError = (): void => { + this.errorMessage = '' + } + + private clearDocument (): void { + this.errorMessage = '' + this.pdfJs = undefined + this.pdfData = undefined + if (this.pdfLoadingTask && !this.pdfLoadingTask.destroyed) { + this.pdfLoadingTask.destroy() + } + this.pdfLoadingTask = undefined + if (this.pdfDocument) { + this.pdfDocument.cleanup() + this.pdfDocument = undefined + } + } + + private selectPage (pageNumber: number): void { + if (!this.pdfDocument || pageNumber < 1 || pageNumber > this.pageCount) return + this.currentPage = pageNumber + } + + private async renderPage ( + pageNumber: number, + canvas: HTMLCanvasElement, + scale: number, + generation: number + ): Promise { + if (!this.pdfDocument || generation !== this.fetchGeneration) return + const page = await this.pdfDocument.getPage(pageNumber) + if (!this.isConnected || generation !== this.fetchGeneration) return + const viewport = page.getViewport({ scale }) + const canvasContext = canvas.getContext('2d') + if (!canvasContext) throw new Error('Unable to create a PDF canvas.') + canvas.width = viewport.width + canvas.height = viewport.height + await page.render({ canvas, canvasContext, viewport }).promise + } + + private async renderMainCanvases (generation: number): Promise { + await this.updateComplete + const canvases = this.renderRoot.querySelectorAll('.canvas') + if (canvases.length === 0) throw new Error('Unable to create a PDF canvas.') + await Promise.all(Array.from(canvases, (canvas, index) => + this.renderPage(index + 1, canvas, 1.25, generation) + )) + } + + private async renderThumbnailCanvases (generation: number): Promise { + await this.updateComplete + const canvases = this.renderRoot.querySelectorAll('.thumbnail-canvas') + await Promise.all(Array.from(canvases, (canvas, index) => + this.renderPage(index + 1, canvas, 0.18, generation) + )) + } + + private async renderMainPage (generation: number): Promise { + if (!this.pdfJs || !this.pdfData) return + + this.pdfJs.GlobalWorkerOptions.workerSrc = new URL( + 'pdfjs-dist/build/pdf.worker.min.mjs', + import.meta.url + ).toString() + const loadingTask = this.pdfJs.getDocument({ data: this.pdfData }) + this.pdfLoadingTask = loadingTask + const pdfDocument = await loadingTask.promise + if (!this.isConnected || generation !== this.fetchGeneration) { + await loadingTask.destroy() + return + } + + this.pdfDocument = pdfDocument + this.pageCount = pdfDocument.numPages + this.currentPage = 1 + if (!this.isConnected || generation !== this.fetchGeneration) return + + await this.renderMainCanvases(generation) + await this.renderThumbnailCanvases(generation) + } + + private renderThumbnailLayout (): TemplateResult { + return html` +
+ ${this.pageCount > 0 + ? Array.from({ length: this.pageCount }, (_, index) => html` + + `) + : nothing} +
` + } + + private async fetchDocument (): Promise { + const generation = ++this.fetchGeneration + const { subject, store } = this + this.clearDocument() + if (!subject || !store) return + + const isCurrent = () => this.isConnected && + generation === this.fetchGeneration && this.subject === subject && this.store === store + + try { + const response = await store.fetcher._fetch(subject.uri) + if (!response.ok) throw new Error(`HTTP ${response.status}`) + const pdfData = await response.arrayBuffer() + if (!isCurrent()) return + const pdfJs = await loadPdfJs() + if (!isCurrent()) return + this.pdfJs = pdfJs + this.pdfData = pdfData + await this.renderMainPage(generation) + } catch (error) { + if (isCurrent()) { + this.errorMessage = error instanceof Error ? error.message : String(error) + } + } + } + + connectedCallback (): void { + super.connectedCallback() + if (this.hasUpdated) this.fetchDocument() + } + + protected updated (changed: Map): void { + super.updated(changed) + if (changed.has('subject') || changed.has('store')) { + this.fetchDocument() + } + } + + disconnectedCallback (): void { + ++this.fetchGeneration + this.clearDocument() + super.disconnectedCallback() + } + + render () { + return html` +
+
+
+ + This preview displays pages as images. PDF text and links are not accessible in this preview. + + ${(this.pageCount > 0 ? Array.from({ length: this.pageCount }, (_, index) => index + 1) : [1]).map(pageNumber => html` +
+ +
+ `)} +
+ +
+ ${this.errorMessage + ? html`` + : nothing} +
+ ` + } +} diff --git a/src/components/pdf-viewer/PdfViewier.styles.css b/src/components/pdf-viewer/PdfViewier.styles.css new file mode 100644 index 00000000..a6af770b --- /dev/null +++ b/src/components/pdf-viewer/PdfViewier.styles.css @@ -0,0 +1,207 @@ +:host { + display: flex; + flex: 1 1 0%; + min-width: 0; + min-height: 0; +} + +.pdf-viewer { + display: flex; + flex: 1 1 0%; + min-width: 0; + min-height: 0; + overflow: hidden; + color: var(--solid-ui-color-gray-800, #2f323f); + background: var(--solid-ui-color-white, #fff); + border: 1px solid var(--solid-ui-color-gray-200, #c7c9d0); +} + +.content { + display: grid; + grid-template-columns: minmax(0, 1fr) 120px; + flex: 1 1 0%; + min-width: 0; + min-height: 0; +} + +.main { + display: flex; + flex: 1 1 0%; + min-width: 0; + min-height: 0; + justify-content: center; + padding: 16px; + overflow: auto; +} + +.main:focus-visible { + outline: 2px solid var(--solid-ui-color-gray-800, #101828); + outline-offset: -2px; +} + +.page { + display: none; + flex: 0 0 auto; + width: 100%; + max-width: 100%; +} + +.page[data-current] { + display: block; +} + +.canvas { + display: block; + width: 100%; + height: auto; + border: 1.316px solid var(--solid-ui-color-gray-400, #99A1AF); +} + +.thumbnails { + position: relative; + min-width: 0; + min-height: 0; +} + +.thumbnail-container { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + box-sizing: border-box; + padding: 12px 10px; + gap: 25px; + overflow-x: hidden; + overflow-y: auto; +} + +.thumbnail { + display: flex; + flex: 0 0 auto; + flex-direction: column; + align-items: center; + align-self: stretch; + min-width: 44px; + min-height: 44px; +} + +.thumbnail:focus-visible { + outline: 2px solid var(--solid-ui-color-gray-800, #101828); + outline-offset: 2px; +} + +.thumbnail-content { + display: flex; + flex-direction: column; + align-items: center; + align-self: stretch; + gap: 9px; +} + +.thumbnail-canvas { + display: block; + width: 100%; + height: auto; +} + +.thumbnail-label { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: 20px; + height: 19px; + padding: 10px; + color: var(--solid-ui-color-gray-500, #6a7282); + text-align: center; + font-size: var(--solid-ui-font-size-sm, 0.875rem); + font-weight: 500; +} + +.thumbnail[aria-current='page'] .thumbnail-canvas { + border: 1px solid var(--solid-ui-color-primary, #7c4dff); +} + +.thumbnail[aria-current='page'] .thumbnail-label { + color: var(--solid-ui-color-gray-700, #364153); + background: var(--solid-ui-color-lavender-300, #e6dcff); +} + +@media (max-width: 768px) { + .pdf-viewer { + border-radius: 5px; + } + + .content { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 20px; + padding: 15px 20px 15px 16px; + box-sizing: border-box; + } + + .main { + width: 100%; + flex-direction: column; + align-items: center; + gap: 20px; + padding: 0; + box-sizing: border-box; + } + + .page { + display: block; + } + + .thumbnails { + display: none; + } + + .thumbnail-container { + display: flex; + align-items: flex-start; + width: 100%; + height: auto; + gap: 8px; + padding: 0; + overflow-x: auto; + overflow-y: hidden; + } + + .thumbnail { + flex: 0 0 58px; + } +} + +:host([data-layout='mobile']) { + .pdf-viewer { + border-radius: 5px; + } + + .content { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 20px; + padding: 15px 20px 15px 16px; + box-sizing: border-box; + } + + .main { + width: 100%; + flex-direction: column; + align-items: center; + gap: 20px; + padding: 0; + box-sizing: border-box; + } + + .page { + display: block; + } + + .thumbnails { + display: none; + } +} diff --git a/src/components/pdf-viewer/index.ts b/src/components/pdf-viewer/index.ts new file mode 100644 index 00000000..74714165 --- /dev/null +++ b/src/components/pdf-viewer/index.ts @@ -0,0 +1,4 @@ +import PdfViewer from './PdfViewer' + +export { PdfViewer } +export default PdfViewer \ No newline at end of file diff --git a/src/components/pdf-viewer/pdfJs.ts b/src/components/pdf-viewer/pdfJs.ts new file mode 100644 index 00000000..b872b0b7 --- /dev/null +++ b/src/components/pdf-viewer/pdfJs.ts @@ -0,0 +1,3 @@ +import * as pdfJs from 'pdfjs-dist' + +export default pdfJs diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index ce1f829c..2fba33d9 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -15,6 +15,8 @@ import { renderMarkdownContent } from './markdown' import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' import type IframePreview from '../components/iframe-preview' import '../components/iframe-preview' +import type PdfViewer from '../components/pdf-viewer' +import '../components/pdf-viewer' export { IFRAME_PREVIEW_FRAME_NAME } from './previewHelpers' @@ -444,6 +446,7 @@ const humanReadablePane: HumanReadablePaneDefinition = { // Fallback: detect markdown by file extension if content-type is not text/markdown const isMarkdown = ct === 'text/markdown' || isMarkdownFile(subject.uri) const isPlainText = ct === 'text/plain' || ct === 'application/json' || (!ct && isJsonFile(subject.uri)) + const isPdf = ct === 'application/pdf' if (ct) { // console.log('humanReadablePane: c-t:' + ct) @@ -468,7 +471,14 @@ const humanReadablePane: HumanReadablePaneDefinition = { }) } - if (isMarkdown) { + if (isPdf) { + const preview = myDocument.createElement('solid-panes-pdf-viewer') as PdfViewer + preview.dataset.layout = context.environment?.layout ?? 'desktop' + preview.store = kb + preview.subject = subject + div.appendChild(preview) + div.classList.add('human-readable-pane--document') + } else if (isMarkdown) { // For markdown, use a DIV element and render the content const frame = myDocument.createElement('div') renderMarkdownContent(kb, subject, frame) diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 77ff6045..3d3c231c 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -11,12 +11,16 @@ import humanReadablePane, { const uri = 'https://pod.example/docs/page.html' -function renderWith (contentType: string, fetcher: Record) { +function renderWith ( + contentType: string, + fetcher: Record, + environment: Record = {} +) { const subject = { uri, doc: () => subject } const store = { fetcher: { getHeader: vi.fn().mockReturnValue([contentType]), ...fetcher } } - const context = { dom: document, session: { store } } as any + const context = { dom: document, session: { store }, environment } as any const pane = humanReadablePane.render(subject as any, context) document.body.appendChild(pane) return pane @@ -422,17 +426,26 @@ describe('human readable pane iframe rendering', () => { revokeObjectURL.mockRestore() }) - it('revokes an active blob URL when the preview is removed', async () => { - const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:https://pod.example/resource') - const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) + it('renders the PDF viewer without an iframe or blob URL', async () => { const pane = renderWith('application/pdf', { _fetch: vi.fn().mockResolvedValue(new Response('pdf', { headers: { 'content-type': 'application/pdf' } })) }) - await vi.waitFor(() => expect(getFrame(pane)?.src).toBe('blob:https://pod.example/resource')) - pane.remove() - expect(revokeObjectURL).toHaveBeenCalledWith('blob:https://pod.example/resource') - createObjectURL.mockRestore() - revokeObjectURL.mockRestore() + const preview = pane.querySelector('solid-panes-pdf-viewer') as HTMLElement & { + pdfData?: ArrayBuffer + } + await vi.waitFor(() => expect(preview.pdfData).toBeInstanceOf(ArrayBuffer)) + expect(pane.querySelector('iframe')).toBeNull() + const main = preview.shadowRoot?.querySelector('.main') + expect(main).toHaveAttribute('tabindex', '0') + expect(main).toHaveAttribute('aria-describedby', 'pdf-preview-description') + expect(preview.shadowRoot?.querySelector('#pdf-preview-description')?.textContent) + .toContain('PDF text and links are not accessible in this preview') + expect(preview.shadowRoot?.querySelector('.canvas')).toHaveAttribute('role', 'img') + }) + + it('passes the pane registry mobile layout to the PDF viewer', () => { + const pane = renderWith('application/pdf', { _fetch: vi.fn() }, { layout: 'mobile' }) + expect(pane.querySelector('solid-panes-pdf-viewer')).toHaveAttribute('data-layout', 'mobile') }) it('loads a changed subject and ignores the earlier response', async () => { @@ -506,9 +519,9 @@ describe('human readable pane iframe rendering', () => { } const pane = humanReadablePane.render(subject as any, { dom: document, session: { store } } as any) document.body.appendChild(pane) - await vi.waitFor(() => expect(getFrame(pane)?.title).toBe('file%FF.pdf')) - - expect(getFrame(pane)?.title).toBe('file%FF.pdf') + await vi.waitFor(() => expect( + pane.querySelector('solid-panes-pdf-viewer')?.shadowRoot?.querySelector('section') + ).toHaveAttribute('aria-label', 'Preview of file%FF.pdf')) }) it('gives Dokieli the signed-in viewer as a bridged session', async () => { From 4dbc824a13b6e8a4788d6139a93b02ed9b658d4d Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 13:53:38 +1100 Subject: [PATCH 05/24] improve plaintext --- src/humanReadable/humanReadablePane.css | 6 +++++- src/humanReadable/index.ts | 19 ++++--------------- src/humanReadable/markdown.ts | 3 +-- src/humanReadable/previewFrame.ts | 6 +----- src/humanReadable/textPreview.ts | 21 +++++++++++++++++++++ test/unit/humanReadablePane.test.ts | 20 ++++++++++++++++++++ 6 files changed, 52 insertions(+), 23 deletions(-) create mode 100644 src/humanReadable/textPreview.ts diff --git a/src/humanReadable/humanReadablePane.css b/src/humanReadable/humanReadablePane.css index 02fb53fc..71469882 100644 --- a/src/humanReadable/humanReadablePane.css +++ b/src/humanReadable/humanReadablePane.css @@ -115,13 +115,17 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { } .human-readable-pane__frame--plain-text { - font-family: monospace; margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; } +.human-readable-pane__frame--plain-text:focus-visible { + outline: 2px solid var(--solid-ui-color-gray-800, #101828); + outline-offset: -2px; +} + .human-readable-pane__frame--markdown > * { max-width: 100%; box-sizing: border-box; diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index 2fba33d9..7737a191 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -10,8 +10,8 @@ import type { DataBrowserContext, RenderEnvironment } from 'pane-registry' import type { NamedNode } from 'rdflib' import './humanReadablePane.css' import { createPreviewBridge } from './previewBridge' -import { configurePreviewFrame } from './previewFrame' import { renderMarkdownContent } from './markdown' +import { renderPlainTextContent } from './textPreview' import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' import type IframePreview from '../components/iframe-preview' import '../components/iframe-preview' @@ -458,19 +458,6 @@ const humanReadablePane: HumanReadablePaneDefinition = { div.classList.add('human-readable-pane') applyEnvironmentAttributes(div) - // render plain text in a PRE element - const renderPlainTextContent = function (frame: HTMLPreElement) { - kb.fetcher.webOperation('GET', subject.uri).then(response => { - const plainText = response.responseText ?? '' - const lines = Math.min(30, plainText.split(/\n/).length + 5) - frame.textContent = plainText - configurePreviewFrame(frame, 'plain-text', lines) - }).catch(error => { - console.error('Error fetching plain text content:', error) - frame.textContent = 'Error loading content' - }) - } - if (isPdf) { const preview = myDocument.createElement('solid-panes-pdf-viewer') as PdfViewer preview.dataset.layout = context.environment?.layout ?? 'desktop' @@ -490,7 +477,9 @@ const humanReadablePane: HumanReadablePaneDefinition = { } else if (isPlainText) { // For plain text, use a PRE element and render the content const frame = myDocument.createElement('pre') - renderPlainTextContent(frame) + frame.tabIndex = 0 + frame.setAttribute('aria-label', 'Plain text document') + renderPlainTextContent(kb, subject, frame) const frameContainer = myDocument.createElement('div') frameContainer.classList.add('human-readable-pane__container') frameContainer.appendChild(frame) diff --git a/src/humanReadable/markdown.ts b/src/humanReadable/markdown.ts index e12fc928..a318b5d5 100644 --- a/src/humanReadable/markdown.ts +++ b/src/humanReadable/markdown.ts @@ -7,11 +7,10 @@ import { configurePreviewFrame } from './previewFrame' export const renderMarkdownContent = function (store: LiveStore, subject: NamedNode, frame: HTMLDivElement) { store.fetcher.webOperation('GET', subject.uri).then(response => { const markdownText = response.responseText ?? '' - const lines = Math.min(30, markdownText.split(/\n/).length + 5) const res = marked.parse(markdownText, { async: false }) const clean = DOMPurify.sanitize(res) frame.innerHTML = clean - configurePreviewFrame(frame, 'markdown', lines) + configurePreviewFrame(frame, 'markdown') }).catch(error => { console.error('Error fetching markdown content:', error) frame.innerHTML = '

Error loading content

' diff --git a/src/humanReadable/previewFrame.ts b/src/humanReadable/previewFrame.ts index 4020c2a0..6e60c645 100644 --- a/src/humanReadable/previewFrame.ts +++ b/src/humanReadable/previewFrame.ts @@ -1,12 +1,8 @@ export function configurePreviewFrame ( frame: HTMLElement, - modifier: 'markdown' | 'plain-text' | 'iframe', - lines?: number + modifier: 'markdown' | 'plain-text' | 'iframe' ): void { frame.className = '' frame.classList.add('human-readable-pane__frame') frame.classList.add(`human-readable-pane__frame--${modifier}`) - if (lines !== undefined) { - frame.style.setProperty('--human-readable-pane-height', `${lines * 16}px`) - } } diff --git a/src/humanReadable/textPreview.ts b/src/humanReadable/textPreview.ts new file mode 100644 index 00000000..f2d027b8 --- /dev/null +++ b/src/humanReadable/textPreview.ts @@ -0,0 +1,21 @@ +import type { DataBrowserContext } from 'pane-registry' +import type { NamedNode } from 'rdflib' +import { html, render } from 'lit-html' +import { configurePreviewFrame } from './previewFrame' + +type Store = DataBrowserContext['session']['store'] + +export function renderPlainTextContent ( + store: Store, + subject: NamedNode, + frame: HTMLPreElement +): void { + store.fetcher.webOperation('GET', subject.uri).then(response => { + const plainText = response.responseText ?? '' + render(html`${plainText}`, frame) + configurePreviewFrame(frame, 'plain-text') + }).catch(error => { + console.error('Error fetching plain text content:', error) + render(html`Error loading content`, frame) + }) +} diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 3d3c231c..87019f85 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -151,6 +151,26 @@ describe('human readable pane iframe rendering', () => { expect(webOperation).toHaveBeenCalledWith('GET', uri) }) + it('renders plain text as escaped text through Lit', async () => { + const webOperation = vi.fn().mockResolvedValue({ responseText: '' }) + const pane = renderWith('text/plain', { webOperation }) + await flush() + + expect(pane.querySelector('pre')?.textContent).toBe('') + expect(pane.querySelector('script')).toBeNull() + }) + + it('makes plain text keyboard accessible in the mobile layout', () => { + const pane = renderWith('text/plain', { + webOperation: vi.fn().mockResolvedValue({ responseText: 'Text' }) + }, { layout: 'mobile' }) + const frame = pane.querySelector('pre') + + expect(pane).toHaveAttribute('data-layout', 'mobile') + expect(frame).toHaveAttribute('tabindex', '0') + expect(frame).toHaveAttribute('aria-label', 'Plain text document') + }) + it('renders HTML from the authenticated fetch instead of letting the iframe request it', async () => { const fetch = vi.fn().mockResolvedValue(htmlResponse('Hello')) const pane = renderWith('text/html', { _fetch: fetch }) From a722436632988b69def061d242f626369e3beb72 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 15:35:14 +1100 Subject: [PATCH 06/24] use markdown it instead of marked and improve code --- package-lock.json | 472 +++++++-------------------- package.json | 3 +- src/humanReadable/markdown.ts | 18 - src/humanReadable/markdownIt.ts | 3 + src/humanReadable/markdownPreview.ts | 40 +++ test/unit/markdownPreview.test.ts | 58 ++++ 6 files changed, 220 insertions(+), 374 deletions(-) delete mode 100644 src/humanReadable/markdown.ts create mode 100644 src/humanReadable/markdownIt.ts create mode 100644 src/humanReadable/markdownPreview.ts create mode 100644 test/unit/markdownPreview.test.ts diff --git a/package-lock.json b/package-lock.json index b3a29148..ca5047bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "folder-pane": "4.1.5-0", "issue-pane": "4.1.1-0", "lit-html": "^3.3.2", - "marked": "^18.0.3", + "markdown-it": "^15.0.3", "meeting-pane": "4.1.1-0", "mime-types": "^3.0.2", "pane-registry": "5.1.2-0", @@ -34,6 +34,7 @@ "@iconify/json": "2.2.494", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "^6.9.1", + "@types/markdown-it": "^14.2.0", "@types/node": "^22.20.0", "@typescript-eslint/parser": "^8.59.3", "@vitest/coverage-v8": "^4.0.18", @@ -3381,17 +3382,6 @@ "url": "https://paulmillr.com/funding/" } }, - "node_modules/@oxc-project/types": { - "version": "0.159.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.159.0.tgz", - "integrity": "sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==", - "dev": true, - "license": "MIT", - "peer": true, - "funding": { - "url": "https://github.com/sponsors/oxc-project" - } - }, "node_modules/@parse5/tools": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/@parse5/tools/-/tools-0.3.0.tgz", @@ -3443,296 +3433,6 @@ "@types/node": "*" } }, - "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.3.tgz", - "integrity": "sha512-K1itOg1Xl50XyjLDa4qQZqaYsfiQbFbFRWXOEOupOsGr3whhm5ed4lgySd6Inohv2TB0+sdU4AxORKuS/TGang==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.3.tgz", - "integrity": "sha512-re+E0E3YSJXjEFzdOvBgkVUev1Gg49ileia04qy+Djn0lIMBr7pnwVOYQ+4vc9XbLClCmMziasqXHM7KTmKNKQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.3.tgz", - "integrity": "sha512-6pMLYsUiQJXPkUj/CG447hOBKtbe+hjWw/wbxe/mucoPKgnLSVRTzey7s0kXfqrjxhDd3gQ2hj6lgUKRumsIzw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.3.tgz", - "integrity": "sha512-Lz+TskwvhceQgwnP+0ox5ZeL7HDDXHKWVRpOqC1Eo05y6rYyfvvep0msGqC95kQTykXrmGgP6qwJB1NdgNZVhg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.3.tgz", - "integrity": "sha512-sIzqNDbA7GFDXU8k9/vcJyV1p45mCe+xHOLo9qD7gdbTbMlwB+SpnFoP7WSpC2iYdGfOX9pjBxCfViRn/Nu3Jw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.3.tgz", - "integrity": "sha512-HYysnZZ7HD3FM5RIBN6wDMoxtOjw4LS9HhRuQ57MsZt5XGpGRPxVpplvr7vUXRN+9MD8zb6vn1JRP06PXIuMYQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.3.tgz", - "integrity": "sha512-XAyLqWSoEKVc8wsDbCIz5o2sBY6ye+0YByK9ib5QxFReoM1KHyThSHsdUODa1DKNzlEfae+p9QwK62LsVwo6Nw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.3.tgz", - "integrity": "sha512-oVyicDPj6vUVFRnuoQS7M2Ab8EkGWoq3a5ntyQqjtZoXfgVykIJqN2IAJSi9q9UyNoQUW0vbBLQSgGtlPJ40Kg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.3.tgz", - "integrity": "sha512-k7aFSWgUoi/X7jCst7UEof7pS5jc5ymD8mT/pdFE+pO1IBBI2+JU5Os4HEDqS/tYhetRggwM7MOiLP3cg1bSBQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.3.tgz", - "integrity": "sha512-D5mxHpr1qIb1Pt5UT+Bm2p6vJ7+VxcxWcxZCYVDFzZwWRq9iLiEg4/ROsaXFQl1O8sDQZZJ55UoRWWMK64uH5w==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.3.tgz", - "integrity": "sha512-nmW1O4BbNEmQI9+KTHbJgbDv0EuyZy64oBnRlMCtLJ8lQMIJ/H/iziQ0g2IUlHEhNrSebGvs9cRrlRj8oEfP+g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.3.tgz", - "integrity": "sha512-ivU4JFHK5nFzrRbzp3+vwYdLj8mFckH4oz3hEl5LH/YeThr9/m2N2vF3NvLevtHq6e0COimgrEVyYTwQhh4ODg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.3.tgz", - "integrity": "sha512-XxZoRIkNZ/7pFgvOA8QJmx3uFjMyVz7zS2/urzlaFffoOGclDvpUAMu3AHKT551E8JBKXLxIjpYxYMdF6Mz9vQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.3.tgz", - "integrity": "sha512-bBl1MB2gF26PSPy3CiDLiv+A6JGI546WbsDR34LfKAywSGeBeQXaDanoDG6QdZDJs53M1QyJir5MTKTu1n4ptA==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@emnapi/core": "2.0.0-beta.2", - "@emnapi/runtime": "2.0.0-beta.2", - "@napi-rs/wasm-runtime": "1.2.6" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=23.5.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.3.tgz", - "integrity": "sha512-6rZur0hyen4LPhOxWIg7az1YX+Eo8Vvauc0D6lFYGK/QCvN+1XpnB8aFe3jQc/PBUGIReJJnLX3sS8h33/5v7A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.3.tgz", - "integrity": "sha512-Ggzyuq1mN7claruAZH10aiiM1N3LRCoMP5xDXPdU514ulL0D2bksCWgFqEmEM2/pDzEP7Dq+dcv7IH452jtr1w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "peer": true, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, "node_modules/@rolldown/plugin-babel": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/@rolldown/plugin-babel/-/plugin-babel-0.2.4.tgz", @@ -3983,6 +3683,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.2.0.tgz", + "integrity": "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -3992,16 +3717,6 @@ "undici-types": "~6.21.0" } }, - "node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "license": "MIT", - "peer": true, - "dependencies": { - "csstype": "^3.2.2" - } - }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -8172,6 +7887,25 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, "node_modules/lit": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz", @@ -8327,16 +8061,59 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/marked": { - "version": "18.2.1", - "resolved": "https://registry.npmjs.org/marked/-/marked-18.2.1.tgz", - "integrity": "sha512-ii4bxCTCqqwpT86XZWgJNs+ZnAIZksmLGYMViWA7PDIXYIeNo1x6cDdX3JOip9NM/cI6p8z57FxliACboTruMA==", + "node_modules/markdown-it": { + "version": "15.0.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", + "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], "license": "MIT", - "bin": { - "marked": "bin/marked.js" + "dependencies": { + "argparse": "^3.0.3", + "entities": "^8.1.0", + "linkify-it": "^6.1.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/argparse": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", + "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "license": "BSD-2-Clause", "engines": { - "node": ">= 20" + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" } }, "node_modules/math-intrinsics": { @@ -8355,6 +8132,12 @@ "dev": true, "license": "CC0-1.0" }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, "node_modules/meeting-pane": { "version": "4.1.1-0", "resolved": "https://registry.npmjs.org/meeting-pane/-/meeting-pane-4.1.1-0.tgz", @@ -9313,6 +9096,15 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -9632,42 +9424,6 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, - "node_modules/rolldown": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.3.tgz", - "integrity": "sha512-ksB1g74e7haRy02OYm4lOQAlr6sK6hBpAY5R+YC30Gkv4L1COwF6M9umBAYAPxWpGow6Vr+IXtyDjH9fq7A+Zg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "@oxc-project/types": "=0.159.0", - "@rolldown/pluginutils": "^1.0.0" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.3.3", - "@rolldown/binding-android-arm64": "1.3.3", - "@rolldown/binding-darwin-arm64": "1.3.3", - "@rolldown/binding-darwin-x64": "1.3.3", - "@rolldown/binding-freebsd-x64": "1.3.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.3.3", - "@rolldown/binding-linux-arm64-gnu": "1.3.3", - "@rolldown/binding-linux-arm64-musl": "1.3.3", - "@rolldown/binding-linux-ppc64-gnu": "1.3.3", - "@rolldown/binding-linux-s390x-gnu": "1.3.3", - "@rolldown/binding-linux-x64-gnu": "1.3.3", - "@rolldown/binding-linux-x64-musl": "1.3.3", - "@rolldown/binding-openharmony-arm64": "1.3.3", - "@rolldown/binding-wasm32-wasi": "1.3.3", - "@rolldown/binding-win32-arm64-msvc": "1.3.3", - "@rolldown/binding-win32-x64-msvc": "1.3.3" - } - }, "node_modules/safe-array-concat": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", @@ -10655,6 +10411,12 @@ "typescript": ">=4.8.4 <6.1.0" } }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "license": "MIT" + }, "node_modules/ufo": { "version": "1.6.4", "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", diff --git a/package.json b/package.json index 57dc886e..709044b1 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "folder-pane": "4.1.5-0", "issue-pane": "4.1.1-0", "lit-html": "^3.3.2", - "marked": "^18.0.3", + "markdown-it": "^15.0.3", "meeting-pane": "4.1.1-0", "mime-types": "^3.0.2", "pane-registry": "5.1.2-0", @@ -84,6 +84,7 @@ "@iconify/json": "2.2.494", "@testing-library/dom": "^10.4.1", "@testing-library/jest-dom": "^6.9.1", + "@types/markdown-it": "^14.2.0", "@types/node": "^22.20.0", "@typescript-eslint/parser": "^8.59.3", "@vitest/coverage-v8": "^4.0.18", diff --git a/src/humanReadable/markdown.ts b/src/humanReadable/markdown.ts deleted file mode 100644 index a318b5d5..00000000 --- a/src/humanReadable/markdown.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { LiveStore, NamedNode } from "rdflib" -import { marked } from "marked" -import DOMPurify from 'dompurify' -import { configurePreviewFrame } from './previewFrame' - - // render markdown to html in a DIV element -export const renderMarkdownContent = function (store: LiveStore, subject: NamedNode, frame: HTMLDivElement) { - store.fetcher.webOperation('GET', subject.uri).then(response => { - const markdownText = response.responseText ?? '' - const res = marked.parse(markdownText, { async: false }) - const clean = DOMPurify.sanitize(res) - frame.innerHTML = clean - configurePreviewFrame(frame, 'markdown') - }).catch(error => { - console.error('Error fetching markdown content:', error) - frame.innerHTML = '

Error loading content

' - }) - } diff --git a/src/humanReadable/markdownIt.ts b/src/humanReadable/markdownIt.ts new file mode 100644 index 00000000..88cc7675 --- /dev/null +++ b/src/humanReadable/markdownIt.ts @@ -0,0 +1,3 @@ +import MarkdownIt from 'markdown-it' + +export default MarkdownIt diff --git a/src/humanReadable/markdownPreview.ts b/src/humanReadable/markdownPreview.ts new file mode 100644 index 00000000..9073c961 --- /dev/null +++ b/src/humanReadable/markdownPreview.ts @@ -0,0 +1,40 @@ +import DOMPurify from 'dompurify' +import { html, render } from 'lit-html' +import { unsafeHTML } from 'lit-html/directives/unsafe-html.js' +import type { DataBrowserContext } from 'pane-registry' +import type { NamedNode } from 'rdflib' +import { configurePreviewFrame } from './previewFrame' + +type Store = DataBrowserContext['session']['store'] + +let markdownItPromise: Promise | undefined + +function loadMarkdownIt (): Promise { + markdownItPromise ??= import('./markdownIt') + return markdownItPromise +} + +export function renderMarkdownContent ( + store: Store, + subject: NamedNode, + frame: HTMLDivElement +): void { + store.fetcher.webOperation('GET', subject.uri).then(async response => { + const markdownText = response.responseText ?? '' + const MarkdownIt = (await loadMarkdownIt()).default + const markdown = new MarkdownIt({ + breaks: true, + html: false, + linkify: true, + typographer: true + }) + const renderedMarkdown = markdown.render(markdownText) + const sanitizedMarkdown = DOMPurify.sanitize(renderedMarkdown) + + render(html`${unsafeHTML(sanitizedMarkdown)}`, frame) + configurePreviewFrame(frame, 'markdown') + }).catch(error => { + console.error('Error fetching markdown content:', error) + render(html`

Error loading content

`, frame) + }) +} diff --git a/test/unit/markdownPreview.test.ts b/test/unit/markdownPreview.test.ts new file mode 100644 index 00000000..d6b9538b --- /dev/null +++ b/test/unit/markdownPreview.test.ts @@ -0,0 +1,58 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { renderMarkdownContent } from '../../src/humanReadable/markdownPreview' + +const subject = { uri: 'https://pod.example/docs/readme.md' } as any + +function createFrame () { + const frame = document.createElement('div') + document.body.appendChild(frame) + return frame +} + +afterEach(() => { + document.body.replaceChildren() + vi.restoreAllMocks() +}) + +describe('renderMarkdownContent', () => { + it('renders Markdown and removes raw HTML', async () => { + const frame = createFrame() + const store = { + fetcher: { + webOperation: vi.fn().mockResolvedValue({ + responseText: '# Heading\n\n\n\n**bold**' + }) + } + } + + renderMarkdownContent(store as any, subject, frame) + + await vi.waitFor(() => { + expect(frame.querySelector('h1')?.textContent).toBe('Heading') + }) + expect(frame.querySelector('strong')?.textContent).toBe('bold') + expect(frame.querySelector('script')).toBeNull() + expect(frame).toHaveClass('human-readable-document-frame', 'human-readable-markdown-preview') + expect(store.fetcher.webOperation).toHaveBeenCalledWith('GET', subject.uri) + }) + + it('shows an error when Markdown cannot be fetched', async () => { + const frame = createFrame() + vi.spyOn(console, 'error').mockImplementation(() => {}) + const store = { + fetcher: { + webOperation: vi.fn().mockRejectedValue(new Error('network failure')) + } + } + + renderMarkdownContent(store as any, subject, frame) + + await vi.waitFor(() => { + expect(frame.textContent).toBe('Error loading content') + }) + expect(console.error).toHaveBeenCalledWith( + 'Error fetching markdown content:', + expect.any(Error) + ) + }) +}) From cca8a32b65acad58691ade705fae00faf4c2edc6 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 15:35:30 +1100 Subject: [PATCH 07/24] Add JSON separately and format nicely Prompt: tokenize JSON to display nicely Co-authored-by: GPT-5.6 Luna --- src/humanReadable/index.ts | 37 ++++++-- src/humanReadable/jsonPreview.ts | 144 +++++++++++++++++++++++++++++++ 2 files changed, 176 insertions(+), 5 deletions(-) create mode 100644 src/humanReadable/jsonPreview.ts diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index 7737a191..a73b4acc 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -10,7 +10,8 @@ import type { DataBrowserContext, RenderEnvironment } from 'pane-registry' import type { NamedNode } from 'rdflib' import './humanReadablePane.css' import { createPreviewBridge } from './previewBridge' -import { renderMarkdownContent } from './markdown' +import { renderMarkdownContent } from './markdownPreview' +import { renderJsonContent } from './jsonPreview' import { renderPlainTextContent } from './textPreview' import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' import type IframePreview from '../components/iframe-preview' @@ -49,9 +50,15 @@ const isMarkdownFile = (uri?: string | null): boolean => { const isJsonFile = (uri?: string | null): boolean => { if (!uri) return false const path = uri.split('?')[0].split('#')[0] - return /\.json$/i.test(path) + return /\.(json|jsonld)$/i.test(path) } +const isJsonContentType = (contentType?: string | null): boolean => + contentType === 'application/json' || contentType === 'application/ld+json' + +const canUseJsonExtensionFallback = (contentType?: string | null): boolean => + !contentType || contentType === 'application/octet-stream' + // Cache for dokieli detection results (keyed by subject URI) const dokieliCache = new Map() @@ -351,6 +358,7 @@ const humanReadablePane: HumanReadablePaneDefinition = { 'text/html', 'text/markdown', 'application/json', + 'application/ld+json', 'application/xhtml+xml', 'application/pdf', 'video/mp4' @@ -399,6 +407,13 @@ const humanReadablePane: HumanReadablePaneDefinition = { return 'View' } + const cts = kb.fetcher.getHeader(subject.doc(), 'content-type') + const contentType = cts ? cts[0].split(';', 1)[0].trim() : null + if (isJsonFile(subject.uri) && + (isJsonContentType(contentType) || canUseJsonExtensionFallback(contentType))) { + return 'View' + } + if ( hasContentTypeIn(kb, subject, allowed) || hasContentTypeIn2(kb, subject, allowed) @@ -445,7 +460,9 @@ const humanReadablePane: HumanReadablePaneDefinition = { // Fallback: detect markdown by file extension if content-type is not text/markdown const isMarkdown = ct === 'text/markdown' || isMarkdownFile(subject.uri) - const isPlainText = ct === 'text/plain' || ct === 'application/json' || (!ct && isJsonFile(subject.uri)) + const isJson = isJsonContentType(ct) || + (isJsonFile(subject.uri) && canUseJsonExtensionFallback(ct)) + const isPlainText = ct === 'text/plain' const isPdf = ct === 'application/pdf' if (ct) { @@ -470,7 +487,17 @@ const humanReadablePane: HumanReadablePaneDefinition = { const frame = myDocument.createElement('div') renderMarkdownContent(kb, subject, frame) const frameContainer = myDocument.createElement('div') - frameContainer.classList.add('human-readable-pane__container') + frameContainer.classList.add('human-readable-document-container') + frameContainer.appendChild(frame) + div.appendChild(frameContainer) + div.classList.add('human-readable-pane--document') + } else if (isJson) { + const frame = myDocument.createElement('pre') + frame.tabIndex = 0 + frame.setAttribute('aria-label', 'JSON document') + renderJsonContent(kb, subject, frame) + const frameContainer = myDocument.createElement('div') + frameContainer.classList.add('human-readable-document-container') frameContainer.appendChild(frame) div.appendChild(frameContainer) div.classList.add('human-readable-pane--document') @@ -481,7 +508,7 @@ const humanReadablePane: HumanReadablePaneDefinition = { frame.setAttribute('aria-label', 'Plain text document') renderPlainTextContent(kb, subject, frame) const frameContainer = myDocument.createElement('div') - frameContainer.classList.add('human-readable-pane__container') + frameContainer.classList.add('human-readable-document-container') frameContainer.appendChild(frame) div.appendChild(frameContainer) div.classList.add('human-readable-pane--document') diff --git a/src/humanReadable/jsonPreview.ts b/src/humanReadable/jsonPreview.ts new file mode 100644 index 00000000..f986bf77 --- /dev/null +++ b/src/humanReadable/jsonPreview.ts @@ -0,0 +1,144 @@ +import type { LiveStore, NamedNode } from 'rdflib' +import { html, render } from 'lit-html' +import { configurePreviewFrame } from './previewFrame' + +type JsonToken = { + text: string + kind: 'key' | 'string' | 'number' | 'boolean' | 'null' | 'punctuation' +} + +const TOKEN = /"(?:\\u[0-9a-fA-F]{4}|\\["\\/bfnrt]|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|\{|\}|\[|\]|,|:/y + +function tokenize (source: string): JsonToken[] { + const tokens: JsonToken[] = [] + let position = 0 + + while (position < source.length) { + while (position < source.length) { + const code = source.charCodeAt(position) + if (code !== 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) break + position++ + } + if (position === source.length) break + + TOKEN.lastIndex = position + const match = TOKEN.exec(source) + if (!match) throw new SyntaxError('Unexpected token in JSON') + const text = match[0] + let kind: JsonToken['kind'] + if (text[0] === '"') { + kind = 'string' + } else if (/^[0-9-]/.test(text)) { + kind = 'number' + } else if ('{}[],:'.includes(text)) { + kind = 'punctuation' + } else if (text === 'true' || text === 'false') { + kind = 'boolean' + } else { + kind = 'null' + } + tokens.push({ text, kind }) + position = TOKEN.lastIndex + } + + return tokens +} + +function prettyTokens (tokens: JsonToken[]): Array { + const output: Array = [] + let depth = 0 + + for (let index = 0; index < tokens.length; index++) { + const token = tokens[index] + const next = tokens[index + 1] + const previous = tokens[index - 1] + + if (token.text === '{' || token.text === '[') { + output.push(token) + if (next?.text !== (token.text === '{' ? '}' : ']')) { + depth++ + output.push(`\n${' '.repeat(depth)}`) + } + } else if (token.text === '}' || token.text === ']') { + if (previous?.text !== (token.text === '}' ? '{' : '[')) { + depth-- + output.push(`\n${' '.repeat(depth)}`) + } + output.push(token) + } else if (token.text === ',') { + output.push(token, `\n${' '.repeat(depth)}`) + } else if (token.text === ':') { + output.push(token, ' ') + } else { + output.push(token) + } + } + + return output +} + +function showOriginalWithError ( + frame: HTMLPreElement, + source: string, + errorMessage: string +): void { + const message = frame.ownerDocument.createElement('div') + message.className = 'human-readable-json-error' + message.setAttribute('role', 'alert') + message.textContent = errorMessage + frame.parentElement?.insertBefore(message, frame) + render(html`${source}`, frame) +} + +function renderJson (frame: HTMLPreElement, source: string): void { + try { + // Validate without serializing: JSON.parse/stringify would round large numeric values. + JSON.parse(source) + } catch (error) { + if (error instanceof SyntaxError) { + showOriginalWithError(frame, source, 'Invalid JSON — showing the original content.') + } else { + console.error('Error validating JSON content:', error) + showOriginalWithError(frame, source, 'Unable to validate JSON — showing the original content.') + } + return + } + + try { + const tokens = tokenize(source) + const markedTokens = tokens.map((token, index) => + token.kind === 'string' && tokens[index + 1]?.text === ':' + ? { ...token, kind: 'key' as const } + : token + ) + const parts = prettyTokens(markedTokens) + const highlightedParts = parts.map(part => { + if (typeof part === 'string') return part + return html`${part.text}` + }) + render(html`${highlightedParts}`, frame) + } catch (error) { + console.error('Error formatting JSON content:', error) + showOriginalWithError(frame, source, 'Unable to format JSON content — showing the original content.') + } +} + +export function renderJsonContent ( + store: LiveStore, + subject: NamedNode, + frame: HTMLPreElement +): void { + store.fetcher.webOperation('GET', subject.uri).then(response => { + configurePreviewFrame(frame, 'json') + renderJson(frame, response.responseText ?? '') + }).catch(error => { + console.error('Error fetching JSON content:', error) + const message = frame.ownerDocument.createElement('div') + message.className = 'human-readable-json-error' + message.setAttribute('role', 'alert') + message.textContent = 'Unable to load JSON content.' + frame.parentElement?.insertBefore(message, frame) + configurePreviewFrame(frame, 'json') + render(html``, frame) + }) +} From 4cfdf56274aaf149c088e29c32a6f63ea7db6732 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 15:38:55 +1100 Subject: [PATCH 08/24] fix(pdf): emit worker as separate asset Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: GPT-5.6 Luna --- src/components/pdf-viewer/PdfViewer.ts | 6 ++---- typings/pdf-worker-url.d.ts | 4 ++++ 2 files changed, 6 insertions(+), 4 deletions(-) create mode 100644 typings/pdf-worker-url.d.ts diff --git a/src/components/pdf-viewer/PdfViewer.ts b/src/components/pdf-viewer/PdfViewer.ts index 8bbc03ec..b583d7ef 100644 --- a/src/components/pdf-viewer/PdfViewer.ts +++ b/src/components/pdf-viewer/PdfViewer.ts @@ -5,6 +5,7 @@ import type { LiveStore, NamedNode } from 'rdflib' import { resourceFilename } from '../../humanReadable/previewHelpers' import 'solid-ui/components/error-state' import styles from './PdfViewier.styles.css' +import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url' type PdfJsModule = typeof import('pdfjs-dist') type PdfDocument = Awaited['promise']> @@ -106,10 +107,7 @@ export default class PdfViewer extends WebComponent { private async renderMainPage (generation: number): Promise { if (!this.pdfJs || !this.pdfData) return - this.pdfJs.GlobalWorkerOptions.workerSrc = new URL( - 'pdfjs-dist/build/pdf.worker.min.mjs', - import.meta.url - ).toString() + this.pdfJs.GlobalWorkerOptions.workerSrc = pdfWorkerUrl const loadingTask = this.pdfJs.getDocument({ data: this.pdfData }) this.pdfLoadingTask = loadingTask const pdfDocument = await loadingTask.promise diff --git a/typings/pdf-worker-url.d.ts b/typings/pdf-worker-url.d.ts new file mode 100644 index 00000000..8a522cd6 --- /dev/null +++ b/typings/pdf-worker-url.d.ts @@ -0,0 +1,4 @@ +declare module 'pdfjs-dist/build/pdf.worker.min.mjs?url' { + const workerUrl: string + export default workerUrl +} From 2f7acd3635e7405e8ba06c5a6eb074b410e59ff4 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 15:43:30 +1100 Subject: [PATCH 09/24] small improvements --- src/components/iframe-preview/index.ts | 2 +- src/components/pdf-viewer/index.ts | 2 +- src/humanReadable/humanReadablePane.css | 175 +++++++++++++++++++----- src/humanReadable/previewFrame.ts | 6 +- test/unit/humanReadablePane.test.ts | 112 ++++++++++++++- 5 files changed, 255 insertions(+), 42 deletions(-) diff --git a/src/components/iframe-preview/index.ts b/src/components/iframe-preview/index.ts index 79258d61..95aaaac1 100644 --- a/src/components/iframe-preview/index.ts +++ b/src/components/iframe-preview/index.ts @@ -1,4 +1,4 @@ import IframePreview from './IframePreview' export { IframePreview } -export default IframePreview \ No newline at end of file +export default IframePreview diff --git a/src/components/pdf-viewer/index.ts b/src/components/pdf-viewer/index.ts index 74714165..3dd3519f 100644 --- a/src/components/pdf-viewer/index.ts +++ b/src/components/pdf-viewer/index.ts @@ -1,4 +1,4 @@ import PdfViewer from './PdfViewer' export { PdfViewer } -export default PdfViewer \ No newline at end of file +export default PdfViewer diff --git a/src/humanReadable/humanReadablePane.css b/src/humanReadable/humanReadablePane.css index 71469882..98eeeb4a 100644 --- a/src/humanReadable/humanReadablePane.css +++ b/src/humanReadable/humanReadablePane.css @@ -13,7 +13,7 @@ overflow: auto; } -.human-readable-pane__container { +.human-readable-document-container { display: flex; flex: 1 1 auto; flex-direction: column; @@ -27,7 +27,8 @@ overflow-x: hidden; } -.human-readable-pane__frame { +.human-readable-pane__frame, +.human-readable-document-frame { display: block; border: 1px solid var(--solid-ui-color-slate-200, #E2E8F0); padding: 1rem; @@ -40,8 +41,9 @@ overflow: auto; } -.human-readable-pane__frame--markdown, -.human-readable-pane__frame--plain-text { +.human-readable-markdown-preview, +.human-readable-plain-text-preview, +.human-readable-json-preview { flex: 1 1 auto; height: auto; min-height: 100%; @@ -86,8 +88,9 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { resize: none; } -.human-readable-pane__frame--markdown, -.human-readable-pane__frame--plain-text { +.human-readable-markdown-preview, +.human-readable-plain-text-preview, +.human-readable-json-preview { overflow: visible; max-height: none; } @@ -96,12 +99,13 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { overflow: hidden; } -.human-readable-pane--document > .human-readable-pane__container { +.human-readable-pane--document > .human-readable-document-container { overflow: hidden; } -.human-readable-pane--document > .human-readable-pane__container > .human-readable-pane__frame--markdown, -.human-readable-pane--document > .human-readable-pane__container > .human-readable-pane__frame--plain-text { +.human-readable-pane--document > .human-readable-document-container > .human-readable-markdown-preview, +.human-readable-pane--document > .human-readable-document-container > .human-readable-plain-text-preview, +.human-readable-pane--document > .human-readable-document-container > .human-readable-json-preview { flex: 1 1 0%; height: 100%; min-height: 0; @@ -109,48 +113,142 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { overflow: auto; } -.human-readable-pane__frame--markdown { +.human-readable-markdown-preview { overflow-wrap: anywhere; word-break: break-word; } -.human-readable-pane__frame--plain-text { +.human-readable-markdown-preview h1, +.human-readable-markdown-preview h2, +.human-readable-markdown-preview h3, +.human-readable-markdown-preview h4, +.human-readable-markdown-preview h5, +.human-readable-markdown-preview h6 { + line-height: 1.25; + margin: 0 0 0.75rem; +} + +.human-readable-markdown-preview a { + color: var(--solid-ui-color-primary, #2563EB); + text-decoration: underline; + text-underline-offset: 0.15em; +} + +.human-readable-markdown-preview blockquote { + border-left: 4px solid var(--solid-ui-color-slate-400, #98A2B3); + margin: 1rem 0; + padding: 0 1rem; +} + +.human-readable-markdown-preview code { + background: var(--solid-ui-color-slate-100, #F1F5F9); + border-radius: 0.25rem; + padding: 0.1em 0.25em; +} + +.human-readable-markdown-preview pre { + background: var(--solid-ui-color-slate-100, #F1F5F9); + border-radius: 0.375rem; + overflow: auto; + padding: 1rem; +} + +.human-readable-markdown-preview pre code { + background: transparent; + padding: 0; +} + +.human-readable-plain-text-preview { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; } -.human-readable-pane__frame--plain-text:focus-visible { +.human-readable-json-preview { + margin: 0; + background: var(--solid-ui-color-slate-50, #F8FAFC); + color: var(--solid-ui-color-gray-900, #101828); + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace); + font-size: 0.875rem; + line-height: 1.5; + white-space: pre; + overflow: auto; + overflow-wrap: normal; + word-break: normal; + tab-size: 2; +} + +.human-readable-json-preview:focus-visible { outline: 2px solid var(--solid-ui-color-gray-800, #101828); outline-offset: -2px; } -.human-readable-pane__frame--markdown > * { +.human-readable-json-string { + color: #067647; +} + +.human-readable-json-key { + color: #6941c6; + font-weight: 600; +} + +.human-readable-json-number { + color: #175cd3; +} + +.human-readable-json-boolean { + color: #b54708; + font-weight: 600; +} + +.human-readable-json-null { + color: #475467; +} + +.human-readable-json-punctuation { + color: #475467; +} + +.human-readable-json-error { + flex: 0 0 auto; + padding: 0.5rem 1rem; + color: #b42318; + background: #fef3f2; + font-weight: 600; +} + +.human-readable-plain-text-preview:focus-visible { + outline: 2px solid var(--solid-ui-color-gray-800, #101828); + outline-offset: -2px; +} + +.human-readable-markdown-preview > * { max-width: 100%; box-sizing: border-box; } -.human-readable-pane__frame--markdown img, -.human-readable-pane__frame--markdown video, -.human-readable-pane__frame--markdown canvas, -.human-readable-pane__frame--markdown iframe { +.human-readable-markdown-preview img, +.human-readable-markdown-preview video, +.human-readable-markdown-preview canvas, +.human-readable-markdown-preview iframe { max-width: 100%; height: auto; } -.human-readable-pane__frame--markdown pre, -.human-readable-pane__frame--markdown code { +.human-readable-markdown-preview pre, +.human-readable-markdown-preview code { max-width: 100%; overflow-wrap: anywhere; word-break: break-word; } -.human-readable-pane__frame--markdown pre { +.human-readable-markdown-preview pre { white-space: pre-wrap; } -.human-readable-pane__frame--markdown table { +.human-readable-markdown-preview table { + border-collapse: collapse; display: block; width: 100%; max-width: 100%; @@ -158,21 +256,25 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { box-sizing: border-box; } -.human-readable-pane__frame--markdown th, -.human-readable-pane__frame--markdown td { +.human-readable-markdown-preview th, +.human-readable-markdown-preview td { + border: 1px solid var(--solid-ui-color-slate-300, #CBD5E1); + padding: 0.5rem; white-space: normal; overflow-wrap: anywhere; word-break: break-word; } -.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame { +.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame, +.human-readable-pane[data-layout='mobile'] .human-readable-document-frame { padding: 0.75rem; resize: none; min-width: 0; } -.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame--markdown, -.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame--plain-text { +.human-readable-pane[data-layout='mobile'] .human-readable-markdown-preview, +.human-readable-pane[data-layout='mobile'] .human-readable-plain-text-preview, +.human-readable-pane[data-layout='mobile'] .human-readable-json-preview { min-height: 100%; max-height: none; } @@ -181,12 +283,17 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { padding: 0; } -.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame--markdown, -.human-readable-pane[data-layout='mobile'] .human-readable-pane__frame--plain-text { +.human-readable-pane[data-layout='mobile'] .human-readable-markdown-preview, +.human-readable-pane[data-layout='mobile'] .human-readable-plain-text-preview, +.human-readable-pane[data-layout='mobile'] .human-readable-json-preview { overflow-wrap: anywhere; word-break: break-word; } +.human-readable-pane[data-layout='mobile'] .human-readable-json-preview { + white-space: pre-wrap; +} + .human-readable-pane[data-layout='mobile'] .human-readable-pane__frame--iframe { width: 100%; max-width: 100%; @@ -200,18 +307,24 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { padding: 0; } - .human-readable-pane__frame { + .human-readable-pane__frame, + .human-readable-document-frame { padding: 0.75rem; resize: none; min-width: 0; } - .human-readable-pane__frame--markdown, - .human-readable-pane__frame--plain-text { + .human-readable-markdown-preview, + .human-readable-plain-text-preview, + .human-readable-json-preview { overflow-wrap: anywhere; word-break: break-word; } + .human-readable-json-preview { + white-space: pre-wrap; + } + .human-readable-pane__frame--iframe { width: 100%; max-width: 100%; diff --git a/src/humanReadable/previewFrame.ts b/src/humanReadable/previewFrame.ts index 6e60c645..84fda6e4 100644 --- a/src/humanReadable/previewFrame.ts +++ b/src/humanReadable/previewFrame.ts @@ -1,8 +1,8 @@ export function configurePreviewFrame ( frame: HTMLElement, - modifier: 'markdown' | 'plain-text' | 'iframe' + modifier: 'markdown' | 'plain-text' | 'json' ): void { frame.className = '' - frame.classList.add('human-readable-pane__frame') - frame.classList.add(`human-readable-pane__frame--${modifier}`) + frame.classList.add('human-readable-document-frame') + frame.classList.add(`human-readable-${modifier}-preview`) } diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 87019f85..1d098447 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -14,9 +14,10 @@ const uri = 'https://pod.example/docs/page.html' function renderWith ( contentType: string, fetcher: Record, - environment: Record = {} + environment: Record = {}, + resourceUri: string = uri ) { - const subject = { uri, doc: () => subject } + const subject = { uri: resourceUri, doc: () => subject } const store = { fetcher: { getHeader: vi.fn().mockReturnValue([contentType]), ...fetcher } } @@ -133,24 +134,123 @@ describe('human readable pane iframe rendering', () => { const pane = renderWith(contentType, { webOperation }) await vi.waitFor(() => { - expect(pane.querySelector('.human-readable-pane__frame--markdown h1')?.textContent) + expect(pane.querySelector('.human-readable-markdown-preview h1')?.textContent) .toBe('Markdown heading') }) - expect(pane.querySelector('.human-readable-pane__frame--plain-text')).toBeNull() + expect(pane.querySelector('.human-readable-plain-text-preview')).toBeNull() expect(getFrame(pane)).toBeNull() } ) - it('renders JSON as readable text', async () => { + it('enhances Markdown with links, line breaks, and formatting', async () => { + const webOperation = vi.fn().mockResolvedValue({ + responseText: 'Visit https://example.com\nfor more.\n\n~~old~~' + }) + const pane = renderWith('text/markdown', { webOperation }) + + await vi.waitFor(() => { + expect(pane.querySelector('a[href="https://example.com"]')).not.toBeNull() + }) + expect(pane.querySelector('br')).not.toBeNull() + expect(pane.querySelector('s')?.textContent).toBe('old') + }) + + it('renders JSON in the syntax-highlighted JSON frame', async () => { const webOperation = vi.fn().mockResolvedValue({ responseText: '{\n "enabled": true\n}' }) const pane = renderWith('application/json', { webOperation }) await flush() - expect(pane.querySelector('pre')?.textContent).toBe('{\n "enabled": true\n}') + expect(pane.querySelector('.human-readable-json-preview')?.textContent) + .toBe('{\n "enabled": true\n}') + expect(pane.querySelector('.human-readable-plain-text-preview')).toBeNull() expect(pane.querySelector('iframe')).toBeNull() expect(webOperation).toHaveBeenCalledWith('GET', uri) }) + it('pretty prints and safely colors JSON-LD without changing large number lexemes', async () => { + const source = '{"@context":{"name":"https://schema.org/name"},"value":900719925474099312345,"active":true,"empty":null,"script":""}' + const pane = renderWith('application/ld+json; charset=utf-8', { + webOperation: vi.fn().mockResolvedValue({ responseText: source }) + }) + await vi.waitFor(() => { + expect(pane.querySelector('.human-readable-json-preview')).not.toBeNull() + }) + const frame = pane.querySelector('pre')! + + await vi.waitFor(() => expect(frame.textContent).toContain('900719925474099312345')) + expect(frame.textContent).toContain(' "@context": {') + expect(frame.querySelector('.human-readable-json-number')?.textContent) + .toBe('900719925474099312345') + expect(frame.querySelector('.human-readable-json-key')?.textContent) + .toBe('"@context"') + expect(frame.querySelector('.human-readable-json-string')?.textContent) + .toBe('"https://schema.org/name"') + expect(frame.querySelector('.human-readable-json-boolean')?.textContent).toBe('true') + expect(frame.querySelector('.human-readable-json-null')?.textContent).toBe('null') + expect(frame.querySelector('img')).toBeNull() + expect(frame).toHaveAttribute('tabindex', '0') + expect(frame).toHaveAttribute('aria-label', 'JSON document') + }) + + it('preserves invalid JSON exactly and displays an accessible parse error', async () => { + const source = '{ "value": 01, "": "" }' + const pane = renderWith('application/json', { + webOperation: vi.fn().mockResolvedValue({ responseText: source }) + }) + + await vi.waitFor(() => { + expect(pane.querySelector('[role="alert"]')?.textContent) + .toBe('Invalid JSON — showing the original content.') + }) + expect(pane.querySelector('pre')?.textContent).toBe(source) + expect(pane.querySelector('script, img')).toBeNull() + }) + + it('does not report internal JSON validation errors as invalid JSON', async () => { + vi.spyOn(JSON, 'parse').mockImplementation(() => { + throw new Error('unexpected validator failure') + }) + const pane = renderWith('application/json', { + webOperation: vi.fn().mockResolvedValue({ responseText: '{"valid":true}' }) + }) + + await vi.waitFor(() => { + expect(pane.querySelector('[role="alert"]')?.textContent) + .toBe('Unable to validate JSON — showing the original content.') + }) + expect(pane.querySelector('[role="alert"]')?.textContent).not.toContain('Invalid JSON') + expect(pane.querySelector('pre')?.textContent).toBe('{"valid":true}') + }) + + it('keeps long JSON available in the mobile layout', async () => { + const pane = renderWith('application/json', { + webOperation: vi.fn().mockResolvedValue({ responseText: `{"value":"${'x'.repeat(120)}"}` }) + }, { layout: 'mobile' }) + const frame = pane.querySelector('pre')! + + await vi.waitFor(() => expect(frame.textContent).toContain('x'.repeat(120))) + expect(pane).toHaveAttribute('data-layout', 'mobile') + expect(frame).toHaveClass('human-readable-json-preview') + }) + + it('uses JSON filename fallback only without a conflicting known MIME type', async () => { + const jsonPane = renderWith('', { + webOperation: vi.fn().mockResolvedValue({ responseText: '{"ok":true}' }) + }, {}, 'https://pod.example/docs/data.jsonld?download=1') + await vi.waitFor(() => expect(jsonPane.querySelector('.human-readable-json-preview')).not.toBeNull()) + + const genericMimePane = renderWith('application/octet-stream', { + webOperation: vi.fn().mockResolvedValue({ responseText: '{"ok":true}' }) + }, {}, 'https://pod.example/docs/data.json') + await vi.waitFor(() => expect(genericMimePane.querySelector('.human-readable-json-preview')).not.toBeNull()) + + const htmlPane = renderWith('text/html', { + _fetch: vi.fn().mockResolvedValue(htmlResponse('Known HTML')) + }, {}, 'https://pod.example/docs/data.json') + await waitForSrcdoc(htmlPane, 'Known HTML') + expect(htmlPane.querySelector('.human-readable-json-preview')).toBeNull() + }) + it('renders plain text as escaped text through Lit', async () => { const webOperation = vi.fn().mockResolvedValue({ responseText: '' }) const pane = renderWith('text/plain', { webOperation }) From 0d10829e2e0389a01b5122e791f8d008c240eacb Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 16:00:58 +1100 Subject: [PATCH 10/24] nicely handle errors --- src/humanReadable/humanReadablePane.css | 40 +++++++++++++++++++------ src/humanReadable/index.ts | 25 +++++++--------- src/humanReadable/jsonPreview.ts | 37 ++++++++++------------- src/humanReadable/markdownPreview.ts | 12 +++++--- src/humanReadable/previewError.ts | 21 +++++++++++++ src/humanReadable/previewFrame.ts | 12 ++++++++ src/humanReadable/textPreview.ts | 12 +++++--- test/unit/humanReadablePane.test.ts | 11 +++---- test/unit/markdownPreview.test.ts | 19 +++++++----- 9 files changed, 123 insertions(+), 66 deletions(-) create mode 100644 src/humanReadable/previewError.ts diff --git a/src/humanReadable/humanReadablePane.css b/src/humanReadable/humanReadablePane.css index 98eeeb4a..65c01a1d 100644 --- a/src/humanReadable/humanReadablePane.css +++ b/src/humanReadable/humanReadablePane.css @@ -78,7 +78,34 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { display: flex; flex-direction: column; min-height: 0; - overflow: hidden; +} + +.human-readable-document-status { + display: none; + box-sizing: border-box; + flex: 1 1 auto; + width: 100%; + min-width: 0; + min-height: 0; + align-items: center; + justify-content: center; + padding: 16px; + border: 0; + background: transparent; +} + +.human-readable-document-status[data-visible='true'] { + display: flex; + flex: 1 1 0%; +} + +.human-readable-document-status > solid-ui-error-state { + display: block; + width: 100%; +} + +.human-readable-document-status[data-visible='true'] ~ .human-readable-document-frame { + display: none; } .human-readable-pane__container--iframe > .human-readable-pane__frame--iframe { @@ -96,6 +123,9 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { } .human-readable-pane--document { + display: flex; + flex: 1 1 0%; + min-height: 0; overflow: hidden; } @@ -210,14 +240,6 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { color: #475467; } -.human-readable-json-error { - flex: 0 0 auto; - padding: 0.5rem 1rem; - color: #b42318; - background: #fef3f2; - font-weight: 600; -} - .human-readable-plain-text-preview:focus-visible { outline: 2px solid var(--solid-ui-color-gray-800, #101828); outline-offset: -2px; diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index a73b4acc..10b9712f 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -3,7 +3,7 @@ ** This outline pane contains the document contents for an HTML document ** This is for peeking at a page, because the user might not want to leave the data browser. */ -import { icons, ns } from 'solid-ui' +import { icons, log, ns } from 'solid-ui' import { Util } from 'rdflib' import { authn } from 'solid-logic' import type { DataBrowserContext, RenderEnvironment } from 'pane-registry' @@ -13,6 +13,7 @@ import { createPreviewBridge } from './previewBridge' import { renderMarkdownContent } from './markdownPreview' import { renderJsonContent } from './jsonPreview' import { renderPlainTextContent } from './textPreview' +import { createPreviewContainer } from './previewFrame' import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' import type IframePreview from '../components/iframe-preview' import '../components/iframe-preview' @@ -466,9 +467,9 @@ const humanReadablePane: HumanReadablePaneDefinition = { const isPdf = ct === 'application/pdf' if (ct) { - // console.log('humanReadablePane: c-t:' + ct) + // Unknown types are intentionally left to the browser fallback. } else { - console.log('humanReadablePane: unknown content-type?') + log.debug(`Human Readable: unknown content type ${ct}`) } // @@ When we can, use CSP to turn off scripts within the iframe @@ -485,20 +486,16 @@ const humanReadablePane: HumanReadablePaneDefinition = { } else if (isMarkdown) { // For markdown, use a DIV element and render the content const frame = myDocument.createElement('div') - renderMarkdownContent(kb, subject, frame) - const frameContainer = myDocument.createElement('div') - frameContainer.classList.add('human-readable-document-container') - frameContainer.appendChild(frame) + const { container: frameContainer, status } = createPreviewContainer(myDocument, frame) + renderMarkdownContent(kb, subject, frame, status) div.appendChild(frameContainer) div.classList.add('human-readable-pane--document') } else if (isJson) { const frame = myDocument.createElement('pre') frame.tabIndex = 0 frame.setAttribute('aria-label', 'JSON document') - renderJsonContent(kb, subject, frame) - const frameContainer = myDocument.createElement('div') - frameContainer.classList.add('human-readable-document-container') - frameContainer.appendChild(frame) + const { container: frameContainer, status } = createPreviewContainer(myDocument, frame) + renderJsonContent(kb, subject, frame, status) div.appendChild(frameContainer) div.classList.add('human-readable-pane--document') } else if (isPlainText) { @@ -506,10 +503,8 @@ const humanReadablePane: HumanReadablePaneDefinition = { const frame = myDocument.createElement('pre') frame.tabIndex = 0 frame.setAttribute('aria-label', 'Plain text document') - renderPlainTextContent(kb, subject, frame) - const frameContainer = myDocument.createElement('div') - frameContainer.classList.add('human-readable-document-container') - frameContainer.appendChild(frame) + const { container: frameContainer, status } = createPreviewContainer(myDocument, frame) + renderPlainTextContent(kb, subject, frame, status) div.appendChild(frameContainer) div.classList.add('human-readable-pane--document') } else { diff --git a/src/humanReadable/jsonPreview.ts b/src/humanReadable/jsonPreview.ts index f986bf77..8aeee575 100644 --- a/src/humanReadable/jsonPreview.ts +++ b/src/humanReadable/jsonPreview.ts @@ -1,6 +1,8 @@ +import { log } from 'solid-ui' import type { LiveStore, NamedNode } from 'rdflib' import { html, render } from 'lit-html' import { configurePreviewFrame } from './previewFrame' +import { renderPreviewError } from './previewError' type JsonToken = { text: string @@ -79,27 +81,24 @@ function prettyTokens (tokens: JsonToken[]): Array { function showOriginalWithError ( frame: HTMLPreElement, + status: HTMLElement, source: string, errorMessage: string ): void { - const message = frame.ownerDocument.createElement('div') - message.className = 'human-readable-json-error' - message.setAttribute('role', 'alert') - message.textContent = errorMessage - frame.parentElement?.insertBefore(message, frame) + renderPreviewError(status, 'Unable to display JSON', errorMessage) render(html`${source}`, frame) } -function renderJson (frame: HTMLPreElement, source: string): void { +function renderJson (frame: HTMLPreElement, status: HTMLElement, source: string): void { try { // Validate without serializing: JSON.parse/stringify would round large numeric values. JSON.parse(source) } catch (error) { if (error instanceof SyntaxError) { - showOriginalWithError(frame, source, 'Invalid JSON — showing the original content.') + showOriginalWithError(frame, status, source, 'Invalid JSON — showing the original content.') } else { - console.error('Error validating JSON content:', error) - showOriginalWithError(frame, source, 'Unable to validate JSON — showing the original content.') + log.debug(`Error validating JSON content: ${String(error)}`) + showOriginalWithError(frame, status, source, 'Unable to validate JSON — showing the original content.') } return } @@ -118,27 +117,23 @@ function renderJson (frame: HTMLPreElement, source: string): void { }) render(html`${highlightedParts}`, frame) } catch (error) { - console.error('Error formatting JSON content:', error) - showOriginalWithError(frame, source, 'Unable to format JSON content — showing the original content.') + log.debug(`Error formatting JSON content: ${String(error)}`) + showOriginalWithError(frame, status, source, 'Unable to format JSON content — showing the original content.') } } export function renderJsonContent ( store: LiveStore, subject: NamedNode, - frame: HTMLPreElement + frame: HTMLPreElement, + status: HTMLElement ): void { + configurePreviewFrame(frame, 'json') store.fetcher.webOperation('GET', subject.uri).then(response => { - configurePreviewFrame(frame, 'json') - renderJson(frame, response.responseText ?? '') + renderJson(frame, status, response.responseText ?? '') }).catch(error => { - console.error('Error fetching JSON content:', error) - const message = frame.ownerDocument.createElement('div') - message.className = 'human-readable-json-error' - message.setAttribute('role', 'alert') - message.textContent = 'Unable to load JSON content.' - frame.parentElement?.insertBefore(message, frame) - configurePreviewFrame(frame, 'json') + log.debug(`Error fetching JSON content: ${String(error)}`) + renderPreviewError(status, 'Unable to load JSON', 'The document could not be loaded.') render(html``, frame) }) } diff --git a/src/humanReadable/markdownPreview.ts b/src/humanReadable/markdownPreview.ts index 9073c961..b88eb21b 100644 --- a/src/humanReadable/markdownPreview.ts +++ b/src/humanReadable/markdownPreview.ts @@ -1,9 +1,11 @@ import DOMPurify from 'dompurify' import { html, render } from 'lit-html' import { unsafeHTML } from 'lit-html/directives/unsafe-html.js' +import { log } from 'solid-ui' import type { DataBrowserContext } from 'pane-registry' import type { NamedNode } from 'rdflib' import { configurePreviewFrame } from './previewFrame' +import { renderPreviewError } from './previewError' type Store = DataBrowserContext['session']['store'] @@ -17,8 +19,10 @@ function loadMarkdownIt (): Promise { export function renderMarkdownContent ( store: Store, subject: NamedNode, - frame: HTMLDivElement + frame: HTMLDivElement, + status: HTMLElement ): void { + configurePreviewFrame(frame, 'markdown') store.fetcher.webOperation('GET', subject.uri).then(async response => { const markdownText = response.responseText ?? '' const MarkdownIt = (await loadMarkdownIt()).default @@ -32,9 +36,9 @@ export function renderMarkdownContent ( const sanitizedMarkdown = DOMPurify.sanitize(renderedMarkdown) render(html`${unsafeHTML(sanitizedMarkdown)}`, frame) - configurePreviewFrame(frame, 'markdown') }).catch(error => { - console.error('Error fetching markdown content:', error) - render(html`

Error loading content

`, frame) + log.debug(`Error fetching markdown content: ${String(error)}`) + renderPreviewError(status, 'Unable to load Markdown', 'The document could not be loaded.') + render(html``, frame) }) } diff --git a/src/humanReadable/previewError.ts b/src/humanReadable/previewError.ts new file mode 100644 index 00000000..57675f4e --- /dev/null +++ b/src/humanReadable/previewError.ts @@ -0,0 +1,21 @@ +import { html, nothing, render } from 'lit' +import 'solid-ui/components/error-state' + +export function renderPreviewError ( + status: HTMLElement, + title: string, + message: string +): void { + status.dataset.visible = 'true' + const clearError = () => { + status.dataset.visible = 'false' + render(nothing, status) + } + render(html` + + `, status) +} diff --git a/src/humanReadable/previewFrame.ts b/src/humanReadable/previewFrame.ts index 84fda6e4..eba5db4d 100644 --- a/src/humanReadable/previewFrame.ts +++ b/src/humanReadable/previewFrame.ts @@ -1,3 +1,15 @@ +export function createPreviewContainer ( + document: Document, + frame: HTMLElement +): { container: HTMLDivElement, status: HTMLDivElement } { + const container = document.createElement('div') + container.classList.add('human-readable-document-container') + const status = document.createElement('div') + status.className = 'human-readable-document-status' + container.append(status, frame) + return { container, status } +} + export function configurePreviewFrame ( frame: HTMLElement, modifier: 'markdown' | 'plain-text' | 'json' diff --git a/src/humanReadable/textPreview.ts b/src/humanReadable/textPreview.ts index f2d027b8..6675bb6a 100644 --- a/src/humanReadable/textPreview.ts +++ b/src/humanReadable/textPreview.ts @@ -1,21 +1,25 @@ +import { log } from 'solid-ui' import type { DataBrowserContext } from 'pane-registry' import type { NamedNode } from 'rdflib' import { html, render } from 'lit-html' import { configurePreviewFrame } from './previewFrame' +import { renderPreviewError } from './previewError' type Store = DataBrowserContext['session']['store'] export function renderPlainTextContent ( store: Store, subject: NamedNode, - frame: HTMLPreElement + frame: HTMLPreElement, + status: HTMLElement ): void { + configurePreviewFrame(frame, 'plain-text') store.fetcher.webOperation('GET', subject.uri).then(response => { const plainText = response.responseText ?? '' render(html`${plainText}`, frame) - configurePreviewFrame(frame, 'plain-text') }).catch(error => { - console.error('Error fetching plain text content:', error) - render(html`Error loading content`, frame) + log.debug(`Error fetching plain text content: ${String(error)}`) + renderPreviewError(status, 'Unable to load plain text', 'The document could not be loaded.') + render(html``, frame) }) } diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 1d098447..ac427c16 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -199,9 +199,10 @@ describe('human readable pane iframe rendering', () => { }) await vi.waitFor(() => { - expect(pane.querySelector('[role="alert"]')?.textContent) - .toBe('Invalid JSON — showing the original content.') + expect(pane.querySelector('solid-ui-error-state')).not.toBeNull() }) + expect((pane.querySelector('solid-ui-error-state') as HTMLElement & { message: string }).message) + .toBe('Invalid JSON — showing the original content.') expect(pane.querySelector('pre')?.textContent).toBe(source) expect(pane.querySelector('script, img')).toBeNull() }) @@ -215,10 +216,10 @@ describe('human readable pane iframe rendering', () => { }) await vi.waitFor(() => { - expect(pane.querySelector('[role="alert"]')?.textContent) - .toBe('Unable to validate JSON — showing the original content.') + expect(pane.querySelector('solid-ui-error-state')).not.toBeNull() }) - expect(pane.querySelector('[role="alert"]')?.textContent).not.toContain('Invalid JSON') + expect((pane.querySelector('solid-ui-error-state') as HTMLElement & { message: string }).message) + .toBe('Unable to validate JSON — showing the original content.') expect(pane.querySelector('pre')?.textContent).toBe('{"valid":true}') }) diff --git a/test/unit/markdownPreview.test.ts b/test/unit/markdownPreview.test.ts index d6b9538b..7545de85 100644 --- a/test/unit/markdownPreview.test.ts +++ b/test/unit/markdownPreview.test.ts @@ -17,6 +17,8 @@ afterEach(() => { describe('renderMarkdownContent', () => { it('renders Markdown and removes raw HTML', async () => { const frame = createFrame() + const status = document.createElement('div') + document.body.appendChild(status) const store = { fetcher: { webOperation: vi.fn().mockResolvedValue({ @@ -25,7 +27,7 @@ describe('renderMarkdownContent', () => { } } - renderMarkdownContent(store as any, subject, frame) + renderMarkdownContent(store as any, subject, frame, status) await vi.waitFor(() => { expect(frame.querySelector('h1')?.textContent).toBe('Heading') @@ -38,21 +40,22 @@ describe('renderMarkdownContent', () => { it('shows an error when Markdown cannot be fetched', async () => { const frame = createFrame() - vi.spyOn(console, 'error').mockImplementation(() => {}) + const status = document.createElement('div') + document.body.appendChild(status) const store = { fetcher: { webOperation: vi.fn().mockRejectedValue(new Error('network failure')) } } - renderMarkdownContent(store as any, subject, frame) + renderMarkdownContent(store as any, subject, frame, status) await vi.waitFor(() => { - expect(frame.textContent).toBe('Error loading content') + expect(status.querySelector('solid-ui-error-state')).not.toBeNull() + }) + await vi.waitFor(() => { + expect(status.querySelector('solid-ui-error-state')?.shadowRoot?.textContent) + .toContain('The document could not be loaded.') }) - expect(console.error).toHaveBeenCalledWith( - 'Error fetching markdown content:', - expect.any(Error) - ) }) }) From 5e334da39d46827bdb46708a3bee0f00e50f8b2c Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 17:24:58 +1100 Subject: [PATCH 11/24] update video and styles --- src/humanReadable/index.ts | 16 +++++++++-- src/video/videoPane.css | 36 ++++++++++++++++++++++++ src/video/{videoPane.js => videoPane.ts} | 16 ++++++----- 3 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 src/video/videoPane.css rename src/video/{videoPane.js => videoPane.ts} (69%) diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index 10b9712f..e66aa307 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -13,6 +13,7 @@ import { createPreviewBridge } from './previewBridge' import { renderMarkdownContent } from './markdownPreview' import { renderJsonContent } from './jsonPreview' import { renderPlainTextContent } from './textPreview' +import { isDocxContentType, isDocxFile, renderDocxContent } from './docxPreview' import { createPreviewContainer } from './previewFrame' import { escapeAttribute, HTML_PREVIEW_SANDBOX } from './previewHelpers' import type IframePreview from '../components/iframe-preview' @@ -361,8 +362,8 @@ const humanReadablePane: HumanReadablePaneDefinition = { 'application/json', 'application/ld+json', 'application/xhtml+xml', - 'application/pdf', - 'video/mp4' + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/pdf' ] const hasContentTypeIn = function ( @@ -408,6 +409,10 @@ const humanReadablePane: HumanReadablePaneDefinition = { return 'View' } + if (isDocxFile(subject.uri)) { + return 'View' + } + const cts = kb.fetcher.getHeader(subject.doc(), 'content-type') const contentType = cts ? cts[0].split(';', 1)[0].trim() : null if (isJsonFile(subject.uri) && @@ -461,6 +466,7 @@ const humanReadablePane: HumanReadablePaneDefinition = { // Fallback: detect markdown by file extension if content-type is not text/markdown const isMarkdown = ct === 'text/markdown' || isMarkdownFile(subject.uri) + const isDocx = isDocxContentType(ct) || isDocxFile(subject.uri) const isJson = isJsonContentType(ct) || (isJsonFile(subject.uri) && canUseJsonExtensionFallback(ct)) const isPlainText = ct === 'text/plain' @@ -483,6 +489,12 @@ const humanReadablePane: HumanReadablePaneDefinition = { preview.subject = subject div.appendChild(preview) div.classList.add('human-readable-pane--document') + } else if (isDocx) { + const frame = myDocument.createElement('div') + const { container: frameContainer, status } = createPreviewContainer(myDocument, frame) + renderDocxContent(kb, subject, frame, status) + div.appendChild(frameContainer) + div.classList.add('human-readable-pane--document') } else if (isMarkdown) { // For markdown, use a DIV element and render the content const frame = myDocument.createElement('div') diff --git a/src/video/videoPane.css b/src/video/videoPane.css new file mode 100644 index 00000000..39f1c6a2 --- /dev/null +++ b/src/video/videoPane.css @@ -0,0 +1,36 @@ +.video-pane { + display: flex; + flex-direction: column; + align-items: center; + gap: 23px; + box-sizing: border-box; + width: 100%; + min-width: 0; + padding: 0 40px; +} + +.video-pane video { + display: block; + width: 100%; + max-width: 100%; + min-width: 0; + height: auto; + border: 1px solid var(--solid-ui-color-gray-200, #E5E7EB); + border-radius: 5px; + object-fit: contain; +} + +.video-pane[data-layout='mobile'] { + padding: 0 16px; +} + +.video-pane[data-layout='mobile'] video { + width: 100%; +} + +@media (max-width: 768px) { + .video-pane { + gap: 16px; + padding: 0 16px; + } +} diff --git a/src/video/videoPane.js b/src/video/videoPane.ts similarity index 69% rename from src/video/videoPane.js rename to src/video/videoPane.ts index 47a36e27..b56d7b83 100644 --- a/src/video/videoPane.js +++ b/src/video/videoPane.ts @@ -1,19 +1,19 @@ /* Single video play Pane ** */ -import * as UI from 'solid-ui' -import * as $rdf from 'rdflib' +import { icons } from 'solid-ui' +import { Util } from 'rdflib' +import './videoPane.css' export default { - icon: UI.icons.iconBase + 'noun_1619.svg', + icon: icons.iconBase + 'noun_1619.svg', name: 'video', - // Does the subject deserve an slideshow pane? label: function (subject, context) { const kb = context.session.store const typeURIs = kb.findTypeURIs(subject) - const prefix = $rdf.Util.mediaTypeClass('video/*').uri.split('*')[0] + const prefix = Util.mediaTypeClass('video/*').uri.split('*')[0] for (const t in typeURIs) { if (t.startsWith(prefix)) return 'Play video' } @@ -25,8 +25,12 @@ export default { const kb = context.session.store const dom = context.dom const div = dom.createElement('div') + div.classList.add('video-pane') + div.dataset.layout = context.environment?.layout ?? 'desktop' const video = div.appendChild(dom.createElement('video')) video.setAttribute('controls', 'yes') + video.setAttribute('aria-label', 'Video preview') + video.setAttribute('playsinline', '') // get video with authenticated fetch kb.fetcher._fetch(subject.uri) .then(function (response) { @@ -37,8 +41,6 @@ export default { video.setAttribute('src', objectURL) // w640 h480 // }) - video.setAttribute('width', '100%') return div } } -// ends From c4e6dea879b4a50f7620a663c91fe4503f5a5bca Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 18:59:04 +1100 Subject: [PATCH 12/24] human readable axe testing --- package-lock.json | 52 ++++++- package.json | 4 +- test/unit/humanReadable.accessibility.test.ts | 136 ++++++++++++++++++ 3 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 test/unit/humanReadable.accessibility.test.ts diff --git a/package-lock.json b/package-lock.json index ca5047bd..e81e02ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "@types/node": "^22.20.0", "@typescript-eslint/parser": "^8.59.3", "@vitest/coverage-v8": "^4.0.18", + "axe-core": "^4.14.1", "eslint": "^9.39.4", "globals": "^17.6.0", "jsdom": "^28.1.0", @@ -46,7 +47,8 @@ "typescript": "^6.0.3", "unplugin-icons": "^23.0.1", "vite": "^8.0.16", - "vitest": "^4.0.18" + "vitest": "^4.0.18", + "vitest-axe": "^0.1.0" } }, "node_modules/@acemir/cssom": { @@ -4532,6 +4534,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axe-core": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz", + "integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, "node_modules/babel-plugin-polyfill-corejs2": { "version": "0.4.17", "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", @@ -7971,6 +7983,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "dev": true, + "license": "MIT" + }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", @@ -11203,6 +11222,37 @@ } } }, + "node_modules/vitest-axe": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/vitest-axe/-/vitest-axe-0.1.0.tgz", + "integrity": "sha512-jvtXxeQPg8R/2ANTY8QicA5pvvdRP4F0FsVUAHANJ46YCDASie/cuhlSzu0DGcLmZvGBSBNsNuK3HqfaeknyvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "aria-query": "^5.0.0", + "axe-core": "^4.4.2", + "chalk": "^5.0.1", + "dom-accessibility-api": "^0.5.14", + "lodash-es": "^4.17.21", + "redent": "^3.0.0" + }, + "peerDependencies": { + "vitest": ">=0.16.0" + } + }, + "node_modules/vitest-axe/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/vscode-jsonrpc": { "version": "10.0.1", "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.1.tgz", diff --git a/package.json b/package.json index 709044b1..5e54b838 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,7 @@ "@types/node": "^22.20.0", "@typescript-eslint/parser": "^8.59.3", "@vitest/coverage-v8": "^4.0.18", + "axe-core": "^4.14.1", "eslint": "^9.39.4", "globals": "^17.6.0", "jsdom": "^28.1.0", @@ -96,7 +97,8 @@ "typescript": "^6.0.3", "unplugin-icons": "^23.0.1", "vite": "^8.0.16", - "vitest": "^4.0.18" + "vitest": "^4.0.18", + "vitest-axe": "^0.1.0" }, "solidosDependencies": [ "rdflib", diff --git a/test/unit/humanReadable.accessibility.test.ts b/test/unit/humanReadable.accessibility.test.ts new file mode 100644 index 00000000..8151d4df --- /dev/null +++ b/test/unit/humanReadable.accessibility.test.ts @@ -0,0 +1,136 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { axe } from 'vitest-axe' +import { sym } from 'rdflib' +import humanReadablePane from '../../src/humanReadable' + +const uri = 'https://pod.example/docs/resource' +const subject = sym(uri) + +function renderPane ( + contentType: string, + fetcher: Record = {}, + environment: Record = {} +): HTMLElement { + const store = { + fetcher: { + getHeader: vi.fn().mockReturnValue([contentType]), + ...fetcher + } + } + const context = { + dom: document, + session: { store }, + environment + } + const pane = humanReadablePane.render(subject, context as any) + document.body.appendChild(pane) + return pane +} + +async function expectAxeClean (pane: Element): Promise { + const results = await axe(pane) + expect(results.violations).toHaveLength(0) +} + +afterEach(() => { + document.body.innerHTML = '' + vi.restoreAllMocks() +}) + +describe('Human Readable accessibility', () => { + it('keeps plain text accessible in the mobile layout', async () => { + const pane = renderPane('text/plain', { + webOperation: vi.fn().mockResolvedValue({ responseText: 'Readable text' }) + }, { layout: 'mobile' }) + + await vi.waitFor(() => { + expect(pane.querySelector('.human-readable-plain-text-preview')).not.toBeNull() + }) + await expectAxeClean(pane) + }) + + it('keeps the preview keyboard focusable', async () => { + const pane = renderPane('text/plain', { + webOperation: vi.fn().mockResolvedValue({ responseText: 'Readable text' }) + }) + const preview = pane.querySelector('.human-readable-plain-text-preview') as HTMLElement + + await vi.waitFor(() => { + expect(preview).toHaveAttribute('tabindex', '0') + }) + preview.focus() + expect(document.activeElement).toBe(preview) + await expectAxeClean(pane) + }) + + it('keeps Markdown and JSON previews accessible', async () => { + const markdown = renderPane('text/markdown', { + webOperation: vi.fn().mockResolvedValue({ responseText: '# Markdown heading' }) + }) + await vi.waitFor(() => { + expect(markdown.querySelector('h1')).not.toBeNull() + }) + await expectAxeClean(markdown) + + const json = renderPane('application/json', { + webOperation: vi.fn().mockResolvedValue({ responseText: '{"enabled":true}' }) + }) + await vi.waitFor(() => { + expect(json.querySelector('.human-readable-json-preview')).not.toBeNull() + }) + await expectAxeClean(json) + }) + + it('keeps invalid JSON errors and original content accessible', async () => { + const pane = renderPane('application/json', { + webOperation: vi.fn().mockResolvedValue({ responseText: '{ "value": 01 }' }) + }) + + await vi.waitFor(() => { + expect(pane.querySelector('solid-ui-error-state')).not.toBeNull() + }) + expect(pane.querySelector('.human-readable-json-preview')).toHaveTextContent('{ "value": 01 }') + await expectAxeClean(pane) + }) + + it('gives image and video previews accessible labels and controls', async () => { + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:https://pod.example/media') + const response = { + ok: true, + blob: vi.fn().mockResolvedValue(new Blob(['media'])) + } + const image = renderPane('image/png', { + _fetch: vi.fn().mockResolvedValue(response) + }) + await vi.waitFor(() => { + expect(image.querySelector('img')).not.toBeNull() + }) + expect(image.querySelector('img')).toHaveAttribute('alt', 'Image preview') + await expectAxeClean(image) + + const videoResponse = { + ok: true, + blob: vi.fn().mockResolvedValue(new Blob(['media'])) + } + const video = renderPane('video/mp4', { + _fetch: vi.fn().mockResolvedValue(videoResponse) + }) + await vi.waitFor(() => { + expect(video.querySelector('video')).not.toBeNull() + }) + expect(video.querySelector('video')).toHaveAttribute('controls') + expect(video.querySelector('video')).toHaveAttribute('playsinline') + await expectAxeClean(video) + }) + + it('keeps the media error state accessible', async () => { + const pane = renderPane('image/png', { + _fetch: vi.fn().mockRejectedValue(new Error('network failure')) + }) + + await vi.waitFor(() => { + expect(pane.querySelector('solid-ui-error-state')).not.toBeNull() + }) + await expectAxeClean(pane) + }) +}) From 357af6464311ea81423547a26966884c7744a364 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 21:06:36 +1100 Subject: [PATCH 13/24] pad creation test --- test/unit/creationPromises.test.ts | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/unit/creationPromises.test.ts b/test/unit/creationPromises.test.ts index 674ba115..d536081b 100644 --- a/test/unit/creationPromises.test.ts +++ b/test/unit/creationPromises.test.ts @@ -116,4 +116,42 @@ describe('pane creation promise contracts', () => { newBase: 'https://pod.example/pad/' })).rejects.toThrow('write failed') }) + + it('writes the initial Pad linked-list pointers to the indexed subject', async () => { + const store = $rdf.graph() + const put = vi.fn((_doc, statements, _contentType, callback) => { + expect(statements).toEqual(expect.arrayContaining([ + expect.objectContaining({ + subject: expect.objectContaining({ + uri: 'https://pod.example/pad/index.ttl#this' + }), + predicate: expect.objectContaining({ uri: 'http://www.w3.org/ns/pim/pad#next' }), + object: expect.objectContaining({ + uri: 'https://pod.example/pad/index.ttl#this_line0' + }) + }), + expect.objectContaining({ + subject: expect.objectContaining({ + uri: 'https://pod.example/pad/index.ttl#this_line0' + }), + predicate: expect.objectContaining({ uri: 'http://www.w3.org/ns/pim/pad#next' }), + object: expect.objectContaining({ + uri: 'https://pod.example/pad/index.ttl#this' + }) + }) + ])) + callback(_doc.uri, true) + }) + store.updater = { put } as any + + await (padPane as any).mintNew({ session: { store } }, { + newBase: 'https://pod.example/pad/', + me: $rdf.sym('https://pod.example/profile#me') + }) + + expect((store.any( + $rdf.sym('https://pod.example/pad/index.ttl#this'), + $rdf.sym('http://www.w3.org/ns/pim/pad#next') + ) as $rdf.NamedNode | undefined)?.uri).toBe('https://pod.example/pad/index.ttl#this_line0') + }) }) From 3c3f7492b3077ec638bc3179c7f0f011178963ca Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sat, 21 Nov 2026 21:18:53 +1100 Subject: [PATCH 14/24] some cleanup --- src/components/pdf-viewer/PdfViewer.ts | 23 ++++++++++++++++--- .../{dokieliPane.js => dokieliPane.ts} | 15 ++++++------ src/humanReadable/humanReadablePane.css | 2 +- src/humanReadable/jsonPreview.ts | 2 +- src/humanReadable/previewError.ts | 5 +++- test/unit/humanReadablePane.test.ts | 1 + 6 files changed, 34 insertions(+), 14 deletions(-) rename src/dokieli/{dokieliPane.js => dokieliPane.ts} (85%) diff --git a/src/components/pdf-viewer/PdfViewer.ts b/src/components/pdf-viewer/PdfViewer.ts index b583d7ef..6f6c7804 100644 --- a/src/components/pdf-viewer/PdfViewer.ts +++ b/src/components/pdf-viewer/PdfViewer.ts @@ -68,6 +68,18 @@ export default class PdfViewer extends WebComponent { private selectPage (pageNumber: number): void { if (!this.pdfDocument || pageNumber < 1 || pageNumber > this.pageCount) return this.currentPage = pageNumber + const generation = this.fetchGeneration + this.renderSelectedPage(pageNumber, generation).catch(error => { + if (generation === this.fetchGeneration) { + this.errorMessage = error instanceof Error ? error.message : String(error) + } + }) + } + + private async renderSelectedPage (pageNumber: number, generation: number): Promise { + await this.updateComplete + const canvas = this.renderRoot.querySelectorAll('.canvas')[pageNumber - 1] + if (canvas) await this.renderPage(pageNumber, canvas, 1.25, generation) } private async renderPage ( @@ -91,12 +103,17 @@ export default class PdfViewer extends WebComponent { await this.updateComplete const canvases = this.renderRoot.querySelectorAll('.canvas') if (canvases.length === 0) throw new Error('Unable to create a PDF canvas.') - await Promise.all(Array.from(canvases, (canvas, index) => - this.renderPage(index + 1, canvas, 1.25, generation) - )) + if (this.dataset.layout === 'mobile') { + await Promise.all(Array.from(canvases, (canvas, index) => + this.renderPage(index + 1, canvas, 1.25, generation) + )) + return + } + await this.renderPage(this.currentPage, canvases[this.currentPage - 1], 1.25, generation) } private async renderThumbnailCanvases (generation: number): Promise { + if (this.dataset.layout === 'mobile') return await this.updateComplete const canvases = this.renderRoot.querySelectorAll('.thumbnail-canvas') await Promise.all(Array.from(canvases, (canvas, index) => diff --git a/src/dokieli/dokieliPane.js b/src/dokieli/dokieliPane.ts similarity index 85% rename from src/dokieli/dokieliPane.js rename to src/dokieli/dokieliPane.ts index 4c5d2ca1..5b11da58 100644 --- a/src/dokieli/dokieliPane.js +++ b/src/dokieli/dokieliPane.ts @@ -5,8 +5,8 @@ ** review. It does not use turtle, but RDF/a */ -import * as UI from 'solid-ui' -import * as $rdf from 'rdflib' +import { icons, log, ns } from 'solid-ui' +import { sym } from 'rdflib' import * as mime from 'mime-types' // const DOKIELI_TEMPLATE_URI = 'https://dokie.li/new' // Copy to make new dok @@ -14,11 +14,11 @@ import * as mime from 'mime-types' import DOKIELI_TEMPLATE from './new.js' // Distributed with this library export default { - icon: UI.icons.iconBase + 'dokieli-logo.png', // @@ improve? more like doccument? + icon: icons.iconBase + 'dokieli-logo.png', // @@ improve? more like doccument? name: 'Dokieli', - mintClass: UI.ns.solid('DokieliDocument'), // @@ A better class? + mintClass: ns.solid('DokieliDocument'), // @@ A better class? // Don't provide viewing - let humanReadablePane handle that with appropriate icon label: function (subject, context) { @@ -40,7 +40,7 @@ export default { const contentType = mime.lookup(newInstance.uri) if (!contentType || !contentType.includes('html')) { - newInstance = $rdf.sym(newInstance.uri + '.html') + newInstance = sym(newInstance.uri + '.html') } newPaneOptions.newInstance = newInstance // Save for creation system @@ -65,13 +65,12 @@ export default { contentType: 'text/html' }) .then(function () { - console.log( + log.info( 'new Dokieli document created at ' + newPaneOptions.newInstance ) return newPaneOptions }) } - // render: removed - now handled by humanReadablePane with appropriate dokieli icon } -// ends + diff --git a/src/humanReadable/humanReadablePane.css b/src/humanReadable/humanReadablePane.css index 65c01a1d..c5f086d8 100644 --- a/src/humanReadable/humanReadablePane.css +++ b/src/humanReadable/humanReadablePane.css @@ -104,7 +104,7 @@ solid-ui-file-explorer-provider > .paneDiv.human-readable-pane--iframe { width: 100%; } -.human-readable-document-status[data-visible='true'] ~ .human-readable-document-frame { +.human-readable-document-status[data-visible='true'][data-keep-frame='false'] ~ .human-readable-document-frame { display: none; } diff --git a/src/humanReadable/jsonPreview.ts b/src/humanReadable/jsonPreview.ts index 8aeee575..ca3c32dc 100644 --- a/src/humanReadable/jsonPreview.ts +++ b/src/humanReadable/jsonPreview.ts @@ -85,7 +85,7 @@ function showOriginalWithError ( source: string, errorMessage: string ): void { - renderPreviewError(status, 'Unable to display JSON', errorMessage) + renderPreviewError(status, 'Unable to display JSON', errorMessage, false) render(html`${source}`, frame) } diff --git a/src/humanReadable/previewError.ts b/src/humanReadable/previewError.ts index 57675f4e..37ef6f40 100644 --- a/src/humanReadable/previewError.ts +++ b/src/humanReadable/previewError.ts @@ -4,11 +4,14 @@ import 'solid-ui/components/error-state' export function renderPreviewError ( status: HTMLElement, title: string, - message: string + message: string, + hideFrame = true ): void { status.dataset.visible = 'true' + status.dataset.keepFrame = String(!hideFrame) const clearError = () => { status.dataset.visible = 'false' + delete status.dataset.keepFrame render(nothing, status) } render(html` diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index ac427c16..5961cb63 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -204,6 +204,7 @@ describe('human readable pane iframe rendering', () => { expect((pane.querySelector('solid-ui-error-state') as HTMLElement & { message: string }).message) .toBe('Invalid JSON — showing the original content.') expect(pane.querySelector('pre')?.textContent).toBe(source) + expect(pane.querySelector('.human-readable-document-status')).toHaveAttribute('data-keep-frame', 'true') expect(pane.querySelector('script, img')).toBeNull() }) From 0e8ed4be0d422ccba159c0c5c5e22e7c19552cf3 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Sun, 22 Nov 2026 06:33:37 +1100 Subject: [PATCH 15/24] Address PR feedback Prompt: Help addressing PR feedback a few prompts Co-authored-by: GPT-5.6 Luna --- package-lock.json | 1 + package.json | 1 + .../iframe-preview/IframePreview.ts | 1 + src/components/pdf-viewer/PdfViewer.ts | 126 ++++++++++++++++-- .../pdf-viewer/PdfViewier.styles.css | 1 + src/dataContentPane.ts | 8 +- src/humanReadable/index.ts | 13 +- src/mainPage/index.ts | 5 +- src/navigation/controller.ts | 8 +- src/navigation/state.ts | 5 + test/unit/dataContentPane.test.ts | 9 +- test/unit/humanReadablePane.test.ts | 28 ++++ test/unit/navigation/controller.test.ts | 9 ++ 13 files changed, 193 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index e81e02ec..af05c521 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "dompurify": "^3.4.4", "folder-pane": "4.1.5-0", "issue-pane": "4.1.1-0", + "lit": "^3.3.3", "lit-html": "^3.3.2", "markdown-it": "^15.0.3", "meeting-pane": "4.1.1-0", diff --git a/package.json b/package.json index 5e54b838..9f503fb4 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "dompurify": "^3.4.4", "folder-pane": "4.1.5-0", "issue-pane": "4.1.1-0", + "lit": "^3.3.3", "lit-html": "^3.3.2", "markdown-it": "^15.0.3", "meeting-pane": "4.1.1-0", diff --git a/src/components/iframe-preview/IframePreview.ts b/src/components/iframe-preview/IframePreview.ts index 73ff2aac..1793445e 100644 --- a/src/components/iframe-preview/IframePreview.ts +++ b/src/components/iframe-preview/IframePreview.ts @@ -65,6 +65,7 @@ export default class IframePreview extends WebComponent { private clearPreview (): void { this.removeDokieliBridge() this.removeDokieliBridge = () => {} + this.renderRoot.querySelector('iframe')?.removeAttribute('srcdoc') if (this.objectUrl) { URL.revokeObjectURL(this.objectUrl) this.objectUrl = undefined diff --git a/src/components/pdf-viewer/PdfViewer.ts b/src/components/pdf-viewer/PdfViewer.ts index 6f6c7804..d8ab09e0 100644 --- a/src/components/pdf-viewer/PdfViewer.ts +++ b/src/components/pdf-viewer/PdfViewer.ts @@ -36,6 +36,87 @@ export default class PdfViewer extends WebComponent { private pdfDocument: PdfDocument | undefined private pdfLoadingTask: ReturnType | undefined private fetchGeneration = 0 + private effectiveMobileLayout = false + private readonly maxConcurrentRenders = 2 + private pageObserver: IntersectionObserver | undefined + private readonly visibleMobilePages = new Set() + private readonly renderedPages = new Set() + private renderQueue: Promise = Promise.resolve() + private readonly handleViewportChange = (): void => { + const mobile = this.isMobileLayout() + if (mobile === this.effectiveMobileLayout || !this.pdfDocument) return + this.effectiveMobileLayout = mobile + const generation = this.fetchGeneration + Promise.all([ + this.renderMainCanvases(generation), + this.renderThumbnailCanvases(generation) + ]).catch(error => { + if (generation === this.fetchGeneration) { + this.errorMessage = error instanceof Error ? error.message : String(error) + } + }) + } + + private async renderPageBatch (pageNumbers: number[], generation: number): Promise { + const render = this.renderQueue.then(async () => { + const pending = pageNumbers.filter(pageNumber => !this.renderedPages.has(pageNumber)) + const canvases = this.renderRoot.querySelectorAll('.canvas') + for (let start = 0; start < pending.length; start += this.maxConcurrentRenders) { + await Promise.all(pending.slice(start, start + this.maxConcurrentRenders).map(async pageNumber => { + const canvas = canvases[pageNumber - 1] + if (!canvas) return + await this.renderPage(pageNumber, canvas, 1.25, generation) + if (generation === this.fetchGeneration) this.renderedPages.add(pageNumber) + })) + } + }) + this.renderQueue = render.catch(() => {}) + await render + } + + private observeMobilePages (generation: number): void { + this.pageObserver?.disconnect() + if (!this.isMobileLayout() || typeof IntersectionObserver === 'undefined') return + const pages = this.renderRoot.querySelectorAll('.page') + this.pageObserver = new IntersectionObserver(entries => { + entries.forEach(entry => { + const pageNumber = Number((entry.target as HTMLElement).dataset.page) + if (entry.isIntersecting) this.visibleMobilePages.add(pageNumber) + else this.visibleMobilePages.delete(pageNumber) + }) + if (this.visibleMobilePages.size === 0) return + const visible = Array.from(this.visibleMobilePages) + const firstVisible = Math.min(...visible) + const lastVisible = Math.max(...visible) + const keep = new Set( + Array.from( + { length: lastVisible - firstVisible + 3 }, + (_, index) => Math.max(1, firstVisible - 1 + index) + ).filter(pageNumber => pageNumber <= this.pageCount) + ) + this.releaseDistantPages(keep) + this.renderPageBatch(Array.from(keep), generation).catch(error => { + if (generation === this.fetchGeneration) { + this.errorMessage = error instanceof Error ? error.message : String(error) + } + }) + }, { root: this.renderRoot.querySelector('.main'), rootMargin: '800px 0px' }) + pages.forEach(page => this.pageObserver?.observe(page)) + } + + private releaseDistantPages (keep: Set): void { + if (!this.isMobileLayout()) return + const canvases = this.renderRoot.querySelectorAll('.canvas') + this.renderedPages.forEach(pageNumber => { + if (keep.has(pageNumber)) return + const canvas = canvases[pageNumber - 1] + if (canvas) { + canvas.width = 0 + canvas.height = 0 + } + this.renderedPages.delete(pageNumber) + }) + } @state() private accessor pageCount = 0 @@ -51,6 +132,11 @@ export default class PdfViewer extends WebComponent { this.errorMessage = '' } + private isMobileLayout (): boolean { + return this.dataset.layout === 'mobile' || + window.matchMedia?.('(max-width: 768px)').matches === true + } + private clearDocument (): void { this.errorMessage = '' this.pdfJs = undefined @@ -63,6 +149,10 @@ export default class PdfViewer extends WebComponent { this.pdfDocument.cleanup() this.pdfDocument = undefined } + this.pageObserver?.disconnect() + this.pageObserver = undefined + this.renderedPages.clear() + this.visibleMobilePages.clear() } private selectPage (pageNumber: number): void { @@ -103,22 +193,30 @@ export default class PdfViewer extends WebComponent { await this.updateComplete const canvases = this.renderRoot.querySelectorAll('.canvas') if (canvases.length === 0) throw new Error('Unable to create a PDF canvas.') - if (this.dataset.layout === 'mobile') { - await Promise.all(Array.from(canvases, (canvas, index) => - this.renderPage(index + 1, canvas, 1.25, generation) - )) + if (this.isMobileLayout()) { + const firstPage = Math.max(1, this.currentPage - 2) + const lastPage = Math.min(this.pageCount, this.currentPage + 2) + await this.renderPageBatch( + Array.from({ length: lastPage - firstPage + 1 }, (_, index) => firstPage + index), + generation + ) + this.observeMobilePages(generation) return } - await this.renderPage(this.currentPage, canvases[this.currentPage - 1], 1.25, generation) + await this.renderPageBatch([this.currentPage], generation) + this.releaseDistantPages(new Set([this.currentPage])) } private async renderThumbnailCanvases (generation: number): Promise { - if (this.dataset.layout === 'mobile') return + if (this.isMobileLayout()) return await this.updateComplete const canvases = this.renderRoot.querySelectorAll('.thumbnail-canvas') - await Promise.all(Array.from(canvases, (canvas, index) => - this.renderPage(index + 1, canvas, 0.18, generation) - )) + for (let start = 0; start < canvases.length; start += this.maxConcurrentRenders) { + await Promise.all(Array.from( + { length: Math.min(this.maxConcurrentRenders, canvases.length - start) }, + (_, offset) => this.renderPage(start + offset + 1, canvases[start + offset], 0.18, generation) + )) + } } private async renderMainPage (generation: number): Promise { @@ -134,6 +232,7 @@ export default class PdfViewer extends WebComponent { } this.pdfDocument = pdfDocument + this.effectiveMobileLayout = this.isMobileLayout() this.pageCount = pdfDocument.numPages this.currentPage = 1 if (!this.isConnected || generation !== this.fetchGeneration) return @@ -192,6 +291,8 @@ export default class PdfViewer extends WebComponent { connectedCallback (): void { super.connectedCallback() + this.effectiveMobileLayout = this.isMobileLayout() + window.addEventListener('resize', this.handleViewportChange) if (this.hasUpdated) this.fetchDocument() } @@ -203,6 +304,7 @@ export default class PdfViewer extends WebComponent { } disconnectedCallback (): void { + window.removeEventListener('resize', this.handleViewportChange) ++this.fetchGeneration this.clearDocument() super.disconnectedCallback() @@ -217,7 +319,11 @@ export default class PdfViewer extends WebComponent { This preview displays pages as images. PDF text and links are not accessible in this preview. ${(this.pageCount > 0 ? Array.from({ length: this.pageCount }, (_, index) => index + 1) : [1]).map(pageNumber => html` -
+
`)} diff --git a/src/components/pdf-viewer/PdfViewier.styles.css b/src/components/pdf-viewer/PdfViewier.styles.css index a6af770b..5034f4ac 100644 --- a/src/components/pdf-viewer/PdfViewier.styles.css +++ b/src/components/pdf-viewer/PdfViewier.styles.css @@ -44,6 +44,7 @@ flex: 0 0 auto; width: 100%; max-width: 100%; + aspect-ratio: 0.707 / 1; } .page[data-current] { diff --git a/src/dataContentPane.ts b/src/dataContentPane.ts index 8c552449..06107eae 100644 --- a/src/dataContentPane.ts +++ b/src/dataContentPane.ts @@ -198,9 +198,9 @@ export const dataContentPane = { referenceAnchor.setAttribute('class', 'bnodeRef') referenceAnchor.setAttribute( 'aria-label', - `Referenced blank node ${obj.toNT().slice(3)}` + `Referenced blank node ${obj.toNT().slice(2)}` ) - referenceAnchor.textContent = '*' + obj.toNT().slice(3) + referenceAnchor.textContent = '*' + obj.toNT().slice(2) return referenceAnchor } doneBnodes[obj.toNT()] = true @@ -279,8 +279,8 @@ export const dataContentPane = { anchor.setAttribute('id', bNT.slice(2)) anchor.setAttribute('tabindex', '-1') anchor.setAttribute('class', 'bnodeDef') - anchor.setAttribute('aria-label', `Blank node ${bNT.slice(3)}`) - anchor.textContent = bNT.slice(3) + ')' + anchor.setAttribute('aria-label', `Blank node ${bNT.slice(2)}`) + anchor.textContent = bNT.slice(2) + ')' caption.appendChild(anchor) table.insertBefore(caption, table.firstChild) } diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index e66aa307..dbeda6b4 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -374,8 +374,12 @@ const humanReadablePane: HumanReadablePaneDefinition = { const cts = kb.fetcher.getHeader(x, 'content-type') if (cts) { for (let j = 0; j < cts.length; j++) { + const contentType = cts[j].split(';', 1)[0].trim().toLowerCase() for (let k = 0; k < displayables.length; k++) { - if (cts[j].indexOf(displayables[k]) >= 0) { + const displayable = displayables[k] + if (displayable.endsWith('/') + ? contentType.startsWith(displayable) + : contentType === displayable) { return true } } @@ -391,8 +395,13 @@ const humanReadablePane: HumanReadablePaneDefinition = { displayables: string[] ): boolean { const t = kb.findTypeURIs(x) + if (t['http://purl.org/dc/terms/Image']) return true for (let k = 0; k < displayables.length; k++) { - if (Util.mediaTypeClass(displayables[k]).uri in t) { + const displayable = displayables[k] + if (displayable.endsWith('/')) { + const mediaTypePrefix = `http://www.w3.org/ns/iana/media-types/${displayable}` + if (Object.keys(t).some(type => type.startsWith(mediaTypePrefix))) return true + } else if (Util.mediaTypeClass(displayable).uri in t) { return true } } diff --git a/src/mainPage/index.ts b/src/mainPage/index.ts index 11ae4b6f..24bcbaf5 100644 --- a/src/mainPage/index.ts +++ b/src/mainPage/index.ts @@ -12,7 +12,7 @@ import { createNavbar } from './navbar' import { navigationFor } from './navigation' import { initializeProfileHeading, placeProfileHeading } from './profileHeading' import { registerBrowserNavigation } from '../navigation/browserEvents' -import { clearPaneState } from '../navigation/state' +import { clearPaneState, navigationSubjectUri } from '../navigation/state' import { resetPodContexts } from '../navigation/podContext' import { IFRAME_PREVIEW_FRAME_NAME } from '../humanReadable' @@ -56,8 +56,7 @@ export async function initMainPage ( return } ensureMainContent() - const requestedUri = new URL(window.location.href).searchParams.get('uri') - uri = requestedUri || uri || window.location.href + uri = navigationSubjectUri() || uri || window.location.href const subject: NamedNode = typeof uri === 'string' ? store.sym(uri) : uri // A reload shows what the URL is, whatever the history entry last displayed through the navbar // or the account menu: the profile on a profile page, otherwise the resource or container itself. diff --git a/src/navigation/controller.ts b/src/navigation/controller.ts index 01fbfdc6..85265441 100644 --- a/src/navigation/controller.ts +++ b/src/navigation/controller.ts @@ -12,7 +12,7 @@ import type { PaneDefinition } from 'pane-registry' import type { OutlineManager } from '../outline/manager' import { getFolderPaneForStorage, getProfilePaneFromURI, getSocialPaneFromURI, type PaneItem } from '../utils/paneUtils' import { setNavbarHidden } from './navbarVisibility' -import { readNavigationState, type NavigationState, type NavigationView } from './state' +import { navigationSubjectUri, readNavigationState, type NavigationState, type NavigationView } from './state' import type { FolderView, NavigationSource } from './options' import { isWebIdUri } from '../utils/webIdUtils' import { deriveStorageView } from './chrome' @@ -114,7 +114,11 @@ export function createNavigationController (deps: NavigationDeps): NavigationCon // The account menu shows the viewer's own content, so the navbar for the page is not offered if (source === 'accountMenu') setNavbarHidden(true) - const subject = store.sym(intent.kind === 'restore' && intent.subject ? intent.subject : window.location.href) + const subject = store.sym( + intent.kind === 'restore' + ? intent.subject ?? navigationSubjectUri() ?? window.location.href + : window.location.href + ) const pane = await paneFor(intent, subject, state) if (request !== latest) return diff --git a/src/navigation/state.ts b/src/navigation/state.ts index a5cd7c79..b7cecf48 100644 --- a/src/navigation/state.ts +++ b/src/navigation/state.ts @@ -52,6 +52,11 @@ export function readNavigationState (): NavigationState { return parseNavigationState(window.history.state) } +/** Resolve the resource represented by the application URL, including ?uri= deep links. */ +export function navigationSubjectUri (location: Location = window.location): string | undefined { + return new URL(location.href).searchParams.get('uri') || undefined +} + const historyWrites = new WeakMap() /** Whether a synchronous history write is being made by this application. */ diff --git a/test/unit/dataContentPane.test.ts b/test/unit/dataContentPane.test.ts index b5d8aecc..63569912 100644 --- a/test/unit/dataContentPane.test.ts +++ b/test/unit/dataContentPane.test.ts @@ -102,7 +102,14 @@ describe('data content pane', () => { expect(table.querySelector(`a[href="${related.uri}"]`)).toBeTruthy() expect(table.querySelector('ol > li')).toBeTruthy() expect(table.querySelector('table[aria-label="Properties"]')).toBeTruthy() - expect(table.querySelector('.bnodeDef[tabindex="-1"]')).toBeTruthy() + const reference = table.querySelector('.bnodeRef') + const definition = table.querySelector('.bnodeDef[tabindex="-1"]') + expect(reference).toHaveAttribute('href', '#nested') + expect(reference).toHaveTextContent('*nested') + expect(reference).toHaveAttribute('aria-label', 'Referenced blank node nested') + expect(definition).toHaveAttribute('id', 'nested') + expect(definition).toHaveTextContent('nested)') + expect(definition).toHaveAttribute('aria-label', 'Blank node nested') }) it('preserves sanitized XMLLiteral content and labels its embedded region', () => { diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 5961cb63..4702336d 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -125,6 +125,18 @@ describe('isAllowedPreviewRequest', () => { }) describe('human readable pane iframe rendering', () => { + it.each([ + 'http://www.w3.org/ns/iana/media-types/image/png#Resource', + 'http://purl.org/dc/terms/Image' + ])('recognizes image RDF types without a cached content type (%s)', typeUri => { + const store = { + fetcher: { getHeader: vi.fn().mockReturnValue(null) }, + findTypeURIs: vi.fn().mockReturnValue({ [typeUri]: true }) + } + + expect(humanReadablePane.label(sym(uri), { session: { store } } as any)).toBe('View') + }) + it.each(['text/markdown', 'text/markdown; charset=utf-8', 'text/markdown; charset=UTF-8; format=flowed'])( 'renders Markdown from content type %s without a Markdown filename', async contentType => { @@ -591,6 +603,22 @@ describe('human readable pane iframe rendering', () => { expect(getFrame(pane)?.srcdoc).not.toContain('Stale document') }) + it('clears an old srcdoc when switching to a blob preview', async () => { + const fetch = vi.fn() + .mockResolvedValueOnce(htmlResponse('HTML preview')) + .mockResolvedValueOnce(new Response('binary', { headers: { 'content-type': 'application/octet-stream' } })) + const pane = renderWith('text/html', { _fetch: fetch }) + const preview = pane.querySelector('solid-panes-iframe-preview') as IframePreview + await waitForSrcdoc(pane, 'HTML preview') + + vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:https://pod.example/next') + preview.subject = sym('https://pod.example/docs/next.bin') + await vi.waitFor(() => expect(getFrame(pane)?.src).toBe('blob:https://pod.example/next')) + + expect(getFrame(pane)?.getAttribute('srcdoc')).toBeNull() + vi.restoreAllMocks() + }) + it.each(['text/html', 'application/octet-stream'])('does not attach a late Dokieli bridge after a %s preview is removed', async contentType => { let resolveResponse!: (response: Response) => void const responsePromise = new Promise(resolve => { resolveResponse = resolve }) diff --git a/test/unit/navigation/controller.test.ts b/test/unit/navigation/controller.test.ts index 0bf69eaf..d6c313b4 100644 --- a/test/unit/navigation/controller.test.ts +++ b/test/unit/navigation/controller.test.ts @@ -209,6 +209,15 @@ describe('restoring a history entry', () => { expect(refreshHeading).toHaveBeenCalledWith(false) }) + it('restores a cross-origin resource from a ?uri= deep link', async () => { + const target = 'https://other.example/private/document.html' + window.history.replaceState({}, '', `/?uri=${encodeURIComponent(target)}`) + + await controller.show({ kind: 'restore' }) + + expect(GotoSubject.mock.calls[0][0]).toEqual(store.sym(target)) + }) + it('still shows the default view when the entry names a pane that cannot be built', async () => { getFolderPane.mockResolvedValue(null) window.history.replaceState({ paneName: 'folder', paneUri: 'https://pod.example/timea/' }, '', '/timea2/docs/') From ca9f7359abef99b1c6987aaebc3508fab47ca0b4 Mon Sep 17 00:00:00 2001 From: Sharon Stratsianis Date: Tue, 24 Nov 2026 08:10:40 +0000 Subject: [PATCH 16/24] fix mobile Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iframe-preview/IframePreview.ts | 6 ++- src/humanReadable/index.ts | 1 + src/humanReadable/previewBridge.ts | 5 +- src/humanReadable/previewHelpers.ts | 52 +++++++++++++++++++ test/unit/humanReadablePane.test.ts | 14 ++++- 5 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/components/iframe-preview/IframePreview.ts b/src/components/iframe-preview/IframePreview.ts index 1793445e..7bf731ad 100644 --- a/src/components/iframe-preview/IframePreview.ts +++ b/src/components/iframe-preview/IframePreview.ts @@ -6,7 +6,8 @@ import { documentTitle, HTML_PREVIEW_SANDBOX, IFRAME_PREVIEW_FRAME_NAME, - resourceFilename + resourceFilename, + addResponsivePreviewStyles } from '../../humanReadable/previewHelpers' import styles from './IframePreview.styles.css' import 'solid-ui/components/error-state' @@ -101,7 +102,8 @@ export default class IframePreview extends WebComponent { this.rawHtml = htmlContent this.fetchedTitle = documentTitle(htmlContent, subject.uri) this.contentType = contentType - this.content = this.withBaseHref?.(htmlContent, subject.uri) ?? htmlContent + const documentHtml = this.withBaseHref?.(htmlContent, subject.uri) ?? htmlContent + this.content = addResponsivePreviewStyles(documentHtml) } else { const blob = await response.blob() if (!isCurrent()) return diff --git a/src/humanReadable/index.ts b/src/humanReadable/index.ts index dbeda6b4..88214099 100644 --- a/src/humanReadable/index.ts +++ b/src/humanReadable/index.ts @@ -22,6 +22,7 @@ import type PdfViewer from '../components/pdf-viewer' import '../components/pdf-viewer' export { IFRAME_PREVIEW_FRAME_NAME } from './previewHelpers' +export { addResponsivePreviewStyles } from './previewHelpers' function viewerWebId (): string | null { try { diff --git a/src/humanReadable/previewBridge.ts b/src/humanReadable/previewBridge.ts index 58e8b593..dcd09182 100644 --- a/src/humanReadable/previewBridge.ts +++ b/src/humanReadable/previewBridge.ts @@ -4,6 +4,8 @@ * The preview remains untrusted: the parent window validates every request * before delegating it to the authenticated Solid fetcher. */ +import { addResponsivePreviewStyles } from './previewHelpers' + export type PreviewBridgeOptions = { bridgeAttribute: string requestType: string @@ -399,5 +401,6 @@ export function createPreviewBridge ( })() ` const cleanHtml = options.stripPreviewBridgeScripts(html) ?? html - return options.withBaseHref(cleanHtml, uri).replace(/]*)?>/i, match => `${match}${bridge}`) + const previewHtml = options.withBaseHref(cleanHtml, uri) + return addResponsivePreviewStyles(previewHtml).replace(/]*)?>/i, match => `${match}${bridge}`) } diff --git a/src/humanReadable/previewHelpers.ts b/src/humanReadable/previewHelpers.ts index 90d0a258..baf0fa5a 100644 --- a/src/humanReadable/previewHelpers.ts +++ b/src/humanReadable/previewHelpers.ts @@ -1,10 +1,62 @@ export const IFRAME_PREVIEW_FRAME_NAME = 'solidos-iframe-preview' export const HTML_PREVIEW_SANDBOX = 'allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals' +const MOBILE_PREVIEW_STYLES = ` +` + export function escapeAttribute (value: string): string { return value.replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') } +export function addResponsivePreviewStyles (html: string): string { + if (html.includes('data-solidos-mobile-preview')) return html + const headMatch = html.match(/]*)?>/i) + if (headMatch && headMatch.index !== undefined) { + const insertAt = headMatch.index + headMatch[0].length + return html.slice(0, insertAt) + MOBILE_PREVIEW_STYLES + html.slice(insertAt) + } + return MOBILE_PREVIEW_STYLES + html +} + export function resourceFilename (uri: string): string { const encodedFilename = uri.split('/').pop() || uri try { diff --git a/test/unit/humanReadablePane.test.ts b/test/unit/humanReadablePane.test.ts index 4702336d..f0e47524 100644 --- a/test/unit/humanReadablePane.test.ts +++ b/test/unit/humanReadablePane.test.ts @@ -6,7 +6,8 @@ import humanReadablePane, { IFRAME_PREVIEW_FRAME_NAME, isAllowedPreviewRequest, previewRequestUrl, - withBaseHref + withBaseHref, + addResponsivePreviewStyles } from '../../src/humanReadable' const uri = 'https://pod.example/docs/page.html' @@ -70,6 +71,17 @@ describe('withBaseHref', () => { }) }) +describe('addResponsivePreviewStyles', () => { + it('adds mobile document sizing styles inside the preview document head', () => { + const html = addResponsivePreviewStyles('x') + + expect(html).toContain('' + ) + + expect(html.indexOf('body { margin: 40px }')).toBeLessThan(html.indexOf('