Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
feat(code-block): minimal electric blue syntax highlighting for cards and expanded preview
Deepender25d3af9bbddfcd
diff --git a/electron/main/ipc.ts b/electron/main/ipc.tsindex 93ac646..f657110 100644--- a/electron/main/ipc.ts+++ b/electron/main/ipc.ts@@ -696,6 +696,9 @@ export function registerIpc(): void {if (patch.hotZoneWidth !== undefined) {setHotZoneWidth(patch.hotZoneWidth)}+ if (patch.incognito !== undefined) {+ getWatcher().setPaused(patch.incognito)+ }if (patch.stickPosition !== undefined || patch.stickDisplayId !== undefined || patch.verticalOffset !== undefined || patch.horizontalOffset !== undefined) {repositionWindow()if (patch.stickPosition !== undefined || patch.stickDisplayId !== undefined) {diff --git a/package-lock.json b/package-lock.jsonindex 5a91fb0..ac0ecef 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,17 +1,18 @@{"name": "edge-drop",- "version": "0.3.1",+ "version": "0.3.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "edge-drop",- "version": "0.3.1",+ "version": "0.3.2","license": "Apache-2.0","dependencies": {"@resvg/resvg-js": "^2.6.2","electron-updater": "^6.8.9","koffi": "^3.1.2",+ "prism-react-renderer": "^2.4.1","react": "^18.2.0","zustand": "^4.5.2"},@@ -2889,6 +2890,12 @@"undici-types": "~6.21.0"}},+ "node_modules/@types/prismjs": {+ "version": "1.26.6",+ "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.6.tgz",+ "integrity": "sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==",+ "license": "MIT"+ },"node_modules/@types/prop-types": {"version": "15.7.15","resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",@@ -3749,6 +3756,15 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/color-convert": {"version": "2.0.1","resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",@@ -6362,6 +6378,19 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/prism-react-renderer": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/prism-react-renderer/-/prism-react-renderer-2.4.1.tgz",+ "integrity": "sha512-ey8Ls/+Di31eqzUxC46h8MksNuGx/n0AAC8uKpwFau4RPDYLuE3EXTp8N8G2vX2N7UC/+IXeNUnlWBGGcAG+Ig==",+ "license": "MIT",+ "dependencies": {+ "@types/prismjs": "^1.26.0",+ "clsx": "^2.0.0"+ },+ "peerDependencies": {+ "react": ">=16.0.0"+ }+ },"node_modules/proc-log": {"version": "6.1.0","resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz",diff --git a/package.json b/package.jsonindex e5fcf5c..ced9b09 100644--- a/package.json+++ b/package.json@@ -46,6 +46,7 @@"!**/node_modules/@radix-ui/**","!**/node_modules/svg-path-bbox/**","!**/node_modules/react-dom/**",+ "!**/node_modules/prism-react-renderer/**","!**/node_modules/koffi/doc/**"],"extraResources": [@@ -127,6 +128,7 @@"framer-motion": "^11.0.24","gsap": "^3.15.0","lucide-react": "^1.26.0",+ "prism-react-renderer": "^2.4.1","react-dom": "^18.2.0","svg-path-bbox": "^2.1.0","typescript": "^5.4.3",@@ -140,4 +142,4 @@"react": "^18.2.0","zustand": "^4.5.2"}-}\ No newline at end of file+}diff --git a/src/components/ClipboardItem.tsx b/src/components/ClipboardItem.tsxindex 1164ca3..fe06644 100644--- a/src/components/ClipboardItem.tsx+++ b/src/components/ClipboardItem.tsx@@ -25,8 +25,10 @@ import { itemRenderKey } from '../lib/itemSignature'import { basename, formatBytes, previewText, relativeTime, formatImageDisplayName } from '../lib/format'import { getFileKind } from '../lib/fileType'import { playButtonClickSound, playToggleSound, playDeleteSound, playCardExpandSound } from '../lib/soundEffects'-import { CopyIcon, FileKindIcon, FileStackPhoto, PinIcon, PinFillIcon, TrashIcon, MinusIcon, ChevronUpIcon, ChevronLeftIcon, ExpandIcon, ContractIcon, ExternalLinkIcon, ImageIcon } from './icons'+import { CopyIcon, FileKindIcon, FileStackPhoto, PinIcon, PinFillIcon, TrashIcon, MinusIcon, ChevronUpIcon, ChevronLeftIcon, ExpandIcon, ContractIcon, ExternalLinkIcon } from './icons'import { LinkPreviewCard } from './LinkPreviewCard'+import { CodeBlock } from './CodeBlock'+import { detectCode } from '../lib/codeDetect'import '../styles/item.css'import { tryPaste } from '../lib/tryPaste'import { parseColor } from '../lib/colorUtils'@@ -84,13 +86,13 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {const isSingleImage = item.data.kind === 'image' || (item.data.kind === 'files' &&item.data.paths.length === 1 &&- !item.data.entries?.[0]?.isDirectory &&- (item.data.entries?.[0]?.isImage || getFileKind(item.data.paths[0]).kind === 'image')+ !(item.data as any).entries?.[0]?.isDirectory &&+ ((item.data as any).entries?.[0]?.isImage || getFileKind(item.data.paths[0]).kind === 'image'))const isImageStack = item.data.kind === 'image-collection' || (item.data.kind === 'files' &&item.data.paths.length > 1 &&- item.data.paths.every((p, i) => !item.data.entries?.[i]?.isDirectory && (item.data.entries?.[i]?.isImage || getFileKind(p).kind === 'image'))+ item.data.paths.every((p, i) => !(item.data as any).entries?.[i]?.isDirectory && ((item.data as any).entries?.[i]?.isImage || getFileKind(p).kind === 'image')))const isImageFolderCard = isSingleImage || isImageStack@@ -1155,7 +1157,7 @@ function getImageEntries(item: ClipboardItemDto): ImageCardEntry[] {}if (item.data.kind === 'files') {return item.data.paths.map((filePath, i) => {- const entry = item.data.entries?.[i]+ const entry = (item.data as any).entries?.[i]const fallback = fileStreamUrl(filePath)return {id: `${item.id}-${filePath}-${i}`,@@ -1178,12 +1180,11 @@ function getImageEntries(item: ClipboardItemDto): ImageCardEntry[] {function MiniImageFolderCard({item,img,- isHorizontal,onDragStart}: {item: ClipboardItemDtoimg: ImageCardEntry- isHorizontal: boolean+ isHorizontal?: booleanonDragStart?: (e: React.DragEvent, req: DragRequest) => void}) {const { t } = useTranslation()@@ -1194,7 +1195,7 @@ function MiniImageFolderCard({const size = img.bytes ? formatBytes(img.bytes) : ''const displayName = img.name && img.name !== 'clipboard' && !img.name.startsWith('image-') ? img.name : dims || 'image'- const handleCopy = (e: React.MouseEvent) => {+ const handleCopy = (e: React.MouseEvent<HTMLButtonElement>) => {e.stopPropagation()e.currentTarget.blur()playButtonClickSound()@@ -1207,7 +1208,7 @@ function MiniImageFolderCard({setTimeout(() => setCopied(false), 900)}- const handleUngroup = (e: React.MouseEvent) => {+ const handleUngroup = (e: React.MouseEvent<HTMLButtonElement>) => {e.stopPropagation()e.currentTarget.blur()playDeleteSound()@@ -1584,6 +1585,23 @@ function Preview({ item }: { item: ClipboardItemDto }) {</div>)}+ const codeInfo = detectCode(item.data.text)+ if (codeInfo.isCode) {+ return (+ <div className="code-card-preview">+ <CodeBlock+ code={item.data.text}+ language={codeInfo.language}+ showFrame={false}+ showHeader={false}+ showLineNumbers={true}+ showCopyButton={false}+ compact={true}+ maxLines={5}+ />+ </div>+ )+ }return <div className="preview">{previewText(item.data.text)}</div>}@@ -1727,11 +1745,6 @@ function ItemDetails({ item }: { item: ClipboardItemDto }) {return null}- const colorInfo = parseColor(item.data.text)- if (item.data.isColor || colorInfo) {- return null- }-return null}diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsxnew file mode 100644index 0000000..3d86859--- /dev/null+++ b/src/components/CodeBlock.tsx@@ -0,0 +1,510 @@+import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'+import { Highlight, type PrismTheme } from 'prism-react-renderer'+import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'+import { CopyIcon, CheckIcon } from './icons'++const TAP_SPRING = { type: 'spring', stiffness: 500, damping: 30 } as const+const SWAP_SPRING = { type: 'spring', duration: 0.3, bounce: 0 } as const+const CHECK_SPRING = { type: 'spring', duration: 0.4, bounce: 0.35 } as const+const COPY_RESET_MS = 1800+const DEFAULT_ACCENT = '#0A84FF' // Signature electric blue accent++export type CodeBlockProps = Omit<React.ComponentProps<'div'>, 'children'> & {+ /** The source code to render. */+ code: string+ /** Prism language id, e.g. "tsx", "css", "json", "bash". */+ language?: string+ /** Any hex color. The whole theme is built from shades of it. */+ accent?: string+ /** "auto" follows the page theme; pass "dark" or "light" to pin it. */+ mode?: 'auto' | 'dark' | 'light'+ /** Filename or path shown in the header. Falls back to the language id when omitted. */+ filename?: string+ /** Show the outer frame — background, border, rounded corners, and header. */+ showFrame?: boolean+ /** Show the header bar. Ignored when the frame is off. */+ showHeader?: boolean+ /** Show the line-number gutter. */+ showLineNumbers?: boolean+ /** Show the copy-to-clipboard button. */+ showCopyButton?: boolean+ /** Optional 1-based line numbers to highlight with an accent wash. */+ highlightLines?: number[]+ /** Maximum lines to show (e.g. for card thumbnail previews). */+ maxLines?: number+ /** Compact styling for inside the card preview. */+ compact?: boolean+}++function resolvePageMode(): 'dark' | 'light' {+ if (typeof document === 'undefined') return 'dark'+ const root = document.documentElement+ if (root.classList.contains('dark')) return 'dark'+ if (root.classList.contains('light')) return 'light'+ const attr = root.getAttribute('data-theme')+ if (attr === 'dark') return 'dark'+ if (attr === 'light') return 'light'+ if (typeof window.matchMedia !== 'function') return 'dark'+ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'+}++function subscribeToPageMode(onChange: () => void) {+ if (typeof document === 'undefined') return () => {}+ const observer = new MutationObserver(onChange)+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class', 'data-theme'],+ })+ const media = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-color-scheme: dark)') : null+ media?.addEventListener?.('change', onChange)+ return () => {+ observer.disconnect()+ media?.removeEventListener?.('change', onChange)+ }+}++const serverMode = () => 'dark' as const++const FALLBACK_HSL: [number, number, number] = [211, 100, 52]++function hexToHsl(hex: string): [number, number, number] {+ if (typeof hex !== 'string') return FALLBACK_HSL+ let value = hex.replace('#', '')+ if (value.length === 4 || value.length === 8) {+ value = value.slice(0, value.length === 4 ? 3 : 6)+ }+ if (value.length === 3) {+ value = value.split('').map((c) => c + c).join('')+ }+ const r = parseInt(value.slice(0, 2), 16) / 255+ const g = parseInt(value.slice(2, 4), 16) / 255+ const b = parseInt(value.slice(4, 6), 16) / 255+ if (value.length !== 6 || [r, g, b].some(Number.isNaN)) return FALLBACK_HSL++ const max = Math.max(r, g, b)+ const min = Math.min(r, g, b)+ const l = (max + min) / 2+ if (max === min) return [0, 0, l * 100]++ const d = max - min+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)+ let h: number+ switch (max) {+ case r:+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6+ break+ case g:+ h = ((b - r) / d + 2) / 6+ break+ default:+ h = ((r - g) / d + 4) / 6+ }+ return [h * 360, s * 100, l * 100]+}++const hsl = (h: number, s: number, l: number, a = 1) => {+ const hue = ((h % 360) + 360) % 360+ return a === 1+ ? `hsl(${hue.toFixed(1)} ${s.toFixed(1)}% ${l.toFixed(1)}%)`+ : `hsl(${hue.toFixed(1)} ${s.toFixed(1)}% ${l.toFixed(1)}% / ${a})`+}++export function buildTheme(accent: string = DEFAULT_ACCENT, mode: 'dark' | 'light' = 'dark') {+ const [h, s, l] = hexToHsl(accent)+ const tint = (lightness: number, sat = s) => hsl(h, sat, lightness)+ const dark = mode !== 'light'+ const accentTone = dark+ ? tint(Math.min(Math.max(l, 56), 72))+ : tint(Math.min(Math.max(l, 38), 50))+ const colors = dark+ ? {+ accent: accentTone,+ bg: '#0e0e12',+ border: 'rgba(255, 255, 255, 0.08)',+ headerBg: 'rgba(255, 255, 255, 0.03)',+ plain: '#ffffff',+ muted: 'rgba(255, 255, 255, 0.6)',+ gutter: 'rgba(255, 255, 255, 0.28)',+ hoverWash: 'rgba(255, 255, 255, 0.08)',+ floatBg: 'rgba(20, 20, 26, 0.75)',+ selection: hsl(h, s, 58, 0.3),+ lineWash: hsl(h, s, 58, 0.12),+ }+ : {+ accent: accentTone,+ bg: '#f8fafc',+ border: 'rgba(0, 0, 0, 0.08)',+ headerBg: 'rgba(0, 0, 0, 0.03)',+ plain: '#171717',+ muted: 'rgba(0, 0, 0, 0.6)',+ gutter: 'rgba(0, 0, 0, 0.32)',+ hoverWash: 'rgba(0, 0, 0, 0.06)',+ floatBg: 'rgba(0, 0, 0, 0.04)',+ selection: hsl(h, s, 45, 0.25),+ lineWash: hsl(h, s, 45, 0.08),+ }++ const theme: PrismTheme = {+ plain: { color: colors.plain, backgroundColor: 'transparent' },+ styles: [+ { types: ['comment', 'prolog', 'doctype', 'cdata'], style: { color: 'rgba(255, 255, 255, 0.35)', fontStyle: 'italic' } },+ { types: ['punctuation'], style: { color: 'rgba(255, 255, 255, 0.55)' } },+ { types: ['operator', 'combinator'], style: { color: '#38bdf8' } },+ { types: ['keyword', 'selector', 'atrule', 'important'], style: { color: '#0A84FF', fontWeight: '500' } },+ { types: ['tag'], style: { color: '#0A84FF' } },+ { types: ['string', 'char', 'inserted', 'url'], style: { color: '#38bdf8' } },+ { types: ['function'], style: { color: '#ffffff' } },+ { types: ['attr-name'], style: { color: '#93c5fd', fontStyle: 'italic' } },+ { types: ['number', 'boolean', 'constant', 'symbol', 'deleted'], style: { color: '#60a5fa' } },+ { types: ['class-name', 'maybe-class-name', 'builtin'], style: { color: '#ffffff' } },+ { types: ['property', 'variable', 'parameter'], style: { color: '#ffffff' } },+ { types: ['regex'], style: { color: '#60a5fa' } },+ ],+ }++ return { colors, theme }+}++/* ------------------------------- copy button ------------------------------- */++function CopyButton({ code, floating }: { code: string; floating?: boolean }) {+ const [copied, setCopied] = useState(false)+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)++ useEffect(() => () => {+ if (timer.current) clearTimeout(timer.current)+ }, [])++ const copy = useCallback(async (e: React.MouseEvent) => {+ e.stopPropagation()+ e.preventDefault()+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(code)+ } else {+ const area = document.createElement('textarea')+ area.value = code+ area.style.position = 'fixed'+ area.style.opacity = '0'+ document.body.appendChild(area)+ area.select()+ document.execCommand('copy')+ area.remove()+ }+ } catch {+ return+ }+ setCopied(true)+ if (timer.current) clearTimeout(timer.current)+ timer.current = setTimeout(() => setCopied(false), COPY_RESET_MS)+ }, [code])++ const reduceMotion = useReducedMotion()+ const swap = reduceMotion+ ? {+ initial: { opacity: 0 },+ animate: { opacity: 1 },+ exit: { opacity: 0 },+ }+ : {+ initial: { opacity: 0, scale: 0.5, filter: 'blur(4px)' },+ animate: { opacity: 1, scale: 1, filter: 'blur(0px)' },+ exit: { opacity: 0, scale: 0.5, filter: 'blur(4px)' },+ }++ return (+ <motion.button+ type="button"+ aria-label={copied ? 'Copied' : 'Copy code'}+ onClick={copy}+ whileTap={reduceMotion ? undefined : { scale: 0.9 }}+ transition={TAP_SPRING}+ style={{+ position: floating ? 'absolute' : 'relative',+ top: floating ? 8 : undefined,+ right: floating ? 8 : undefined,+ zIndex: floating ? 10 : undefined,+ width: 26,+ height: 26,+ borderRadius: 7,+ display: 'grid',+ placeItems: 'center',+ background: copied ? 'rgba(10, 132, 255, 0.18)' : floating ? 'var(--cb-float-bg)' : 'transparent',+ border: floating ? '1px solid var(--cb-border)' : 'none',+ color: copied ? 'var(--cb-accent)' : 'var(--cb-muted)',+ cursor: 'pointer',+ padding: 0,+ outline: 'none',+ transition: 'all 0.15s ease',+ }}+ onMouseEnter={(e) => {+ if (!copied) {+ e.currentTarget.style.background = 'var(--cb-hover-wash)'+ e.currentTarget.style.color = 'var(--cb-plain)'+ }+ }}+ onMouseLeave={(e) => {+ if (!copied) {+ e.currentTarget.style.background = floating ? 'var(--cb-float-bg)' : 'transparent'+ e.currentTarget.style.color = 'var(--cb-muted)'+ }+ }}+ >+ <AnimatePresence initial={false} mode="wait">+ {copied ? (+ <motion.span+ key="check"+ style={{ gridColumn: 1, gridRow: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}+ {...swap}+ transition={reduceMotion ? { duration: 0.15 } : CHECK_SPRING}+ >+ <CheckIcon width={13} height={13} style={{ color: 'var(--cb-accent)', strokeWidth: 2.5 }} />+ </motion.span>+ ) : (+ <motion.span+ key="copy"+ style={{ gridColumn: 1, gridRow: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}+ {...swap}+ transition={reduceMotion ? { duration: 0.15 } : SWAP_SPRING}+ >+ <CopyIcon width={12} height={12} />+ </motion.span>+ )}+ </AnimatePresence>+ </motion.button>+ )+}++export function CodeBlock({+ code,+ language = 'tsx',+ accent = DEFAULT_ACCENT,+ mode = 'auto',+ filename,+ showFrame = true,+ showHeader = true,+ showLineNumbers = true,+ showCopyButton = true,+ highlightLines,+ maxLines,+ compact = false,+ className = '',+ style,+ ...props+}: CodeBlockProps) {+ const safeLanguage = typeof language === 'string' && language.trim() ? language.trim().toLowerCase() : 'tsx'+ const pageMode = useSyncExternalStore(subscribeToPageMode, resolvePageMode, serverMode)+ const safeMode = mode === 'light' || mode === 'dark' ? mode : pageMode+ const { colors, theme } = useMemo(() => buildTheme(accent, safeMode), [accent, safeMode])++ const { trimmed, lineMap } = useMemo(() => {+ const source = typeof code === 'string' ? code : String(code ?? '')+ const rawLines = source.split('\n')++ if (compact) {+ // In compact thumbnail mode, collapse/skip empty lines so meaningful code fills the card+ const denseLines: { line: string; originalIndex: number }[] = []+ for (let i = 0; i < rawLines.length; i++) {+ const line = rawLines[i]+ if (line.trim().length > 0) {+ denseLines.push({ line, originalIndex: i + 1 })+ if (maxLines && denseLines.length >= maxLines) break+ }+ }+ return {+ trimmed: denseLines.map((d) => d.line).join('\n'),+ lineMap: denseLines.map((d) => d.originalIndex),+ }+ }++ const cleaned = source.replace(/^\n+/, '').trimEnd()+ if (maxLines && maxLines > 0) {+ const lines = cleaned.split('\n')+ if (lines.length > maxLines) {+ return {+ trimmed: lines.slice(0, maxLines).join('\n'),+ lineMap: null,+ }+ }+ }+ return { trimmed: cleaned, lineMap: null }+ }, [code, maxLines, compact])++ const highlighted = useMemo(+ () => new Set(Array.isArray(highlightLines) ? highlightLines : []),+ [highlightLines]+ )++ const cssVars = {+ '--cb-accent': colors.accent,+ '--cb-bg': colors.bg,+ '--cb-border': colors.border,+ '--cb-header-bg': colors.headerBg,+ '--cb-plain': colors.plain,+ '--cb-muted': colors.muted,+ '--cb-gutter': colors.gutter,+ '--cb-hover-wash': colors.hoverWash,+ '--cb-float-bg': colors.floatBg,+ '--cb-selection': colors.selection,+ '--cb-line-wash': colors.lineWash,+ } as React.CSSProperties++ const fontSize = compact ? '11.5px' : '13px'+ const lineHeight = compact ? '1.4' : '1.7'+ const paddingX = showFrame ? (compact ? '8px' : '14px') : '0px'+ const paddingY = showFrame ? (compact ? '6px' : '12px') : '0px'++ return (+ <div+ className={`code-block-container ${compact ? 'is-compact' : ''} ${className}`.trim()}+ style={{+ ...cssVars,+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ textAlign: 'left',+ borderRadius: showFrame ? (compact ? 10 : 16) : 0,+ border: showFrame ? '1px solid var(--cb-border)' : 'none',+ background: showFrame ? 'var(--cb-bg)' : 'transparent',+ boxShadow: showFrame && !compact ? '0 8px 24px rgba(0, 0, 0, 0.45)' : 'none',+ fontFamily: 'var(--font-mono)',+ ...style,+ }}+ {...props}+ >+ {showFrame && showHeader && (+ <div+ style={{+ display: 'flex',+ height: compact ? 26 : 34,+ flexShrink: 0,+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 10,+ borderBottom: '1px solid var(--cb-border)',+ background: 'var(--cb-header-bg)',+ padding: `0 ${paddingX}`,+ boxSizing: 'border-box',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0, flex: 1 }}>+ <span+ style={{+ display: 'inline-block',+ width: 6,+ height: 6,+ borderRadius: 999,+ background: 'var(--cb-accent)',+ boxShadow: '0 0 8px var(--cb-accent)',+ flexShrink: 0,+ }}+ />+ <span+ style={{+ fontFamily: 'var(--font-mono)',+ fontSize: compact ? 10 : 11.5,+ fontWeight: 600,+ color: 'var(--cb-muted)',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ letterSpacing: '0.02em',+ }}+ >+ {filename ?? safeLanguage}+ </span>+ </div>+ {showCopyButton && <CopyButton code={typeof code === 'string' ? code : trimmed} />}+ </div>+ )}++ {!(showFrame && showHeader) && showCopyButton && (+ <CopyButton code={typeof code === 'string' ? code : trimmed} floating />+ )}++ <div+ role="region"+ aria-label={filename ?? `${safeLanguage} code`}+ tabIndex={0}+ style={{+ minHeight: 0,+ flex: 1,+ overflow: compact ? 'hidden' : 'auto',+ outline: 'none',+ padding: `${paddingY} 0`,+ boxSizing: 'border-box',+ scrollbarWidth: 'thin',+ scrollbarColor: 'var(--cb-border) transparent',+ }}+ >+ <Highlight code={trimmed} language={safeLanguage} theme={theme}>+ {({ tokens, getLineProps, getTokenProps }) => {+ const maxLineNum = lineMap && lineMap.length > 0 ? lineMap[lineMap.length - 1] : tokens.length+ const gutterWidth = `${String(maxLineNum).length}ch`+ return (+ <pre+ style={{+ margin: 0,+ padding: 0,+ width: 'max-content',+ minWidth: '100%',+ fontFamily: 'var(--font-mono)',+ fontSize,+ lineHeight,+ tabSize: 2,+ boxSizing: 'border-box',+ }}+ >+ {tokens.map((line, i) => {+ const lineProps = getLineProps({ line })+ const isHighlighted = highlighted.has(i + 1)+ const lineNumber = lineMap ? lineMap[i] : i + 1+ return (+ <div+ key={i}+ {...lineProps}+ style={{+ ...lineProps.style,+ position: 'relative',+ display: 'flex',+ minWidth: '100%',+ padding: `0 ${paddingX}`,+ background: isHighlighted ? 'var(--cb-line-wash)' : undefined,+ boxSizing: 'border-box',+ }}+ >+ {showLineNumbers && (+ <span+ aria-hidden+ style={{+ marginRight: compact ? 10 : 18,+ flexShrink: 0,+ textAlign: 'right',+ color: 'var(--cb-gutter)',+ userSelect: 'none',+ width: gutterWidth,+ fontSize: compact ? '10px' : '12px',+ }}+ >+ {lineNumber}+ </span>+ )}+ <span style={{ paddingRight: showFrame ? paddingX : '8px', whiteSpace: 'pre', wordBreak: 'normal' }}>+ {line.map((token, key) => (+ <span key={key} {...getTokenProps({ token })} />+ ))}+ </span>+ </div>+ )+ })}+ </pre>+ )+ }}+ </Highlight>+ </div>+ </div>+ )+}++export default CodeBlockdiff --git a/src/components/PreviewFlyout.tsx b/src/components/PreviewFlyout.tsxindex 13fe948..7b834dd 100644--- a/src/components/PreviewFlyout.tsx+++ b/src/components/PreviewFlyout.tsx@@ -5,6 +5,9 @@ import { formatBytes, formatImageDisplayName } from '../lib/format'import { getFileKind } from '../lib/fileType'import { FileKindIcon, FolderOpenIcon, CopyIcon, CheckIcon, ExternalLinkIcon, CloseIcon, GlobeIcon } from './icons'import { parseUrlPreview } from '../lib/urlPreview'+import { parseColor } from '../lib/colorUtils'+import { detectCode } from '../lib/codeDetect'+import { CodeBlock } from './CodeBlock'import { createPortal } from 'react-dom'import { useAdaptiveSpring } from '../hooks/useAdaptiveSpring'import { useDragOut } from '../hooks/useDragOut'@@ -527,16 +530,18 @@ function QuickActionButton({title,icon: Icon,onClick,- size = 28+ size = 28,+ solidDark = false}: {title: stringicon: anyonClick: () => anysize?: number+ solidDark?: boolean}) {const [copied, setCopied] = useState(false)- const handleClick = async (e: React.MouseEvent) => {+ const handleClick = async (e: React.MouseEvent<HTMLButtonElement>) => {e.stopPropagation()e.preventDefault()e.currentTarget.blur()@@ -549,7 +554,7 @@ function QuickActionButton({return (<button- className={`act${copied ? ' active' : ''}`}+ className={`act${copied ? ' active' : ''}${solidDark ? ' solid-dark' : ''}`}title={copied ? t('flyout.copied') : title}onClick={handleClick}style={{ width: size, height: size }}@@ -757,6 +762,85 @@ function PreviewContent({)}+ const colorInfo = parseColor(activeText)+ if (colorInfo) {+ return (+ <div+ onClick={(e) => {+ const sel = window.getSelection()?.toString()+ if (sel && sel.trim().length > 0) return+ e.stopPropagation()+ tryPaste(() => useStore.getState().paste(item.id))+ }}+ title={t('flyout.clickToPaste')}+ style={{+ position: 'relative',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: 12,+ padding: '36px 20px',+ borderRadius: 16,+ background: colorInfo.cssColor,+ color: colorInfo.isLight ? '#111827' : '#ffffff',+ cursor: 'pointer',+ boxShadow: '0 8px 24px rgba(0, 0, 0, 0.35)',+ boxSizing: 'border-box',+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'flex-end', width: '100%', position: 'absolute', top: 10, right: 10 }}>+ <QuickActionButton+ title={t('flyout.copyText')}+ icon={CopyIcon}+ onClick={() => useStore.getState().copy(item.id)}+ />+ </div>+ <div style={{+ fontFamily: 'var(--font-mono)',+ fontSize: 24,+ fontWeight: 700,+ letterSpacing: '0.04em',+ textShadow: colorInfo.isLight ? '0 1px 2px rgba(255,255,255,0.5)' : '0 2px 4px rgba(0,0,0,0.6)',+ }}>+ {colorInfo.displayText}+ </div>+ </div>+ )+ }++ const codeInfo = detectCode(activeText)+ if (codeInfo.isCode) {+ return (+ <div+ onClick={(e) => {+ const sel = window.getSelection()?.toString()+ if (sel && sel.trim().length > 0) return+ e.stopPropagation()+ tryPaste(() => useStore.getState().paste(item.id))+ }}+ title={t('flyout.clickToPaste')}+ style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 10, cursor: 'pointer', width: '100%' }}+ >+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 6, position: 'sticky', top: 0, zIndex: 2 }}>+ <QuickActionButton+ title={t('flyout.copyText')}+ icon={CopyIcon}+ onClick={() => useStore.getState().copy(item.id)}+ />+ </div>+ <CodeBlock+ code={text}+ language={codeInfo.language}+ showFrame={false}+ showHeader={false}+ showLineNumbers={true}+ showCopyButton={false}+ />+ </div>+ )+ }+return (<divonClick={(e) => {diff --git a/src/components/SlideCommit.tsx b/src/components/SlideCommit.tsxindex e0799f5..aea0a51 100644--- a/src/components/SlideCommit.tsx+++ b/src/components/SlideCommit.tsx@@ -13,7 +13,7 @@ const SQUASH_MAX = 0.08const SQUASH_DIV = 110const SWELL = 1.03const MIN_PENDING = 300-const EASE_OUT = [0.23, 1, 0.32, 1]+const EASE_OUT = [0.23, 1, 0.32, 1] as constconst SHAKE = [0, -5, 5, -3, 3, -1, 0]const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))@@ -140,18 +140,18 @@ export function SlideCommit({const pulse = useMotionValue(1)const shake = useMotionValue(0)const seen = useTransform(x, (v) => clamp(v, 0, TRAVEL))- const edge = useTransform([seen, anchor], ([v, a]) => v + GRIP + clamp(a - v, 0, TRAVEL))- const clip = useTransform(edge, (R) => `inset(0 ${Math.max(0, INNER - R)}px 0 0 round ${gripR}px)`)- const content = useTransform([seen, edge], ([v, R]) => `translateX(${(v + R) / 2 - INNER / 2}px)`)+ const edge = useTransform([seen, anchor], ([v, a]: any[]) => (v as number) + GRIP + clamp((a as number) - (v as number), 0, TRAVEL))+ const clip = useTransform(edge, (R: number) => `inset(0 ${Math.max(0, INNER - R)}px 0 0 round ${gripR}px)`)+ const content = useTransform([seen, edge], ([v, R]: any[]) => `translateX(${((v as number) + (R as number)) / 2 - INNER / 2}px)`)const swell = hot && !held && phase === 'idle' && !reduce ? SWELL : 1- const shape = useTransform(x, (v) => {+ const shape = useTransform(x, (v: number) => {const q = 1 - Math.min(SQUASH_MAX, Math.max(0, -v) / SQUASH_DIV)return `scale(${q * swell}, ${swell / q})`})- const origin = useTransform(seen, (v) => `${v}px 50%`)+ const origin = useTransform(seen, (v: number) => `${v}px 50%`)const say = useTransform(seen, [0, TRAVEL * 0.55], [1, 0])- const arrow = useTransform([seen, shown], ([v, on]) => on * clamp(1 - (v - TRAVEL * 0.55) / (TRAVEL * 0.4), 0, 1))- const trackTransform = useTransform([shake, pulse], ([s, p]) => `translateX(${s}px) scale(${p})`)+ const arrow = useTransform([seen, shown], ([v, on]: any[]) => (on as number) * clamp(1 - ((v as number) - TRAVEL * 0.55) / (TRAVEL * 0.4), 0, 1))+ const trackTransform = useTransform([shake, pulse], ([s, p]: any[]) => `translateX(${s}px) scale(${p})`)const labelText = typeof label === 'string' ? label : 'Slide to confirm'useMotionValueEvent(seen, 'change', (v) => {@@ -179,26 +179,26 @@ export function SlideCommit({}const goHome = (velocity: number) => {- if (reduce) animate(x, 0, { duration: 0.2, ease: EASE_OUT })- else animate(x, 0, { ...homeSpring, velocity: Math.min(0, velocity) })+ if (reduce) animate(x, 0 as any, { duration: 0.2, ease: EASE_OUT })+ else animate(x, 0 as any, { ...homeSpring, velocity: Math.min(0, velocity) })}const settle = () => {setPhase('idle')- animate(shown, 1, { duration: 0.2, delay: 0.12 })+ animate(shown, 1 as any, { duration: 0.2, delay: 0.12 })if (reduce) anchor.set(0)- else animate(anchor, 0, { type: 'spring', duration: 0.3, bounce: 0 })+ else animate(anchor, 0 as any, { type: 'spring', duration: 0.3, bounce: 0 })}const resolve = (viaKey: boolean) => {setPhase('done')anchor.set(x.get())- animate(spin, 0, { duration: 0.12 })+ animate(spin, 0 as any, { duration: 0.12 })if (reduce) x.set(0)else {- animate(x, 0, commitSpring)+ animate(x, 0 as any, commitSpring)if (!viaKey && landingDip > 0) {- animate(pulse, [1, 1 - landingDip, 1], { duration: 0.46, times: [0, 0.62, 1], ease: EASE_OUT, delay: 0.1 })+ animate(pulse, [1, 1 - landingDip, 1] as any, { duration: 0.46, times: [0, 0.62, 1], ease: EASE_OUT, delay: 0.1 })}}onDone?.()@@ -208,11 +208,11 @@ export function SlideCommit({const reject = (reason?: unknown) => {setPhase('error')onError?.(reason)- animate(spin, 0, { duration: 0.12 })- animate(shown, 1, { duration: 0.2, delay: 0.12 })+ animate(spin, 0 as any, { duration: 0.12 })+ animate(shown, 1 as any, { duration: 0.2, delay: 0.12 })if (reduce) goHome(0)else {- animate(shake, SHAKE, { duration: 0.45, ease: EASE_OUT })+ animate(shake, SHAKE as any, { duration: 0.45, ease: EASE_OUT })homeTimer.current = setTimeout(() => {if (!grip.current) goHome(0)}, 300)diff --git a/src/lib/codeDetect.ts b/src/lib/codeDetect.tsnew file mode 100644index 0000000..7dea159--- /dev/null+++ b/src/lib/codeDetect.ts@@ -0,0 +1,187 @@+/**+ * codeDetect.ts — Fast heuristic syntax and language detection for clipboard text.+ */++export interface CodeDetectionResult {+ isCode: boolean+ language: string+ displayName: string+}++export const LANGUAGE_DISPLAY_NAMES: Record<string, string> = {+ tsx: 'TSX',+ typescript: 'TypeScript',+ jsx: 'JSX',+ javascript: 'JavaScript',+ json: 'JSON',+ css: 'CSS',+ html: 'HTML',+ python: 'Python',+ bash: 'Bash',+ sql: 'SQL',+ rust: 'Rust',+ go: 'Go',+ cpp: 'C++',+ c: 'C',+ csharp: 'C#',+ yaml: 'YAML',+ markdown: 'Markdown',+ graphql: 'GraphQL',+}++/**+ * Detects if a given text string is a code snippet, and infers its programming language.+ */+export function detectCode(raw: string): CodeDetectionResult {+ if (!raw || typeof raw !== 'string') {+ return { isCode: false, language: 'text', displayName: 'Text' }+ }++ const text = raw.trim()++ // Ignore very short single tokens (like "hello" or numbers)+ if (text.length < 4) {+ return { isCode: false, language: 'text', displayName: 'Text' }+ }++ // 1. JSON Detection+ if ((text.startsWith('{') && text.endsWith('}')) || (text.startsWith('[') && text.endsWith(']'))) {+ try {+ JSON.parse(text)+ // Check if it's a multi-line or formatted JSON object/array+ if (text.includes(':') || text.includes('\n') || text.length > 20) {+ return { isCode: true, language: 'json', displayName: 'JSON' }+ }+ } catch {+ // If it looks like JSON structure with quotes and colons+ if (/^\{[\s\S]*"[a-zA-Z0-9_$-]+"\s*:[\s\S]*\}$/.test(text)) {+ return { isCode: true, language: 'json', displayName: 'JSON' }+ }+ }+ }++ // 2. HTML / XML / SVG Detection+ if (+ /<!DOCTYPE\s+html/i.test(text) ||+ /<(html|head|body|div|span|p|a|svg|script|style|path|button|input|h[1-6]|table|form|ul|li|section|header|footer|template)\b[^>]*>/i.test(text) ||+ (text.startsWith('<') && text.endsWith('>') && /<\/?[a-z][a-z0-9-]*\b/i.test(text))+ ) {+ return { isCode: true, language: 'html', displayName: 'HTML' }+ }++ // 3. CSS / SCSS Detection+ if (+ /@(media|keyframes|import|supports|font-face|container)\b/.test(text) ||+ /:(root|hover|focus|active|before|after|nth-child)\b/.test(text) ||+ /(?:^|\n)\s*([.#]?[a-zA-Z0-9_#-]+(\s*,\s*[.#]?[a-zA-Z0-9_#-]+)*)\s*\{\s*[\n\r]?(?:\s*[a-zA-Z-]+:\s*[^;]+;\s*[\n\r]?)+\}/.test(text) ||+ /(\b(color|background|padding|margin|display|flex|font-size|border|width|height|opacity|z-index|transform|box-shadow|overflow|position)\s*:\s*[^;]+;)/.test(text)+ ) {+ // If it has CSS properties and brackets/colons+ if (text.includes('{') && text.includes('}') && text.includes(':')) {+ return { isCode: true, language: 'css', displayName: 'CSS' }+ }+ }++ // 4. SQL Detection+ if (+ /^\s*(SELECT\s+[\s\S]+?\s+FROM\s+|INSERT\s+INTO\s+|UPDATE\s+[\s\S]+?\s+SET\s+|DELETE\s+FROM\s+|CREATE\s+(TABLE|INDEX|VIEW|DATABASE)\s+|ALTER\s+TABLE\s+|DROP\s+(TABLE|DATABASE)\s+|WITH\s+\w+\s+AS\s*\()/i.test(text)+ ) {+ return { isCode: true, language: 'sql', displayName: 'SQL' }+ }++ // 5. Bash / Shell Script / Terminal Commands+ if (+ /^#!\/bin\/(bash|sh|zsh)/.test(text) ||+ /^\s*(npm|pnpm|yarn|bun|git|curl|docker|sudo|brew|npx|apt-get|systemctl|cargo|cargo-build|pip|pip3|pytest|vitest)\s+[a-zA-Z0-9_./:-]+/m.test(text) ||+ /^\s*(export\s+[A-Z0-9_]+=|chmod\s+\+?[0-9xrw]+|mkdir\s+-p|rm\s+-rf|grep\s+-)/m.test(text)+ ) {+ return { isCode: true, language: 'bash', displayName: 'Bash' }+ }++ // 6. Python Detection+ if (+ /(?:^|\n)\s*def\s+[a-zA-Z_]\w*\s*\(.*?\)\s*(?:->\s*[^:]+)?\s*:/m.test(text) ||+ /(?:^|\n)\s*class\s+[a-zA-Z_]\w*(?:\(.*?\))?\s*:/m.test(text) ||+ /(?:^|\n)\s*from\s+[a-zA-Z_.]+\s+import\s+/m.test(text) ||+ /(?:^|\n)\s*if\s+__name__\s*==\s*['"]__main__['"]\s*:/m.test(text) ||+ /(?:^|\n)\s*elif\s+[^:]+:/m.test(text) ||+ /\bprint\(.*?\)/m.test(text) && /\b(self|elif|import|None|True|False)\b/.test(text)+ ) {+ return { isCode: true, language: 'python', displayName: 'Python' }+ }++ // 7. Rust Detection+ if (+ /\bfn\s+[a-zA-Z_]\w*\s*\(.*?\)\s*(?:->\s*[^\{]+)?\s*\{/.test(text) ||+ /\b(let\s+mut\s+|impl\s+[A-Z]\w*|pub\s+struct\s+[A-Z]\w*|use\s+std::|match\s+\w+\s*\{|println!\()/.test(text)+ ) {+ return { isCode: true, language: 'rust', displayName: 'Rust' }+ }++ // 8. Go Detection+ if (+ /\bpackage\s+[a-zA-Z_]\w*/.test(text) ||+ /\bfunc\s+(?:\([a-zA-Z0-9_* ]+\)\s+)?[a-zA-Z_]\w*\(.*?\)/.test(text) ||+ /\b(import\s*\(\s*[\r\n]+|fmt\.Print|go\s+func\(\))/.test(text)+ ) {+ return { isCode: true, language: 'go', displayName: 'Go' }+ }++ // 9. C / C++ / C#+ if (+ /#include\s+<[a-zA-Z0-9_.]+>/.test(text) ||+ /\bstd::(cout|cin|vector|string|make_unique|make_shared)\b/.test(text) ||+ /\bint\s+main\s*\([^)]*\)\s*\{/.test(text)+ ) {+ return { isCode: true, language: 'cpp', displayName: 'C++' }+ }++ if (+ /\busing\s+System(\.[A-Za-z0-9_]+)*;/.test(text) ||+ /\bnamespace\s+[A-Za-z0-9_.]+\s*\{/.test(text) ||+ /\b(public|private|protected)\s+(class|interface|enum|struct|async\s+Task)\s+[A-Za-z0-9_]+/.test(text)+ ) {+ return { isCode: true, language: 'csharp', displayName: 'C#' }+ }++ // 10. TypeScript / TSX / JavaScript / JSX+ const hasTsTypes = /:\s*(string|number|boolean|any|void|unknown|never|Record<|Array<|Promise<|React\.[A-Za-z]+)\b/.test(text) ||+ /\b(interface\s+[A-Z]\w*|type\s+[A-Z]\w*\s*=|as\s+const\b|<[A-Z]\w*>\s*\()/.test(text)+ const hasJsx = /<[A-Z][a-zA-Z0-9]*\b[^>]*(\/?>|>[\s\S]*?<\/[A-Z][a-zA-Z0-9]*>)/.test(text) ||+ /<>\s*[\s\S]*?<\/>/.test(text) ||+ /\bclassName=/.test(text)++ const hasJsKeywords = /\b(import\s+.*?from\s+['"]|export\s+(default\s+|const\s+|function\s+|class\s+)|const\s+[a-zA-Z0-9_$]+(\s*:\s*[^=]+)?\s*=|let\s+[a-zA-Z0-9_$]+(\s*:\s*[^=]+)?\s*=|function\s+[a-zA-Z0-9_$]+\s*\(|console\.(log|error|warn|info)|async\s+function|await\s+[a-zA-Z0-9_$]+|=>\s*[\{\(])/.test(text)++ if (hasJsKeywords || hasJsx || hasTsTypes) {+ if (hasJsx) {+ return {+ isCode: true,+ language: hasTsTypes ? 'tsx' : 'jsx',+ displayName: hasTsTypes ? 'TSX' : 'JSX'+ }+ }+ if (hasTsTypes) {+ return { isCode: true, language: 'typescript', displayName: 'TypeScript' }+ }+ return { isCode: true, language: 'javascript', displayName: 'JavaScript' }+ }++ // 11. General Code Heuristics (e.g. multi-line structured block with brackets and operators)+ const lines = text.split('\n')+ if (lines.length >= 2) {+ let codeScore = 0+ if (/[{}\[\]();]/.test(text)) codeScore += 2+ if (/===|!==|=>|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|::|->/.test(text)) codeScore += 2+ if (/^\s{2,}|\t/m.test(text)) codeScore += 2+ if (/\b(return|if|else|for|while|switch|case|break|try|catch|throw|new|typeof|instanceof)\b/.test(text)) codeScore += 3+ if (/\b(true|false|null|undefined|NaN)\b/.test(text)) codeScore += 1+ if (/(\/\/|#|\/\*|\*\/)/.test(text)) codeScore += 1++ if (codeScore >= 5) {+ return { isCode: true, language: 'javascript', displayName: 'Code' }+ }+ }++ return { isCode: false, language: 'text', displayName: 'Text' }+}diff --git a/src/styles/item.css b/src/styles/item.cssindex fd10a8e..b9a7b6d 100644--- a/src/styles/item.css+++ b/src/styles/item.css@@ -306,6 +306,43 @@.kind-badge.url {color: rgba(255, 255, 255, 0.9);}+.kind-badge.code {+ color: #38bdf8;+ font-family: var(--font-mono);+ font-size: calc(10.5px * var(--font-scale, 1));+ font-weight: 600;+ letter-spacing: 0.02em;+}++/* Minimal Code Block Preview for Item Card */+.code-card-preview {+ position: relative;+ width: 100%;+ height: 100%;+ min-height: 0;+ flex: 1;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ background: transparent;+ border: none;+ box-shadow: none;+}++.code-card-preview .code-block-container {+ width: 100%;+ height: 100%;+ min-height: 0;+}++.code-card-preview pre {+ font-family: var(--font-mono) !important;+}++.list.horizontal .code-card-preview {+ height: 86px;+ max-height: 86px;+}/* Clean Professional Link Card */.link-card {