-
Notifications
You must be signed in to change notification settings - Fork 3
feat: file viewer #87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c1f2124
feat: file viewer
kemuru c1d83a4
feat: feedback
kemuru e2990a4
feat(file-viewer): block unsafe URL schemes, add pdf worker override
kemuru 0fc501c
fix(file-viewer): decode data: URIs per RFC 2397
kemuru 888e50e
feat(file-viewer): translucent pdf toolbar with per-theme tint
kemuru 8e451d4
feat(attachment-display): wire image checker color into file viewer s…
kemuru d17f8a9
style(file-viewer): trim image preview vertical padding
kemuru e9eb308
chore: delete vertical padding on png viewer altogether
kemuru 1f54562
feat: feedback
kemuru File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,3 +25,6 @@ yarn-debug.log* | |
| yarn-error.log* | ||
|
|
||
| *storybook.log | ||
|
|
||
| # "yarn pack" output | ||
| *.tgz | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| /* PNG transparency checkerboard color. | ||
| Upstream `@cyntler/react-doc-viewer` hardcodes `#e0e0e0` on `#image-renderer` | ||
| for PNGs. That's fine on white (subtle, industry-standard) but visually loud | ||
| on a dark surface, and impossible to retune without overriding the property. | ||
|
|
||
| We replace the hardcoded color with `--klerosUIComponentsImageCheckerColor` | ||
| so consumers (scout, etc.) can swap a single token to match their palette. | ||
| Defaults in theme.css: light = #e0e0e0 (matches upstream), dark = #2c0d63 | ||
| (slight lift over the dark surface). Selector specificity (2 ids = 0,2,0) | ||
| beats the styled-component without !important. */ | ||
| #react-doc-viewer #image-renderer { | ||
|
kemuru marked this conversation as resolved.
Outdated
|
||
| background-image: linear-gradient( | ||
| 45deg, | ||
| var(--klerosUIComponentsImageCheckerColor, #e0e0e0) 25%, | ||
| transparent 25% | ||
| ), | ||
| linear-gradient( | ||
| -45deg, | ||
| var(--klerosUIComponentsImageCheckerColor, #e0e0e0) 25%, | ||
| transparent 25% | ||
| ), | ||
| linear-gradient( | ||
| 45deg, | ||
| transparent 75%, | ||
| var(--klerosUIComponentsImageCheckerColor, #e0e0e0) 75% | ||
| ), | ||
| linear-gradient( | ||
| -45deg, | ||
| transparent 75%, | ||
| var(--klerosUIComponentsImageCheckerColor, #e0e0e0) 75% | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,254 @@ | ||
| import React, { useMemo } from "react"; | ||
| import DocViewer, { | ||
| DocViewerRenderers, | ||
| type IConfig, | ||
| type ITheme, | ||
| type IDocument, | ||
| } from "@cyntler/react-doc-viewer"; | ||
|
|
||
| import { cn } from "../../utils"; | ||
| import MarkdownDocRenderer from "./markdown-viewer"; | ||
| import "@cyntler/react-doc-viewer/dist/index.css"; | ||
| import "./file-viewer.css"; | ||
|
|
||
| interface FileViewerProps { | ||
| /** URL of the file to display. Supports https:, http:, blob:, and data: URIs. */ | ||
| url: string; | ||
| /** Optional file name override (used for download). Useful when the URL path lacks a meaningful filename. */ | ||
| fileName?: string; | ||
| /** Override the DocViewer config. Merged shallowly over the defaults. */ | ||
| config?: IConfig; | ||
| /** Class applied to the outer wrapper. */ | ||
| className?: string; | ||
| } | ||
|
|
||
| const SAFE_URL_SCHEMES = new Set(["http:", "https:", "blob:", "data:"]); | ||
|
|
||
| // Data-URL MIMEs that execute script on top-frame navigation. Modern Firefox | ||
| // and Chrome already block most of these via their data:-navigation | ||
| // restrictions, but coverage varies by version and type (XHTML and XML have | ||
| // historically slipped through), so re-enforcing at the gate keeps the threat | ||
| // model trivially auditable. SVG is included because `<svg onload>` runs | ||
| // script when navigated to (it does not when loaded via `<img src>`). XML and | ||
| // XHTML can execute script via xml-stylesheet processing instructions or | ||
| // inline `<script>` once parsed as a document. | ||
| const UNSAFE_DATA_MIMES = new Set([ | ||
|
kemuru marked this conversation as resolved.
|
||
| "text/html", | ||
| "application/xhtml+xml", | ||
| "application/xml", | ||
| "text/xml", | ||
| "image/svg+xml", | ||
| ]); | ||
|
|
||
| /** | ||
| * Returns true if `raw` is a relative URL or uses an allowlisted scheme. | ||
| * Blocks `javascript:`, `vbscript:`, `file:`, `about:`, and anything else | ||
| * that could execute code or escape sandboxing when clicked. | ||
| */ | ||
| const isSafeUrl = (raw: string): boolean => { | ||
| if (typeof raw !== "string" || raw.length === 0) return false; | ||
| let parsed: URL; | ||
| try { | ||
| parsed = new URL(raw); | ||
| } catch { | ||
| // Relative URLs (e.g. "/foo", "./bar.pdf") throw — they resolve against | ||
| // the page origin and inherit its safety, so they're allowed. | ||
| return true; | ||
| } | ||
| const protocol = parsed.protocol.toLowerCase(); | ||
| if (!SAFE_URL_SCHEMES.has(protocol)) return false; | ||
| if (protocol === "data:") { | ||
| const rawMime = parsed.pathname.split(/[,;]/)[0].trim().toLowerCase(); | ||
| // Defense-in-depth: spec-compliant browsers do NOT percent-decode the | ||
| // data:-URL mediatype (WHATWG Fetch § data URL processor parses it raw; | ||
| // Chromium's DataURL::Parse only unescapes the body), so `text%2Fhtml` | ||
| // fails MIME parsing and falls back to `text/plain` — already safe. We | ||
| // decode anyway to harden against legacy or non-conforming runtimes; | ||
| // reject if decoding throws so malformed inputs can't slip through. | ||
| let mime: string; | ||
| try { | ||
| mime = decodeURIComponent(rawMime); | ||
| } catch { | ||
| return false; | ||
| } | ||
| if (UNSAFE_DATA_MIMES.has(mime)) return false; | ||
| } | ||
| return true; | ||
| }; | ||
|
|
||
| type PdfjsLib = { | ||
| version?: string; | ||
| GlobalWorkerOptions?: { workerSrc?: string }; | ||
| }; | ||
|
|
||
| const getPdfjs = (): PdfjsLib | undefined => | ||
| typeof globalThis === "undefined" | ||
| ? undefined | ||
| : (globalThis as unknown as { pdfjsLib?: PdfjsLib }).pdfjsLib; | ||
|
|
||
| const buildDefaultPdfWorkerSrc = (): string => { | ||
| // doc-viewer bundles its own pdfjs and assigns it to globalThis.pdfjsLib at | ||
| // module init; reading the version from there guarantees the worker we load | ||
| // matches the runtime pdfjs (mismatched versions throw "incompatible worker"). | ||
| // Fallback constant is the version doc-viewer@1.17.x ships with. | ||
| const version = getPdfjs()?.version ?? "4.3.136"; | ||
| return `https://cdn.jsdelivr.net/npm/pdfjs-dist@${version}/build/pdf.worker.min.mjs`; | ||
| }; | ||
|
|
||
| const setPdfWorkerSrc = (src: string): void => { | ||
| const lib = getPdfjs(); | ||
| if (lib?.GlobalWorkerOptions && lib.GlobalWorkerOptions.workerSrc !== src) { | ||
| lib.GlobalWorkerOptions.workerSrc = src; | ||
| } | ||
| }; | ||
|
|
||
| // Module init: doc-viewer's module top-level code points workerSrc at | ||
| // unpkg.com. Override it immediately so no unpkg request ever fires (the | ||
| // worker is only fetched when a PDF is rendered, which is always after this). | ||
| setPdfWorkerSrc(buildDefaultPdfWorkerSrc()); | ||
|
|
||
| /** | ||
| * Override the PDF.js worker URL globally. Call once at app startup if you | ||
| * want to self-host the worker (e.g. under strict CSP) instead of using the | ||
| * default version-pinned jsDelivr URL. The worker is a process-wide singleton | ||
| * on `globalThis.pdfjsLib.GlobalWorkerOptions` — there is no per-instance | ||
| * configuration. | ||
| */ | ||
| export const configurePdfWorker = (src: string): void => { | ||
|
kemuru marked this conversation as resolved.
Outdated
|
||
| setPdfWorkerSrc(src); | ||
| }; | ||
|
|
||
| const defaultConfig: IConfig = { | ||
| header: { | ||
| disableHeader: true, | ||
| disableFileName: true, | ||
| }, | ||
| pdfZoom: { | ||
| defaultZoom: 0.8, | ||
| zoomJump: 0.1, | ||
| }, | ||
| pdfVerticalScrollByDefault: true, | ||
| }; | ||
|
|
||
| const docTheme: ITheme = { | ||
| primary: "var(--klerosUIComponentsWhiteBackground)", | ||
| secondary: "var(--klerosUIComponentsLightBackground)", | ||
| tertiary: "var(--klerosUIComponentsLightBackground)", | ||
| textPrimary: "var(--klerosUIComponentsPrimaryText)", | ||
| textSecondary: "var(--klerosUIComponentsSecondaryText)", | ||
| textTertiary: "var(--klerosUIComponentsSecondaryText)", | ||
| }; | ||
|
|
||
| const UnsupportedUrlMessage = ({ url }: { url: string }) => ( | ||
| <div | ||
| className={cn( | ||
| "text-klerosUIComponentsSecondaryText", | ||
| "flex flex-col gap-2 p-6 text-sm", | ||
| )} | ||
| > | ||
| <p>Unable to display this file.</p> | ||
| <p className="font-mono text-xs break-all">{url}</p> | ||
| </div> | ||
| ); | ||
|
|
||
| const NoRendererFallback = ({ | ||
| document, | ||
| fileName, | ||
| }: { | ||
| document: IDocument | undefined; | ||
| fileName: string; | ||
| }) => ( | ||
| <div | ||
| className={cn( | ||
| "text-klerosUIComponentsPrimaryText", | ||
| "flex flex-col items-start gap-3 p-6 text-sm", | ||
|
kemuru marked this conversation as resolved.
Outdated
|
||
| )} | ||
| > | ||
| <p>This file type can't be previewed.</p> | ||
| <a | ||
| className="text-klerosUIComponentsPrimaryBlue underline" | ||
| href={document?.uri ?? ""} | ||
| download={fileName} | ||
| rel="noopener noreferrer" | ||
| target="_blank" | ||
| > | ||
| Open in a new tab | ||
| </a> | ||
| </div> | ||
| ); | ||
|
|
||
| /** | ||
| * Displays a file from a URL inside the application. Supports PDFs, images, | ||
| * markdown, plaintext, and common document formats. | ||
| * | ||
| * Security: rejects `javascript:`, `vbscript:`, `file:`, and other unlisted | ||
| * schemes up front so a hostile `url` can't deliver code execution through | ||
| * the underlying viewer or its fallback download link. | ||
| */ | ||
| function FileViewer({ | ||
| url, | ||
| fileName, | ||
| config, | ||
| className, | ||
| }: Readonly<FileViewerProps>) { | ||
| const safe = isSafeUrl(url); | ||
|
|
||
| const docs = useMemo(() => [{ uri: url, fileName }], [url, fileName]); | ||
|
|
||
| const pluginRenderers = useMemo( | ||
| () => [...DocViewerRenderers, MarkdownDocRenderer], | ||
| [], | ||
| ); | ||
|
|
||
| const mergedConfig = useMemo<IConfig>( | ||
| () => ({ | ||
| ...defaultConfig, | ||
| ...config, | ||
| noRenderer: { | ||
| ...config?.noRenderer, | ||
| overrideComponent: | ||
| config?.noRenderer?.overrideComponent ?? NoRendererFallback, | ||
| }, | ||
| }), | ||
| [config], | ||
| ); | ||
|
|
||
| return ( | ||
| <div | ||
| className={cn( | ||
| "bg-klerosUIComponentsWhiteBackground shadow-default", | ||
| "rounded-base max-h-[80vh] overflow-auto", | ||
| className, | ||
| )} | ||
| > | ||
| {safe ? ( | ||
| <DocViewer | ||
| documents={docs} | ||
| pluginRenderers={pluginRenderers} | ||
| config={mergedConfig} | ||
| theme={docTheme} | ||
| className={cn( | ||
| "!bg-klerosUIComponentsWhiteBackground", | ||
| "[&_#pdf-controls]:!z-[3]", | ||
| "[&_#pdf-controls]:!bg-klerosUIComponentsPrimaryPurple/15", | ||
| "dark:[&_#pdf-controls]:!bg-klerosUIComponentsLightBackground/50", | ||
| "[&_#pdf-controls]:!backdrop-saturate-150", | ||
| "[&_#pdf-controls_svg_path]:!fill-klerosUIComponentsPrimaryText", | ||
| "[&_#pdf-controls_svg_polygon]:!fill-klerosUIComponentsPrimaryText", | ||
| "[&_#image-renderer]:!bg-klerosUIComponentsWhiteBackground", | ||
| "[&_#image-renderer]:!h-auto", | ||
| "[&_#image-renderer]:!flex-none", | ||
| "[&_#image-renderer]:!px-6", | ||
| "[&_#image-img]:!max-w-full", | ||
| "[&_#image-img]:!max-h-[80vh]", | ||
| "[&_[class*='--loading']]:text-klerosUIComponentsSecondaryText", | ||
| )} | ||
| /> | ||
| ) : ( | ||
| <UnsupportedUrlMessage url={url} /> | ||
| )} | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| export default FileViewer; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import React from "react"; | ||
| import { type DocRenderer } from "@cyntler/react-doc-viewer"; | ||
| import ReactMarkdown from "react-markdown"; | ||
|
|
||
| const decodeBase64Utf8 = (base64: string): string => { | ||
| const binary = atob(base64); | ||
| const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); | ||
|
Check warning on line 7 in src/lib/file-viewer/markdown-viewer.tsx
|
||
|
kemuru marked this conversation as resolved.
Outdated
|
||
| return new TextDecoder("utf-8").decode(bytes); | ||
| }; | ||
|
|
||
| const MarkdownDocRenderer: DocRenderer = ({ | ||
| mainState: { currentDocument }, | ||
| }) => { | ||
| if (!currentDocument?.fileData) return null; | ||
|
|
||
| const { fileData } = currentDocument; | ||
| let text: string; | ||
|
|
||
| if (fileData instanceof ArrayBuffer) { | ||
| text = new TextDecoder("utf-8").decode(fileData); | ||
| } else if (fileData.startsWith("data:")) { | ||
| // RFC 2397: `data:[<mediatype>][;base64],<payload>` — the payload is | ||
| // base64 only when `;base64` is the last parameter before the comma; | ||
| // otherwise it's percent-encoded. Dispatching on `atob` success would | ||
| // mis-decode payloads that happen to be valid base64 by coincidence | ||
| // (e.g. the literal string "test" atob's into garbage bytes). | ||
| const commaIdx = fileData.indexOf(","); | ||
| const header = | ||
| commaIdx === -1 ? "" : fileData.slice("data:".length, commaIdx); | ||
| const payload = commaIdx === -1 ? "" : fileData.slice(commaIdx + 1); | ||
| const isBase64 = header.toLowerCase().endsWith(";base64"); | ||
| try { | ||
| text = isBase64 ? decodeBase64Utf8(payload) : decodeURIComponent(payload); | ||
| } catch { | ||
| text = ""; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
kemuru marked this conversation as resolved.
|
||
| } else { | ||
| text = fileData; | ||
| } | ||
|
|
||
| return ( | ||
| <div | ||
| id="md-renderer" | ||
| className="text-klerosUIComponentsPrimaryText [&_code]:text-klerosUIComponentsSecondaryText p-4 [&_a]:text-base" | ||
| > | ||
| <ReactMarkdown>{text}</ReactMarkdown> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| MarkdownDocRenderer.fileTypes = ["md", "text/plain"]; | ||
| MarkdownDocRenderer.weight = 1; | ||
|
|
||
| export default MarkdownDocRenderer; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.