Files
rhema-together/web/app/components/FilesPane.vue
T
vhaudiquet 7d98b04d63 feat(web): expand folders in place in the file browser
Opening a folder replaced the root listing, so every step inward lost
the way back and the tree above it. A folder now opens under its
parent, nested folders open under theirs, and the root stays visible.

Each folder is read again when it is expanded, so files a turn added or
removed show up the next time the folder opens. The size column hides
below 260px of list width, where the indent leaves no room for both a
name and a size.
2026-12-01 01:09:12 +01:00

412 lines
14 KiB
Vue

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ChevronRight, File, Folder, Link as LinkIcon } from 'lucide-vue-next'
import type { FileContentResponse, FileEntry, FileListResponse, GitSummaryResponse } from '~/types'
import { apiErrorMessage } from '~/utils/errors'
import { formatSize } from '~/utils/format'
const props = defineProps<{ roomId: string; roomName: string }>()
const api = useApi()
const FILES_WIDTH_KEY = 'together.files-list-width'
const FILES_HEIGHT_KEY = 'together.files-list-height'
const FILES_MIN_WIDTH = 140
const FILES_MIN_HEIGHT = 120
const FILES_DEFAULT_WIDTH_PERCENT = 0.34
const FILES_DEFAULT_HEIGHT_PERCENT = 0.38
const FILES_MAX_WIDTH_PERCENT = 0.55
const FILES_MAX_HEIGHT_PERCENT = 0.6
const FILES_STACKED_WIDTH = 430
type DirState = { loading: boolean; error: string; entries: FileEntry[] }
type TreeRow =
| { kind: 'entry'; key: string; entry: FileEntry; depth: number }
| { kind: 'note'; key: string; text: string; depth: number; error: boolean }
const dirs = reactive(new Map<string, DirState>())
const expanded = reactive(new Set<string>())
const dirTokens = new Map<string, number>()
let dirSeq = 0
const filesEl = ref<HTMLElement | null>(null)
const browserEl = ref<HTMLElement | null>(null)
const filesWidth = ref(0)
const filesHeight = ref(0)
const listWidth = ref<number | null>(null)
const listHeight = ref<number | null>(null)
let filesObserver: ResizeObserver | null = null
type FilesDrag = {
pointerId: number
startX: number
startY: number
startSize: number
narrow: boolean
moved: boolean
}
let filesDrag: FilesDrag | null = null
const selected = ref<FileEntry | null>(null)
const file = ref<FileContentResponse | null>(null)
const fileLoading = ref(false)
const fileError = ref('')
const git = ref<GitSummaryResponse | null>(null)
const gitLoading = ref(false)
const gitError = ref('')
let fileRequest = 0
const narrow = computed(() => filesWidth.value > 0 && filesWidth.value <= FILES_STACKED_WIDTH)
function fileListRange(stacked: boolean): { min: number; max: number } {
const total = stacked ? filesHeight.value : filesWidth.value
const ratio = stacked ? FILES_MAX_HEIGHT_PERCENT : FILES_MAX_WIDTH_PERCENT
const minimum = stacked ? FILES_MIN_HEIGHT : FILES_MIN_WIDTH
return { min: minimum, max: Math.max(minimum, Math.floor(total * ratio)) }
}
function clampFileListSize(size: number, stacked = narrow.value): number {
const range = fileListRange(stacked)
return Math.min(Math.max(Math.round(size), range.min), range.max)
}
const fileListMax = computed(() => fileListRange(narrow.value).max)
const fileListValue = computed(() => {
const stored = narrow.value ? listHeight.value : listWidth.value
if (stored !== null) return clampFileListSize(stored)
const total = narrow.value ? filesHeight.value : filesWidth.value
const ratio = narrow.value ? FILES_DEFAULT_HEIGHT_PERCENT : FILES_DEFAULT_WIDTH_PERCENT
const minimum = narrow.value ? FILES_MIN_HEIGHT : FILES_MIN_WIDTH
return clampFileListSize(Math.round(total * ratio) || minimum)
})
const filesStyle = computed(() => {
const style: Record<string, string> = {}
if (narrow.value) {
if (listHeight.value !== null) {
style['--files-browser-height'] = `${clampFileListSize(listHeight.value)}px`
}
} else if (listWidth.value !== null) {
style['--files-browser-width'] = `${clampFileListSize(listWidth.value)}px`
}
return Object.keys(style).length > 0 ? style : undefined
})
function readSize(key: string): number | null {
if (typeof window === 'undefined') return null
try {
const raw = window.localStorage.getItem(key)
if (!raw) return null
const value = Number.parseInt(raw, 10)
return Number.isFinite(value) && value > 0 ? value : null
} catch {
return null
}
}
function saveSize(key: string, size: number) {
try {
window.localStorage.setItem(key, String(Math.round(size)))
} catch {
// A browser that refuses storage keeps the size for this visit.
}
}
function onFilesResizeStart(event: PointerEvent) {
if (event.button !== 0) return
const browser = browserEl.value
const container = filesEl.value
if (!browser || !container) return
event.preventDefault()
filesWidth.value = container.clientWidth
filesHeight.value = container.clientHeight
const isNarrow = narrow.value
const rect = browser.getBoundingClientRect()
filesDrag = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
startSize: isNarrow ? rect.height : rect.width,
narrow: isNarrow,
moved: false,
}
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
document.body.classList.add(isNarrow ? 'files-resizing-y' : 'files-resizing-x')
}
function onFilesResizeMove(event: PointerEvent) {
if (!filesDrag || event.pointerId !== filesDrag.pointerId) return
const delta = filesDrag.narrow ? event.clientY - filesDrag.startY : event.clientX - filesDrag.startX
if (Math.abs(delta) >= 1) filesDrag.moved = true
const next = clampFileListSize(filesDrag.startSize + delta, filesDrag.narrow)
if (filesDrag.narrow) listHeight.value = next
else listWidth.value = next
}
function endFilesResize() {
if (!filesDrag) return
const { moved, narrow: wasNarrow } = filesDrag
filesDrag = null
document.body.classList.remove('files-resizing-x', 'files-resizing-y')
if (!moved) return
if (wasNarrow) {
if (listHeight.value !== null) saveSize(FILES_HEIGHT_KEY, listHeight.value)
} else if (listWidth.value !== null) {
saveSize(FILES_WIDTH_KEY, listWidth.value)
}
}
function onFilesResizeKey(event: KeyboardEvent) {
const isNarrow = narrow.value
const browser = browserEl.value
const current = isNarrow
? (browser?.getBoundingClientRect().height ?? fileListValue.value)
: (browser?.getBoundingClientRect().width ?? fileListValue.value)
const step = event.shiftKey ? 64 : 16
const decrease = isNarrow ? 'ArrowUp' : 'ArrowLeft'
const increase = isNarrow ? 'ArrowDown' : 'ArrowRight'
let next: number
if (event.key === decrease) next = current - step
else if (event.key === increase) next = current + step
else if (event.key === 'Home') next = isNarrow ? FILES_MIN_HEIGHT : FILES_MIN_WIDTH
else if (event.key === 'End') next = fileListMax.value
else return
event.preventDefault()
const clamped = clampFileListSize(next, isNarrow)
if (isNarrow) listHeight.value = clamped
else listWidth.value = clamped
saveSize(isNarrow ? FILES_HEIGHT_KEY : FILES_WIDTH_KEY, clamped)
}
// The visible rows: the root's entries, then the entries of every
// expanded folder under it, each one a level deeper.
const rows = computed<TreeRow[]>(() => {
const out: TreeRow[] = []
const walk = (dir: string, depth: number) => {
const state = dirs.get(dir)
if (!state) return
if (state.loading) {
out.push({ kind: 'note', key: `${dir}:loading`, text: 'Loading files.', depth, error: false })
return
}
if (state.error) {
out.push({ kind: 'note', key: `${dir}:error`, text: state.error, depth, error: true })
return
}
if (state.entries.length === 0) {
const text = dir === '' ? 'The workspace is empty.' : 'This folder is empty.'
out.push({ kind: 'note', key: `${dir}:empty`, text, depth, error: false })
return
}
for (const entry of state.entries) {
out.push({ kind: 'entry', key: entry.path, entry, depth })
if (entry.kind === 'dir' && expanded.has(entry.path)) walk(entry.path, depth + 1)
}
}
walk('', 0)
return out
})
function indent(depth: number) {
return { '--tree-depth': String(depth) }
}
const lineNumbers = computed(() => {
const content = file.value?.content ?? ''
const count = content === '' ? 1 : content.replace(/\n$/, '').split('\n').length
return Array.from({ length: count }, (_, index) => index + 1).join('\n')
})
// Expanding a folder reads it again, so a file a turn added or removed
// shows up the next time the folder is opened.
async function loadDir(target: string) {
const request = ++dirSeq
dirTokens.set(target, request)
const previous = dirs.get(target)
dirs.set(target, { loading: true, error: '', entries: previous?.entries ?? [] })
try {
const response = await api.get<FileListResponse>(`/rooms/${props.roomId}/files`, { path: target })
if (dirTokens.get(target) !== request) return
dirs.set(target, { loading: false, error: '', entries: response.entries })
} catch (err) {
if (dirTokens.get(target) !== request) return
dirs.set(target, {
loading: false,
error: apiErrorMessage(err),
entries: previous?.entries ?? [],
})
}
}
async function openFile(entry: FileEntry) {
const request = ++fileRequest
selected.value = entry
file.value = null
fileError.value = ''
fileLoading.value = true
try {
const response = await api.get<FileContentResponse>(`/rooms/${props.roomId}/file`, { path: entry.path })
if (request !== fileRequest) return
file.value = response
} catch (err) {
if (request !== fileRequest) return
fileError.value = apiErrorMessage(err)
} finally {
if (request === fileRequest) fileLoading.value = false
}
}
function toggleDir(entry: FileEntry) {
if (expanded.has(entry.path)) {
expanded.delete(entry.path)
return
}
expanded.add(entry.path)
void loadDir(entry.path)
}
function activateEntry(entry: FileEntry) {
if (entry.kind === 'dir') toggleDir(entry)
else void openFile(entry)
}
async function loadGit() {
gitLoading.value = true
gitError.value = ''
try {
git.value = await api.get<GitSummaryResponse>(`/rooms/${props.roomId}/git`)
} catch (err) {
gitError.value = apiErrorMessage(err)
} finally {
gitLoading.value = false
}
}
onMounted(() => {
listWidth.value = readSize(FILES_WIDTH_KEY)
listHeight.value = readSize(FILES_HEIGHT_KEY)
const element = filesEl.value
if (element) {
filesWidth.value = element.clientWidth
filesHeight.value = element.clientHeight
filesObserver = new ResizeObserver(() => {
filesWidth.value = filesEl.value?.clientWidth ?? 0
filesHeight.value = filesEl.value?.clientHeight ?? 0
})
filesObserver.observe(element)
}
void loadDir('')
void loadGit()
})
onBeforeUnmount(() => {
filesObserver?.disconnect()
filesObserver = null
document.body.classList.remove('files-resizing-x', 'files-resizing-y')
})
</script>
<template>
<div class="files-pane">
<div ref="filesEl" class="files" :style="filesStyle">
<div ref="browserEl" class="files-browser">
<div class="tree-head">Workspace</div>
<div class="file-list" aria-label="Workspace files">
<template v-for="row in rows" :key="row.key">
<p
v-if="row.kind === 'note'"
class="tree-note"
:class="{ error: row.error }"
:style="indent(row.depth)"
>
{{ row.text }}
</p>
<button
v-else
type="button"
class="file-row"
:class="{ active: selected?.path === row.entry.path }"
:style="indent(row.depth)"
:title="row.entry.path"
:aria-expanded="row.entry.kind === 'dir' ? expanded.has(row.entry.path) : undefined"
@click="activateEntry(row.entry)"
>
<ChevronRight
v-if="row.entry.kind === 'dir'"
:size="14"
class="tree-caret"
:class="{ open: expanded.has(row.entry.path) }"
aria-hidden="true"
/>
<span v-else class="tree-caret-gap" aria-hidden="true"></span>
<Folder v-if="row.entry.kind === 'dir'" :size="14" aria-hidden="true" />
<LinkIcon v-else-if="row.entry.kind === 'link'" :size="14" aria-hidden="true" />
<File v-else :size="14" aria-hidden="true" />
<span class="file-row-name">{{ row.entry.name }}</span>
<span v-if="row.entry.kind === 'file'" class="file-row-size">{{ formatSize(row.entry.size) }}</span>
</button>
</template>
</div>
</div>
<div
class="files-resizer"
role="separator"
:aria-orientation="narrow ? 'horizontal' : 'vertical'"
aria-label="Resize file list"
:aria-valuemin="narrow ? FILES_MIN_HEIGHT : FILES_MIN_WIDTH"
:aria-valuemax="fileListMax"
:aria-valuenow="fileListValue"
:aria-valuetext="`${fileListValue} pixels`"
title="Drag to resize. Arrow keys also work."
tabindex="0"
@pointerdown="onFilesResizeStart"
@pointermove="onFilesResizeMove"
@pointerup="endFilesResize"
@pointercancel="endFilesResize"
@lostpointercapture="endFilesResize"
@keydown="onFilesResizeKey"
></div>
<div class="files-viewer">
<template v-if="selected">
<div class="viewer-head">
<span class="viewer-path" :title="selected.path">{{ selected.path }}</span>
<span v-if="file" class="file-row-size">{{ formatSize(file.size) }}</span>
</div>
<div class="viewer-scroll">
<p v-if="fileLoading" class="meta pane-pad-3">Reading file.</p>
<p v-else-if="fileError" class="form-error pane-pad-3">{{ fileError }}</p>
<p v-else-if="file?.binary" class="meta pane-pad-3">Binary file. Preview is not available.</p>
<p v-else-if="file && file.content === ''" class="meta pane-pad-3">This file is empty.</p>
<template v-else-if="file">
<pre class="gutter" aria-hidden="true">{{ lineNumbers }}</pre>
<pre class="viewer-code">{{ file.content }}</pre>
</template>
</div>
<p v-if="file?.truncated" class="meta viewer-note">
Showing the first 400 KB.
</p>
</template>
<p v-else class="empty pane-pad-3">Select a file to read.</p>
</div>
</div>
<details class="git-strip">
<summary>Git status</summary>
<p v-if="gitLoading" class="meta pane-note">Reading git status.</p>
<p v-else-if="gitError" class="form-error pane-note">{{ gitError }}</p>
<pre v-else-if="git?.text">{{ git.text }}</pre>
<p v-else class="meta pane-note">No git output.</p>
</details>
</div>
</template>