Files
genoffice/packages/electron-utils/src/drop-open.ts
T
merrick-2002andGenOffice d24c964a3e Sync snapshot (2026-09-09) (#271)
- **New app: GenOffice HTML.** Open, edit and generate .html pages: a source pane with a sandboxed live preview, click-to-select elements with a floating toolbar and style panel, device-size preview, image tools and a present mode. AI generates whole pages from a brief with style directions and offers page-wide Restyle, Theme and Summarize. Export to Word runs locally through the built-in html2docx converter (native, editable OOXML; no print-to-PDF detour).
- **AI:** separate BYOK providers for web search, image generation and image/video analysis; new Codex App Server provider; Ask AI quotes the selected text and keeps it highlighted while it runs; custom AI panel text size; blocked requests retry through the Chromium network stack.
- **App:** global AutoSave setting shared by every editor; AI panel text size and chat spellcheck toggles (genoffice#249); Czech (cs) UI locale (genoffice#259); Save As defaults to the document's folder; PDF export no longer aborts on CJK file paths on Windows.
- **Docs:** Export as HTML; comments and replies edit in place from the comments pane; the caret can leave a trailing table (genoffice#266); spellcheck re-marks text as soon as it is re-enabled; AI edits are character-precise on partial selections; zoom keeps the scroll position; pasting a cell from Sheets takes the destination font.
- **Sheets:** Find no longer freezes on wide or streamed grids; Replace searches as you type; cached values of external-workbook formulas are kept instead of #ERROR! (genoffice#235); "number stored as text" is a warning, not an error (genoffice#236); paste repeats into the target range like Excel; filter criteria survive save/reopen; saves retry when Windows locks the file; many Excel-fidelity fixes for column widths, row heights, charts, slicers, number formats and CJK fonts.
- **Slides:** PDF export works for large presentations (genoffice#264); EMF/WMF picture fonts and East Asian theme fonts resolve correctly; decks with missing layouts or embedded styles still open; outline-only pie slices render.
- **PDF:** highlight and underline geometry aligns with the text; Shift+arrows extend the selection instead of paging.
- **Markdown:** Find and replace (Ctrl+F / Ctrl+H) (genoffice#253); mermaid code blocks render as diagrams (genoffice#263); better print quality.
- Thanks to community contributors @GoodScholar, @aniruddhaadak80 and @Sun8854, and to @hanyscz, @qgzln, @zyp997, @bisslot, @krakotay and @Ben03151 for the reports.

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
2026-09-09 18:19:13 +08:00

131 lines
5.7 KiB
TypeScript

/// Drag & drop a local document file anywhere in the app window to open it.
///
/// Renderers share one main process (the shell hosts every editor view), so the
/// bridge only has to resolve dropped files to paths and send them over ONE
/// channel; the shell routes each path through its normal open pipeline. The
/// installer runs inside preloads, where `webUtils.getPathForFile` is callable
/// and DOM listeners see real OS drops — paths never cross contextBridge.
///
/// Ownership contract with page-level drop zones: a zone that handles its own
/// file drops (AI attachment panels, slides image insert) cancels the event
/// before it bubbles here (`defaultPrevented`), and this bridge stays out of
/// the way. Text/media drags without OS files are untouched.
import { ipcRenderer, webUtils } from 'electron'
export const DROP_OPEN_CHANNEL = 'app:open-dropped-files'
/** Extensions routed by apps/shell routeDocumentPath — keep in sync there and
* with OPEN_DIALOG_EXTENSIONS / OPEN_LOCAL_EXTENSIONS on the home screen. */
export const OPENABLE_DOC_RE = /\.(docx|xlsx|xlsm|xls|csv|pptx|pdf|md|markdown|html|htm)$/i
/** Recognized-but-unsupported formats: kept in the sent payload so the shell
* can show its "not supported" dialog instead of dropping them silently.
* Mirrors UNSUPPORTED_DOC_RE in apps/shell/src/main/index.ts. */
export const KNOWN_UNSUPPORTED_DOC_RE = /\.(doc|rtf|odt|ppt|pps|odp|ods|xlsb|pages|key|numbers)$/i
/** upper bound on how many files one drop may ask to open */
const MAX_DROPPED_FILES = 20
/** the resolver signature webUtils.getPathForFile satisfies; injectable for tests */
type PathResolver = (file: File) => string
/** Resolve one dropped file, tolerating resolver failures (see droppableFilePaths). */
function tryResolvePath(file: File, getPathForFile: PathResolver): string {
try {
return getPathForFile(file).trim()
} catch {
return ''
}
}
/**
* Resolve an event's dropped files to local paths. Returns null when the drag
* carries no OS files at all (internal text/element drags), or [] when it does
* but none resolve (directories, virtual entries) — both mean "not ours".
*/
export function droppableFilePaths(
ev: Pick<DragEvent, 'dataTransfer'>,
getPathForFile: PathResolver,
): string[] | null {
const transfer = ev.dataTransfer
if (!transfer || !transfer.types.includes('Files')) return null
const paths: string[] = []
for (const file of Array.from(transfer.files)) {
// A throwing resolver (e.g. a sandboxed entry Electron cannot map) must
// not abort the whole drop: skip that file like a virtual entry.
// Non-empty guard covers virtual entries (e.g. page-referenced blobs).
const path = tryResolvePath(file, getPathForFile)
if (path) paths.push(path)
}
return paths
}
/**
* Sanitize + classify a raw IPC payload: strings only, trimmed, deduped,
* capped, then split into directly-openable paths and known-unsupported
* extensions (unique, first-seen order). Anything unrecognized (.png, .zip,
* nonexistent junk from a hostile sender) falls out silently.
*/
export function partitionDropPayload(raw: unknown): {
supported: string[]
unsupportedExts: string[]
} {
const supported: string[] = []
const unsupportedExts: string[] = []
if (!Array.isArray(raw)) return { supported, unsupportedExts }
const seen = new Set<string>()
for (const entry of raw as unknown[]) {
if (typeof entry !== 'string') continue
const path = entry.trim()
if (!path || seen.has(path)) continue
seen.add(path)
if (OPENABLE_DOC_RE.test(path)) {
// keep scanning for unsupported entries even after hitting the open cap
if (supported.length < MAX_DROPPED_FILES) supported.push(path)
} else if (KNOWN_UNSUPPORTED_DOC_RE.test(path)) {
const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase()
if (!unsupportedExts.includes(ext)) unsupportedExts.push(ext)
}
}
return { supported, unsupportedExts }
}
/** Symbol.for keeps repeated installs idempotent when several bundled copies of
* this module end up in one process (mirrors navigation-guard). */
const INSTALLED = Symbol.for('genoffice.drop-open-installed')
/**
* Preload-side hook: makes `drop` fire for document drags anywhere in the
* page and forwards recognized files to the shell's router. Intentionally not
* exposed through contextBridge — page code cannot spoof these events with
* arbitrary paths because payload construction happens here in the preload
* world only.
*/
export function installDropOpenBridge(): void {
const holder = globalThis as Record<symbol, boolean | undefined>
if (typeof window === 'undefined' || holder[INSTALLED]) return
holder[INSTALLED] = true
// Without a canceled dragover Chromium never fires `drop`; canceling here is
// what lets a document-drag land anywhere that isn't already a drop zone.
window.addEventListener('dragover', (ev: DragEvent) => {
if (ev.defaultPrevented) return
if (!ev.dataTransfer?.types.includes('Files')) return
ev.preventDefault()
})
window.addEventListener('drop', (ev: DragEvent) => {
// first: something in the page already claimed this drop (image insert,
// AI attachments...) — never second-guess it
if (ev.defaultPrevented) return
const paths = droppableFilePaths(ev, (file) => webUtils.getPathForFile(file))
if (!paths) return
// only recognized documents ride along; stray images/folders are swallowed
// here so they neither navigate the page nor produce open attempts
const payload = paths.filter((p) => OPENABLE_DOC_RE.test(p) || KNOWN_UNSUPPORTED_DOC_RE.test(p))
ev.preventDefault()
if (payload.length === 0) return
ipcRenderer.send(DROP_OPEN_CHANNEL, payload.slice(0, MAX_DROPPED_FILES))
})
}