🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(portal): turn the local-file preview into a usable code editor (#19379)
Arvin Xuab9a788582b6
diff --git a/locales/en-US/components.json b/locales/en-US/components.jsonindex 0d05db4655e..9e9aec1995d 100644--- a/locales/en-US/components.json+++ b/locales/en-US/components.json@@ -2,6 +2,14 @@"ArgsInput.addArgument": "Add Argument","ArgsInput.argumentPlaceholder": "Argument {{index}}","ArgsInput.enterFirstArgument": "Enter first argument...",+ "CodeEditorPane.cursor": "Ln {{line}}, Col {{column}}",+ "CodeEditorPane.readOnly": "Read-only",+ "CodeEditorPane.selected": "({{length}} selected)",+ "CodeEditorPane.spaces": "Spaces: {{size}}",+ "CodeEditorPane.tabSize": "Tab Size: {{size}}",+ "CodeEditorPane.toggleWordWrap": "Toggle word wrap",+ "CodeEditorPane.wrapOff": "No Wrap",+ "CodeEditorPane.wrapOn": "Wrap","DragUpload.dragDesc": "Drag and drop files here to upload multiple images.","DragUpload.dragFileDesc": "Drag and drop images and files here to upload multiple images and files.","DragUpload.dragFileTitle": "Upload Files",diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.jsonindex 4882ec1873e..a9ae349606d 100644--- a/locales/zh-CN/components.json+++ b/locales/zh-CN/components.json@@ -2,6 +2,14 @@"ArgsInput.addArgument": "添加参数","ArgsInput.argumentPlaceholder": "参数 {{index}}","ArgsInput.enterFirstArgument": "输入第一个参数…",+ "CodeEditorPane.cursor": "第 {{line}} 行,第 {{column}} 列",+ "CodeEditorPane.readOnly": "只读",+ "CodeEditorPane.selected": "(已选 {{length}})",+ "CodeEditorPane.spaces": "空格:{{size}}",+ "CodeEditorPane.tabSize": "制表符:{{size}}",+ "CodeEditorPane.toggleWordWrap": "切换自动换行",+ "CodeEditorPane.wrapOff": "不换行",+ "CodeEditorPane.wrapOn": "自动换行","DragUpload.dragDesc": "拖拽文件到这里,支持上传多个图片。","DragUpload.dragFileDesc": "拖拽图片和文件到这里,支持上传多个图片和文件。","DragUpload.dragFileTitle": "上传文件",diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.tsindex 68f4a0fbea1..692d5de4352 100644--- a/packages/locales/src/default/components.ts+++ b/packages/locales/src/default/components.ts@@ -2,6 +2,14 @@ export default {'ArgsInput.addArgument': 'Add Argument','ArgsInput.argumentPlaceholder': 'Argument {{index}}','ArgsInput.enterFirstArgument': 'Enter first argument...',+ 'CodeEditorPane.cursor': 'Ln {{line}}, Col {{column}}',+ 'CodeEditorPane.readOnly': 'Read-only',+ 'CodeEditorPane.selected': '({{length}} selected)',+ 'CodeEditorPane.spaces': 'Spaces: {{size}}',+ 'CodeEditorPane.tabSize': 'Tab Size: {{size}}',+ 'CodeEditorPane.toggleWordWrap': 'Toggle word wrap',+ 'CodeEditorPane.wrapOff': 'No Wrap',+ 'CodeEditorPane.wrapOn': 'Wrap','DragUpload.dragDesc': 'Drag and drop files here to upload multiple images.','DragUpload.dragFileDesc':'Drag and drop images and files here to upload multiple images and files.',diff --git a/src/components/CodeEditorPane/StatusBar.tsx b/src/components/CodeEditorPane/StatusBar.tsxnew file mode 100644index 00000000000..59058d2302a--- /dev/null+++ b/src/components/CodeEditorPane/StatusBar.tsx@@ -0,0 +1,117 @@+'use client';++import { Flexbox, Tooltip } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { useTranslation } from 'react-i18next';++import type { IndentStyle } from './indent';++const styles = createStaticStyles(({ css }) => ({+ bar: css`+ flex-shrink: 0;++ height: 24px;+ padding-inline: 10px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};++ font-size: 11px;+ line-height: 1;+ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorBgContainer};+ `,+ button: css`+ cursor: pointer;++ height: 18px;+ padding-inline: 6px;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ font-size: 11px;+ line-height: 1;+ color: inherit;+ white-space: nowrap;++ background: none;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ item: css`+ padding-inline: 6px;+ white-space: nowrap;+ `,+ readOnly: css`+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadiusSM};+ color: ${cssVar.colorTextSecondary};+ background: ${cssVar.colorFillTertiary};+ `,+}));++export interface CursorPosition {+ column: number;+ line: number;+ /** Characters covered by the current selection; 0 when it is just a caret. */+ selectionLength: number;+}++interface StatusBarProps {+ cursor?: CursorPosition;+ indent: IndentStyle;+ languageLabel: string;+ lineWrapping: boolean;+ onLineWrappingChange: (next: boolean) => void;+ readOnly?: boolean;+}++const StatusBar = ({+ cursor,+ indent,+ languageLabel,+ lineWrapping,+ onLineWrappingChange,+ readOnly,+}: StatusBarProps) => {+ const { t } = useTranslation('components');++ return (+ <Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>+ <Flexbox horizontal align={'center'}>+ {readOnly && <span className={styles.readOnly}>{t('CodeEditorPane.readOnly')}</span>}+ </Flexbox>+ <Flexbox horizontal align={'center'}>+ {cursor && (+ <span className={styles.item}>+ {t('CodeEditorPane.cursor', { column: cursor.column, line: cursor.line })}+ {cursor.selectionLength > 0 &&+ ` ${t('CodeEditorPane.selected', { length: cursor.selectionLength })}`}+ </span>+ )}+ <span className={styles.item}>+ {t(indent.useTabs ? 'CodeEditorPane.tabSize' : 'CodeEditorPane.spaces', {+ size: indent.size,+ })}+ </span>+ <Tooltip title={t('CodeEditorPane.toggleWordWrap')}>+ <button+ aria-pressed={lineWrapping}+ className={styles.button}+ type={'button'}+ onClick={() => onLineWrappingChange(!lineWrapping)}+ >+ {t(lineWrapping ? 'CodeEditorPane.wrapOn' : 'CodeEditorPane.wrapOff')}+ </button>+ </Tooltip>+ <span className={styles.item}>{languageLabel}</span>+ </Flexbox>+ </Flexbox>+ );+};++StatusBar.displayName = 'StatusBar';++export default StatusBar;diff --git a/src/components/CodeEditorPane/indent.test.ts b/src/components/CodeEditorPane/indent.test.tsnew file mode 100644index 00000000000..3f8d435e458--- /dev/null+++ b/src/components/CodeEditorPane/indent.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';++import { detectIndentStyle } from './indent';++describe('detectIndentStyle', () => {+ it('detects two-space indentation', () => {+ const content = ['const a = {', ' b: 1,', ' c: {', ' d: 2,', ' },', '};'].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 2, useTabs: false });+ });++ it('detects four-space indentation from nested levels', () => {+ const content = [+ 'def outer():',+ ' if True:',+ ' for i in range(3):',+ ' print(i)',+ ' return 1',+ ].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 4, useTabs: false });+ });++ it('detects tabs', () => {+ const content = ['func main() {', '\tif true {', '\t\tprintln("hi")', '\t}', '}'].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 4, useTabs: true });+ });++ it('falls back to two spaces when a file has no indentation', () => {+ expect(detectIndentStyle('one\ntwo\nthree')).toEqual({ size: 2, useTabs: false });+ expect(detectIndentStyle('')).toEqual({ size: 2, useTabs: false });+ });++ it('ignores whitespace-only lines', () => {+ const content = ['a', ' ', ' b', ' ', ' c'].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 2, useTabs: false });+ });++ it('ignores the one-space alignment of block-comment continuation lines', () => {+ // The asterisks of a JSDoc block sit one column in. Before this was+ // excluded, four such lines outvoted the file's real two-space steps.+ const content = [+ '/**',+ ' * Resolve the editor grammar for a file.',+ ' * Falls back to plain text.',+ ' */',+ 'const MODES = new Set([',+ " 'go',",+ " 'rust',",+ ']);',+ '',+ '/** Another block. */',+ 'export const run = () => {',+ ' return MODES;',+ '};',+ ].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 2, useTabs: false });+ });++ it('ignores deep continuation alignment', () => {+ const content = [+ 'call(',+ ' aligned,',+ ' alsoAligned,',+ ')',+ ].join('\n');++ expect(detectIndentStyle(content)).toEqual({ size: 2, useTabs: false });+ });+});diff --git a/src/components/CodeEditorPane/indent.ts b/src/components/CodeEditorPane/indent.tsnew file mode 100644index 00000000000..eb41f5f0ab6--- /dev/null+++ b/src/components/CodeEditorPane/indent.ts@@ -0,0 +1,69 @@+export interface IndentStyle {+ size: number;+ useTabs: boolean;+}++const DEFAULT_INDENT: IndentStyle = { size: 2, useTabs: false };++const SAMPLE_LINE_LIMIT = 400;++const BLOCK_COMMENT_CONTINUATION = /^\s*\*/;++/**+ * Infer a file's own indentation so the editor reports it and the Tab key+ * matches what is already on disk, instead of forcing one project-wide guess.+ *+ * Counts how often each indentation *step* occurs — the difference between one+ * indented line and the previous one — which is what makes a file indented in+ * 4s read as 4 even though its deeper lines sit at 8, 12 and 16 columns.+ */+export const detectIndentStyle = (content: string): IndentStyle => {+ const lines = content.split('\n', SAMPLE_LINE_LIMIT);++ let tabLines = 0;+ let spaceLines = 0;+ const stepCounts = new Map<number, number>();+ let previousWidth = 0;++ for (const line of lines) {+ // A block comment's continuation lines sit one space in to align their+ // asterisks. Counting them buries a 2- or 4-space file under a pile of+ // 1-space steps, so they never reach the histogram.+ if (BLOCK_COMMENT_CONTINUATION.test(line)) continue;++ const indent = /^[\t ]*/.exec(line)?.[0] ?? '';+ // Blank and unindented lines carry no signal, and a line that is only+ // whitespace is usually trailing padding rather than real structure.+ if (!indent || indent.length === line.length) continue;++ if (indent.includes('\t')) {+ tabLines += 1;+ continue;+ }++ spaceLines += 1;+ const step = indent.length - previousWidth;+ previousWidth = indent.length;+ if (step > 0) stepCounts.set(step, (stepCounts.get(step) ?? 0) + 1);+ }++ if (tabLines > spaceLines) return { size: 4, useTabs: true };+ if (spaceLines === 0) return DEFAULT_INDENT;++ let bestStep = 0;+ let bestCount = 0;+ for (const [step, count] of stepCounts) {+ // Ties go to the smaller step: a file indented in 2s also shows plenty of+ // 4-column jumps, but never the other way round.+ if (count > bestCount || (count === bestCount && step < bestStep)) {+ bestStep = step;+ bestCount = count;+ }+ }++ // Anything past 8 is far more likely to be wrapped-argument alignment than a+ // real indent unit.+ if (bestStep < 1 || bestStep > 8) return DEFAULT_INDENT;++ return { size: bestStep, useTabs: false };+};diff --git a/src/components/CodeEditorPane/index.tsx b/src/components/CodeEditorPane/index.tsxindex d1ab8736dc3..fac25353f03 100644--- a/src/components/CodeEditorPane/index.tsx+++ b/src/components/CodeEditorPane/index.tsx@@ -1,37 +1,89 @@'use client';-import { type ICodeMirrorInstance, loadCodeMirror, lobeTheme } from '@lobehub/editor/codemirror';-import { createStaticStyles, cssVar } from 'antd-style';-import { type CSSProperties, memo, useEffect, useRef } from 'react';--const styles = createStaticStyles(- ({ css }) => css`- overflow: auto;- width: 100%;- height: 100%;- background: ${cssVar.colorFillQuaternary};-- .cm-textarea {- height: 0;- opacity: 0;- }- `,-);+import {+ type CodeMirrorOptions,+ type ICodeMirrorInstance,+ loadCodeMirror,+ lobeTheme,+} from '@lobehub/editor/codemirror';+import { type CSSProperties, memo, useEffect, useMemo, useRef, useState } from 'react';++import { useIsDark } from '@/hooks/useIsDark';++import { detectIndentStyle } from './indent';+import { getEditorLanguage } from './language';+import StatusBar, { type CursorPosition } from './StatusBar';+import { styles } from './style';++/**+ * The parts of the underlying CodeMirror 6 view that the compat wrapper does+ * not re-export. Reading the live selection is the only way to drive a cursor+ * readout, since the wrapper emits no `cursorActivity` event.+ */+interface EditorViewInternals {+ constructor: { theme: (spec: unknown, config: { dark: boolean }) => unknown };+ dispatch: (spec: { effects: unknown }) => void;+ dom: HTMLElement;+ state: {+ doc: { lineAt: (pos: number) => { from: number; number: number } };+ selection: { main: { from: number; head: number; to: number } };+ };+}++/**+ * Options the bundled wrapper handles at runtime but leaves out of its public+ * types. Each one is backed by a case in the bundle's `setOption` switch.+ */+interface ExtendedCodeMirrorOptions extends CodeMirrorOptions {+ autoCloseBrackets?: boolean;+ matchBrackets?: boolean;+ styleActiveLine?: boolean;+}++const setEditorOption = (+ instance: ICodeMirrorInstance | null,+ option: keyof ExtendedCodeMirrorOptions,+ value: unknown,+) => instance?.setOption(option as keyof CodeMirrorOptions, value);++const readCursor = (view: EditorViewInternals): CursorPosition => {+ const { from, head, to } = view.state.selection.main;+ const line = view.state.doc.lineAt(head);++ return { column: head - line.from + 1, line: line.number, selectionLength: to - from };+};export interface CodeEditorPaneProps {className?: string;- language: string;+ /**+ * Path or filename of the edited file. Selects the grammar and names the+ * language in the status bar; takes precedence over `language`.+ */+ filePath?: string;+ /** Explicit CodeMirror grammar id, for content that has no file behind it. */+ language?: string;onChange?: (value: string) => void;/** Triggered when the user presses Cmd/Ctrl + S while the editor has focus. */onSave?: () => void | Promise<void>;readOnly?: boolean;+ /** Shows the cursor position, indentation, word wrap toggle and language. */+ showStatusBar?: boolean;style?: CSSProperties;value: string;}const CodeEditorPane = memo<CodeEditorPaneProps>(- ({ value, language, style, className, readOnly = false, onChange, onSave }) => {- const containerRef = useRef<HTMLDivElement>(null);+ ({+ value,+ filePath,+ language,+ style,+ className,+ readOnly = false,+ showStatusBar = false,+ onChange,+ onSave,+ }) => {const textareaRef = useRef<HTMLTextAreaElement>(null);const instanceRef = useRef<ICodeMirrorInstance | null>(null);const onChangeRef = useRef(onChange);@@ -39,26 +91,58 @@ const CodeEditorPane = memo<CodeEditorPaneProps>(onChangeRef.current = onChange;onSaveRef.current = onSave;+ const isDark = useIsDark();+ const [lineWrapping, setLineWrapping] = useState(true);+ const [cursor, setCursor] = useState<CursorPosition>();++ const editorLanguage = useMemo(+ () => (filePath ? getEditorLanguage(filePath) : undefined),+ [filePath],+ );+ const mode = editorLanguage?.mode ?? language ?? '';++ // Indentation is a property of the file, so it is sampled once from the+ // content the editor opened with rather than re-derived on every keystroke.+ const [indent] = useState(() => detectIndentStyle(value));++ // Read once at mount: these seed the initial CodeMirror options, and each+ // has its own effect below to push later changes through `setOption`.+ const initialOptionsRef = useRef({ indent, lineWrapping, mode, readOnly });+useEffect(() => {if (!textareaRef.current) return;const dom = textareaRef.current;let disposed = false;+ let detachCursorListeners: (() => void) | undefined;loadCodeMirror().then((CodeMirror) => {if (disposed || instanceRef.current) return;- const instance = CodeMirror.fromTextArea(dom, {+ const initial = initialOptionsRef.current;+ const options: ExtendedCodeMirrorOptions = {+ // Auto-closing a bracket in a file you cannot save is pure noise.+ autoCloseBrackets: !initial.readOnly,+ foldGutter: true,+ indentWithTabs: initial.indent.useTabs,lineNumbers: true,- lineWrapping: true,- mode: language,- readOnly,+ lineWrapping: initial.lineWrapping,+ matchBrackets: true,+ mode: initial.mode,+ readOnly: initial.readOnly,+ styleActiveLine: true,+ tabSize: initial.indent.size,theme: 'default',value,- });- instance.view.dispatch({+ };+ const instance = CodeMirror.fromTextArea(dom, options);++ const view = instance.view as unknown as EditorViewInternals;++ view.dispatch({effects: instance.optionHelper.theme.reconfigure(- instance.view.constructor.theme(lobeTheme, { dark: false }),+ view.constructor.theme(lobeTheme, { dark: isDark }),),});+instance.on('change', () => {onChangeRef.current?.(instance.getValue());});@@ -69,11 +153,28 @@ const CodeEditorPane = memo<CodeEditorPaneProps>(onSaveRef.current?.();}});++ // `keyup` covers typing and caret keys, `mouseup` covers clicks and+ // drag-selection, `focusin` restores the readout when focus returns.+ const syncCursor = () => setCursor(readCursor(view));+ // Seed the readout so the status bar opens with a position rather than+ // a gap that only fills in once the file is touched.+ syncCursor();+ const events = ['keyup', 'mouseup', 'focusin'] as const;+ // Removed by `detachCursorListeners` in this effect's cleanup, which the+ // lint rule cannot follow across the loader promise.+ // eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener+ for (const event of events) view.dom.addEventListener(event, syncCursor);+ detachCursorListeners = () => {+ for (const event of events) view.dom.removeEventListener(event, syncCursor);+ };+instanceRef.current = instance;});return () => {disposed = true;+ detachCursorListeners?.();if (instanceRef.current) {instanceRef.current.destroy();instanceRef.current = null;@@ -89,16 +190,44 @@ const CodeEditorPane = memo<CodeEditorPaneProps>(}, [value]);useEffect(() => {- instanceRef.current?.setOption('mode', language);- }, [language]);+ setEditorOption(instanceRef.current, 'mode', mode);+ }, [mode]);useEffect(() => {- instanceRef.current?.setOption('readOnly', readOnly);+ setEditorOption(instanceRef.current, 'readOnly', readOnly);+ setEditorOption(instanceRef.current, 'autoCloseBrackets', !readOnly);}, [readOnly]);+ useEffect(() => {+ setEditorOption(instanceRef.current, 'lineWrapping', lineWrapping);+ }, [lineWrapping]);++ useEffect(() => {+ const instance = instanceRef.current;+ if (!instance) return;+ const view = instance.view as unknown as EditorViewInternals;+ view.dispatch({+ effects: instance.optionHelper.theme.reconfigure(+ view.constructor.theme(lobeTheme, { dark: isDark }),+ ),+ });+ }, [isDark]);+return (- <div className={`${styles} ${className ?? ''}`.trim()} ref={containerRef} style={style}>- <textarea className={'cm-textarea'} ref={textareaRef} />+ <div className={`${styles.container} ${className ?? ''}`.trim()} style={style}>+ <div className={styles.editorArea}>+ <textarea className={'cm-textarea'} ref={textareaRef} />+ </div>+ {showStatusBar && (+ <StatusBar+ cursor={cursor}+ indent={indent}+ languageLabel={editorLanguage?.label ?? language ?? ''}+ lineWrapping={lineWrapping}+ readOnly={readOnly}+ onLineWrappingChange={setLineWrapping}+ />+ )}</div>);},diff --git a/src/components/CodeEditorPane/language.test.ts b/src/components/CodeEditorPane/language.test.tsnew file mode 100644index 00000000000..3eccb98401a--- /dev/null+++ b/src/components/CodeEditorPane/language.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import {+ EXTENSION_LANGUAGES_FOR_TEST,+ FILENAME_LANGUAGES_FOR_TEST,+ getEditorLanguage,+ isSupportedEditorMode,+} from './language';++describe('getEditorLanguage', () => {+ it('resolves by extension, ignoring the directory prefix', () => {+ expect(getEditorLanguage('/Users/a/project/src/index.ts')).toEqual({+ label: 'TypeScript',+ mode: 'typescript',+ });+ expect(getEditorLanguage('C:\\repo\\main.rs')).toEqual({ label: 'Rust', mode: 'rust' });+ });++ it('maps every style-sheet flavour onto a grammar the bundle ships', () => {+ // SCSS used to resolve to an id with no grammar behind it, so the file+ // rendered as unhighlighted plain text.+ expect(getEditorLanguage('theme.scss').mode).toBe('sass');+ expect(getEditorLanguage('theme.less').mode).toBe('css');+ expect(getEditorLanguage('theme.css').mode).toBe('css');+ });++ it('keeps a language on its own grammar rather than a near neighbour', () => {+ // Downgrading these to a lookalike grammar visibly weakens highlighting;+ // the bundle registers all three under their own name.+ expect(getEditorLanguage('Cargo.toml').mode).toBe('toml');+ expect(getEditorLanguage('Main.kt').mode).toBe('kotlin');+ expect(getEditorLanguage('Build.scala').mode).toBe('scala');+ });++ it('maps every shell dialect onto the shell grammar', () => {+ expect(getEditorLanguage('deploy.sh').mode).toBe('shell');+ expect(getEditorLanguage('setup.zsh').mode).toBe('shell');+ expect(getEditorLanguage('.bashrc').mode).toBe('shell');+ });++ it('keeps the reported name when a language borrows another grammar', () => {+ expect(getEditorLanguage('App.svelte')).toEqual({ label: 'Svelte', mode: 'html' });+ expect(getEditorLanguage('notes.tex')).toEqual({ label: 'LaTeX', mode: 'stex' });+ });++ it('recognises extensionless files by name', () => {+ expect(getEditorLanguage('Dockerfile').mode).toBe('dockerfile');+ expect(getEditorLanguage('some/dir/Makefile').mode).toBe('makefile');+ expect(getEditorLanguage('.gitignore').mode).toBe('properties');+ });++ it('reads a qualified name from its leading segment', () => {+ expect(getEditorLanguage('.env.production').mode).toBe('properties');+ expect(getEditorLanguage('Dockerfile.dev').mode).toBe('dockerfile');+ });++ it('prefers a real extension over the leading segment', () => {+ expect(getEditorLanguage('Makefile.md')).toEqual({ label: 'Markdown', mode: '' });+ });++ it('falls back to plain text instead of guessing', () => {+ expect(getEditorLanguage('archive.unknownext')).toEqual({ label: 'Plain Text', mode: '' });+ expect(getEditorLanguage('')).toEqual({ label: 'Plain Text', mode: '' });+ expect(getEditorLanguage(undefined)).toEqual({ label: 'Plain Text', mode: '' });+ });++ it('only ever emits a grammar the bundle ships', () => {+ const entries = [+ ...Object.values(FILENAME_LANGUAGES_FOR_TEST),+ ...Object.values(EXTENSION_LANGUAGES_FOR_TEST),+ ];++ const unsupported = entries+ .filter((entry) => entry.mode !== '' && !isSupportedEditorMode(entry.mode))+ .map((entry) => `${entry.label} -> ${entry.mode}`);++ expect(unsupported).toEqual([]);+ });+});diff --git a/src/components/CodeEditorPane/language.ts b/src/components/CodeEditorPane/language.tsnew file mode 100644index 00000000000..ef5c65a9607--- /dev/null+++ b/src/components/CodeEditorPane/language.ts@@ -0,0 +1,255 @@+/**+ * Grammar ids the bundled CodeMirror build actually ships, read off its own+ * language registry. A mode outside this set is silently dropped and the file+ * renders as unhighlighted plain text, so every value produced below must be+ * one of these; a language with no grammar borrows the closest one rather than+ * inventing an id.+ */+const SUPPORTED_MODES = new Set([+ 'abap',+ 'agda',+ 'arkts',+ 'basic',+ 'c',+ 'clojure',+ 'cmake',+ 'commonlisp',+ 'cpp',+ 'csharp',+ 'css',+ 'cypher',+ 'dart',+ 'diff',+ 'dockerfile',+ 'erlang',+ 'fortran',+ 'glsl',+ 'go',+ 'graphql',+ 'groovy',+ 'haskell',+ 'html',+ 'java',+ 'javascript',+ 'json',+ 'jsx',+ 'julia',+ 'kotlin',+ 'lua',+ 'makefile',+ 'nginx',+ 'objectivec',+ 'ocaml',+ 'pascal',+ 'perl',+ 'php',+ 'plantuml',+ 'plsql',+ 'powershell',+ 'properties',+ 'protobuf',+ 'python',+ 'r',+ 'ruby',+ 'rust',+ 'sass',+ 'scala',+ 'scheme',+ 'shell',+ 'solidity',+ 'sql',+ 'stex',+ 'swift',+ 'tcl',+ 'toml',+ 'tsx',+ 'typescript',+ 'vbnet',+ 'velocity',+ 'verilog',+ 'vue',+ 'xml',+ 'yaml',+ 'z80',+]);++export interface EditorLanguage {+ /**+ * Human-readable name for the status bar. Kept apart from `mode` so a+ * language that borrows another's grammar still reports its own name.+ */+ label: string;+ /** CodeMirror grammar id, or an empty string to render as plain text. */+ mode: string;+}++const plain = (label: string): EditorLanguage => ({ label, mode: '' });++const lang = (label: string, mode: string): EditorLanguage => ({ label, mode });++/** Matched against the whole lowercased filename before any extension lookup. */+const FILENAME_LANGUAGES: Record<string, EditorLanguage> = {+ '.bash_profile': lang('Shell', 'shell'),+ '.bashrc': lang('Shell', 'shell'),+ '.dockerignore': lang('Ignore', 'properties'),+ '.env': lang('Dotenv', 'properties'),+ '.editorconfig': lang('EditorConfig', 'properties'),+ '.gitattributes': lang('Git Attributes', 'properties'),+ '.gitignore': lang('Ignore', 'properties'),+ '.npmrc': lang('npmrc', 'properties'),+ '.profile': lang('Shell', 'shell'),+ '.zshrc': lang('Shell', 'shell'),+ 'cmakelists.txt': lang('CMake', 'cmake'),+ 'containerfile': lang('Dockerfile', 'dockerfile'),+ 'dockerfile': lang('Dockerfile', 'dockerfile'),+ 'gnumakefile': lang('Makefile', 'makefile'),+ 'makefile': lang('Makefile', 'makefile'),+ 'nginx.conf': lang('Nginx', 'nginx'),+};++const EXTENSION_LANGUAGES: Record<string, EditorLanguage> = {+ bash: lang('Shell', 'shell'),+ c: lang('C', 'c'),+ cc: lang('C++', 'cpp'),+ cfg: lang('Config', 'properties'),+ cjs: lang('JavaScript', 'javascript'),+ cmake: lang('CMake', 'cmake'),+ conf: lang('Config', 'properties'),+ cpp: lang('C++', 'cpp'),+ cs: lang('C#', 'csharp'),+ css: lang('CSS', 'css'),+ cts: lang('TypeScript', 'typescript'),+ cxx: lang('C++', 'cpp'),+ dart: lang('Dart', 'dart'),+ diff: lang('Diff', 'diff'),+ dockerfile: lang('Dockerfile', 'dockerfile'),+ env: lang('Dotenv', 'properties'),+ erl: lang('Erlang', 'erlang'),+ // ArkTS is TypeScript with decorators; the bundle ships a dedicated grammar.+ ets: lang('ArkTS', 'arkts'),+ fish: lang('Shell', 'shell'),+ frag: lang('GLSL', 'glsl'),+ glsl: lang('GLSL', 'glsl'),+ gql: lang('GraphQL', 'graphql'),+ gradle: lang('Gradle', 'groovy'),+ graphql: lang('GraphQL', 'graphql'),+ groovy: lang('Groovy', 'groovy'),+ h: lang('C', 'c'),+ hh: lang('C++', 'cpp'),+ hpp: lang('C++', 'cpp'),+ hrl: lang('Erlang', 'erlang'),+ clj: lang('Clojure', 'clojure'),+ cljc: lang('Clojure', 'clojure'),+ cljs: lang('Clojure', 'clojure'),+ hs: lang('Haskell', 'haskell'),+ htm: lang('HTML', 'html'),+ html: lang('HTML', 'html'),+ http: plain('HTTP'),+ hxx: lang('C++', 'cpp'),+ ini: lang('INI', 'properties'),+ java: lang('Java', 'java'),+ js: lang('JavaScript', 'javascript'),+ json: lang('JSON', 'json'),+ jl: lang('Julia', 'julia'),+ json5: lang('JSON5', 'json'),+ jsonc: lang('JSON', 'json'),+ jsx: lang('JSX', 'jsx'),+ kt: lang('Kotlin', 'kotlin'),+ kts: lang('Kotlin', 'kotlin'),+ ksh: lang('Shell', 'shell'),+ less: lang('Less', 'css'),+ lua: lang('Lua', 'lua'),+ markdown: plain('Markdown'),+ md: plain('Markdown'),+ mdx: plain('MDX'),+ mjs: lang('JavaScript', 'javascript'),+ mts: lang('TypeScript', 'typescript'),+ patch: lang('Diff', 'diff'),+ pas: lang('Pascal', 'pascal'),+ php: lang('PHP', 'php'),+ pl: lang('Perl', 'perl'),+ plist: lang('Property List', 'xml'),+ pm: lang('Perl', 'perl'),+ prisma: plain('Prisma'),+ properties: lang('Properties', 'properties'),+ proto: lang('Protocol Buffers', 'protobuf'),+ ps1: lang('PowerShell', 'powershell'),+ psm1: lang('PowerShell', 'powershell'),+ py: lang('Python', 'python'),+ pyi: lang('Python', 'python'),+ pyw: lang('Python', 'python'),+ r: lang('R', 'r'),+ rake: lang('Ruby', 'ruby'),+ rb: lang('Ruby', 'ruby'),+ rs: lang('Rust', 'rust'),+ sass: lang('Sass', 'sass'),+ scala: lang('Scala', 'scala'),+ scss: lang('SCSS', 'sass'),+ sh: lang('Shell', 'shell'),+ sol: lang('Solidity', 'solidity'),+ sql: lang('SQL', 'sql'),+ sv: lang('SystemVerilog', 'verilog'),+ svelte: lang('Svelte', 'html'),+ svg: lang('SVG', 'xml'),+ svh: lang('SystemVerilog', 'verilog'),+ swift: lang('Swift', 'swift'),+ tcl: lang('Tcl', 'tcl'),+ tex: lang('LaTeX', 'stex'),+ tf: plain('Terraform'),+ tfvars: plain('Terraform'),+ toml: lang('TOML', 'toml'),+ ts: lang('TypeScript', 'typescript'),+ tsx: lang('TSX', 'tsx'),+ txt: plain('Plain Text'),+ v: lang('Verilog', 'verilog'),+ vb: lang('Visual Basic', 'vbnet'),+ vh: lang('Verilog', 'verilog'),+ vert: lang('GLSL', 'glsl'),+ vue: lang('Vue', 'vue'),+ xml: lang('XML', 'xml'),+ xsl: lang('XSL', 'xml'),+ yaml: lang('YAML', 'yaml'),+ yml: lang('YAML', 'yaml'),+ zsh: lang('Shell', 'shell'),+};++const PLAIN_TEXT: EditorLanguage = plain('Plain Text');++/**+ * Resolve the editor grammar and status-bar label for a file. Accepts a bare+ * name or a full path, and falls back to plain text rather than guessing.+ */+export const getEditorLanguage = (filePath?: string | null): EditorLanguage => {+ if (!filePath) return PLAIN_TEXT;++ const name = (filePath.split(/[/\\]/).at(-1) ?? '').toLowerCase();+ if (!name) return PLAIN_TEXT;++ const byFilename = FILENAME_LANGUAGES[name];+ if (byFilename) return byFilename;++ const dotIndex = name.lastIndexOf('.');+ // A leading dot is part of the name (`.gitignore`), not an extension marker.+ if (dotIndex > 0) {+ const byExtension = EXTENSION_LANGUAGES[name.slice(dotIndex + 1)];+ if (byExtension) return byExtension;+ }++ // `.env.production` and `Dockerfile.dev` name their type first and qualify it+ // after, the opposite of `app.ts`. Only consulted once the trailing extension+ // has come up empty, so `Makefile.md` still reads as Markdown.+ const leadingSegment = name.split('.').find(Boolean);+ if (leadingSegment && name.includes('.')) {+ const byPrefix = FILENAME_LANGUAGES[leadingSegment] ?? FILENAME_LANGUAGES[`.${leadingSegment}`];+ if (byPrefix) return byPrefix;+ }++ return PLAIN_TEXT;+};++/** Guard against a mapping drifting away from the shipped grammar set. */+export const isSupportedEditorMode = (mode: string): boolean => SUPPORTED_MODES.has(mode);++/** Exported so a test can assert every mapping still points at a real grammar. */+export const FILENAME_LANGUAGES_FOR_TEST = FILENAME_LANGUAGES;+export const EXTENSION_LANGUAGES_FOR_TEST = EXTENSION_LANGUAGES;diff --git a/src/components/CodeEditorPane/style.ts b/src/components/CodeEditorPane/style.tsnew file mode 100644index 00000000000..cd4119df309--- /dev/null+++ b/src/components/CodeEditorPane/style.ts@@ -0,0 +1,172 @@+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * The editor chrome. Selectors are one level deeper than the CodeMirror theme+ * emits (`.cm-editor.cm-editor`) so these rules win regardless of which style+ * sheet the browser inserted last.+ */+export const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: hidden;+ display: flex;+ flex-direction: column;++ width: 100%;+ height: 100%;++ background: ${cssVar.colorBgContainer};++ .cm-textarea {+ height: 0;+ opacity: 0;+ }+ `,++ editorArea: css`+ overflow: hidden;+ flex: 1;+ min-height: 0;++ .cm-editor {+ height: 100%;+ padding-block: 0;+ }++ /* Own the vertical scroll here rather than in an outer wrapper, so the+ gutter and the fold markers stay pinned while the text scrolls. */+ .cm-scroller {+ overflow: auto;+ font-variant-ligatures: none;+ line-height: 20px;+ }++ .cm-editor.cm-editor span,+ .cm-editor.cm-editor .cm-line {+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ line-height: 20px;+ }++ /* Clicking below the last line should still land in the document, the way+ every desktop editor behaves. */+ .cm-content {+ min-height: 100%;+ padding-block: 8px;+ }++ .cm-gutters {+ user-select: none;+ border-inline-end: 1px solid ${cssVar.colorBorderSecondary};+ background: ${cssVar.colorBgContainer};+ }++ /* The bundled theme pads every line by 12px, which lands on top of the+ gutter's own trailing space and pushes the code away from its number. */+ .cm-editor.cm-editor .cm-line {+ padding-inline: 6px 12px;+ }++ /* The number sits closer to the code than to the pane edge: it labels the+ line, so the eye should travel from it rightwards, not across a gap. */+ .cm-lineNumbers .cm-gutterElement {+ min-width: 22px;+ padding-inline: 16px 2px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ line-height: 20px;+ color: ${cssVar.colorTextQuaternary};+ }++ .cm-activeLineGutter {+ color: ${cssVar.colorText} !important;+ background: transparent;+ }++ .cm-activeLine {+ background: ${cssVar.colorFillQuaternary};+ }++ /* A focused editor gets the stronger cue; an unfocused one keeps a faint+ marker so the caret position is still findable after a click elsewhere. */+ .cm-editor:not(.cm-focused) .cm-activeLine {+ background: transparent;+ }++ .cm-matchingBracket,+ .cm-editor.cm-focused .cm-matchingBracket {+ border-radius: 2px;+ background: ${cssVar.colorFillSecondary};+ outline: 1px solid ${cssVar.colorBorder};+ }++ .cm-nonmatchingBracket {+ border-radius: 2px;+ background: ${cssVar.colorErrorBg};+ }++ /* Fold markers render as empty divs; the chevron is entirely ours. */+ .gutter-fold-open,+ .gutter-fold-close {+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 13px;+ height: 20px;++ color: ${cssVar.colorTextTertiary};++ transition: opacity 0.15s;++ &::before {+ content: '';++ width: 5px;+ height: 5px;+ border-block-end: 1.4px solid currentcolor;+ border-inline-end: 1.4px solid currentcolor;+ }+ }++ /* Pointing down: this range is expanded. Only offered on gutter hover, so+ the gutter is not a column of permanent arrows. */+ .gutter-fold-open {+ opacity: 0;++ &::before {+ transform: translateY(-1px) rotate(45deg);+ }+ }++ /* Pointing right: content is hidden here, so this one always shows. */+ .gutter-fold-close::before {+ transform: translateX(-2px) rotate(-45deg);+ }++ .gutter-fold-open:hover,+ .gutter-fold-close:hover {+ color: ${cssVar.colorText};+ }++ .cm-gutters:hover .gutter-fold-open {+ opacity: 1;+ }++ .cm-editor.cm-editor .cm-foldPlaceholder {+ width: auto;+ height: auto;+ padding-inline: 6px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 4px;++ font-size: 11px;+ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorFillTertiary};+ }+ `,+}));diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex 59e19cf74a7..caa285f74ab 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -213,11 +213,11 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frinterface HighlightEditorProps {content: string;documentId: string;- language: string;+ filename: string;onSaved: (newContent: string) => void;}-const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, language, onSaved }) => {+const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, filename, onSaved }) => {const [buffer, setBuffer] = useState<string | undefined>(undefined);const editingValue = buffer ?? content;@@ -307,8 +307,8 @@ const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, langureturn (<CodeEditorPane- language={language}- style={{ minHeight: '100%' }}+ showStatusBar+ filePath={filename}value={editingValue}onChange={handleChange}onSave={handleSave}@@ -365,8 +365,8 @@ const DocumentBody = memo(() => {<HighlightEditorcontent={documentMeta?.content ?? ''}documentId={documentId}+ filename={documentMeta?.filename ?? ''}key={documentId}- language={renderMode.language}onSaved={handleHighlightSaved}/>) : (diff --git a/src/features/Portal/LocalFile/Body.helpers.ts b/src/features/Portal/LocalFile/Body.helpers.tsindex 5c1515e35e2..ee949372ae8 100644--- a/src/features/Portal/LocalFile/Body.helpers.ts+++ b/src/features/Portal/LocalFile/Body.helpers.ts@@ -1,49 +1,3 @@-const EXT_TO_LANG: Record<string, string> = {- bash: 'bash',- c: 'c',- cpp: 'cpp',- cs: 'csharp',- css: 'css',- dockerfile: 'dockerfile',- fish: 'fish',- go: 'go',- graphql: 'graphql',- html: 'html',- java: 'java',- js: 'javascript',- json: 'json',- jsx: 'jsx',- kt: 'kotlin',- lua: 'lua',- md: 'markdown',- mdx: 'mdx',- php: 'php',- prisma: 'prisma',- proto: 'protobuf',- py: 'python',- rb: 'ruby',- rs: 'rust',- scala: 'scala',- scss: 'scss',- sh: 'bash',- sql: 'sql',- swift: 'swift',- tf: 'hcl',- toml: 'toml',- ts: 'typescript',- tsx: 'tsx',- txt: 'txt',- xml: 'xml',- yaml: 'yaml',- yml: 'yaml',- zsh: 'bash',-};--export const extensionToLanguage = (ext: string): string => {- if (!ext) return 'txt';- return EXT_TO_LANG[ext.toLowerCase()] ?? 'txt';-};-export const getFileExtension = (filename: string): string => {const base = filename.split('/').at(-1) ?? filename;if (base.startsWith('.') && !base.slice(1).includes('.')) return '';diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsxindex b797e211a20..1cbb5026c36 100644--- a/src/features/Portal/LocalFile/Body.test.tsx+++ b/src/features/Portal/LocalFile/Body.test.tsx@@ -74,6 +74,8 @@ vi.mock('@/components/Loading/CircleLoading', () => ({const mockUseClientDataSWR = vi.hoisted(() => vi.fn());const mockProjectFileService = vi.hoisted(() => ({getLocalFilePreview: vi.fn(),+ // The toolbar breadcrumb reads the project index to offer sibling files.+ getProjectFileIndex: vi.fn().mockResolvedValue(undefined),}));vi.mock('@/libs/swr', () => ({@@ -269,8 +271,12 @@ describe('LocalFile Body', () => {{ revalidateOnFocus: false },);- const fetcher = mockUseClientDataSWR.mock.calls.at(-1)?.[1] as () => Promise<unknown>;- void fetcher();+ // The toolbar breadcrumb registers its own SWR call, so pick the preview+ // fetcher by its key rather than by position.+ const previewCall = mockUseClientDataSWR.mock.calls.findLast((call) =>+ String(call[0]).includes('/tmp/worktree-switcher-demo.html'),+ );+ void (previewCall?.[1] as () => Promise<unknown>)();expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({allowExternalFile: true,deviceId: undefined,@@ -311,8 +317,12 @@ describe('LocalFile Body', () => {render(<Body />);- const fetcher = mockUseClientDataSWR.mock.calls.at(-1)?.[1] as () => Promise<unknown>;- void fetcher();+ // The toolbar breadcrumb registers its own SWR call, so pick the preview+ // fetcher by its key rather than by position.+ const previewCall = mockUseClientDataSWR.mock.calls.findLast((call) =>+ String(call[0]).includes('/project-a/pages/index.html'),+ );+ void (previewCall?.[1] as () => Promise<unknown>)();expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({allowExternalFile: undefined,deviceId: undefined,diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 88da559e706..e8b33388548 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -29,7 +29,7 @@ import {type SkillMarkdownMetadataItem,} from '@/utils/skillMarkdown';-import { extensionToLanguage, getFileExtension } from './Body.helpers';+import { getFileExtension } from './Body.helpers';import MarkdownImage from './MarkdownImage';import PreviewToolbar, { ToolbarActionButton } from './PreviewToolbar';@@ -254,6 +254,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>([modeScopeKey],);const showHtmlPreview = isHtml && mode === 'render';+ const showSourceView = showHtmlPreview || !(isMarkdown && mode === 'render');const [htmlPreviewRevision, setHtmlPreviewRevision] = useState(0);const handleReloadPreview = useCallback(async () => {await onReload?.();@@ -292,7 +293,9 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(<Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}><PublishHtmlArtifactLiveBar /><PreviewToolbar+ deviceId={deviceId}path={filePath}+ rootPath={workingDirectory}actions={<>{isHtml && (@@ -338,7 +341,10 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(}/><Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>- <div style={{ flex: 1, minHeight: 0, overflow: showHtmlPreview ? 'hidden' : 'auto' }}>+ {/* The rendered-markdown branch scrolls here; the HTML preview and+ the code editor each own their scrolling, and the editor needs+ that so its gutter and status bar stay pinned. */}+ <div style={{ flex: 1, minHeight: 0, overflow: showSourceView ? 'hidden' : 'auto' }}>{isMarkdown && mode === 'render' ? (<><SkillFrontmatterPreviewCard metadata={frontmatterMetadata} />@@ -357,9 +363,9 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(/>) : (<CodeEditorPane- language={extensionToLanguage(ext)}+ showStatusBar+ filePath={filePath}readOnly={readOnly}- style={{ fontSize: 12, minHeight: '100%' }}value={editingValue}onChange={readOnly ? undefined : handleCodeChange}onSave={readOnly ? undefined : handleSave}diff --git a/src/features/Portal/LocalFile/PathBreadcrumb.tsx b/src/features/Portal/LocalFile/PathBreadcrumb.tsxnew file mode 100644index 00000000000..858381870b7--- /dev/null+++ b/src/features/Portal/LocalFile/PathBreadcrumb.tsx@@ -0,0 +1,222 @@+'use client';++import type { ProjectFileIndexEntry } from '@lobechat/electron-client-ipc';+import { type DropdownItem, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronRightIcon } from 'lucide-react';+import { memo, useMemo } from 'react';++import FileIcon from '@/components/FileIcon';+import { useProjectFiles } from '@/features/Conversation/WorkingSidebar/Files/useProjectFiles';+import { useChatStore } from '@/store/chat';++import {+ type BreadcrumbSegment,+ groupChildrenByParent,+ toBreadcrumbSegments,+} from './filePathBreadcrumb';++const styles = createStaticStyles(({ css }) => ({+ crumb: css`+ cursor: pointer;++ overflow: hidden;++ min-width: 0;+ padding-block: 2px;+ padding-inline: 4px;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ font-family: inherit;+ font-size: inherit;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: none;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ crumbStatic: css`+ cursor: default;++ &:hover {+ color: ${cssVar.colorTextTertiary};+ background: none;+ }+ `,+ /* The previewed file is the crumb a reader always needs in full, so it is the+ last one to give up width. */+ group: css`+ overflow: hidden;+ flex-shrink: 1;+ min-width: 0;+ `,+ groupLast: css`+ flex-shrink: 0;++ span {+ color: ${cssVar.colorText};+ }+ `,+ separator: css`+ display: flex;+ flex: none;+ align-items: center;+ color: ${cssVar.colorTextQuaternary};+ `,+}));++interface BuildMenuParams {+ byParent: Map<string, ProjectFileIndexEntry[]>;+ deviceId?: string;+ openFile: (filePath: string) => void;+ parentRelativePath: string;+}++/**+ * The contents of one folder as menu items: files open the preview, folders+ * become submenus of their own contents, so the breadcrumb walks the tree the+ * way a desktop editor's does.+ *+ * A folder with nothing indexed under it is left out rather than rendered as an+ * empty submenu — there would be nothing to pick.+ */+const buildFolderItems = ({+ byParent,+ deviceId,+ openFile,+ parentRelativePath,+}: BuildMenuParams): DropdownItem[] => {+ const children = byParent.get(parentRelativePath) ?? [];++ return children.flatMap((child): DropdownItem[] => {+ const relativePath = child.relativePath.replace(/\/$/, '');+ const icon = (+ <FileIcon fileName={child.name} isDirectory={child.isDirectory} size={14} variant={'raw'} />+ );++ if (!child.isDirectory) {+ return [{ icon, key: child.path, label: child.name, onClick: () => openFile(child.path) }];+ }++ const grandChildren = buildFolderItems({+ byParent,+ deviceId,+ openFile,+ parentRelativePath: relativePath,+ });+ if (grandChildren.length === 0) return [];++ return [+ {+ children: grandChildren,+ icon,+ key: child.path,+ label: child.name,+ openOnHover: true,+ type: 'submenu',+ },+ ];+ });+};++/**+ * One level of the path. A level backed by the project index opens a menu of+ * that folder's contents, so the breadcrumb doubles as a file switcher.+ */+const Crumb = memo<{+ byParent?: Map<string, ProjectFileIndexEntry[]>;+ deviceId?: string;+ isLast: boolean;+ rootPath?: string;+ segment: BreadcrumbSegment;+}>(({ byParent, deviceId, isLast, rootPath, segment }) => {+ const openLocalFile = useChatStore((s) => s.openLocalFile);++ const ownFolder = useMemo(() => {+ if (segment.relativePath === undefined) return;+ // The last crumb is the previewed file, so its menu lists its siblings.+ return isLast ? segment.relativePath.split('/').slice(0, -1).join('/') : segment.relativePath;+ }, [isLast, segment.relativePath]);++ const items = useMemo(() => {+ if (!byParent || !rootPath || ownFolder === undefined) return [];++ return buildFolderItems({+ byParent,+ deviceId,+ openFile: (filePath) => openLocalFile({ deviceId, filePath, workingDirectory: rootPath }),+ parentRelativePath: ownFolder,+ });+ }, [byParent, deviceId, openLocalFile, ownFolder, rootPath]);++ // A folder on the path holds at least the open file, so an empty result means+ // the index does not reach here — a project past the walk's cap.+ const canBrowse = items.length > 0;++ // A span rather than a button: the menu's trigger applies its own button+ // semantics, and base-ui rejects a native button as the element it renders.+ const crumb = (+ <span className={cx(styles.crumb, !canBrowse && styles.crumbStatic)}>{segment.name}</span>+ );++ if (!canBrowse) return crumb;++ return <DropdownMenu items={items}>{crumb}</DropdownMenu>;+});++Crumb.displayName = 'Crumb';++interface PathBreadcrumbProps {+ deviceId?: string;+ path: string;+ rootPath?: string;+}++const PathBreadcrumb = memo<PathBreadcrumbProps>(({ deviceId, path, rootPath }) => {+ const { data } = useProjectFiles(deviceId, rootPath);+ const segments = useMemo(() => toBreadcrumbSegments(path, rootPath), [path, rootPath]);+ const byParent = useMemo(+ () => (data?.entries ? groupChildrenByParent(data.entries) : undefined),+ [data?.entries],+ );++ return (+ <>+ {segments.map((segment, index) => {+ const isLast = index === segments.length - 1;++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.group, isLast && styles.groupLast)}+ key={segment.path}+ >+ {index > 0 && (+ <span aria-hidden className={styles.separator}>+ <Icon icon={ChevronRightIcon} size={12} />+ </span>+ )}+ <Crumb+ byParent={byParent}+ deviceId={deviceId}+ isLast={isLast}+ rootPath={rootPath}+ segment={segment}+ />+ </Flexbox>+ );+ })}+ </>+ );+});++PathBreadcrumb.displayName = 'PathBreadcrumb';++export default PathBreadcrumb;diff --git a/src/features/Portal/LocalFile/PreviewToolbar.tsx b/src/features/Portal/LocalFile/PreviewToolbar.tsxindex a1620ee1546..c87de152092 100644--- a/src/features/Portal/LocalFile/PreviewToolbar.tsx+++ b/src/features/Portal/LocalFile/PreviewToolbar.tsx@@ -4,6 +4,8 @@ import type { LucideIcon } from 'lucide-react';import type { MouseEventHandler, ReactNode } from 'react';import { memo } from 'react';+import PathBreadcrumb from './PathBreadcrumb';+const styles = createStaticStyles(({ css }) => ({action: css`cursor: pointer;@@ -68,22 +70,23 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorBgContainer};`,- dir: css`+ crumbGroup: css`overflow: hidden;- /* Shrinks long before the filename does — the filename only starts- ellipsizing once the directory is fully collapsed. */+ /* Ancestors give up their width long before the filename does, so the file+ being previewed is the last thing to ellipsize. */flex-shrink: 100;+ min-width: 0;- color: ${cssVar.colorTextTertiary};- text-overflow: ellipsis;- white-space: nowrap;+ &:last-child {+ flex-shrink: 1;+ }`,- name: css`- overflow: hidden;- color: ${cssVar.colorTextSecondary};- text-overflow: ellipsis;- white-space: nowrap;+ separator: css`+ display: flex;+ flex: none;+ align-items: center;+ color: ${cssVar.colorTextQuaternary};`,path: css`overflow: hidden;@@ -135,39 +138,35 @@ ToolbarActionButton.displayName = 'ToolbarActionButton';interface PreviewToolbarProps {actions?: ReactNode;+ /** Remote device the file lives on; local when absent. */+ deviceId?: string;path: string;+ /** Project root the path is shown relative to, when the file lives inside it. */+ rootPath?: string;}-const PreviewToolbar = memo<PreviewToolbarProps>(({ actions, path }) => {- const lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));- const dir = lastSlash > 0 ? path.slice(0, lastSlash) : '';- const sep = lastSlash > 0 ? path[lastSlash] : '';- const name = path.slice(lastSlash + 1);-- return (- <Flexbox horizontal align={'center'} className={styles.bar} gap={8} justify={'space-between'}>- <Tooltip title={path}>- <Flexbox horizontal align={'center'} className={styles.path} flex={1}>- {dir && <span className={styles.dir}>{dir}</span>}- <span className={styles.name}>{dir ? `${sep}${name}` : name}</span>- </Flexbox>- </Tooltip>- {actions && (- <Flexbox- data-toolbar-actions- horizontal- align={'center'}- className={styles.actions}- flex={'none'}- gap={2}- style={{ marginInlineStart: 'auto' }}- >- {actions}- </Flexbox>- )}- </Flexbox>- );-});+const PreviewToolbar = memo<PreviewToolbarProps>(({ actions, deviceId, path, rootPath }) => (+ <Flexbox horizontal align={'center'} className={styles.bar} gap={8} justify={'space-between'}>+ <Tooltip title={path}>+ <Flexbox horizontal align={'center'} className={styles.path} flex={1}>+ <PathBreadcrumb deviceId={deviceId} path={path} rootPath={rootPath} />+ </Flexbox>+ </Tooltip>+ {actions && (+ <Flexbox+ data-toolbar-actions+ horizontal+ align={'center'}+ className={styles.actions}+ flex={'none'}+ gap={2}+ style={{ marginInlineStart: 'auto' }}+ >+ {actions}+ </Flexbox>+ )}+ </Flexbox>+));PreviewToolbar.displayName = 'PreviewToolbar';diff --git a/src/features/Portal/LocalFile/filePathBreadcrumb.test.ts b/src/features/Portal/LocalFile/filePathBreadcrumb.test.tsnew file mode 100644index 00000000000..5b13fe0521c--- /dev/null+++ b/src/features/Portal/LocalFile/filePathBreadcrumb.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from 'vitest';++import {+ type BreadcrumbEntry,+ groupChildrenByParent,+ listDirectoryChildren,+ toBreadcrumbSegments,+} from './filePathBreadcrumb';++const names = (filePath: string, rootPath?: string) =>+ toBreadcrumbSegments(filePath, rootPath).map((segment) => segment.name);++describe('toBreadcrumbSegments', () => {+ it('anchors on the project root folder name', () => {+ expect(names('/Users/a/work/my-app/src/index.ts', '/Users/a/work/my-app')).toEqual([+ 'my-app',+ 'src',+ 'index.ts',+ ]);+ });++ it('keeps every level of a deep path', () => {+ // The row ellipsizes individual crumbs when it runs out of width, so a+ // deep path must not be pre-collapsed while there is still room.+ expect(+ names('/Users/a/work/my-app/src/features/Portal/LocalFile/Body.tsx', '/Users/a/work/my-app'),+ ).toEqual(['my-app', 'src', 'features', 'Portal', 'LocalFile', 'Body.tsx']);+ });++ it('carries the absolute and root-relative path of each level', () => {+ expect(toBreadcrumbSegments('/w/app/src/index.ts', '/w/app')).toEqual([+ { name: 'app', path: '/w/app', relativePath: '' },+ { name: 'src', path: '/w/app/src', relativePath: 'src' },+ { name: 'index.ts', path: '/w/app/src/index.ts', relativePath: 'src/index.ts' },+ ]);+ });++ it('leaves a path outside the root without a relative path', () => {+ const segments = toBreadcrumbSegments('/etc/hosts', '/Users/a/work/my-app');++ expect(segments.map((s) => s.name)).toEqual(['etc', 'hosts']);+ expect(segments.every((s) => s.relativePath === undefined)).toBe(true);+ });++ it('handles Windows separators', () => {+ expect(toBreadcrumbSegments('C:\\repo\\src\\main.rs', 'C:\\repo')).toEqual([+ { name: 'repo', path: 'C:\\repo', relativePath: '' },+ { name: 'src', path: 'C:\\repo\\src', relativePath: 'src' },+ { name: 'main.rs', path: 'C:\\repo\\src\\main.rs', relativePath: 'src/main.rs' },+ ]);+ });++ it('returns nothing for an empty path', () => {+ expect(toBreadcrumbSegments('')).toEqual([]);+ });+});++describe('listDirectoryChildren', () => {+ // Directory entries arrive from the project index with a trailing slash.+ const entries: BreadcrumbEntry[] = [+ { isDirectory: true, name: 'src', path: '/w/app/src', relativePath: 'src/' },+ {+ isDirectory: false,+ name: 'index.ts',+ path: '/w/app/src/index.ts',+ relativePath: 'src/index.ts',+ },+ { isDirectory: true, name: 'ui', path: '/w/app/src/ui', relativePath: 'src/ui/' },+ {+ isDirectory: false,+ name: 'Button.tsx',+ path: '/w/app/src/ui/Button.tsx',+ relativePath: 'src/ui/Button.tsx',+ },+ { isDirectory: false, name: 'README.md', path: '/w/app/README.md', relativePath: 'README.md' },+ ];++ it('lists only immediate children, folders first', () => {+ expect(listDirectoryChildren(entries, 'src').map((e) => e.name)).toEqual(['ui', 'index.ts']);+ });++ it('accepts a directory path that already carries the index trailing slash', () => {+ expect(listDirectoryChildren(entries, 'src/').map((e) => e.name)).toEqual(['ui', 'index.ts']);+ });++ it('lists the root level for an empty relative path', () => {+ expect(listDirectoryChildren(entries, '').map((e) => e.name)).toEqual(['src', 'README.md']);+ });++ it('does not treat a sibling with a shared name prefix as a child', () => {+ const withPrefixSibling: BreadcrumbEntry[] = [+ ...entries,+ { isDirectory: false, name: 'a.ts', path: '/w/app/srcgen/a.ts', relativePath: 'srcgen/a.ts' },+ ];++ expect(listDirectoryChildren(withPrefixSibling, 'src').map((e) => e.name)).toEqual([+ 'ui',+ 'index.ts',+ ]);+ });+});++describe('groupChildrenByParent', () => {+ const entries: BreadcrumbEntry[] = [+ { isDirectory: true, name: 'src', path: '/w/app/src', relativePath: 'src/' },+ { isDirectory: true, name: 'ui', path: '/w/app/src/ui', relativePath: 'src/ui/' },+ {+ isDirectory: false,+ name: 'Button.tsx',+ path: '/w/app/src/ui/Button.tsx',+ relativePath: 'src/ui/Button.tsx',+ },+ { isDirectory: false, name: 'README.md', path: '/w/app/README.md', relativePath: 'README.md' },+ ];++ it('keys every level by its parent, with the root under an empty string', () => {+ const byParent = groupChildrenByParent(entries);++ expect(byParent.get('')?.map((e) => e.name)).toEqual(['src', 'README.md']);+ expect(byParent.get('src')?.map((e) => e.name)).toEqual(['ui']);+ expect(byParent.get('src/ui')?.map((e) => e.name)).toEqual(['Button.tsx']);+ });++ it('has no entry for a folder that holds nothing', () => {+ expect(groupChildrenByParent(entries).get('src/ui/Button.tsx')).toBeUndefined();+ });+});diff --git a/src/features/Portal/LocalFile/filePathBreadcrumb.ts b/src/features/Portal/LocalFile/filePathBreadcrumb.tsnew file mode 100644index 00000000000..88a496225ec--- /dev/null+++ b/src/features/Portal/LocalFile/filePathBreadcrumb.ts@@ -0,0 +1,112 @@+export interface BreadcrumbSegment {+ /** Display name of this level. */+ name: string;+ /** Absolute path this level points at. */+ path: string;+ /**+ * Path relative to the project root, `''` for the root crumb itself, and+ * `undefined` when the file sits outside the root and has no index behind it.+ */+ relativePath?: string;+}++/** One entry of the project file index, narrowed to what a crumb menu needs. */+export interface BreadcrumbEntry {+ isDirectory: boolean;+ name: string;+ path: string;+ relativePath: string;+}++const splitPath = (filePath: string): string[] =>+ filePath.split(/[/\\]+/).filter((segment) => segment.length > 0);++const isInside = (pathSegments: string[], rootSegments: string[]): boolean =>+ rootSegments.length > 0 &&+ pathSegments.length > rootSegments.length &&+ rootSegments.every((segment, index) => pathSegments[index] === segment);++/**+ * Turn a file path into breadcrumb levels.+ *+ * Anchored on the project root when the file lives inside it, so a preview+ * reads `project › src › index.ts` instead of repeating the machine's home+ * directory on every tab. Every level is returned — the row narrows by+ * ellipsizing individual crumbs, so nothing is dropped while there is room.+ */+export const toBreadcrumbSegments = (filePath: string, rootPath?: string): BreadcrumbSegment[] => {+ const pathSegments = splitPath(filePath);+ if (pathSegments.length === 0) return [];++ const separator = filePath.includes('\\') && !filePath.includes('/') ? '\\' : '/';+ const absolutePrefix = filePath.startsWith('/') ? '/' : '';+ const rootSegments = rootPath ? splitPath(rootPath) : [];++ if (!isInside(pathSegments, rootSegments)) {+ return pathSegments.map((name, index) => ({+ name,+ path: absolutePrefix + pathSegments.slice(0, index + 1).join(separator),+ }));+ }++ const rootAbsolute = absolutePrefix + rootSegments.join(separator);+ const relativeSegments = pathSegments.slice(rootSegments.length);++ return [+ { name: rootSegments.at(-1)!, path: rootAbsolute, relativePath: '' },+ ...relativeSegments.map((name, index) => {+ const relativePath = relativeSegments.slice(0, index + 1).join('/');+ return {+ name,+ path: `${rootAbsolute}${separator}${relativeSegments.slice(0, index + 1).join(separator)}`,+ relativePath,+ };+ }),+ ];+};++/** Strip the trailing slash the project index puts on a directory entry. */+const withoutTrailingSlash = (relativePath: string): string => relativePath.replace(/\/$/, '');++/**+ * Index the flat project file list by parent directory, so a menu can walk the+ * tree without rescanning every entry per folder. The root's children sit under+ * `''`.+ *+ * Directory entries are marked with a trailing slash (`src/`), which has to come+ * off before the depth test or every folder reads as a grandchild and only files+ * ever show up.+ */+export const groupChildrenByParent = <T extends BreadcrumbEntry>(+ entries: T[],+): Map<string, T[]> => {+ const byParent = new Map<string, T[]>();++ for (const entry of entries) {+ const relativePath = withoutTrailingSlash(entry.relativePath);+ if (!relativePath) continue;++ const lastSlash = relativePath.lastIndexOf('/');+ const parent = lastSlash < 0 ? '' : relativePath.slice(0, lastSlash);+ const siblings = byParent.get(parent);+ if (siblings) siblings.push(entry);+ else byParent.set(parent, [entry]);+ }++ for (const siblings of byParent.values()) {+ // Folders first, then case-insensitive by name — the order every file tree+ // in this product already uses.+ siblings.sort((a, b) => {+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;+ return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });+ });+ }++ return byParent;+};++/** Immediate children of a directory, in the same order as the grouping above. */+export const listDirectoryChildren = <T extends BreadcrumbEntry>(+ entries: T[],+ directoryRelativePath: string,+): T[] => groupChildrenByParent(entries).get(withoutTrailingSlash(directoryRelativePath)) ?? [];