tablegridselectiongroups
File Browser
Finder-like file browser using table for the list
view with resizable, sortable columns and grid for
the grid view. Click headers to sort, drag borders to resize.
Double-click folders to navigate. [Experimental]
0
items
/
Source
// File Browser — Finder-like file browser with grid/list views
// Grid view uses grid plugin, list view uses table plugin for resizable/sortable columns
// Demonstrates switching between two layout modes with shared navigation
import { createVList, grid, groups, table, columnPin, columnReorder, selection, scrollbar } from "vlist";
// =============================================================================
// File Type Icons
// =============================================================================
const FILE_ICONS = {
folder: "📁",
js: "📄",
ts: "📘",
json: "📋",
html: "🌐",
css: "🎨",
scss: "🎨",
md: "📝",
png: "🖼️",
jpg: "🖼️",
jpeg: "🖼️",
gif: "🖼️",
svg: "🖼️",
txt: "📄",
pdf: "📕",
zip: "📦",
default: "📄",
};
function getFileIcon(item) {
if (item.type === "directory") return FILE_ICONS.folder;
const ext = item.extension;
return FILE_ICONS[ext] || FILE_ICONS.default;
}
function getFileKind(item) {
if (item.type === "directory") return "Folder";
const ext = item.extension;
const kindMap = {
js: "JavaScript",
ts: "TypeScript",
json: "JSON",
html: "HTML",
css: "CSS",
scss: "SCSS",
md: "Markdown",
txt: "Text",
png: "PNG Image",
jpg: "JPEG Image",
jpeg: "JPEG Image",
gif: "GIF Image",
svg: "SVG Image",
pdf: "PDF",
zip: "Archive",
gz: "Archive",
tar: "Archive",
};
return kindMap[ext] || (ext ? ext.toUpperCase() : "Document");
}
// =============================================================================
// State
// =============================================================================
let currentPath = "";
let items = [];
let sortedItems = [];
let currentView = "list";
let currentColumns = 6;
let currentGap = 8;
let list = null;
let navigationHistory = [""];
let historyIndex = 0;
let selectedItemId = null;
let currentArrangeBy = "none";
// Table sort & column feature state
// Ordered list of { key, direction }, primary key first — what the table's
// `sort` option and `setSort()` take once multiSort is on.
let columnSorts = [];
// Columns pinned right now, keyed by column key ("left" or "right"), exactly
// as the table's columnPin feature reports them in `column:pin`. This is the
// source of truth across re-creates; the Pin select mirrors it.
let currentPins = {};
// Widths the user gave columns with `column:resize`, keyed by column key.
// Every re-create feeds them back into the table, so a resized column does not
// fall back to FILE_COLUMNS' default width (the pin panel used to reset it).
let columnWidths = {};
let useColumnReorder = true;
// =============================================================================
// Utility Functions
// =============================================================================
function formatFileSize(bytes) {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + " " + sizes[i];
}
function formatDate(dateStr) {
const now = new Date();
const modified = new Date(dateStr);
const isToday =
now.getFullYear() === modified.getFullYear() &&
now.getMonth() === modified.getMonth() &&
now.getDate() === modified.getDate();
if (isToday) {
const timeStr = modified.toLocaleTimeString("en-US", {
hour: "numeric",
minute: "2-digit",
hour12: true,
});
return `Today at ${timeStr}`;
}
const month = modified.toLocaleDateString("en-US", { month: "short" });
const day = modified.getDate();
const year = modified.getFullYear();
return `${month} ${day}, ${year}`;
}
function formatPath(path) {
return path || "/";
}
// =============================================================================
// Date Grouping
// =============================================================================
function getDateGroup(item) {
const now = new Date();
const modified = new Date(item.modified);
if (
now.getFullYear() === modified.getFullYear() &&
now.getMonth() === modified.getMonth() &&
now.getDate() === modified.getDate()
) {
return "Today";
}
const diffTime = Math.abs(now - modified);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays <= 7) return "Previous 7 Days";
if (diffDays <= 30) return "Previous 30 Days";
return "Older";
}
function getNameGroup(item) {
const first = item.name.charAt(0).toUpperCase();
if (/[A-Z]/.test(first)) return first;
if (/[0-9]/.test(first)) return "#";
return "•";
}
function getSizeGroup(item) {
if (item.type === "directory") return "—";
const size = item.size || 0;
if (size === 0) return "Zero Bytes";
if (size < 1024) return "Up to 1 KB";
if (size < 100 * 1024) return "1 KB to 100 KB";
if (size < 1024 * 1024) return "100 KB to 1 MB";
if (size < 100 * 1024 * 1024) return "1 MB to 100 MB";
return "100 MB or Greater";
}
// =============================================================================
// Arrangement / Sorting
// =============================================================================
function getArrangementConfig(arrangeBy) {
switch (arrangeBy) {
case "none":
return {
groupBy: "none",
getGroupKey: null,
sortFn: (a, b) => {
if (a.type === "directory" && b.type !== "directory") return -1;
if (a.type !== "directory" && b.type === "directory") return 1;
return a.name.localeCompare(b.name, undefined, { numeric: true });
},
};
case "name":
return {
groupBy: "name",
getGroupKey: getNameGroup,
sortFn: (a, b) =>
a.name.localeCompare(b.name, undefined, { numeric: true }),
};
case "kind":
return {
groupBy: "kind",
getGroupKey: getFileKind,
sortFn: (a, b) => {
const kindA = getFileKind(a);
const kindB = getFileKind(b);
if (kindA !== kindB) return kindA.localeCompare(kindB);
return a.name.localeCompare(b.name, undefined, { numeric: true });
},
};
case "date-modified":
return {
groupBy: "date",
getGroupKey: getDateGroup,
sortFn: (a, b) => {
const groupA = getDateGroup(a);
const groupB = getDateGroup(b);
const groupOrder = [
"Today",
"Previous 7 Days",
"Previous 30 Days",
"Older",
];
const orderA = groupOrder.indexOf(groupA);
const orderB = groupOrder.indexOf(groupB);
if (orderA !== orderB) return orderA - orderB;
const dateA = new Date(a.modified).getTime();
const dateB = new Date(b.modified).getTime();
if (isNaN(dateA)) return 1;
if (isNaN(dateB)) return -1;
return dateB - dateA;
},
};
case "size": {
const sizeGroupOrder = [
"—",
"Zero Bytes",
"Up to 1 KB",
"1 KB to 100 KB",
"100 KB to 1 MB",
"1 MB to 100 MB",
"100 MB or Greater",
];
return {
groupBy: "size",
getGroupKey: getSizeGroup,
sortFn: (a, b) => {
const groupA = getSizeGroup(a);
const groupB = getSizeGroup(b);
const orderA = sizeGroupOrder.indexOf(groupA);
const orderB = sizeGroupOrder.indexOf(groupB);
if (orderA !== orderB) return orderA - orderB;
return (b.size || 0) - (a.size || 0);
},
};
}
default:
return {
groupBy: "none",
getGroupKey: null,
sortFn: (a, b) => a.name.localeCompare(b.name),
};
}
}
// =============================================================================
// Table Column Sorting (for list view)
// =============================================================================
/**
* Per-column comparison, ascending. Shared by single- and multi-column sort so
* the two can never drift: locale compare for names and kinds, numeric for
* size and date. Dates that do not parse sort last in both directions.
*/
const COLUMN_COMPARATORS = {
name: (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }),
size: (a, b) => (a.size || 0) - (b.size || 0),
modified: (a, b) => {
const aVal = new Date(a.modified).getTime();
const bVal = new Date(b.modified).getTime();
if (isNaN(aVal)) return 1;
if (isNaN(bVal)) return -1;
return aVal - bVal;
},
kind: (a, b) => getFileKind(a).localeCompare(getFileKind(b)),
};
function compareByColumn(key, a, b) {
const compare = COLUMN_COMPARATORS[key];
return compare ? compare(a, b) : 0;
}
/** Default order when no column is sorted: folders first, then by name. */
function sortByName(data) {
return [...data].sort((a, b) => {
if (a.type === "directory" && b.type !== "directory") return -1;
if (a.type !== "directory" && b.type === "directory") return 1;
return a.name.localeCompare(b.name, undefined, { numeric: true });
});
}
/**
* Sort items by an ordered list of { key, direction }, primary key first.
* Files and folders are interleaved (like macOS Finder column sort).
*/
function sortByColumns(data, sorts) {
if (!sorts || sorts.length === 0) return sortByName(data);
return [...data].sort((a, b) => {
for (const { key, direction } of sorts) {
const result = compareByColumn(key, a, b);
if (result !== 0) return direction === "desc" ? -result : result;
}
return 0;
});
}
function applyColumnSorts(sorts) {
columnSorts = (sorts || []).map(({ key, direction }) => ({ key, direction }));
sortedItems = sortByColumns(items, columnSorts);
if (list && currentView === "list") {
list.setItems(sortedItems);
}
updateSortDetail();
}
// =============================================================================
// Templates
// =============================================================================
// Grid view template — icon + name card
const gridItemTemplate = (item) => {
const icon = getFileIcon(item);
return `
<div class="file-card" data-type="${item.type}">
<div class="file-card__icon">${icon}</div>
<div class="file-card__name" title="${item.name}">${item.name}</div>
</div>
`;
};
// Fallback template for table (table plugin uses cell renderers instead)
const tableRowTemplate = () => "";
// =============================================================================
// Table Column Definitions
// =============================================================================
/** Icon + name cell renderer */
const nameCell = (item) => {
const icon = getFileIcon(item);
return `
<div class="file-name">
<span class="file-name__icon">${icon}</span>
<span class="file-name__text">${item.name}</span>
</div>
`;
};
/** File size cell renderer */
const sizeCell = (item) => {
if (item.type === "directory") return "—";
return item.size != null ? formatFileSize(item.size) : "—";
};
/** Date modified cell renderer */
const dateCell = (item) => {
return formatDate(item.modified);
};
/** File kind cell renderer */
const kindCell = (item) => {
return getFileKind(item);
};
const FILE_COLUMNS = [
{
key: "name",
label: "Name",
width: 350,
minWidth: 140,
sortable: true,
cell: nameCell,
},
{
key: "size",
label: "Size",
width: 100,
minWidth: 70,
sortable: true,
align: "right",
cell: sizeCell,
},
{
key: "modified",
label: "Date Modified",
width: 200,
minWidth: 120,
sortable: true,
cell: dateCell,
},
{
key: "kind",
label: "Kind",
width: 140,
minWidth: 80,
sortable: true,
cell: kindCell,
},
];
// =============================================================================
// API
// =============================================================================
async function fetchDirectory(path) {
try {
const response = await fetch(`/api/files?path=${encodeURIComponent(path)}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Failed to fetch directory:", error);
return { path, items: [] };
}
}
// =============================================================================
// View Creation
// =============================================================================
async function createBrowser(view = "list") {
if (list) {
if (selectedItemId !== null && typeof list.getSelected === "function") {
const currentSelected = list.getSelected();
selectedItemId = currentSelected.length > 0 ? currentSelected[0] : null;
}
list.destroy();
list = null;
}
const container = document.getElementById("browser-container");
container.innerHTML = "";
currentView = view;
if (view === "grid") {
createGridView();
} else {
createTableList();
}
updateNavigationState();
}
function bindSelection(currentItems) {
list.on("selection:change", ({ selected, items: selectedItems }) => {
if (selected && selected.length > 0) {
selectedItemId = selected[0];
const item =
(selectedItems && selectedItems[0]) ||
currentItems.find((entry) => entry.id === selectedItemId);
if (item) showFileDetail(item);
} else if (selectedItems && selectedItems.length > 0) {
selectedItemId = selectedItems[0].id;
showFileDetail(selectedItems[0]);
} else {
selectedItemId = null;
clearFileDetail();
}
});
if (
selectedItemId !== null &&
currentItems.some((item) => item.id === selectedItemId)
) {
list.select(selectedItemId);
} else {
selectedItemId = null;
clearFileDetail();
}
}
// =============================================================================
// Grid View (grid + groups plugins)
// =============================================================================
function createGridView() {
const container = document.getElementById("browser-container");
const innerWidth = container.clientWidth - 2;
const colWidth =
(innerWidth - (currentColumns - 1) * currentGap) / currentColumns;
const height = Math.max(116, Math.round(colWidth * 0.95));
const config = getArrangementConfig(currentArrangeBy);
const sorted = [...items].sort(config.sortFn);
// Create group map if grouping is enabled
let groupMap = null;
if (config.groupBy !== "none" && config.getGroupKey) {
groupMap = new Map();
const groupCounts = {};
sorted.forEach((item, index) => {
const groupKey = config.getGroupKey(item);
groupMap.set(index, groupKey);
groupCounts[groupKey] = (groupCounts[groupKey] || 0) + 1;
});
}
const plugins = [
grid({ columns: currentColumns, gap: currentGap }),
selection({ mode: "single" }),
scrollbar(),
];
if (groupMap) {
plugins.push(
groups({
getGroupForIndex: (index) => groupMap.get(index) || "",
header: {
height: 40,
template: (groupKey) => {
let count = 0;
groupMap.forEach((key) => {
if (key === groupKey) count++;
});
return `
<div class="group-header">
<span class="group-header__label">${groupKey}</span>
<span class="group-header__count">${count} items</span>
</div>
`;
},
},
sticky: true,
}),
);
}
list = createVList({
container: "#browser-container",
ariaLabel: "File browser",
item: {
height,
template: gridItemTemplate,
},
items: sorted,
}, plugins);
bindSelection(sorted);
list.on("item:dblclick", ({ item }) => {
if (!item.__groupHeader) {
handleItemDoubleClick(item);
}
});
updateSortDetail();
}
// =============================================================================
// List View (table + selection plugins)
// =============================================================================
// The Pin select's two presets, as a pin map the table understands.
function pinsForMode(mode) {
const firstKey = FILE_COLUMNS[0].key;
const lastKey = FILE_COLUMNS[FILE_COLUMNS.length - 1].key;
if (mode === "first") return { [firstKey]: "left" };
if (mode === "both") {
return { [firstKey]: "left", [lastKey]: "right" };
}
return {};
}
// The preset that describes the table's current pins, if any. Shift+Alt+Arrow
// can pin columns the presets do not cover; the select then shows no selection.
function modeForPins(pins) {
const firstKey = FILE_COLUMNS[0].key;
const lastKey = FILE_COLUMNS[FILE_COLUMNS.length - 1].key;
const keys = Object.keys(pins || {});
if (keys.length === 0) return "none";
if (keys.length === 1 && pins[firstKey] === "left") return "first";
if (
keys.length === 2 &&
pins[firstKey] === "left" &&
pins[lastKey] === "right"
) {
return "both";
}
return "";
}
function syncPinModeSelect() {
const select = document.getElementById("pin-mode");
if (select) select.value = modeForPins(currentPins);
}
// The column definitions for a table re-create: FILE_COLUMNS with every width
// the user has set, so navigating, switching view or toggling reorder does not
// throw the resized columns back to their defaults.
function columnsWithWidths() {
return FILE_COLUMNS.map((column) =>
columnWidths[column.key] === undefined
? column
: { ...column, width: columnWidths[column.key] },
);
}
function createTableList() {
const rowHeight = 28;
const headerHeight = 28;
// Check if current arrangement has grouping
const config = getArrangementConfig(currentArrangeBy);
const hasGroups = config.groupBy !== "none";
// When grouping is active, use the arrangement sort (groups must be contiguous).
// Otherwise use the column sorts or the default name sort.
if (hasGroups) {
sortedItems = [...items].sort(config.sortFn);
} else {
sortedItems = sortByColumns(items, columnSorts);
}
// Build group map if grouping is enabled
let groupMap = null;
if (hasGroups && config.getGroupKey) {
groupMap = new Map();
const groupCounts = {};
sortedItems.forEach((item, index) => {
const groupKey = config.getGroupKey(item);
groupMap.set(index, groupKey);
groupCounts[groupKey] = (groupCounts[groupKey] || 0) + 1;
});
}
const features = [
// Always installed: Shift+Alt+Arrow on a header pins or unpins that column
// even while Pin is None, and every pin change reaches the panel below.
columnPin({ pins: { ...currentPins } }),
...(useColumnReorder ? [columnReorder()] : []),
];
const plugins = [
table({
columns: columnsWithWidths(),
rowHeight,
headerHeight,
resizable: true,
columnBorders: false,
rowBorders: false,
minColumnWidth: 50,
multiSort: true,
// Hand the table the whole order so the indicators and their priority
// badges survive a re-create; an empty list means "nothing sorted".
sort: columnSorts.length
? columnSorts.map(({ key, direction }) => ({ key, direction }))
: undefined,
features,
}),
];
if (groupMap) {
plugins.push(
groups({
getGroupForIndex: (index) => groupMap.get(index) || "",
header: {
height: 32,
template: (groupKey) => {
let count = 0;
groupMap.forEach((key) => {
if (key === groupKey) count++;
});
return `
<div class="group-header">
<span class="group-header__label">${groupKey}</span>
<span class="group-header__count">${count} items</span>
</div>
`;
},
},
sticky: false,
}),
);
}
plugins.push(selection({ mode: "single" }));
plugins.push(scrollbar());
list = createVList({
container: "#browser-container",
ariaLabel: "File browser",
padding: [2, 6],
item: {
height: rowHeight,
striped: "odd",
template: tableRowTemplate,
},
items: sortedItems,
}, plugins);
// Column sort — a plain header click sorts by that column alone; Shift/Ctrl/
// Cmd + click (or Enter/Space) adds, flips or removes a column. The event
// carries the whole order in `sorts`, primary first.
list.on("column:sort", ({ key, direction, sorts }) => {
const next = Array.isArray(sorts) ? sorts : direction ? [{ key, direction }] : [];
applyColumnSorts(next);
if (list.setSort) {
list.setSort(columnSorts);
}
});
// Column pin state — the table reports the whole map on every change, from
// the Pin select, a re-create, or Shift+Alt+Arrow on a header.
list.on("column:pin", ({ pins }) => {
currentPins = { ...(pins || {}) };
syncPinModeSelect();
});
// Column widths — remember what the user resized, so the next re-create
// (navigation, view switch, reorder toggle) feeds it back through
// columnsWithWidths() instead of using FILE_COLUMNS' default width.
list.on("column:resize", ({ key, width }) => {
if (key && typeof width === "number") columnWidths[key] = width;
});
// Selection — show detail in panel and restore across rebuilds
bindSelection(sortedItems);
// Double-click row to navigate into folder
list.on("item:dblclick", ({ item }) => {
if (item && !item.__groupHeader && item.type === "directory") {
handleItemDoubleClick(item);
}
});
updateSortDetail();
}
// =============================================================================
// Navigation
// =============================================================================
async function navigateTo(path, addToHistory = true) {
const data = await fetchDirectory(path);
currentPath = data.path;
items = data.items.map((item) => ({ ...item, id: item.name }));
selectedItemId = null;
if (addToHistory) {
navigationHistory = navigationHistory.slice(0, historyIndex + 1);
navigationHistory.push(path);
historyIndex = navigationHistory.length - 1;
}
await createBrowser(currentView);
updateBreadcrumb();
updateNavigationState();
updateInfo();
}
function handleItemDoubleClick(item) {
if (item.type === "directory") {
const newPath = currentPath ? `${currentPath}/${item.name}` : item.name;
selectedItemId = null;
navigateTo(newPath);
}
}
async function navigateBack() {
if (historyIndex > 0) {
historyIndex--;
await navigateTo(navigationHistory[historyIndex], false);
}
}
async function navigateForward() {
if (historyIndex < navigationHistory.length - 1) {
historyIndex++;
await navigateTo(navigationHistory[historyIndex], false);
}
}
// =============================================================================
// UI Updates
// =============================================================================
const breadcrumbEl = document.getElementById("breadcrumb");
function updateBreadcrumb() {
const parts = currentPath ? currentPath.split("/") : [];
let html = `<button class="breadcrumb__item" data-path="">root</button>`;
let pathSoFar = "";
parts.forEach((part, index) => {
pathSoFar += (index > 0 ? "/" : "") + part;
html += `<span class="breadcrumb__sep">›</span>`;
html += `<button class="breadcrumb__item" data-path="${pathSoFar}">${part}</button>`;
});
breadcrumbEl.innerHTML = html;
}
function updateNavigationState() {
const backBtn = document.getElementById("btn-back");
const forwardBtn = document.getElementById("btn-forward");
backBtn.disabled = historyIndex <= 0;
forwardBtn.disabled = historyIndex >= navigationHistory.length - 1;
}
// =============================================================================
// Info Bar Stats
// =============================================================================
const infoItems = document.getElementById("info-items");
const infoPath = document.getElementById("info-path");
function updateInfo() {
if (infoItems) infoItems.textContent = String(items.length);
if (infoPath) infoPath.textContent = currentPath ? `/${currentPath}` : "/";
}
// =============================================================================
// Detail Panel — selected file info
// =============================================================================
const detailEl = document.getElementById("file-detail");
function showFileDetail(item) {
if (!detailEl) return;
const icon = getFileIcon(item);
const kind = getFileKind(item);
const sizeText =
item.type === "file" && item.size != null ? formatFileSize(item.size) : "—";
const dateText = formatDate(item.modified);
detailEl.innerHTML = `
<div class="file-detail__header">
<span class="file-detail__icon">${icon}</span>
<div>
<div class="file-detail__name">${item.name}</div>
<div class="file-detail__kind">${kind}</div>
</div>
</div>
<div class="file-detail__meta">
<span>${sizeText}</span>
<span>${dateText}</span>
</div>
`;
}
function clearFileDetail() {
if (!detailEl) return;
detailEl.innerHTML = `
<span class="ui-detail__empty">Click a row to see details</span>
`;
}
// =============================================================================
// Sort Detail Panel
// =============================================================================
const sortDetailEl = document.getElementById("sort-detail");
/** Column label for the Sort panel — "Kind", not the raw key. */
function sortColumnLabel(key) {
return FILE_COLUMNS.find((column) => column.key === key)?.label ?? key;
}
function updateSortDetail() {
if (!sortDetailEl) return;
let html = "";
// Show arrangement info if active
if (currentArrangeBy !== "none") {
const arrangeLabels = {
name: "Name",
kind: "Kind",
"date-modified": "Date Modified",
size: "Size",
};
const arrangeLabel = arrangeLabels[currentArrangeBy] || currentArrangeBy;
html += `
<div class="sort-info">
<span class="sort-info__label">Grouped by</span>
<span class="sort-info__key">${arrangeLabel}</span>
</div>
`;
}
// Show the column sort order, primary key first
if (columnSorts.length === 1) {
const [{ key, direction }] = columnSorts;
const arrow = direction === "asc" ? "▲" : "▼";
const label = direction === "asc" ? "Ascending" : "Descending";
html += `
<div class="sort-info">
<span class="sort-info__label">Sorted by</span>
<span class="sort-info__key">${sortColumnLabel(key)}</span>
<span class="sort-info__dir">${arrow} ${label}</span>
</div>
`;
} else if (columnSorts.length > 1) {
const parts = columnSorts.map(({ key, direction }) => {
const arrow = direction === "asc" ? "▲" : "▼";
return `
<span class="sort-info__key">${sortColumnLabel(key)}</span>
<span class="sort-info__dir">${arrow}</span>
`;
});
html += `
<div class="sort-info">
<span class="sort-info__label">Sorted by</span>
${parts.join('<span class="sort-info__dir">then</span>')}
</div>
`;
}
if (!html) {
html = `<span class="ui-detail__empty">Click a column header to sort (Shift-click adds a column)</span>`;
}
sortDetailEl.innerHTML = html;
}
// =============================================================================
// Initialization
// =============================================================================
(async () => {
// View switcher
document.getElementById("btn-view-grid").addEventListener("click", () => {
if (currentView === "grid") return;
document
.getElementById("btn-view-grid")
.classList.add("ui-segmented__btn--active");
document
.getElementById("btn-view-list")
.classList.remove("ui-segmented__btn--active");
createBrowser("grid");
});
document.getElementById("btn-view-list").addEventListener("click", () => {
if (currentView === "list") return;
document
.getElementById("btn-view-list")
.classList.add("ui-segmented__btn--active");
document
.getElementById("btn-view-grid")
.classList.remove("ui-segmented__btn--active");
createBrowser("list");
});
// Arrange by (still useful for grid view grouping)
document
.getElementById("arrange-by-select")
.addEventListener("change", (e) => {
currentArrangeBy = e.target.value;
// Arrange-by controls grouping, not column sort.
// Reset column sort when changing arrangement, then rebuild.
columnSorts = [];
createBrowser(currentView);
});
// Column pin mode (list view)
const pinModeSelect = document.getElementById("pin-mode");
if (pinModeSelect) {
pinModeSelect.value = modeForPins(currentPins);
pinModeSelect.addEventListener("change", () => {
const target = pinsForMode(pinModeSelect.value);
// Apply in place: re-creating the table from FILE_COLUMNS would reset
// every resized column to its default width.
if (
currentView === "list" &&
list &&
typeof list.setColumnPin === "function"
) {
const currentOf = () =>
typeof list.getColumnPins === "function" ? list.getColumnPins() : {};
for (const key of Object.keys(currentOf())) {
if (!(key in target)) list.setColumnPin(key, null);
}
for (const [key, pin] of Object.entries(target)) {
if (currentOf()[key] !== pin) list.setColumnPin(key, pin);
}
}
currentPins = target;
syncPinModeSelect();
});
}
// Column reorder toggle (list view)
const reorderToggle = document.getElementById("reorder-toggle");
if (reorderToggle) {
reorderToggle.checked = useColumnReorder;
reorderToggle.addEventListener("change", () => {
useColumnReorder = reorderToggle.checked;
if (currentView === "list") {
createBrowser("list");
}
});
}
// Toolbar navigation
document.getElementById("btn-back").addEventListener("click", () => {
navigateBack();
});
document.getElementById("btn-forward").addEventListener("click", () => {
navigateForward();
});
// Side panel navigation buttons
const btnNavBack = document.getElementById("btn-nav-back");
const btnNavForward = document.getElementById("btn-nav-forward");
if (btnNavBack) {
btnNavBack.addEventListener("click", () => {
navigateBack();
});
}
if (btnNavForward) {
btnNavForward.addEventListener("click", () => {
navigateForward();
});
}
// Breadcrumb click handler
breadcrumbEl.addEventListener("click", (e) => {
const btn = e.target.closest("[data-path]");
if (!btn) return;
navigateTo(btn.dataset.path);
});
// Initial load — start in vlist folder with list view
await navigateTo("vlist");
globalThis.__vlistRecreate = () => createBrowser(currentView);
})();
/* File Browser — example-specific styles
Common styles (.container, h1, .description, .split-layout, .split-panel, .ui-*)
are provided by example/example.css using shell.css design tokens. */
/* ============================================================================
Browser Container
============================================================================ */
#browser-container {
height: 500px;
margin: 0 auto;
background: var(--bg);
}
/* Override vlist default styles for grid view — no borders/radius */
#browser-container .vlist {
border-radius: 0px 0px var(--vlist-border-radius, 0.5rem)
var(--vlist-border-radius, 0.5rem);
}
/* ============================================================================
Table Header Overrides (List View — table plugin)
============================================================================ */
#browser-container .vlist-table-header {
text-transform: uppercase;
font-size: 0.6875rem;
letter-spacing: 0.04em;
background: var(--bg-card) !important;
}
#browser-container .vlist-table-header-cell {
padding-left: 0.75rem;
padding-right: 0.75rem;
}
#browser-container .vlist-table-header-cell--pin-left,
#browser-container .vlist-table-header-cell--pin-right {
background-color: var(--bg-card);
}
#browser-container .vlist-table-header-cell:focus,
#browser-container .vlist-table-header-cell:focus-visible {
outline: none;
background-color: var(--vlist-bg-selected, rgba(59, 130, 246, 0.12));
}
#browser-container .vlist-table-header-sort {
font-size: 1.1em;
}
/* ============================================================================
Table Row & Cell Overrides (List View — table plugin)
============================================================================ */
#browser-container .vlist-table-row {
font-size: 0.8125rem;
}
#browser-container .vlist-table-cell {
padding-left: 0.75rem;
padding-right: 0.75rem;
line-height: 1.4;
}
/* Finder-style selection for table rows — compound selectors because
.vlist-item and .vlist-table-row live on the same element in table mode. */
#browser-container .vlist-table-row.vlist-item--selected {
background: rgba(0, 122, 255, 0.5);
}
#browser-container .vlist-table-row.vlist-item--selected:hover {
background: rgba(0, 122, 255, 0.6);
}
#browser-container .vlist-table-row.vlist-item--selected .vlist-table-cell {
color: white;
}
#browser-container .vlist-table-row.vlist-item--selected .file-name__text {
color: white;
}
#browser-container
.vlist-table-row.vlist-item:not(.vlist-item--odd):not(
.vlist-item--selected
) {
background-color: initial;
}
/* ============================================================================
Name Cell — icon + name inline (used by table plugin cell renderer)
============================================================================ */
.file-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.file-name__icon {
font-size: 16px;
line-height: 1;
flex-shrink: 0;
}
.file-name__text {
font-weight: var(--fw-bold);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
color: var(--vlist-text, #111827);
}
/* ============================================================================
Breadcrumb Navigation
============================================================================ */
.breadcrumb {
display: flex;
align-items: center;
gap: 4px;
padding: 0;
margin: 0;
border-radius: 0;
border: none;
background: transparent;
font-size: 13px;
overflow-x: auto;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.breadcrumb__item {
padding: 4px 8px;
border: none;
border-radius: 4px;
background: transparent;
color: var(--text-muted);
font-size: 14px;
font-weight: var(--fw-bold);
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
white-space: nowrap;
}
.breadcrumb__item:hover {
background: var(--bg-hover);
color: var(--text);
}
.breadcrumb__item:last-child {
color: var(--text);
font-weight: var(--fw-bold);
}
.breadcrumb__sep {
color: var(--text-muted);
font-size: 12px;
}
/* ============================================================================
Toolbar
============================================================================ */
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 4px 8px;
border: 1px solid var(--vlist-border);
border-bottom: none;
border-radius: var(--vlist-border-radius, 0.5rem)
var(--vlist-border-radius, 0.5rem) 0px 0px;
}
.toolbar__left {
display: flex;
gap: 8px;
align-items: center;
flex: 1;
min-width: 0;
}
.toolbar__right {
display: flex;
gap: 8px;
align-items: center;
flex-shrink: 0;
}
.toolbar__label {
font-size: 12px;
font-weight: var(--fw-medium, 500);
color: var(--text-muted);
white-space: nowrap;
}
.toolbar__btn {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font-size: 13px;
font-weight: var(--fw-bold);
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
.toolbar__btn--icon {
padding: 6px;
min-width: 32px;
min-height: 32px;
justify-content: center;
}
.toolbar__btn--icon svg {
display: block;
opacity: 0.7;
transition: opacity 0.15s ease;
}
.toolbar__btn--icon:hover:not(:disabled) svg {
opacity: 1;
}
.toolbar__btn:hover:not(:disabled) {
border-color: var(--accent);
color: var(--accent-text);
}
.toolbar__btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.toolbar__btn .icon {
font-size: 14px;
}
.toolbar__select {
padding: 4px 8px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font-size: 12px;
font-family: inherit;
cursor: pointer;
transition: all 0.15s ease;
}
.toolbar__select:hover {
border-color: var(--accent);
}
.toolbar__select:focus {
outline: none;
border-color: var(--accent);
}
.toolbar #btn-back i {
-webkit-mask-image: url(/examples/icons/navigate/before.svg);
mask-image: url(/examples/icons/navigate/before.svg);
}
.toolbar #btn-forward i {
-webkit-mask-image: url(/examples/icons/navigate/next.svg);
mask-image: url(/examples/icons/navigate/next.svg);
}
.toolbar #btn-view-grid i {
-webkit-mask-image: url(/examples/icons/navigate/grid.svg);
mask-image: url(/examples/icons/grid.svg);
}
.toolbar #btn-view-list i {
-webkit-mask-image: url(/examples/icons/list.svg);
mask-image: url(/examples/icons/list.svg);
}
/* ============================================================================
File Card (Grid View)
============================================================================ */
.file-card {
position: relative;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
gap: 4px;
padding: 8px 6px;
border-radius: 8px;
background: transparent;
cursor: pointer;
transition: all 0.2s ease;
}
.file-card:hover {
background: transparent;
}
.file-card[data-type="directory"]:hover {
background: transparent;
}
/* Finder-style selection — highlight name label only */
.vlist-item[aria-selected="true"] .file-card,
.vlist-item--selected .file-card {
background: transparent;
}
.vlist-item[aria-selected="true"] .file-card__name,
.vlist-item--selected .file-card__name {
background: rgba(0, 122, 255, 0.8);
color: white;
box-decoration-break: clone;
-webkit-box-decoration-break: clone;
}
.file-card__icon {
font-size: 48px;
line-height: 1;
flex-shrink: 0;
}
.file-card__name {
font-size: 12px;
font-weight: var(--fw-bold);
color: var(--text);
text-align: center;
width: 100%;
padding: 2px 6px;
border-radius: 4px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
line-height: 1.35;
word-break: break-word;
}
/* ============================================================================
Group Headers (Grid View)
============================================================================ */
.group-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px 8px 48px;
background: transparent;
margin-top: 12px;
transition: all 0.2s ease;
}
/* Group headers in table/list layout — smaller, tighter */
.vlist--table .group-header {
padding: 8px 12px 8px 24px;
}
.vlist--table .group-header__label {
font-size: 11px;
text-transform: initial;
}
.vlist--table .group-header__count {
font-size: 10px;
}
/* Group headers in grid layout */
.vlist--grid .group-header {
width: 100%;
background: var(--bg-card);
border-bottom: 1px solid var(--vlist-border, var(--border));
margin-top: 0;
margin-bottom: 8px;
}
/* First group header — no margin-top */
.vlist-item:first-child .group-header {
margin-top: 0;
}
/* Sticky header enhancement */
.vlist-item[data-sticky="true"] .group-header {
background: var(--bg-card);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-bottom: 1px solid var(--vlist-border, var(--border));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
z-index: 10;
}
.group-header__label {
font-size: 13px;
font-weight: var(--fw-bold);
color: var(--text);
text-transform: uppercase;
letter-spacing: 0.8px;
}
.group-header__count {
font-size: 11px;
color: var(--text-muted);
opacity: 0.6;
}
/* Enhanced count visibility when sticky */
.vlist-item[data-sticky="true"] .group-header__count {
opacity: 0.8;
background: rgba(255, 255, 255, 0.1);
padding: 2px 8px;
border-radius: 10px;
}
/* ============================================================================
File Detail Panel — selected file info
============================================================================ */
.file-detail__header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
}
.file-detail__icon {
font-size: 28px;
line-height: 1;
flex-shrink: 0;
}
.file-detail__name {
font-size: 13px;
font-weight: var(--fw-bold);
color: var(--text);
word-break: break-all;
}
.file-detail__kind {
font-size: 12px;
color: var(--text-muted);
}
.file-detail__meta {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
color: var(--text-muted);
}
/* ============================================================================
Sort Info Panel
============================================================================ */
.sort-info {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
}
.sort-info__key {
font-weight: var(--fw-bold);
color: var(--vlist-text, #111827);
text-transform: capitalize;
}
.sort-info__dir {
font-size: 12px;
color: var(--text-muted);
}
/* ============================================================================
vlist overrides — remove item borders/padding for grid cards
============================================================================ */
#browser-container .vlist-item {
padding: 0;
border: none;
}
#browser-container .vlist--grid .vlist-item:hover,
#browser-container .vlist--grid .vlist-item--selected,
#browser-container .vlist--grid .vlist-item--selected:hover {
background: transparent;
}
/* ============================================================================
Split layout — browser takes more room
============================================================================ */
.split-main--full #browser-container {
height: 600px;
}
/* ============================================================================
Responsive
============================================================================ */
@media (min-width: 1200px) {
.split-main--full #browser-container {
height: 600px;
}
}
@media (max-width: 820px) {
.split-main--full #browser-container {
height: 480px;
}
.breadcrumb {
font-size: 12px;
}
.toolbar {
flex-direction: column;
gap: 8px;
}
.toolbar__left,
.toolbar__right {
width: 100%;
justify-content: space-between;
}
.file-card__icon {
font-size: 44px;
}
}
<div class="container">
<header>
<h1>File Browser</h1>
<p class="description">
Finder-like file browser using <code>table</code> for the list
view with resizable, sortable columns and <code>grid</code> for
the grid view. Click headers to sort, drag borders to resize.
Double-click folders to navigate. [Experimental]
</p>
</header>
<div class="split-layout">
<div class="split-main split-main--full">
<!-- Toolbar -->
<div class="toolbar">
<div class="toolbar__left">
<button
id="btn-back"
class="ui-btn ui-btn--icon"
disabled
title="Back"
>
<i class="icon icon--prev"></i>
</button>
<button
id="btn-forward"
class="ui-btn ui-btn--icon"
disabled
title="Forward"
>
<i class="icon icon--next"></i>
</button>
<!-- Breadcrumb navigation -->
<div class="breadcrumb" id="breadcrumb">
<button class="breadcrumb__item" data-path="">
root
</button>
</div>
</div>
<div class="toolbar__right">
<label class="toolbar__label" for="arrange-by-select"
>Group by</label
>
<select id="arrange-by-select" class="ui-select">
<option value="none" selected>None</option>
<option value="name">Name</option>
<option value="kind">Kind</option>
<option value="date-modified">Date Modified</option>
<option value="size">Size</option>
</select>
<div class="ui-segmented">
<button
id="btn-view-grid"
class="ui-segmented__btn"
title="Grid View"
>
<i class="icon icon--grid"></i>
</button>
<button
id="btn-view-list"
class="ui-segmented__btn ui-segmented__btn--active"
title="List View"
>
<i class="icon icon--list"></i>
</button>
</div>
</div>
</div>
<!-- File browser container -->
<div id="browser-container"></div>
</div>
<aside class="split-panel">
<!-- Columns -->
<section class="ui-section">
<h3 class="ui-title">Columns</h3>
<div class="ui-row">
<label class="ui-label" for="pin-mode">Pin</label>
<select id="pin-mode" class="ui-select">
<option value="none" selected>None</option>
<option value="first">First column left</option>
<option value="both">First left + last right</option>
</select>
</div>
<div class="ui-row">
<label class="ui-label" for="reorder-toggle">Reorder</label>
<label class="ui-switch">
<input type="checkbox" id="reorder-toggle" checked />
<span class="ui-switch__track"></span>
</label>
</div>
</section>
<!-- Sort State -->
<section class="ui-section">
<h3 class="ui-title">Sort</h3>
<div class="ui-detail" id="sort-detail">
<span class="ui-detail__empty"
>Click a column header to sort</span
>
</div>
</section>
<!-- Selected File -->
<section class="ui-section">
<h3 class="ui-title">Selected File</h3>
<div class="ui-detail" id="file-detail">
<span class="ui-detail__empty"
>Click a row to see details</span
>
</div>
</section>
<!-- Navigation -->
<section class="ui-section">
<h3 class="ui-title">Navigation</h3>
<div class="ui-row">
<div class="ui-btn-group">
<button
id="btn-nav-back"
class="ui-btn ui-btn--icon"
title="Back"
>
<i class="icon icon--up"></i>
</button>
<button
id="btn-nav-forward"
class="ui-btn ui-btn--icon"
title="Forward"
>
<i class="icon icon--down"></i>
</button>
</div>
</div>
</section>
</aside>
</div>
<div class="example-info" id="example-info">
<div class="example-info__left">
<span class="example-info__stat">
<strong id="info-items">0</strong>
<span class="example-info__unit">items</span>
</span>
</div>
<div class="example-info__right">
<span class="example-info__stat">
<strong id="info-path">/</strong>
</span>
</div>
</div>
</div>