feat: 设置页「添加插件」推荐目录 + 复制安装命令;移除内置 Office 预览

- 设置页侧边栏内容/文件预览两个网格末尾各增虚线卡片,弹出对应 kind 的插件弹窗
- 弹窗:GitHub topic 按钮(新标签页)+ 推荐插件目录(plugins-tabs.ts / plugins-viewers.ts)
- 每条目「跳转」(window.open 新标签页直达仓库)与「复制」(writeClipboard + 已复制反馈)
- 不做终端预填流:不关闭弹窗、不打开终端、无失败路径(install/installNotice/installError* 文案删除)
- 内置 Office 预览(docx/xlsx/pptx)整体移除,chunk 白名单 5→2(terminal/editor)
- 文案「内置插件」→「推荐插件」;AGENTS.md/README/设计文档同步
This commit is contained in:
Menghuan1918
2026-08-14 22:30:34 +08:00
parent 1b0b382edc
commit cbc28473a0
40 changed files with 942 additions and 1128 deletions
-131
View File
@@ -1,131 +0,0 @@
/** High-fidelity browser-native PPTX preview with slide navigation. */
import { useEffect, useRef, useState } from 'react'
import { downloadUrl, mediaUrl, type SessionScope } from './api.ts'
import { t } from './locales.ts'
import css from './sidebar.module.css'
type PptxViewerInstance = import('@aiden0z/pptx-renderer').PptxViewer
type LoadState =
| { status: 'loading' }
| { status: 'ready'; count: number }
| { status: 'error'; message: string }
export function PptxView(props: { scope: SessionScope; path: string; title: string }) {
const { scope, path, title } = props
const hostRef = useRef<HTMLDivElement>(null)
const viewerRef = useRef<PptxViewerInstance | null>(null)
const [load, setLoad] = useState<LoadState>({ status: 'loading' })
const [slide, setSlide] = useState(0)
const [navigating, setNavigating] = useState(false)
useEffect(() => {
const controller = new AbortController()
const host = hostRef.current
if (host === null) return
setLoad({ status: 'loading' })
setSlide(0)
void (async () => {
try {
const response = await fetch(mediaUrl(scope, path), { signal: controller.signal })
if (!response.ok) throw new Error(`HTTP ${response.status}`)
const bytes = await response.arrayBuffer()
if (controller.signal.aborted) return
const { PptxViewer, RECOMMENDED_ZIP_LIMITS } = await import('@aiden0z/pptx-renderer')
if (controller.signal.aborted) return
const viewer = await PptxViewer.open(bytes, host, {
renderMode: 'slide',
fitMode: 'contain',
lazyMedia: true,
lazySlides: true,
pdfjs: false,
signal: controller.signal,
zipLimits: RECOMMENDED_ZIP_LIMITS,
onSlideChange: (index) => {
if (!controller.signal.aborted) setSlide(index)
},
})
if (controller.signal.aborted) {
viewer.destroy()
return
}
viewerRef.current = viewer
setSlide(viewer.currentSlideIndex)
setLoad({ status: 'ready', count: viewer.slideCount })
} catch (error) {
if (controller.signal.aborted) return
try {
viewerRef.current?.destroy()
} catch {
// Partially initialized viewer — ignore disposal errors.
}
viewerRef.current = null
host.innerHTML = ''
setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) })
}
})()
return () => {
controller.abort()
try {
viewerRef.current?.destroy()
} catch {
// Already destroyed.
}
viewerRef.current = null
host.innerHTML = ''
}
}, [scope.sessionId, scope.cwd, path])
const navigate = (target: number): void => {
const viewer = viewerRef.current
if (viewer === null || load.status !== 'ready' || navigating) return
const next = Math.max(0, Math.min(load.count - 1, target))
if (next === slide) return
setNavigating(true)
void viewer.goToSlide(next, { behavior: 'auto' }).then(() => {
setSlide(viewer.currentSlideIndex)
}).catch((error: unknown) => {
setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) })
}).finally(() => {
setNavigating(false)
})
}
return (
<div className={css.editorPptx} aria-label={title}>
<div className={css.editorPptxToolbar}>
<button
type="button"
className={css.editorPptxButton}
disabled={load.status !== 'ready' || slide <= 0 || navigating}
onClick={() => { navigate(slide - 1) }}
>
{t('previousSlide')}
</button>
<span className={css.editorPptxPosition}>
{load.status === 'ready' ? `${slide + 1} / ${load.count}` : '– / –'}
</span>
<button
type="button"
className={css.editorPptxButton}
disabled={load.status !== 'ready' || slide >= load.count - 1 || navigating}
onClick={() => { navigate(slide + 1) }}
>
{t('nextSlide')}
</button>
<a className={css.editorDownloadLink} href={downloadUrl(scope, path)} download>
{t('downloadToView')}
</a>
</div>
<div className={css.editorPptxStage}>
<div className={css.editorPptxHost} ref={hostRef} />
{load.status !== 'ready' && (
<div className={css.editorOfficeOverlay}>
{load.status === 'loading' && <div className={css.editorPlaceholder}>{t('loading')}</div>}
{load.status === 'error' && <div className={css.editorError}>{load.message}</div>}
</div>
)}
</div>
</div>
)
}
+205
View File
@@ -198,6 +198,38 @@
text-overflow: ellipsis;
}
/* The "add plugin" card: same grid cell / chrome as the inventory cards
(it shares .card), but a DASHED border — the repo's first dashed surface;
the hover accent follows the existing drag-drop dashed outlines
(sidebar.module.css .dropCenter / .tabBarDrop). */
.addCard {
align-items: flex-start;
padding: 12px;
border-style: dashed;
border-color: var(--dsw-alias-border-l2);
text-align: left;
}
.addCard:hover {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-interactive-bg-hover-accent);
color: var(--dsw-alias-label-primary);
}
.addCard:hover .cardTitle {
color: var(--dsw-alias-label-primary);
}
.addCard:hover .cardIconChip {
border-color: color-mix(in srgb, var(--dsw-alias-button-primary-fill) 35%, transparent);
color: var(--dsw-alias-button-primary-fill);
}
.addCard:focus-visible {
outline: 2px solid var(--dsw-alias-border-l4);
outline-offset: 2px;
}
.cardOn .cardDesc {
color: var(--dsw-alias-label-secondary);
}
@@ -412,6 +444,179 @@
color: var(--dsw-alias-state-error-primary);
}
/* ── "Add plugin" modal ──────────────────────────────────────────────── */
/* A wide dialog like the settings popup (doubled class keeps the width
rule above the primitive's .dialog regardless of stylesheet order). */
.pluginModal.pluginModal {
width: min(560px, 100%);
}
.pluginList {
display: flex;
flex-direction: column;
gap: 12px;
width: 100%;
}
/* The GitHub topic entry: a full-width secondary BUTTON (not a link — it
opens a real new browser tab via window.open, bypassing the sidebar
link takeover). */
.pluginTopicBtn {
width: 100%;
appearance: none;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 8px;
padding: 6px 12px;
font: inherit;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
background: var(--dsw-alias-bg-layer-1);
cursor: pointer;
}
.pluginTopicBtn:hover {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-interactive-bg-hover-accent);
color: var(--dsw-alias-label-primary);
}
.pluginTopicBtn:focus-visible {
outline: 2px solid var(--dsw-alias-border-l4);
outline-offset: 1px;
}
.pluginEmpty {
padding: 20px 2px;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
}
.pluginEntries {
display: flex;
flex-direction: column;
gap: 10px;
}
/* One catalog entry: name + install button on the head row, description,
then the install command in a mono block (the exact script that gets
pre-typed into the terminal — review it here before installing). */
.pluginEntry {
display: flex;
flex-direction: column;
gap: 4px;
padding: 12px;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 12px;
background: var(--dsw-alias-bg-layer-1);
}
.pluginEntryHead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.pluginEntryActions {
display: inline-flex;
align-items: center;
gap: 6px;
flex: none;
}
/* The per-entry "jump" button: opens the plugin repo in a REAL new browser
tab (window.open — a button, so the sidebar link takeover cannot reroute
it). Secondary style, quieter than the Install button. */
.pluginJumpBtn {
flex: none;
appearance: none;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 8px;
padding: 3px 12px;
font: inherit;
font-size: 12px;
line-height: 1.5;
cursor: pointer;
background: transparent;
color: var(--dsw-alias-label-secondary);
}
.pluginJumpBtn:hover {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-interactive-bg-hover-accent);
color: var(--dsw-alias-label-primary);
}
.pluginJumpBtn:focus-visible {
outline: 2px solid var(--dsw-alias-border-l4);
outline-offset: 1px;
}
.pluginName {
min-width: 0;
font-size: 13px;
line-height: 20px;
font-weight: 600;
color: var(--dsw-alias-label-primary);
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pluginName:hover {
text-decoration: underline;
color: var(--dsw-alias-button-primary-fill);
}
.pluginDesc {
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
}
.pluginInstall {
display: block;
padding: 6px 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
line-height: 16px;
color: var(--dsw-alias-label-secondary);
background: var(--dsw-alias-bg-layer-2);
border: 1px solid var(--dsw-alias-border-l1);
border-radius: 8px;
overflow-x: auto;
white-space: nowrap;
}
/* The per-entry copy button: copies the install script to the
clipboard (the settings primary-button recipe, smaller than .done). */
.pluginCopyBtn {
flex: none;
appearance: none;
border: 1px solid transparent;
border-radius: 8px;
padding: 3px 12px;
font: inherit;
font-size: 12px;
line-height: 1.5;
cursor: pointer;
background: var(--dsw-alias-label-primary);
color: var(--dsw-alias-bg-layer-3);
}
.pluginCopyBtn:hover {
background: var(--dsw-alias-button-primary-hover);
}
.pluginCopyBtn:focus-visible {
outline: 2px solid var(--dsw-alias-brand-primary);
outline-offset: 1px;
}
@media (prefers-reduced-motion: reduce) {
.card,
.switchTrack,
+52
View File
@@ -41,6 +41,7 @@
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import {
IconCheckOutline16,
IconPlusOutline16,
IconSettingsOutline16,
Input,
Modal,
@@ -57,6 +58,7 @@ import {
} from '../prefs-shared.ts'
import { api } from './api.ts'
import { parsePrefs } from './prefs.ts'
import { AddPluginModal, type PluginKind } from './add-plugin-modal.tsx'
import { t } from './locales.ts'
import type { SidebarStore } from './state.ts'
import type {
@@ -378,6 +380,10 @@ export function SideCardSection({ store, service }: SideCardSectionProps) {
const [error, setError] = useState<string | null>(null)
// Which feature's secondary settings popup is open (null = closed).
const [settingsFor, setSettingsFor] = useState<TabDescriptor | FileViewerDescriptor | null>(null)
// Whether the "add plugin" modal (a dashed card at the end of the
// 侧边栏内容 / 文件预览 grids) is open, and for which extension point
// (null = closed).
const [addPluginsOpen, setAddPluginsOpen] = useState<PluginKind | null>(null)
// The LATEST optimistic prefs, kept in sync with the state. Nested-map
// merges (tabsEnabled / viewersEnabled / pluginSettings) MUST build from
// this ref, not from the render-time `prefs`: two same-tick writes (e.g.
@@ -681,6 +687,22 @@ export function SideCardSection({ store, service }: SideCardSectionProps) {
})}
</Fragment>
))}
{/* The "add tab plugin" entry: same card size as the inventory,
but a dashed border — it opens the TAB-registration plugin
modal instead of toggling a feature. */}
<button
type="button"
className={clsx(css.card, css.addCard)}
onClick={() => { setAddPluginsOpen('tab') }}
>
<span className={css.cardTop}>
<span className={css.cardIconChip}>
<IconPlusOutline16 size={16} />
</span>
<span className={css.cardTitle}>{t('addPluginsTabCard')}</span>
</span>
<span className={css.cardDesc}>{t('addPluginsTabCardDesc')}</span>
</button>
</div>
</div>
@@ -705,6 +727,21 @@ export function SideCardSection({ store, service }: SideCardSectionProps) {
})}
</Fragment>
))}
{/* The "add preview plugin" entry: dashed card opening the
FILE-PREVIEWER registration modal. */}
<button
type="button"
className={clsx(css.card, css.addCard)}
onClick={() => { setAddPluginsOpen('viewer') }}
>
<span className={css.cardTop}>
<span className={css.cardIconChip}>
<IconPlusOutline16 size={16} />
</span>
<span className={css.cardTitle}>{t('addPluginsViewerCard')}</span>
</span>
<span className={css.cardDesc}>{t('addPluginsViewerCardDesc')}</span>
</button>
</div>
</div>
@@ -746,6 +783,21 @@ export function SideCardSection({ store, service }: SideCardSectionProps) {
</Modal>
)}
{/* The "add plugin" modal (opened by the dashed cards above): declares
the extension point of the clicked kind, opens the GitHub topic,
and lists the matching recommended plugin catalog with per-entry
install buttons (the install flow opens a ~/.dsh terminal with
the command pre-typed; failures render inline here, in settings
only). Mounted only while open (Modal runs hooks unconditionally
— same SSR rule as the settings popup above). */}
{addPluginsOpen !== null && (
<AddPluginModal
service={service}
onClose={() => { setAddPluginsOpen(null) }}
kind={addPluginsOpen}
/>
)}
{error !== null && (
<div className={css.error} role="alert">
{error}
+141
View File
@@ -0,0 +1,141 @@
/**
* The "add plugin" modals (Side card settings → the dashed cards at the
* end of the 侧边栏内容 / 文件预览 grids): declare that the sidebar's
* extension points — tab pages and file previewers — are open to plugins
* (registered through `ctx.betterSidebar`), point at the GitHub topic page
* for discovery, and show the repo's recommended plugin catalog of the
* matching kind (name / url / description / install script).
*
* Per entry there are two actions:
* - 「跳转」opens the plugin's repo in a REAL new browser tab (window.open
* — a button, so the sidebar link takeover cannot reroute it);
* - 「安装」only COPIES the install script to the clipboard (writeClipboard)
* with a transient "已复制" feedback on the button — the user pastes and
* runs it wherever they manage their DSH profile. No terminal is opened,
* nothing is closed, nothing can fail outward.
*
* The body is extracted as {@link PluginListBody} so tests render it
* directly — the Modal primitive runs hooks unconditionally, so an open
* Modal must never be renderToString'd (same rule as the settingsFor popup
* in SideCardSection); the modal itself mounts only while open.
*/
import { useState } from 'react'
import { Modal, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
import type { BetterSidebarService } from './service.ts'
import { PLUGIN_TOPIC_URL, type PluginEntry } from './plugins-shared.ts'
import { builtinTabPlugins } from './plugins-tabs.ts'
import { builtinViewerPlugins } from './plugins-viewers.ts'
import { t } from './locales.ts'
import css from './SideCardSection.module.css'
/** Which extension point the modal is adding a plugin for. */
export type PluginKind = 'tab' | 'viewer'
/** The catalog of one kind (kept in two repo files: plugins-tabs.ts /
* plugins-viewers.ts). */
function catalogOf(kind: PluginKind): readonly PluginEntry[] {
return kind === 'tab' ? builtinTabPlugins : builtinViewerPlugins
}
/** How long the "已复制" feedback stays on the copy button. */
const COPIED_FEEDBACK_MS = 1500
/** The modal body: the GitHub topic button + the recommended plugin list
* with per-entry jump/copy buttons (extracted for direct testing). */
export function PluginListBody(props: { service: BetterSidebarService; kind: PluginKind }) {
const { service, kind } = props
// Which entry's copy button currently shows the "已复制" feedback.
const [copiedId, setCopiedId] = useState<string | null>(null)
/** Copy the entry's install script to the clipboard (best-effort) and
* flash the button's "已复制" label for a moment. Never closes anything,
* never throws outward. */
const copy = (entry: PluginEntry): void => {
void writeClipboard(entry.install)
setCopiedId(entry.id)
window.setTimeout(() => {
setCopiedId(current => (current === entry.id ? null : current))
}, COPIED_FEEDBACK_MS)
}
/** Open the plugin's repo in a REAL new browser tab (a button, so the
* sidebar link takeover cannot reroute it). */
const jump = (entry: PluginEntry): void => {
window.open(entry.url, '_blank', 'noopener')
}
return (
<div className={css.pluginList}>
<button
type="button"
className={css.pluginTopicBtn}
onClick={() => { window.open(PLUGIN_TOPIC_URL, '_blank', 'noopener') }}
>
{t('addPluginsBrowseMore')}
</button>
<div className={css.groupHeading}>
<span>{t('addPluginsRecommended')}</span>
<span className={css.count}>{catalogOf(kind).length}</span>
</div>
{catalogOf(kind).length === 0 ? (
<div className={css.pluginEmpty}>{t('addPluginsEmpty')}</div>
) : (
<div className={css.pluginEntries}>
{catalogOf(kind).map(entry => (
<div key={entry.id} className={css.pluginEntry}>
<div className={css.pluginEntryHead}>
<a className={css.pluginName} href={entry.url} target="_blank" rel="noreferrer">
{entry.name}
</a>
<span className={css.pluginEntryActions}>
<button
type="button"
className={css.pluginJumpBtn}
aria-label={`${t('openPlugin')}: ${entry.name}`}
onClick={() => { jump(entry) }}
>
{t('openPlugin')}
</button>
<button
type="button"
className={css.pluginCopyBtn}
aria-label={`${t('copyInstall')}: ${entry.name}`}
onClick={() => { copy(entry) }}
>
{copiedId === entry.id ? t('copied') : t('copy')}
</button>
</span>
</div>
<div className={css.pluginDesc}>
{typeof entry.description === 'function' ? entry.description() : entry.description}
</div>
<code className={css.pluginInstall}>{entry.install}</code>
</div>
))}
</div>
)}
</div>
)
}
/** The modal itself (mounted only while open — see the module comment). */
export function AddPluginModal(props: { service: BetterSidebarService; onClose: () => void; kind: PluginKind }) {
const { service, onClose, kind } = props
return (
<Modal
open
onClose={onClose}
title={kind === 'tab' ? t('addPluginsTabCard') : t('addPluginsViewerCard')}
description={kind === 'tab' ? t('addPluginsTabDesc') : t('addPluginsViewerDesc')}
closeLabel={t('close')}
className={css.pluginModal}
footer={(
<button type="button" className={css.done} onClick={onClose}>
{t('settingsDone')}
</button>
)}
>
<PluginListBody service={service} kind={kind} />
</Modal>
)
}
+22 -48
View File
@@ -1,18 +1,22 @@
/**
* The 9 built-in file viewer descriptors: every preview surface is a
* registered viewer (image / pdf / docx / xlsx / pptx / markdown / html /
* code / binary-download), exactly like external plugins register theirs.
* The `binary-download` viewer sniffs NUL bytes via `detect` for unknown
* binaries and serves doc/xls/ppt by extension; `code` is the catch-all
* (`exts: []`, lowest priority) that claims any file no other viewer did.
* The 6 built-in file viewer descriptors: every preview surface is a
* registered viewer (image / pdf / markdown / html / code /
* binary-download), exactly like external plugins register theirs. Office
* previews (.docx / .xlsx / .pptx) are NOT built in anymore — they moved to
* the recommended office plugin (see plugins-viewers.ts), which registers
* the same ids through this service.
*
* The heavy viewers (docx/xlsx/pptx and the CodeMirror-backed
* markdown/html/code) render through {@link lazyChunkComponent} wrappers —
* their libraries are fetched only when such a file is first opened (see
* chunk-loader.ts). The descriptor metadata (id/exts/priority/detect) is
* identical either way, so matching semantics and external-plugin
* overrides are unaffected; the `component` wrapper keeps the descriptor
* contract `(props) => ReactNode`.
* The `binary-download` viewer sniffs NUL bytes via `detect` for unknown
* binaries and serves legacy doc/xls/ppt by extension; `code` is the
* catch-all (`exts: []`, lowest priority) that claims any file no other
* viewer did.
*
* The heavy viewers (the CodeMirror-backed markdown/html/code) render
* through {@link lazyChunkComponent} wrappers — their libraries are fetched
* only when such a file is first opened (see chunk-loader.ts). The
* descriptor metadata (id/exts/priority/detect) is identical either way,
* so matching semantics and external-plugin overrides are unaffected; the
* `component` wrapper keeps the descriptor contract `(props) => ReactNode`.
*
* Every viewer carries the declarative settings-surface fields — `title`
* and `icon` — so the Side card settings page can render the enable/disable
@@ -26,9 +30,6 @@ import {
IconImageOutline16,
IconMarkdownOutline16,
IconPdfOutline16,
IconDocxOutline16,
IconXlsxOutline16,
IconPptxOutline16,
IconHtmlOutline16,
} from '../icons.tsx'
import type { ComponentType } from 'react'
@@ -37,17 +38,14 @@ import { t } from '../locales.ts'
import css from '../sidebar.module.css'
/**
* Lazy wrappers over the chunk-resident viewer components. The `pick`
* functions are module-level (stable identity — the wrapper effect depends
* on them); the cast bridges the chunk exports record to the descriptor
* prop shape (the views read only their own subset of FileViewerProps).
* Lazy wrapper over the chunk-resident viewer component. The `pick`
* function is module-level (stable identity — the wrapper effect depends
* on it); the cast bridges the chunk exports record to the descriptor prop
* shape (the view reads only its own subset of FileViewerProps).
*/
const LazyDocx = lazyChunkComponent<FileViewerProps>('docx', (mod) => mod.DocxView as ComponentType<FileViewerProps> | undefined)
const LazyXlsx = lazyChunkComponent<FileViewerProps>('xlsx', (mod) => mod.XlsxView as ComponentType<FileViewerProps> | undefined)
const LazyPptx = lazyChunkComponent<FileViewerProps>('pptx', (mod) => mod.PptxView as ComponentType<FileViewerProps> | undefined)
const LazyTextEditor = lazyChunkComponent<FileViewerProps>('editor', (mod) => mod.TextEditor as ComponentType<FileViewerProps> | undefined)
/** The 9 built-in file viewer descriptors. */
/** The 6 built-in file viewer descriptors. */
export function builtinViewers(): readonly FileViewerDescriptor[] {
return [
{
@@ -72,30 +70,6 @@ export function builtinViewers(): readonly FileViewerDescriptor[] {
<PdfView scope={scope} path={path} title={title} />
),
},
{
id: 'docx',
title: () => t('viewerDocx'),
icon: (size: number) => <IconDocxOutline16 size={size} />,
exts: ['docx'],
fetchStrategy: 'mediaUrl',
component: (props) => <LazyDocx {...props} />,
},
{
id: 'xlsx',
title: () => t('viewerXlsx'),
icon: (size: number) => <IconXlsxOutline16 size={size} />,
exts: ['xlsx'],
fetchStrategy: 'mediaUrl',
component: (props) => <LazyXlsx {...props} />,
},
{
id: 'pptx',
title: () => t('viewerPptx'),
icon: (size: number) => <IconPptxOutline16 size={size} />,
exts: ['pptx'],
fetchStrategy: 'mediaUrl',
component: (props) => <LazyPptx {...props} />,
},
{
id: 'markdown',
title: () => t('viewerMarkdown'),
+7 -5
View File
@@ -1,9 +1,11 @@
/**
* Lazy chunk loader for the client bundle. The heavy preview/terminal
* libraries (Univer, docx-preview, pptx-renderer, CodeMirror, xterm — the
* office/terminal/editor stacks, tens of MB) live in separate build-time
* bundles (`lib/client-<name>.js`) fetched only on first use of the feature
* that needs them, so startup downloads/parses only the ~1MB core bundle.
* libraries (CodeMirror, xterm — the editor/terminal stacks, several MB)
* live in separate build-time bundles (`lib/client-<name>.js`) fetched only
* on first use of the feature that needs them, so startup downloads/parses
* only the ~1MB core bundle. (The office stack — Univer / docx-preview /
* pptx-renderer — is no longer bundled here: Office previews moved to the
* recommended office plugin, see plugins-viewers.ts.)
*
* How a chunk script works (see tsdown.config.ts chunkBundle):
*
@@ -42,7 +44,7 @@
* open. Chunk-only source edits still need a manual page refresh (the HMR
* poll watches only client.js).
*/
export type ChunkName = 'docx' | 'xlsx' | 'pptx' | 'terminal' | 'editor'
export type ChunkName = 'terminal' | 'editor'
/** The module exports a chunk factory provides (namespace-ish record). */
export type ChunkExports = Record<string, unknown>
-8
View File
@@ -1,8 +0,0 @@
/**
* Lazy chunk entry: the .docx preview (docx-preview + jszip). Built as
* `lib/client-docx.js` and registered under `dsh-better-sidebar/docx` —
* fetched only when a .docx is first opened (see chunk-loader.ts and
* docs/plans/2026-08-12-lazy-chunks-design.md). Never import this module
* from the core bundle: it pulls the office library into the startup path.
*/
export { DocxView } from '../docx-view.tsx'
-8
View File
@@ -1,8 +0,0 @@
/**
* Lazy chunk entry: the .pptx preview (pptx-renderer). Built as
* `lib/client-pptx.js` and registered under `dsh-better-sidebar/pptx` —
* fetched only when a .pptx is first opened (see chunk-loader.ts and
* docs/plans/2026-08-12-lazy-chunks-design.md). Never import this module
* from the core bundle: it pulls the renderer into the startup path.
*/
export { PptxView } from '../PptxView.tsx'
-9
View File
@@ -1,9 +0,0 @@
/**
* Lazy chunk entry: the .xlsx preview (Univer family + SheetJS, several MB).
* Built as `lib/client-xlsx.js` and registered under
* `dsh-better-sidebar/xlsx` — fetched only when a .xlsx is first opened
* (see chunk-loader.ts and docs/plans/2026-08-12-lazy-chunks-design.md).
* Never import this module from the core bundle: it pulls Univer into the
* startup path.
*/
export { XlsxView } from '../xlsx-view.tsx'
-113
View File
@@ -1,113 +0,0 @@
/**
* The .docx preview component: renders via docx-preview (preserved
* styles/images/tables). Lives in its own module (split out of the former
* office-view.tsx) so it builds as a standalone lazy chunk
* (`lib/client-docx.js`) — the library is loaded only when a .docx is first
* opened, and never pulls in the Univer/xlsx stack.
*
* Errors degrade to the shared download-button affordance, so a corrupted /
* encrypted / oversized file always leaves the user with a way to get it.
*/
import { useEffect, useRef, useState } from 'react'
import { mediaUrl } from './api.ts'
import { t } from './locales.ts'
import { BinaryFallback, type LoadState, type OfficeViewProps } from './office-shared.tsx'
import css from './sidebar.module.css'
/**
* Render a .docx file via docx-preview. The library renders into a container
* div (no canvas); images and styles are inlined. Unmounting clears the
* container's innerHTML — docx-preview has no dispose API, but tearing down
* the DOM is enough.
*/
export function DocxView(props: OfficeViewProps): JSX.Element {
const { scope, path, title } = props
const viewportRef = useRef<HTMLDivElement>(null)
const wrapRef = useRef<HTMLDivElement>(null)
const [load, setLoad] = useState<LoadState>({ status: 'loading' })
const [zoom, setZoom] = useState(100)
useEffect(() => {
let cancelled = false
const container = viewportRef.current
const wrap = wrapRef.current
if (container === null || wrap === null) return
setZoom(100)
void (async () => {
try {
const response = await fetch(mediaUrl(scope, path))
if (cancelled) return
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const buf = await response.arrayBuffer()
if (cancelled) return
// docx-preview ships its own CSS through the className option; the
// wrapper div scopes its render output.
const { renderAsync } = await import('docx-preview')
await renderAsync(buf, wrap, undefined, {
className: 'docx',
inWrapper: true,
ignoreWidth: false,
ignoreHeight: false,
breakPages: true,
experimental: false,
})
if (!cancelled) setLoad({ status: 'ready' })
} catch (error) {
if (!cancelled) {
setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) })
}
}
})()
return () => {
cancelled = true
// Tear down the rendered DOM so a reopen starts clean.
if (wrap !== null) wrap.innerHTML = ''
}
}, [scope.sessionId, scope.cwd, path])
useEffect(() => {
const viewport = viewportRef.current
if (viewport === null) return
const onWheel = (event: WheelEvent): void => {
if (!event.altKey) return
event.preventDefault()
const delta = event.deltaY < 0 ? 10 : -10
setZoom(current => Math.max(50, Math.min(200, current + delta)))
}
viewport.addEventListener('wheel', onWheel, { passive: false })
return () => { viewport.removeEventListener('wheel', onWheel) }
}, [])
return (
<div className={css.editorDocx}>
<div className={css.editorDocxViewport} ref={viewportRef}>
{load.status === 'loading' && <div className={css.editorPlaceholder}>{t('loading')}</div>}
{load.status === 'error' && <BinaryFallback scope={scope} path={path} message={load.message} />}
{load.status !== 'error' && (
<div
className={css.editorDocxWrap}
ref={wrapRef}
aria-label={title}
style={{ zoom: zoom / 100 }}
/>
)}
</div>
<div className={css.editorDocxZoom}>
<span className={css.editorDocxZoomHint}>{t('zoomHint')}</span>
<input
className={css.editorDocxZoomRange}
type="range"
min={50}
max={200}
step={10}
value={zoom}
aria-label={t('zoom')}
onChange={(event) => { setZoom(Number(event.currentTarget.value)) }}
/>
<span className={css.editorDocxZoomValue}>{zoom}%</span>
</div>
</div>
)
}
-27
View File
@@ -83,33 +83,6 @@ export const IconPdfOutline16 = ({ size = 16, className }: IconProps) => (
</svg>
)
/** Word viewer glyph: a document frame with a "W". */
export const IconDocxOutline16 = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.5 1.5h6.5L13.5 5v9.5h-10z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
<path d="M9.5 1.5V5h4" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
<path d="M6.2 13.4 7.4 10l1.2 3.4M7.4 10.6l-.35-1.1c-.2-.62.2-1.25.85-1.25h.2c.65 0 1.05.63.85 1.25l-.35 1.1" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
<path d="M8.75 10.6 9.2 9.4" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
</svg>
)
/** Excel viewer glyph: a spreadsheet grid. */
export const IconXlsxOutline16 = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="1.5" y="2" width="13" height="12" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M1.5 6h13M1.5 9.5h13M6 6v8M10.5 6v8" stroke="currentColor" strokeWidth="1.25" />
<path d="m3.8 13.2 2-3M5.8 13.2l-2-3" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
</svg>
)
/** PowerPoint viewer glyph: a chart with rising bars. */
export const IconPptxOutline16 = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="1.5" y="2.5" width="13" height="11" rx="2" stroke="currentColor" strokeWidth="1.5" />
<path d="M4 12.5v-3M7 12.5V7M10 12.5V4.5M13 12.5v-1.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
)
/** Markdown viewer glyph: the classic "M with a down arrow" badge. */
export const IconMarkdownOutline16 = ({ size = 16, className }: IconProps) => (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+6 -5
View File
@@ -176,11 +176,12 @@ export function apply(ctx: Context): void {
// The IME guard: composition keys (candidate arrows, confirm, cancel)
// belong to the input method, never to page JS. Inlined third-party UI
// (Univer's office controls) has shipped unguarded keydown handlers that
// hijack ArrowUp/ArrowDown and break Chinese input (#562 regression); the
// document-capture guard neutralizes the whole class before React or any
// native listener sees the event. Registered as early as possible so no
// other capture-phase listener can win the ordering race.
// (formerly Univer's office controls, #562 regression) has shipped
// unguarded keydown handlers that hijack ArrowUp/ArrowDown and break
// Chinese input; the document-capture guard neutralizes the whole class
// before React or any native listener sees the event. Registered as
// early as possible so no other capture-phase listener can win the
// ordering race.
ctx.effect(
() => {
try {
+24 -22
View File
@@ -120,14 +120,6 @@ export const zh = {
settingsConflict: '设置已被其他窗口修改,请重试',
binaryNoPreview: '此文件类型不支持预览',
downloadToView: '下载查看',
officeTooLarge: '文件过大,无法预览',
officeCorrupt: '文件损坏或格式无效',
officeEncrypted: '不支持加密文件',
officeLoadFailed: 'Office 预览组件加载失败',
previousSlide: '上一页',
nextSlide: '下一页',
zoom: '缩放',
zoomHint: 'Alt + 滚轮',
settingsSubagentTitle: '检测到子代理时自动展开任务管理页',
settingsSubagentDesc: '当前会话产生新的子代理时,自动展开侧边栏并打开任务管理页;关闭后需手动打开',
settingsJobsTitle: '有新后台任务时自动展开后台任务页',
@@ -149,9 +141,6 @@ export const zh = {
settingsViewerCatchAll: '兜底:任意文件',
viewerImage: '图片',
viewerPdf: 'PDF',
viewerDocx: 'Word 文档',
viewerXlsx: 'Excel 表格',
viewerPptx: 'PPT 演示',
viewerMarkdown: 'Markdown',
viewerCode: '代码',
viewerBinary: '二进制下载',
@@ -217,6 +206,18 @@ export const zh = {
jobKill: '终止',
jobKillConfirm: '再次点击确认终止',
jobKillError: '终止失败',
addPluginsTabCard: '添加 Tab 插件',
addPluginsTabCardDesc: '注册新的侧边栏页面',
addPluginsViewerCard: '添加预览插件',
addPluginsViewerCardDesc: '注册新的文件类型预览',
addPluginsTabDesc: '侧边栏页面(Tab)可以由插件扩展。插件通过 ctx.betterSidebar 服务注册;点击「安装」复制安装命令,粘贴到 DSH 所在环境的终端执行。',
addPluginsViewerDesc: '文件预览器可以由插件扩展。插件通过 ctx.betterSidebar 服务注册;点击「安装」复制安装命令,粘贴到 DSH 所在环境的终端执行。',
addPluginsBrowseMore: '在 GitHub 上浏览更多插件(topic: dsh-better-sidebar)',
addPluginsRecommended: '推荐插件',
addPluginsEmpty: '暂未收录插件,欢迎在 GitHub topic 下发布你的插件',
openPlugin: '跳转',
copyInstall: '复制安装命令',
pluginOfficeDesc: '为 better-sidebar 编辑器提供 Office 三件套预览(.docx / .xlsx / .pptx),把重型 Office 渲染库拆出主包、按需安装',
}
/** The en dictionary (key-set-equal to zh, enforced by the type annotation). */
@@ -330,14 +331,6 @@ export const en: Record<keyof typeof zh, string> = {
settingsConflict: 'The setting changed in another window — please retry',
binaryNoPreview: 'This file type cannot be previewed',
downloadToView: 'Download to view',
officeTooLarge: 'File too large to preview',
officeCorrupt: 'File is corrupt or in an invalid format',
officeEncrypted: 'Encrypted files are not supported',
officeLoadFailed: 'Office preview component failed to load',
previousSlide: 'Previous',
nextSlide: 'Next',
zoom: 'Zoom',
zoomHint: 'Alt + wheel',
settingsSubagentTitle: 'Auto-open the Tasks page when a subagent appears',
settingsSubagentDesc: 'Expand the side card and open the Tasks page when the current conversation spawns a new subagent; turn off to open it manually',
settingsJobsTitle: 'Auto-open the Jobs page on a new background job',
@@ -359,9 +352,6 @@ export const en: Record<keyof typeof zh, string> = {
settingsViewerCatchAll: 'Catch-all: any file',
viewerImage: 'Image',
viewerPdf: 'PDF',
viewerDocx: 'Word',
viewerXlsx: 'Excel',
viewerPptx: 'PowerPoint',
viewerMarkdown: 'Markdown',
viewerCode: 'Code',
viewerBinary: 'Binary download',
@@ -427,6 +417,18 @@ export const en: Record<keyof typeof zh, string> = {
jobKill: 'Kill',
jobKillConfirm: 'Click again to confirm kill',
jobKillError: 'Kill failed',
addPluginsTabCard: 'Add tab plugins',
addPluginsTabCardDesc: 'Register a new sidebar page',
addPluginsViewerCard: 'Add preview plugins',
addPluginsViewerCardDesc: 'Register a file-type preview',
addPluginsTabDesc: 'Sidebar pages (tabs) can be extended by plugins. Plugins register through the ctx.betterSidebar service; clicking Install copies the install command — paste it into a terminal where your DSH profile lives and run it.',
addPluginsViewerDesc: 'File previewers can be extended by plugins. Plugins register through the ctx.betterSidebar service; clicking Install copies the install command — paste it into a terminal where your DSH profile lives and run it.',
addPluginsBrowseMore: 'Browse more plugins on GitHub (topic: dsh-better-sidebar)',
addPluginsRecommended: 'Recommended plugins',
addPluginsEmpty: 'No plugins curated yet — publish yours under the GitHub topic',
openPlugin: 'Open',
copyInstall: 'Copy install command',
pluginOfficeDesc: 'Office-suite preview (.docx / .xlsx / .pptx) for the better-sidebar editor, keeping the heavy Office render libraries out of the core bundle',
}
/**
-40
View File
@@ -1,40 +0,0 @@
/**
* Shared pieces of the Office preview views (docx / xlsx): the load-state
* union, the shared props, and the download fallback. The two views live in
* their own modules (docx-view.tsx / xlsx-view.tsx) so the bundler can emit
* them as separate lazy chunks — docx-preview and the Univer family (several
* MB) must never share a script (see docs/plans/2026-08-12-lazy-chunks-design.md).
*/
import { downloadUrl, type SessionScope } from './api.ts'
import { t } from './locales.ts'
import css from './sidebar.module.css'
/** Loading / ready / error state shared by both views. */
export type LoadState =
| { status: 'loading' }
| { status: 'ready' }
| { status: 'error'; message: string }
/** Shared props. */
export interface OfficeViewProps {
scope: SessionScope
path: string
title: string
}
/**
* The shared error / fallback affordance: the failure reason plus a download
* link, so the user always has a path to the file. Used by both DocxView and
* XlsxView, and matches the binary placeholder download link.
*/
export function BinaryFallback(props: { scope: SessionScope; path: string; message: string }): JSX.Element {
const { scope, path, message } = props
return (
<div className={css.editorBinary}>
<span className={css.editorBinaryNotice}>{message}</span>
<a className={css.editorDownloadLink} href={downloadUrl(scope, path)} download>
{t('downloadToView')}
</a>
</div>
)
}
-48
View File
@@ -1,48 +0,0 @@
/**
* Office file type dispatch — pure functions mapping file extensions to
* preview kinds. Kept separate from the editor host so the mapping is
* unit-testable without mounting React or pulling in docx-preview / Univer.
*
* The host side never inspects Office extensions: the binary NUL probe in
* {@link ../index.ts} (readText) tags every Office file as binary, and the
* /sidebar/file media route serves raw bytes for any extension. This module
* is the client's sole source of truth for "is this previewable here".
*/
/** Extensions rendered with docx-preview (preserved styles/images/tables). */
export const OFFICE_DOCX_EXT = '.docx' as const
/** Extensions rendered with Univer (sheets: data + formulas + formatting). */
export const OFFICE_XLSX_EXT = '.xlsx' as const
/** Extensions rendered with the browser-native PPTX viewer. */
export const OFFICE_PPTX_EXT = '.pptx' as const
/** Extensions that get a download-only affordance (no client-side renderer). */
export const OFFICE_DOWNLOAD_ONLY_EXT = ['.doc', '.xls', '.ppt'] as readonly string[]
/**
* The preview strategy for one path's extension.
* - `'docx'` — render via docx-preview.
* - `'xlsx'` — render via Univer.
* - `'pptx'` — render via pptx-renderer.
* - `'download-only'` — show the binary download button (no preview renderer
* covers legacy OLE .doc/.xls/.ppt on the client).
* - `null` — not an Office file; the caller's existing image / md / text / binary
* pipeline handles it.
*/
export type OfficeKind = 'docx' | 'xlsx' | 'pptx' | 'download-only' | null
/**
* Map a lowercased extension (with leading dot) to its preview kind.
*
* @param ext - the path extension (with leading dot) (`.docx`,
* `.xlsx`, `.pptx`, `.doc`, `.xls`, `.ppt`, …); `''` when the path has none.
*/
export function officeKindForExt(ext: string): OfficeKind {
if (ext === OFFICE_DOCX_EXT) return 'docx'
if (ext === OFFICE_XLSX_EXT) return 'xlsx'
if (ext === OFFICE_PPTX_EXT) return 'pptx'
if (OFFICE_DOWNLOAD_ONLY_EXT.includes(ext)) return 'download-only'
return null
}
-12
View File
@@ -1,12 +0,0 @@
/**
* Compat re-export shim for the historical `src/client/office-view.tsx`
* path. The office preview views were split into docx-view.tsx /
* xlsx-view.tsx (+ office-shared.tsx) so the bundler can emit each library
* as its own lazy chunk (see docs/plans/2026-08-12-lazy-chunks-design.md).
* This module keeps deep imports of this path resolvable through the
* `./src/*` exports subpath — it deliberately re-exports BOTH views, so it
* must never be imported from the core bundle or a chunk entry (it would
* drag both libraries into that bundle).
*/
export { DocxView } from './docx-view.tsx'
export { XlsxView } from './xlsx-view.tsx'
+26
View File
@@ -0,0 +1,26 @@
/**
* Shared vocabulary of the recommended plugin catalogs: the entry shape and
* the GitHub topic URL. The two catalogs live in sibling modules —
* `plugins-tabs.ts` (tab registrations) and `plugins-viewers.ts` (file
* previewer registrations) — and are shown in the two "add plugin" modals
* (Side card settings → the dashed cards at the end of the 侧边栏内容 /
* 文件预览 grids).
*/
/** The GitHub topic page listing every repo tagged `dsh-better-sidebar`. */
export const PLUGIN_TOPIC_URL = 'https://github.com/topics/dsh-better-sidebar'
/** One curated plugin entry (name / url / description / install script). */
export interface PluginEntry {
/** Unique id (the npm package name). */
id: string
/** Short display name. */
name: string
/** GitHub repository URL. */
url: string
/** One-line description (i18n friendly: string or () => string). */
description: string | (() => string)
/** The full shell command pre-filled into the install terminal (not
* executed until the user presses Enter). */
install: string
}
+15
View File
@@ -0,0 +1,15 @@
/**
* The built-in catalog of TAB-registration plugins (sidebar pages),
* shown in the "add tab plugin" modal (Side card settings → 侧边栏内容 grid
* → the dashed card). Adding an entry: append one object here (unique
* `id` = npm package name, `url` = GitHub repo, `description` =
* i18n-friendly, `install` = the full shell command pre-filled into the
* install terminal — it starts with `cd ~/.dsh` so the install runs with
* the DSH home as the working directory). Data integrity is guarded by
* `tests/plugin-list.spec.ts`.
*/
import type { PluginEntry } from './plugins-shared.ts'
/** Tab-registration plugins (empty until a real one exists — the modal
* renders the empty state and points at the GitHub topic). */
export const builtinTabPlugins: readonly PluginEntry[] = []
+23
View File
@@ -0,0 +1,23 @@
/**
* The built-in catalog of FILE-PREVIEWER plugins (file-type previewers),
* shown in the "add preview plugin" modal (Side card settings → 文件预览
* grid → the dashed card). Adding an entry: append one object here (unique
* `id` = npm package name, `url` = GitHub repo, `description` =
* i18n-friendly, `install` = the full shell command pre-filled into the
* install terminal — it starts with `cd ~/.dsh` so the install runs with
* the DSH home as the working directory). Data integrity is guarded by
* `tests/plugin-list.spec.ts`.
*/
import { t } from './locales.ts'
import type { PluginEntry } from './plugins-shared.ts'
/** File-previewer plugins (alphabetical order). */
export const builtinViewerPlugins: readonly PluginEntry[] = [
{
id: '@huanlin/dsh-plugin-better-sidebar-plugin-office',
name: 'Office 预览插件',
url: 'https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-office',
description: () => t('pluginOfficeDesc'),
install: 'cd ~/.dsh && dsh plugin --profile web add @huanlin/dsh-plugin-better-sidebar-plugin-office',
},
]
+1 -145
View File
@@ -772,7 +772,7 @@
overflow-wrap: anywhere;
}
/* Binary / download-only files (pptx, OLE .doc/.xls/.ppt, unknown binaries):
/* Binary / download-only files (legacy OLE .doc/.xls/.ppt, unknown binaries):
a centered notice plus a download link — the user always gets the file. */
.editorBinary {
flex: 1;
@@ -1108,62 +1108,6 @@
background: var(--dsw-alias-interactive-bg-hover);
}
/* Word preview: the document scrolls independently while the zoom control
stays pinned to the bottom edge. */
.editorDocx {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
background: var(--dsw-alias-bg-base);
}
.editorDocxViewport {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: auto;
background: var(--dsw-alias-bg-base);
}
/* docx-preview renders into a wrapper div with .docx className; the host
above scrolls while the wrapper holds the page flow. */
.editorDocxWrap {
flex: none;
padding: 16px;
}
.editorDocxZoom {
flex: none;
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 4px 10px;
border-top: 1px solid var(--dsw-alias-border-l1);
background: var(--dsw-alias-bg-layer-1);
}
.editorDocxZoomHint,
.editorDocxZoomValue {
flex: none;
font: var(--dsw-font-xxxs-11);
color: var(--dsw-alias-label-tertiary);
}
.editorDocxZoomValue {
width: 36px;
text-align: right;
}
.editorDocxZoomRange {
flex: 1;
min-width: 72px;
accent-color: var(--dsw-alias-brand-primary);
cursor: pointer;
}
.editorPdf {
flex: 1;
min-height: 0;
@@ -1222,94 +1166,6 @@
pointer-events: auto !important;
}
.editorXlsx {
position: relative;
flex: 1;
min-height: 0;
overflow: hidden;
background: var(--dsw-alias-bg-base);
}
.editorUniverHost {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
}
.editorOfficeOverlay {
position: absolute;
inset: 0;
z-index: 2;
display: flex;
background: var(--dsw-alias-bg-base);
}
.editorPptx {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
background: var(--dsw-alias-bg-base);
}
.editorPptxToolbar {
flex: none;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 6px 8px;
border-bottom: 1px solid var(--dsw-alias-border-l1);
}
.editorPptxToolbar .editorDownloadLink {
margin-left: auto;
}
.editorPptxButton {
height: 28px;
padding: 0 10px;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 6px;
background: var(--dsw-alias-bg-layer-2);
color: var(--dsw-alias-label-secondary);
font: var(--dsw-font-xxs-strong-12);
cursor: pointer;
}
.editorPptxButton:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
}
.editorPptxButton:disabled {
opacity: 0.4;
cursor: default;
}
.editorPptxPosition {
min-width: 64px;
text-align: center;
font: var(--dsw-font-xxs-12);
color: var(--dsw-alias-label-tertiary);
}
.editorPptxStage {
position: relative;
flex: 1;
min-height: 0;
overflow: hidden;
}
.editorPptxHost {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
overflow: auto;
}
/* ── Terminal ──────────────────────────────────────────────────────────── */
.terminalWrap {
-260
View File
@@ -1,260 +0,0 @@
/**
* Convert a SheetJS (xlsx) workbook into Univer's {@link IWorkbookData} so
* {@link XlsxView} can render it through the Univer sheets preset.
*
* v1 scope (matches docs/plans/2026-08-10-office-preview-design.md §3.6):
* - Sheet names + order
* - Cell values, typed (string / number / boolean / error → force-string)
* - Cell formulas (text form; Univer's formula engine computes them)
* - Merged cells (!merges → mergeData)
* - Column widths (!cols → columnData) and row heights (!rows → rowData)
*
* Out of scope for v1 (SheetJS community edition does not parse them and the
* Pro edition is commercial): cell styles (font/fill/border/alignment),
* conditional formatting, charts. Users who need style fidelity get the
* download button on the binary placeholder.
*
* The function is pure (no DOM, no Univer imports) so it is unit-testable
* without jsdom or canvas.
*/
import type * as XLSX from 'xlsx'
// Types come from @univerjs/presets (which re-exports @univerjs/core's type
// surface). The enum values BooleanNumber / CellValueType are imported as
// runtime values from the same module — the bundler inlines them, and the
// test environment has @univerjs/presets available as a dependency.
import { BooleanNumber, CellValueType, type LocaleType, type ICellData, type IColumnData, type IRowData, type IWorkbookData, type IWorksheetData, type IObjectArrayPrimitiveType, type IObjectMatrixPrimitiveType, type IRange } from '@univerjs/presets'
/** SheetJS workbook (the slice of the module we use). */
type XLSXWorkbook = XLSX.WorkBook
/**
* Build a Univer workbook snapshot from a SheetJS workbook.
*
* @param wb - the parsed workbook from `XLSX.read(buf, { type: 'array' })`
* @param appVersion - the Univer package version, written into `appVersion`
* (Univer requires the field but does not gate on it).
* @param locale - the locale Univer should render in.
*/
export function xlsxWorkbookToUniver(
wb: XLSXWorkbook,
appVersion: string,
locale: LocaleType,
): IWorkbookData {
const sheetOrder: string[] = []
const sheets: Record<string, Partial<IWorksheetData>> = {}
wb.SheetNames.forEach((name, index) => {
const sheetId = `sheet-${index}`
sheetOrder.push(sheetId)
sheets[sheetId] = worksheetToUniver(wb.Sheets[name] ?? {}, name, sheetId)
})
// Univer requires at least one sheet; an empty workbook gets a placeholder.
if (sheetOrder.length === 0) {
const fallbackId = 'sheet-0'
sheetOrder.push(fallbackId)
sheets[fallbackId] = {
id: fallbackId,
name: 'Sheet1',
rowCount: 20,
columnCount: 26,
cellData: {},
rowData: {},
columnData: {},
mergeData: [],
}
}
return {
id: 'workbook',
name: wb.Props?.Title || 'Workbook',
appVersion,
locale,
styles: {},
sheetOrder,
sheets,
}
}
/** Convert one SheetJS worksheet to a Univer IWorksheetData. */
function worksheetToUniver(
ws: XLSX.WorkSheet,
name: string,
sheetId: string,
): Partial<IWorksheetData> {
const cellData: IObjectMatrixPrimitiveType<ICellData> = {}
const merges: IRange[] = []
// Cell values + formulas: iterate every cell address (skip the !-prefixed
// special keys SheetJS uses for sheet-level metadata).
for (const addr of Object.keys(ws)) {
if (addr.startsWith('!')) continue
const cell = ws[addr] as XLSX.CellObject | undefined
if (cell === undefined) continue
const { r, c } = decodeAddr(addr)
const converted = convertCell(cell)
if (converted === null) continue
let row = cellData[r]
if (row === undefined) {
row = {}
cellData[r] = row
}
row[c] = converted
}
// Merged cells: SheetJS's Range uses { s: { r, c }, e: { r, c } } (0-indexed),
// which is exactly Univer's IRange shape — copy verbatim.
if (Array.isArray(ws['!merges'])) {
for (const m of ws['!merges']!) {
if (m === undefined || m === null) continue
merges.push({ startRow: m.s.r, endRow: m.e.r, startColumn: m.s.c, endColumn: m.e.c })
}
}
const { rowCount, columnCount } = dimensions(ws, cellData)
return {
id: sheetId,
name,
tabColor: '',
hidden: BooleanNumber.FALSE,
freeze: { startRow: -1, startColumn: -1, xSplit: 0, ySplit: 0 },
rowCount,
columnCount,
defaultColumnWidth: 96,
defaultRowHeight: 22,
mergeData: merges,
cellData,
rowData: convertRows(ws['!rows']),
columnData: convertCols(ws['!cols']),
rowHeader: { width: 46 },
columnHeader: { height: 20 },
showGridlines: BooleanNumber.TRUE,
rightToLeft: BooleanNumber.FALSE,
}
}
/** Map a SheetJS CellObject onto Univer's ICellData (or null for empty). */
function convertCell(cell: XLSX.CellObject): ICellData | null {
const out: ICellData = {}
// Type mapping: b→BOOLEAN, n→NUMBER, s→STRING, d→STRING, e→FORCE_STRING, z→skip
switch (cell.t) {
case 'b':
out.t = CellValueType.BOOLEAN
out.v = cell.v === true
break
case 'n':
out.t = CellValueType.NUMBER
out.v = typeof cell.v === 'number' ? cell.v : Number(cell.v)
break
case 'e':
// Excel error strings like #REF! — display verbatim, no formula engine.
out.t = CellValueType.FORCE_STRING
out.v = String(cell.w ?? cell.v ?? '')
break
case 's':
case 'd':
case 'z':
default:
// String / date / stub. SheetJS renders dates as ISO strings in `w`
// when cellDates is on; otherwise `v` is the serial number. Use `w`
// (formatted text) when present so users see what Excel showed.
out.t = CellValueType.STRING
out.v = cell.w ?? (cell.v !== undefined ? String(cell.v) : '')
break
}
// Formula: keep as text; Univer's formula engine computes on load.
if (typeof cell.f === 'string' && cell.f !== '') {
out.f = cell.f
}
return out
}
/** Convert SheetJS `!cols` (ColInfo[]) to Univer columnData (sparse, by index). */
function convertCols(cols: XLSX.ColInfo[] | undefined): IObjectArrayPrimitiveType<Partial<IColumnData>> {
if (!Array.isArray(cols)) return {}
const out: IObjectArrayPrimitiveType<Partial<IColumnData>> = {}
cols.forEach((info, index) => {
if (info === undefined || info === null) return
const w = info.wpx ?? (info.width !== undefined ? Math.round(info.width * 7) : undefined)
out[index] = {
...(w !== undefined ? { w } : {}),
...(info.hidden === true ? { hd: BooleanNumber.TRUE } : {}),
}
})
return out
}
/** Convert SheetJS `!rows` (RowInfo[]) to Univer rowData (sparse, by index). */
function convertRows(rows: XLSX.RowInfo[] | undefined): IObjectArrayPrimitiveType<Partial<IRowData>> {
if (!Array.isArray(rows)) return {}
const out: IObjectArrayPrimitiveType<Partial<IRowData>> = {}
rows.forEach((info, index) => {
if (info === undefined || info === null) return
const h = info.hpx ?? info.hpt
out[index] = {
...(h !== undefined ? { h: Math.round(h) } : {}),
...(info.hidden === true ? { hd: BooleanNumber.TRUE } : {}),
}
})
return out
}
/**
* Resolve the worksheet dimensions. SheetJS's `!ref` is authoritative when
* present; otherwise fall back to the max row/col we actually wrote, with a
* small floor so the canvas has somewhere to paint.
*/
function dimensions(
ws: XLSX.WorkSheet,
cellData: IObjectMatrixPrimitiveType<ICellData>,
): { rowCount: number; columnCount: number } {
const ref = ws['!ref']
if (typeof ref === 'string' && ref !== '') {
const range = decodeRange(ref)
return {
rowCount: Math.max(range.endRow + 1, 20),
columnCount: Math.max(range.endColumn + 1, 10),
}
}
let maxRow = -1
let maxCol = -1
for (const r of Object.keys(cellData)) {
const rowNum = Number(r)
if (rowNum > maxRow) maxRow = rowNum
const rowObj = cellData[rowNum]!
for (const c of Object.keys(rowObj)) {
const colNum = Number(c)
if (colNum > maxCol) maxCol = colNum
}
}
return {
rowCount: Math.max(maxRow + 1, 20),
columnCount: Math.max(maxCol + 1, 10),
}
}
/** Decode an A1-style address (e.g. "AB12") to 0-indexed {row, col}. */
function decodeAddr(addr: string): { r: number; c: number } {
let col = 0
let i = 0
while (i < addr.length) {
const ch = addr.charCodeAt(i)
if (ch >= 65 && ch <= 90) {
col = col * 26 + (ch - 64)
i += 1
} else {
break
}
}
const row = Number(addr.slice(i)) - 1
return { r: row, c: col - 1 }
}
/** Decode an A1-style range (e.g. "A1:AB12") to 0-indexed bounds. */
function decodeRange(range: string): { startRow: number; endRow: number; startColumn: number; endColumn: number } {
const at = range.indexOf(':')
const start = decodeAddr(at === -1 ? range : range.slice(0, at))
const end = at === -1 ? start : decodeAddr(range.slice(at + 1))
return { startRow: start.r, endRow: end.r, startColumn: start.c, endColumn: end.c }
}
-116
View File
@@ -1,116 +0,0 @@
/**
* The .xlsx preview component: renders via the Univer sheets preset (data +
* formulas + formatting). Lives in its own module (split out of the former
* office-view.tsx) so it builds as a standalone lazy chunk
* (`lib/client-xlsx.js`) — the Univer family and SheetJS pull in several MB
* but are loaded only when a .xlsx is first opened. The docx stack never
* shares this script.
*
* Errors degrade to the shared download-button affordance, so a corrupted /
* encrypted / oversized file always leaves the user with a way to get it.
*/
import { useEffect, useRef, useState } from 'react'
import { mediaUrl } from './api.ts'
import { isZh, t } from './locales.ts'
import { BinaryFallback, type LoadState, type OfficeViewProps } from './office-shared.tsx'
import { xlsxWorkbookToUniver } from './xlsx-to-univer.ts'
import css from './sidebar.module.css'
// Univer's stylesheets ride the same dsh-css-inline pipeline as xterm's CSS
// (one <style data-plugin-css> tag, idempotent). Static import so the styles
// are present before the first .xlsx opens.
import '@univerjs/preset-sheets-core/lib/index.css'
/**
* Render a .xlsx file via Univer. The sheets preset creates a canvas-based
* spreadsheet (formula bar, sheet tabs, formula engine) sized to its
* container, so the host fills the pane. Unmounting calls `univer.dispose()`
* — without it the canvas, workers, and DOM listeners leak (mirrors the
* xterm dispose discipline in TerminalView).
*/
export function XlsxView(props: OfficeViewProps): JSX.Element {
const { scope, path, title } = props
const hostRef = useRef<HTMLDivElement>(null)
const univerRef = useRef<{ dispose: () => void } | null>(null)
const [load, setLoad] = useState<LoadState>({ status: 'loading' })
useEffect(() => {
let cancelled = false
const host = hostRef.current
if (host === null) return
void (async () => {
try {
const response = await fetch(mediaUrl(scope, path))
if (cancelled) return
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const buf = await response.arrayBuffer()
if (cancelled) return
// Dynamic imports — collapsed into the chunk by codeSplitting:false.
// The dynamic form keeps the source readable: each lib is only pulled
// in when an .xlsx is actually opened (semantically; the chunk still
// contains all of them — the chunk itself only loads on first .xlsx).
const XLSX = await import('xlsx')
const { createUniver, LocaleType, mergeLocales } = await import('@univerjs/presets')
const { UniverSheetsCorePreset } = await import('@univerjs/preset-sheets-core')
// Locales follow the DSH i18n system (the active locale); falls
// back to the browser language, then en-US.
const localePack = await (isZh()
? import('@univerjs/preset-sheets-core/locales/zh-CN').then(m => m.default).catch(() => null)
: import('@univerjs/preset-sheets-core/locales/en-US').then(m => m.default).catch(() => null))
const wb = XLSX.read(buf, { type: 'array' })
const locale = isZh() ? LocaleType.ZH_CN : LocaleType.EN_US
const workbookData = xlsxWorkbookToUniver(wb, '0.25.1', locale)
if (cancelled) return
const { univer, univerAPI } = createUniver({
locale,
locales: localePack !== null ? { [locale]: mergeLocales(localePack) } : {},
presets: [UniverSheetsCorePreset({ container: host })],
})
univerRef.current = univer
univerAPI.createWorkbook(workbookData)
if (!cancelled) setLoad({ status: 'ready' })
} catch (error) {
if (!cancelled) {
try {
univerRef.current?.dispose()
} catch {
// Partially initialized instance — ignore disposal errors.
}
univerRef.current = null
host.innerHTML = ''
setLoad({ status: 'error', message: error instanceof Error ? error.message : String(error) })
}
}
})()
return () => {
cancelled = true
// Critical: dispose the Univer instance (canvas + workers + listeners).
try {
univerRef.current?.dispose()
} catch {
// Already torn down — ignore.
}
univerRef.current = null
// Clear the host in case dispose left DOM behind.
if (host !== null) host.innerHTML = ''
}
}, [scope.sessionId, scope.cwd, path])
return (
<div className={css.editorXlsx} aria-label={title}>
{/* Univer exclusively owns this element's descendants. React only owns
the sibling overlay, so Univer cannot remove a React child. */}
<div className={css.editorUniverHost} ref={hostRef} />
{load.status !== 'ready' && (
<div className={css.editorOfficeOverlay}>
{load.status === 'loading' && <div className={css.editorPlaceholder}>{t('loading')}</div>}
{load.status === 'error' && <BinaryFallback scope={scope} path={path} message={load.message} />}
</div>
)}
</div>
)
}