Skip to content

Remove highlight and suggetedUrl, use display.html #76

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 2 commits into from
May 4, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat[frontend]: unify decrypt and display page
  • Loading branch information
SharzyL committed May 4, 2025
commit e7c7f8800061eed63a51246583070eeb41379831
66 changes: 41 additions & 25 deletions frontend/components/CodeEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// based on vanilla https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code/
// inspired by https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code/

import React, { useEffect, useRef, useState } from "react"

import "../styles/highlight-theme-light.css"
import { tst } from "../utils/overrides.js"
import { escapeHtml } from "../../worker/common.js"
import { usePrism } from "../utils/HighlightLoader.js"
import { autoCompleteOverrides, inputOverrides, selectOverrides, tst } from "../utils/overrides.js"
import { useHLJS, highlightHTML } from "../utils/HighlightLoader.js"
import { Autocomplete, AutocompleteItem, Input, Select, SelectItem } from "@heroui/react"

import "../styles/highlight-theme-light.css"
Expand Down Expand Up @@ -79,13 +78,15 @@ export function CodeEditor({
className,
...rest
}: CodeInputProps) {
const refHighlighting = useRef<HTMLPreElement | null>(null)
const refHighlighting = useRef<HTMLDivElement | null>(null)
const refTextarea = useRef<HTMLTextAreaElement | null>(null)

const [heightPx, setHeightPx] = useState<number>(0)
const hljs = usePrism()
const hljs = useHLJS()
const [tabSetting, setTabSettings] = useState<TabSetting>({ char: "space", width: 2 })

const lineCount = (content?.match(/\n/g)?.length || 0) + 1

function syncScroll() {
refHighlighting.current!.scrollLeft = refTextarea.current!.scrollLeft
refHighlighting.current!.scrollTop = refTextarea.current!.scrollTop
Expand Down Expand Up @@ -131,21 +132,22 @@ export function CodeEditor({
}
}, [])

function highlightedHTML() {
if (hljs && lang && hljs.listLanguages().includes(lang) && lang !== "plaintext") {
const highlighted = hljs.highlight(handleNewLines(content), { language: lang })
return highlighted.value
} else {
return escapeHtml(content)
}
}
const lineNumOffset = `${Math.floor(Math.log10(lineCount)) + 2}em`

return (
<div className={className} {...rest}>
<div className={"mb-2 gap-2 flex flex-row" + " "}>
<Input type={"text"} label={"File name"} size={"sm"} value={filename || ""} onValueChange={setFilename} />
<Input
classNames={inputOverrides}
type={"text"}
label={"File name"}
size={"sm"}
value={filename || ""}
onValueChange={setFilename}
/>
<Autocomplete
className={"max-w-[10em]"}
classNames={autoCompleteOverrides}
label={"Language"}
size={"sm"}
defaultItems={hljs ? hljs.listLanguages().map((lang) => ({ key: lang })) : []}
Expand All @@ -160,7 +162,8 @@ export function CodeEditor({
<Select
size={"sm"}
label={"Indent With"}
className={"max-w-[10em]"}
className={"max-w-[10em] text-foreground"}
classNames={selectOverrides}
selectedKeys={[formatTabSetting(tabSetting, false)]}
onSelectionChange={(s) => {
setTabSettings(parseTabSetting(s.currentKey as string)!)
Expand All @@ -171,19 +174,32 @@ export function CodeEditor({
))}
</Select>
</div>
<div className={`w-full bg-default-100 ${tst} rounded-xl p-2`}>
<div className={`w-full bg-default-100 ${tst} rounded-xl p-2 relative`}>
<div
className={"relative w-full"}
className={`relative w-full`}
style={{ tabSize: tabSetting.char === "tab" ? tabSetting.width : undefined }}
>
<pre
className={"w-full font-mono overflow-auto text-foreground top-0 left-0 absolute"}
ref={refHighlighting}
dangerouslySetInnerHTML={{ __html: highlightedHTML() }}
style={{ height: `${heightPx}px` }}
></pre>
<div className={"w-full font-mono overflow-auto top-0 left-0 absolute"} ref={refHighlighting}>
<pre
className={`text-foreground ${tst}`}
style={{ paddingLeft: lineNumOffset, height: `${heightPx}px` }}
dangerouslySetInnerHTML={{ __html: highlightHTML(hljs, lang, handleNewLines(content)) }}
></pre>
<span
className={
"line-number-rows font-mono absolute pointer-events-none text-default-500 top-0 left-1 " +
`border-solid border-default-300 border-r-1 ${tst}`
}
>
{Array.from({ length: lineCount }, (_, idx) => {
return <span key={idx} />
})}
</span>
</div>
<textarea
className={`w-full font-mono min-h-[20em] text-[transparent] placeholder-default-400 ${tst} caret-foreground bg-transparent outline-none relative`}
className={`w-full font-mono min-h-[20em] text-[transparent] placeholder-default-400
caret-foreground bg-transparent outline-none relative`}
style={{ paddingLeft: lineNumOffset }}
ref={refTextarea}
readOnly={disabled}
placeholder={placeholder}
Expand Down
11 changes: 11 additions & 0 deletions frontend/components/DarkModeToggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ export function useDarkModeSelection(): [
}, [])

const isDark = modeSelection === undefined || modeSelection === "system" ? isSystemDark : modeSelection === "dark"

useEffect(() => {
if (isDark) {
document.body.classList.remove("light")
document.body.classList.add("dark")
} else {
document.body.classList.remove("dark")
document.body.classList.add("light")
}
}, [isDark])

return [isDark, modeSelection, setModeSelection]
}

Expand Down
36 changes: 19 additions & 17 deletions frontend/components/UploadedPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ interface UploadedPanelProps extends CardProps {
encryptionKey?: string
}

const makeDecryptionUrl = (url: string, key: string) => {
const makeDecryptionUrl = (url: string, key?: string) => {
const urlParsed = new URL(url)
urlParsed.pathname = "/d" + urlParsed.pathname
return urlParsed.toString() + "#" + key
if (key) {
return urlParsed.toString() + "#" + key
} else {
return urlParsed.toString()
}
}

export function UploadedPanel({
Expand Down Expand Up @@ -50,23 +54,21 @@ export function UploadedPanel({
) : (
pasteResponse && (
<>
{encryptionKey && (
<Input
{...inputProps}
label={"Decryption URL"}
color={"success"}
value={makeDecryptionUrl(pasteResponse.url, encryptionKey)}
endContent={
<CopyWidget
className={copyWidgetClassNames}
getCopyContent={() => makeDecryptionUrl(pasteResponse.url, encryptionKey)}
/>
}
/>
)}
<Input
{...inputProps}
label={"Paste URL"}
label={"Display URL"}
color={encryptionKey ? "success" : "default"}
value={makeDecryptionUrl(pasteResponse.url, encryptionKey)}
endContent={
<CopyWidget
className={copyWidgetClassNames}
getCopyContent={() => makeDecryptionUrl(pasteResponse.url, encryptionKey)}
/>
}
/>
<Input
{...inputProps}
label={"Raw URL"}
value={pasteResponse.url}
endContent={<CopyWidget className={copyWidgetClassNames} getCopyContent={() => pasteResponse.url} />}
/>
Expand Down
2 changes: 2 additions & 0 deletions frontend/hero-theme.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { heroui } from "@heroui/react"

export default heroui({
defaultTheme: "light",
themes: {
light: {},
dark: {
colors: {
background: "#111111",
Expand Down
116 changes: 70 additions & 46 deletions frontend/pages/DecryptPaste.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useState } from "react"
import React, { useEffect, useState } from "react"

import { Button, CircularProgress, Link, Tooltip } from "@heroui/react"
import binaryExtensions from "binary-extensions"
Expand All @@ -14,6 +14,9 @@ import { formatSize } from "../utils/utils.js"
import { tst } from "../utils/overrides.js"

import "../style.css"
import "../styles/highlight-theme-light.css"
import "../styles/highlight-theme-dark.css"
import { highlightHTML, useHLJS } from "../utils/HighlightLoader.js"

function isBinaryPath(path: string) {
return binaryExtensions.includes(path.replace(/.*\./, ""))
Expand All @@ -22,31 +25,30 @@ function isBinaryPath(path: string) {
export function DecryptPaste() {
const [pasteFile, setPasteFile] = useState<File | undefined>(undefined)
const [pasteContentBuffer, setPasteContentBuffer] = useState<ArrayBuffer | undefined>(undefined)
const [pasteLang, setPasteLang] = useState<string | undefined>(undefined)

const [isFileBinary, setFileBinary] = useState(false)
const [isDecrypted, setDecrypted] = useState(false)
const [forceShowBinary, setForceShowBinary] = useState(false)
const showFileContent = pasteFile !== undefined && (!isFileBinary || forceShowBinary)

const [isLoading, setIsLoading] = useState<boolean>(false)

const { ErrorModal, showModal, handleFailedResp } = useErrorModal()
const [isDark, modeSelection, setModeSelection] = useDarkModeSelection()
const [_, modeSelection, setModeSelection] = useDarkModeSelection()
const hljs = useHLJS()

const pasteStringContent = useMemo<string | undefined>(() => {
return pasteContentBuffer && new TextDecoder().decode(pasteContentBuffer)
}, [pasteContentBuffer])
const pasteStringContent = pasteContentBuffer && new TextDecoder().decode(pasteContentBuffer)

const pasteLineCount = (pasteStringContent?.match(/\n/g)?.length || 0) + 1

// uncomment the following lines for testing
// const url = new URL("http://localhost:8787/d/dHYQ.jpg.txt#uqeULsBTb2I3iC7rD6AaYh4oJ5lMjJA2nYR+H0U8bEA=")
// const url = new URL("http://localhost:8787/GQbf")
const url = location

const { name, ext, filename } = parsePath(url.pathname)
const keyString = url.hash.slice(1)

useEffect(() => {
if (keyString.length === 0) {
showModal("Error", "No encryption key is given. You should append the key after a “#” character in the URL")
}
const pasteUrl = `${API_URL}/${name}`

const fetchPaste = async () => {
Expand All @@ -59,42 +61,54 @@ export function DecryptPaste() {
}

const scheme: EncryptionScheme | null = resp.headers.get("X-PB-Encryption-Scheme") as EncryptionScheme | null
if (scheme === null) {
showModal("Error", "No encryption scheme is given by the server")
return
}
let key: CryptoKey | undefined
try {
key = await decodeKey(scheme, keyString)
} catch {
showModal("Error", `Failed to parse “${keyString}” as ${scheme} key`)
return
}
if (key === undefined) {
showModal("Error", `Failed to parse “${keyString}” as ${scheme} key`)
return
let filenameFromDisp = resp.headers.has("Content-Disposition")
? parseFilenameFromContentDisposition(resp.headers.get("Content-Disposition")!) || undefined
: undefined
if (filenameFromDisp && scheme !== null) {
filenameFromDisp = filenameFromDisp.replace(/.encrypted$/, "")
}

const decrypted = await decrypt(scheme, key, await resp.bytes())
if (decrypted === null) {
showModal("Error", "Failed to decrypt content")
} else {
const filenameFromDispTrimmed = resp.headers.has("Content-Disposition")
? parseFilenameFromContentDisposition(resp.headers.get("Content-Disposition")!)?.replace(
/.encrypted$/g,
"",
) || undefined
: undefined
const lang = resp.headers.get("X-PB-Highlight-Language")

const inferredFilename = filename || (ext && name + ext) || filenameFromDisp
const respBytes = await resp.bytes()
const isBinary = lang === null && inferredFilename !== undefined && isBinaryPath(inferredFilename)
setPasteLang(lang || undefined)
setFileBinary(isBinary)

// TODO: highlight with lang
const lang = resp.headers.get("X-PB-Highlight-Language")
if (scheme === null) {
setPasteFile(new File([respBytes], inferredFilename || name))
setPasteContentBuffer(respBytes)
} else {
const keyString = url.hash.slice(1)
if (keyString.length === 0) {
showModal("Error", "No encryption key is given. You should append the key after a “#” character in the URL")
}
let key: CryptoKey | undefined
try {
key = await decodeKey(scheme, keyString)
} catch {
showModal("Error", `Failed to parse “${keyString}” as ${scheme} key`)
return
}
if (key === undefined) {
showModal("Error", `Failed to parse “${keyString}” as ${scheme} key`)
return
}

const decrypted = await decrypt(scheme, key, respBytes)
if (decrypted === null) {
showModal("Error", "Failed to decrypt content")
return
}

const inferredFilename = filename || (ext && name + ext) || filenameFromDispTrimmed
setPasteFile(new File([decrypted], inferredFilename || name))
setPasteContentBuffer(decrypted)
setPasteLang(lang || undefined)

const isBinary = lang === null && inferredFilename !== undefined && isBinaryPath(inferredFilename)
setFileBinary(isBinary)
setDecrypted(true)
}
} finally {
setIsLoading(false)
Expand All @@ -108,7 +122,7 @@ export function DecryptPaste() {

const fileIndicator = pasteFile && (
<div className="text-foreground-600 mb-2 text-small">
{`${pasteFile?.name} (${formatSize(pasteFile.size)})`}
{`${pasteFile?.name} (${formatSize(pasteFile.size)})` + (pasteLang ? ` (${pasteLang})` : "")}
{forceShowBinary && (
<button className="ml-2 text-primary-500" onClick={() => setForceShowBinary(false)}>
(Click to hide)
Expand All @@ -132,10 +146,7 @@ export function DecryptPaste() {
const buttonClasses = `rounded-full bg-background hover:bg-default-100 ${tst}`
return (
<main
className={
`flex flex-col items-center min-h-screen transition-transform-background bg-background ${tst} text-foreground w-full p-2` +
(isDark ? " dark" : " light")
}
className={`flex flex-col items-center min-h-screen transition-transform-background bg-background ${tst} text-foreground w-full p-2`}
>
<div className="w-full max-w-[64rem]">
<div className="flex flex-row my-4 items-center justify-between">
Expand All @@ -148,7 +159,7 @@ export function DecryptPaste() {
</Link>
<span className="mx-2">{" / "}</span>
<code>{name}</code>
<span className="ml-1">{isLoading ? " (Loading…)" : pasteFile ? " (Decrypted)" : ""}</span>
<span className="ml-1">{isLoading ? " (Loading…)" : isDecrypted ? " (Decrypted)" : ""}</span>
</h1>
{showFileContent && (
<Tooltip content={`Copy to clipboard`}>
Expand All @@ -167,7 +178,7 @@ export function DecryptPaste() {
<DarkModeToggle modeSelection={modeSelection} setModeSelection={setModeSelection} />
</div>
<div className="my-4">
<div className={`min-h-[30rem] w-full bg-secondary-50 rounded-lg p-3 relative ${tst}`}>
<div className={`min-h-[30rem] w-full bg-default-50 rounded-lg p-3 relative ${tst}`}>
{isLoading ? (
<CircularProgress className="absolute top-[50%] left-[50%] translate-[-50%]" />
) : (
Expand All @@ -176,8 +187,21 @@ export function DecryptPaste() {
{showFileContent ? (
<>
{fileIndicator}
<div className="font-mono whitespace-pre-wrap" role="article">
{pasteStringContent!}
<div className="font-mono whitespace-pre-wrap relative" role="article">
<pre
style={{ paddingLeft: `${Math.floor(Math.log10(pasteLineCount)) + 2}em` }}
dangerouslySetInnerHTML={{ __html: highlightHTML(hljs, pasteLang, pasteStringContent!) }}
/>
<span
className={
"line-number-rows absolute pointer-events-none text-default-500 top-0 left-0 " +
"border-solid border-default-300 border-r-1"
}
>
{Array.from({ length: pasteLineCount }, (_, idx) => {
return <span key={idx} />
})}
</span>
</div>
</>
) : (
Expand Down
Loading