重构代码结构并添加完整功能

主要改动:
- 重构目录结构:合并子目录到根目录,简化项目结构
- 添加完整的查询 API:支持复杂条件查询、字段选择、游标模式
- 实现 LSM-Tree Compaction:7层结构、Score-based策略、后台异步合并
- 添加 Web UI:基于 Lit 的现代化管理界面,支持数据浏览和 Manifest 查看
- 完善文档:添加 README.md 和 examples/webui/README.md

新增功能:
- Query Builder:链式查询 API,支持 Eq/Lt/Gt/In/Between/Contains 等操作符
- Web UI 组件:srdb-app、srdb-table-list、srdb-data-view、srdb-manifest-view 等
- 列选择持久化:自动保存到 localStorage
- 刷新按钮:一键刷新当前视图
- 主题切换:深色/浅色主题支持

代码优化:
- 使用 Go 1.24 新特性:range 7、min()、maps.Copy()、slices.Sort()
- 统一组件命名:所有 Web Components 使用 srdb-* 前缀
- CSS 优化:提取共享样式,减少重复代码
- 清理遗留代码:删除未使用的方法和样式
This commit is contained in:
2025-10-08 16:42:31 +08:00
parent ae87c38776
commit 23843493b8
64 changed files with 8374 additions and 6396 deletions

View File

@@ -1,552 +0,0 @@
package webui
import (
"bytes"
"fmt"
"html"
"strings"
)
// HTML 渲染辅助函数
// renderTablesHTML 渲染表列表 HTML
func renderTablesHTML(tables []TableListItem) string {
var buf bytes.Buffer
for _, table := range tables {
buf.WriteString(`<div class="table-item" data-table="`)
buf.WriteString(html.EscapeString(table.Name))
buf.WriteString(`">`)
buf.WriteString(`<div class="table-header" onclick="selectTable('`)
buf.WriteString(html.EscapeString(table.Name))
buf.WriteString(`')">`)
// 左侧:展开图标和表名
buf.WriteString(`<div class="table-header-left">`)
buf.WriteString(`<span class="expand-icon" onclick="event.stopPropagation(); toggleExpand('`)
buf.WriteString(html.EscapeString(table.Name))
buf.WriteString(`')">▶</span>`)
buf.WriteString(`<span class="table-name">`)
buf.WriteString(html.EscapeString(table.Name))
buf.WriteString(`</span></div>`)
// 右侧:字段数量
buf.WriteString(`<span class="table-count">`)
buf.WriteString(formatCount(int64(len(table.Fields))))
buf.WriteString(` fields</span>`)
buf.WriteString(`</div>`)
// Schema 字段列表(默认隐藏)
if len(table.Fields) > 0 {
buf.WriteString(`<div class="schema-fields">`)
for _, field := range table.Fields {
buf.WriteString(`<div class="field-item">`)
buf.WriteString(`<span class="field-name">`)
buf.WriteString(html.EscapeString(field.Name))
buf.WriteString(`</span>`)
buf.WriteString(`<span class="field-type">`)
buf.WriteString(html.EscapeString(field.Type))
buf.WriteString(`</span>`)
if field.Indexed {
buf.WriteString(`<span class="field-indexed">●indexed</span>`)
}
buf.WriteString(`</div>`)
}
buf.WriteString(`</div>`)
}
buf.WriteString(`</div>`)
}
return buf.String()
}
// renderDataViewHTML 渲染数据视图 HTML
func renderDataViewHTML(tableName string, schema SchemaInfo, tableData TableDataResponse) string {
var buf bytes.Buffer
// 标题
buf.WriteString(`<h2>`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`</h2>`)
// 视图切换标签
buf.WriteString(`<div class="view-tabs">`)
buf.WriteString(`<button class="view-tab active" onclick="switchView('`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`', 'data')">Data</button>`)
buf.WriteString(`<button class="view-tab" onclick="switchView('`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`', 'manifest')">Manifest / LSM-Tree</button>`)
buf.WriteString(`</div>`)
// Schema 部分
if len(schema.Fields) > 0 {
buf.WriteString(`<div class="schema-section">`)
buf.WriteString(`<h3>Schema <span style="font-size: 12px; font-weight: 400; color: var(--text-secondary);">(点击字段卡片选择要显示的列)</span></h3>`)
buf.WriteString(`<div class="schema-grid">`)
for _, field := range schema.Fields {
buf.WriteString(`<div class="schema-field-card selected" data-column="`)
buf.WriteString(html.EscapeString(field.Name))
buf.WriteString(`" onclick="toggleColumn('`)
buf.WriteString(html.EscapeString(field.Name))
buf.WriteString(`')">`)
buf.WriteString(`<div class="field-item">`)
buf.WriteString(`<span class="field-name">`)
buf.WriteString(html.EscapeString(field.Name))
buf.WriteString(`</span>`)
buf.WriteString(`<span class="field-type">`)
buf.WriteString(html.EscapeString(field.Type))
buf.WriteString(`</span>`)
if field.Indexed {
buf.WriteString(`<span class="field-indexed">●indexed</span>`)
}
buf.WriteString(`</div>`)
buf.WriteString(`<div class="field-comment">`)
if field.Comment != "" {
buf.WriteString(html.EscapeString(field.Comment))
}
buf.WriteString(`</div>`)
buf.WriteString(`</div>`)
}
buf.WriteString(`</div>`)
buf.WriteString(`</div>`)
}
// 数据表格
buf.WriteString(`<h3>Data (`)
buf.WriteString(formatCount(tableData.TotalRows))
buf.WriteString(` rows)</h3>`)
if len(tableData.Data) == 0 {
buf.WriteString(`<div class="empty"><p>No data available</p></div>`)
return buf.String()
}
// 获取列并排序_seq 第1列_time 倒数第2列
columns := []string{}
otherColumns := []string{}
hasSeq := false
hasTime := false
if len(tableData.Data) > 0 {
for key := range tableData.Data[0] {
if !strings.HasSuffix(key, "_truncated") {
if key == "_seq" {
hasSeq = true
} else if key == "_time" {
hasTime = true
} else {
otherColumns = append(otherColumns, key)
}
}
}
}
// 按顺序组装_seq, 其他列, _time
if hasSeq {
columns = append(columns, "_seq")
}
columns = append(columns, otherColumns...)
if hasTime {
columns = append(columns, "_time")
}
// 表格
buf.WriteString(`<div class="table-wrapper">`)
buf.WriteString(`<table class="data-table">`)
buf.WriteString(`<thead><tr>`)
for _, col := range columns {
buf.WriteString(`<th data-column="`)
buf.WriteString(html.EscapeString(col))
buf.WriteString(`" title="`)
buf.WriteString(html.EscapeString(col))
buf.WriteString(`">`)
buf.WriteString(html.EscapeString(col))
buf.WriteString(`</th>`)
}
buf.WriteString(`<th style="width: 80px;">Actions</th>`)
buf.WriteString(`</tr></thead>`)
buf.WriteString(`<tbody>`)
for _, row := range tableData.Data {
buf.WriteString(`<tr>`)
for _, col := range columns {
value := row[col]
buf.WriteString(`<td data-column="`)
buf.WriteString(html.EscapeString(col))
buf.WriteString(`" onclick="showCellContent('`)
buf.WriteString(escapeJSString(fmt.Sprintf("%v", value)))
buf.WriteString(`')" title="Click to view full content">`)
buf.WriteString(html.EscapeString(fmt.Sprintf("%v", value)))
// 检查是否被截断
if truncated, ok := row[col+"_truncated"]; ok && truncated == true {
buf.WriteString(`<span class="truncated-icon" title="This field is truncated">✂️</span>`)
}
buf.WriteString(`</td>`)
}
// Actions 列
buf.WriteString(`<td style="text-align: center;">`)
buf.WriteString(`<button class="row-detail-btn" onclick="showRowDetail('`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`', `)
buf.WriteString(fmt.Sprintf("%v", row["_seq"]))
buf.WriteString(`)" title="View full row data">Detail</button>`)
buf.WriteString(`</td>`)
buf.WriteString(`</tr>`)
}
buf.WriteString(`</tbody>`)
buf.WriteString(`</table>`)
buf.WriteString(`</div>`)
// 分页
buf.WriteString(renderPagination(tableData))
return buf.String()
}
// renderManifestViewHTML 渲染 Manifest 视图 HTML
func renderManifestViewHTML(tableName string, manifest ManifestResponse) string {
var buf bytes.Buffer
// 标题
buf.WriteString(`<h2>`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`</h2>`)
// 视图切换标签
buf.WriteString(`<div class="view-tabs">`)
buf.WriteString(`<button class="view-tab" onclick="switchView('`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`', 'data')">Data</button>`)
buf.WriteString(`<button class="view-tab active" onclick="switchView('`)
buf.WriteString(html.EscapeString(tableName))
buf.WriteString(`', 'manifest')">Manifest / LSM-Tree</button>`)
buf.WriteString(`</div>`)
// 标题和控制按钮
buf.WriteString(`<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">`)
buf.WriteString(`<h3>LSM-Tree Structure</h3>`)
buf.WriteString(`<div class="control-buttons">`)
buf.WriteString(`<button>📖 Expand All</button>`)
buf.WriteString(`<button>📕 Collapse All</button>`)
buf.WriteString(`</div>`)
buf.WriteString(`</div>`)
// 统计卡片
totalLevels := len(manifest.Levels)
totalFiles := 0
totalSize := int64(0)
for _, level := range manifest.Levels {
totalFiles += level.FileCount
totalSize += level.TotalSize
}
buf.WriteString(`<div class="manifest-stats">`)
// Active Levels
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Active Levels</div>`)
buf.WriteString(`<div class="stat-value">`)
buf.WriteString(fmt.Sprintf("%d", totalLevels))
buf.WriteString(`</div></div>`)
// Total Files
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Total Files</div>`)
buf.WriteString(`<div class="stat-value">`)
buf.WriteString(fmt.Sprintf("%d", totalFiles))
buf.WriteString(`</div></div>`)
// Total Size
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Total Size</div>`)
buf.WriteString(`<div class="stat-value">`)
buf.WriteString(formatBytes(totalSize))
buf.WriteString(`</div></div>`)
// Next File Number
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Next File Number</div>`)
buf.WriteString(`<div class="stat-value">`)
buf.WriteString(fmt.Sprintf("%d", manifest.NextFileNumber))
buf.WriteString(`</div></div>`)
// Last Sequence
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Last Sequence</div>`)
buf.WriteString(`<div class="stat-value">`)
buf.WriteString(fmt.Sprintf("%d", manifest.LastSequence))
buf.WriteString(`</div></div>`)
// Total Compactions
buf.WriteString(`<div class="stat-card">`)
buf.WriteString(`<div class="stat-label">Total Compactions</div>`)
buf.WriteString(`<div class="stat-value">`)
totalCompactions := 0
if manifest.CompactionStats != nil {
if tc, ok := manifest.CompactionStats["total_compactions"]; ok {
if tcInt, ok := tc.(float64); ok {
totalCompactions = int(tcInt)
}
}
}
buf.WriteString(fmt.Sprintf("%d", totalCompactions))
buf.WriteString(`</div></div>`)
buf.WriteString(`</div>`)
// 渲染所有层级L0-L6
for i := 0; i <= 6; i++ {
var level *LevelInfo
for j := range manifest.Levels {
if manifest.Levels[j].Level == i {
level = &manifest.Levels[j]
break
}
}
if level == nil {
// 创建空层级
level = &LevelInfo{
Level: i,
FileCount: 0,
TotalSize: 0,
Score: 0,
Files: []FileInfo{},
}
}
buf.WriteString(renderLevelCard(*level))
}
return buf.String()
}
// renderLevelCard 渲染层级卡片
func renderLevelCard(level LevelInfo) string {
var buf bytes.Buffer
scoreClass := "normal"
if level.Score >= 1.0 {
scoreClass = "critical"
} else if level.Score >= 0.8 {
scoreClass = "warning"
}
buf.WriteString(`<div class="level-card" data-level="`)
buf.WriteString(fmt.Sprintf("%d", level.Level))
buf.WriteString(`">`)
buf.WriteString(`<div class="level-header" onclick="toggleLevel(`)
buf.WriteString(fmt.Sprintf("%d", level.Level))
buf.WriteString(`)">`)
// 左侧:展开图标和标题
buf.WriteString(`<div style="display: flex; align-items: center; gap: 10px;">`)
buf.WriteString(`<span class="expand-icon">▶</span>`)
buf.WriteString(`<div class="level-title">Level `)
buf.WriteString(fmt.Sprintf("%d", level.Level))
buf.WriteString(`</div></div>`)
// 右侧:统计信息
buf.WriteString(`<div class="level-stats">`)
buf.WriteString(`<span>`)
buf.WriteString(fmt.Sprintf("%d", level.FileCount))
buf.WriteString(` files</span>`)
buf.WriteString(`<span>`)
buf.WriteString(formatBytes(level.TotalSize))
buf.WriteString(`</span>`)
buf.WriteString(`<span class="score-badge `)
buf.WriteString(scoreClass)
buf.WriteString(`">Score: `)
buf.WriteString(fmt.Sprintf("%.2f", level.Score))
buf.WriteString(`</span>`)
buf.WriteString(`</div>`)
buf.WriteString(`</div>`)
// 文件列表(默认隐藏)
buf.WriteString(`<div class="file-list">`)
if len(level.Files) == 0 {
buf.WriteString(`<div class="empty-files">No files in this level</div>`)
} else {
for _, file := range level.Files {
buf.WriteString(`<div class="file-card">`)
buf.WriteString(`<div class="file-header">`)
buf.WriteString(`<span>File #`)
buf.WriteString(fmt.Sprintf("%d", file.FileNumber))
buf.WriteString(`</span>`)
buf.WriteString(`<b>`)
buf.WriteString(formatBytes(file.FileSize))
buf.WriteString(`</b>`)
buf.WriteString(`</div>`)
buf.WriteString(`<div class="file-detail">`)
buf.WriteString(`<span>Key Range:</span>`)
buf.WriteString(`<span>`)
buf.WriteString(fmt.Sprintf("%d - %d", file.MinKey, file.MaxKey))
buf.WriteString(`</span></div>`)
buf.WriteString(`<div class="file-detail">`)
buf.WriteString(`<span>Rows:</span>`)
buf.WriteString(`<span>`)
buf.WriteString(formatCount(file.RowCount))
buf.WriteString(`</span></div>`)
buf.WriteString(`</div>`)
}
}
buf.WriteString(`</div>`)
buf.WriteString(`</div>`)
return buf.String()
}
// renderPagination 渲染分页 HTML
func renderPagination(data TableDataResponse) string {
var buf bytes.Buffer
buf.WriteString(`<div class="pagination">`)
// 页大小选择器
buf.WriteString(`<select onchange="changePageSize(this.value)">`)
for _, size := range []int{10, 20, 50, 100} {
buf.WriteString(`<option value="`)
buf.WriteString(fmt.Sprintf("%d", size))
buf.WriteString(`"`)
if int64(size) == data.PageSize {
buf.WriteString(` selected`)
}
buf.WriteString(`>`)
buf.WriteString(fmt.Sprintf("%d", size))
buf.WriteString(` / page</option>`)
}
buf.WriteString(`</select>`)
// 上一页按钮
buf.WriteString(`<button onclick="changePage(-1)"`)
if data.Page <= 1 {
buf.WriteString(` disabled`)
}
buf.WriteString(`>Previous</button>`)
// 页码信息
buf.WriteString(`<span>Page `)
buf.WriteString(fmt.Sprintf("%d", data.Page))
buf.WriteString(` of `)
buf.WriteString(fmt.Sprintf("%d", data.TotalPages))
buf.WriteString(` (`)
buf.WriteString(formatCount(data.TotalRows))
buf.WriteString(` rows)</span>`)
// 跳转输入框
buf.WriteString(`<input type="number" min="1" max="`)
buf.WriteString(fmt.Sprintf("%d", data.TotalPages))
buf.WriteString(`" placeholder="Jump to" onkeydown="if(event.key==='Enter') jumpToPage(this.value)">`)
// Go 按钮
buf.WriteString(`<button onclick="jumpToPage(this.previousElementSibling.value)">Go</button>`)
// 下一页按钮
buf.WriteString(`<button onclick="changePage(1)"`)
if data.Page >= data.TotalPages {
buf.WriteString(` disabled`)
}
buf.WriteString(`>Next</button>`)
buf.WriteString(`</div>`)
return buf.String()
}
// formatBytes 格式化字节数
func formatBytes(bytes int64) string {
if bytes == 0 {
return "0 B"
}
const k = 1024
sizes := []string{"B", "KB", "MB", "GB", "TB"}
i := 0
size := float64(bytes)
for size >= k && i < len(sizes)-1 {
size /= k
i++
}
return fmt.Sprintf("%.2f %s", size, sizes[i])
}
// formatCount 格式化数量K/M
func formatCount(count int64) string {
if count >= 1000000 {
return fmt.Sprintf("%.1fM", float64(count)/1000000)
}
if count >= 1000 {
return fmt.Sprintf("%.1fK", float64(count)/1000)
}
return fmt.Sprintf("%d", count)
}
// escapeJSString 转义 JavaScript 字符串
func escapeJSString(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `'`, `\'`)
s = strings.ReplaceAll(s, `"`, `\"`)
s = strings.ReplaceAll(s, "\n", `\n`)
s = strings.ReplaceAll(s, "\r", `\r`)
s = strings.ReplaceAll(s, "\t", `\t`)
return s
}
// 数据结构定义
type TableListItem struct {
Name string `json:"name"`
CreatedAt int64 `json:"created_at"`
Fields []FieldInfo `json:"fields"`
}
type FieldInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Indexed bool `json:"indexed"`
Comment string `json:"comment"`
}
type SchemaInfo struct {
Name string `json:"name"`
Fields []FieldInfo `json:"fields"`
}
type TableDataResponse struct {
Data []map[string]any `json:"data"`
Page int64 `json:"page"`
PageSize int64 `json:"pageSize"`
TotalRows int64 `json:"totalRows"`
TotalPages int64 `json:"totalPages"`
}
type ManifestResponse struct {
Levels []LevelInfo `json:"levels"`
NextFileNumber int64 `json:"next_file_number"`
LastSequence int64 `json:"last_sequence"`
CompactionStats map[string]any `json:"compaction_stats"`
}
type LevelInfo struct {
Level int `json:"level"`
FileCount int `json:"file_count"`
TotalSize int64 `json:"total_size"`
Score float64 `json:"score"`
Files []FileInfo `json:"files"`
}
type FileInfo struct {
FileNumber int64 `json:"file_number"`
Level int `json:"level"`
FileSize int64 `json:"file_size"`
MinKey int64 `json:"min_key"`
MaxKey int64 `json:"max_key"`
RowCount int64 `json:"row_count"`
}

View File

@@ -1,4 +1,4 @@
/* SRDB WebUI - Modern Design */
/* SRDB WebUI - Modern Design with Lit */
:root {
/* 主色调 - 优雅的紫蓝色 */
@@ -53,6 +53,11 @@
padding: 0;
}
:root {
/* 主题过渡动画 */
transition: background-color 0.3s ease, color 0.3s ease;
}
body {
font-family:
"Inter",
@@ -67,837 +72,9 @@ body {
font-size: 14px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 布局 */
.container {
display: flex;
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
/* 侧边栏 */
.sidebar {
width: 280px;
background: var(--bg-surface);
border-right: 1px solid var(--border-color);
overflow-y: auto;
overflow-x: hidden;
padding: 16px 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.sidebar::-webkit-scrollbar {
width: 6px;
}
.sidebar::-webkit-scrollbar-track {
background: transparent;
}
.sidebar::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
border-radius: 3px;
}
.sidebar::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
.sidebar h1 {
font-size: 18px;
font-weight: 700;
letter-spacing: -0.02em;
background: linear-gradient(135deg, var(--primary-light), var(--primary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 4px;
}
/* 主内容区 */
.main {
flex: 1;
padding: 20px;
overflow-y: auto;
overflow-x: hidden;
background: var(--bg-main);
}
.main h2 {
font-size: 24px;
font-weight: 700;
margin-bottom: 16px;
background: linear-gradient(
135deg,
var(--text-primary) 0%,
var(--primary-light) 100%
);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: -0.02em;
}
.main h3 {
font-size: 16px;
font-weight: 600;
margin-bottom: 12px;
margin-top: 20px;
color: var(--text-primary);
display: flex;
align-items: center;
gap: 8px;
}
.main h3::before {
content: "";
width: 3px;
height: 18px;
background: linear-gradient(135deg, var(--primary), var(--primary-light));
border-radius: 2px;
}
.main::-webkit-scrollbar {
width: 8px;
}
.main::-webkit-scrollbar-track {
background: transparent;
}
.main::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
}
.main::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
/* 表列表卡片 */
.table-item {
margin-bottom: 6px;
border-radius: var(--radius-md);
overflow: hidden;
transition: var(--transition);
}
.table-header {
padding: 10px 12px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
transition: var(--transition);
}
.table-header:hover {
background: var(--bg-hover);
border-color: var(--border-hover);
/*transform: translateX(2px);*/
}
.table-header.selected,
.table-item.selected .table-header {
background: linear-gradient(135deg, var(--primary), var(--primary-dark));
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-bg);
}
.table-header-left {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
}
.expand-icon {
font-size: 10px;
color: var(--text-secondary);
transition: var(--transition);
user-select: none;
flex-shrink: 0;
}
.expand-icon.expanded {
transform: rotate(90deg);
}
.table-name {
font-weight: 600;
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
}
.table-count {
font-size: 11px;
font-weight: 500;
padding: 3px 8px;
background: rgba(255, 255, 255, 0.1);
border-radius: 12px;
color: var(--text-secondary);
flex-shrink: 0;
}
.table-item.selected .table-count {
background: rgba(255, 255, 255, 0.2);
color: white;
}
/* Schema 字段列表 */
.schema-fields {
display: none;
margin-top: 8px;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.03);
border-left: 2px solid var(--primary);
border-radius: var(--radius-md);
gap: 6px;
flex-direction: column;
}
.field-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 4px 0;
}
.field-name {
font-size: 13px;
font-weight: 500;
color: var(--text-primary);
min-width: 90px;
}
.field-type {
font-size: 12px;
font-family: "SF Mono", Monaco, monospace;
color: var(--primary-light);
background: rgba(99, 102, 241, 0.15);
padding: 2px 8px;
border-radius: 4px;
}
.field-indexed {
font-size: 10px;
font-weight: 600;
color: var(--success);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.field-comment {
font-size: 12px;
color: #999;
margin-top: 4px;
}
/* 视图切换标签 */
.view-tabs {
display: flex;
gap: 8px;
margin-bottom: 20px;
padding: 4px;
background: var(--bg-surface);
border-radius: var(--radius-lg);
border: 1px solid var(--border-color);
box-shadow: var(--shadow-sm);
}
.view-tab {
padding: 10px 20px;
background: transparent;
border: none;
border-radius: var(--radius-md);
cursor: pointer;
font-size: 14px;
font-weight: 600;
color: var(--text-secondary);
transition: var(--transition);
position: relative;
letter-spacing: -0.01em;
}
.view-tab:hover {
color: var(--text-primary);
background: rgba(255, 255, 255, 0.05);
}
.view-tab.active {
color: white;
background: linear-gradient(
135deg,
var(--primary) 0%,
var(--primary-dark) 100%
);
box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}
/* Schema 展示 */
/*.schema-section {
background: linear-gradient(
135deg,
rgba(99, 102, 241, 0.05) 0%,
rgba(99, 102, 241, 0.02) 100%
);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
padding: 18px;
margin-bottom: 20px;
box-shadow: var(--shadow-sm);
}*/
.schema-section h3 {
font-size: 15px;
font-weight: 600;
margin-bottom: 14px;
margin-top: 0;
color: var(--text-primary);
}
.schema-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 10px;
}
.schema-field-card {
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
padding: 12px;
transition: var(--transition);
cursor: pointer;
position: relative;
opacity: 0.5;
}
.schema-field-card.selected {
opacity: 1;
border-color: var(--primary);
background: linear-gradient(
135deg,
rgba(99, 102, 241, 0.1) 0%,
rgba(99, 102, 241, 0.05) 100%
);
}
/*.schema-field-card::after {
content: "✓";
position: absolute;
bottom: 8px;
right: 8px;
font-size: 14px;
font-weight: bold;
color: var(--primary);
opacity: 0;
transition: var(--transition);
}
.schema-field-card.selected::after {
opacity: 1;
}*/
.schema-field-card:hover {
border-color: var(--primary-light);
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
/* 数据表格 */
.table-wrapper {
overflow-x: auto;
margin-bottom: 16px;
border-radius: var(--radius-lg);
border: 1px solid var(--border-color);
background: var(--bg-surface);
}
.data-table {
width: 100%;
border-collapse: collapse;
}
.data-table th {
background: var(--bg-elevated);
padding: 10px 12px;
text-align: left;
font-size: 11px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
border-bottom: 1px solid var(--border-color);
position: sticky;
top: 0;
z-index: 10;
}
.data-table td {
padding: 10px 12px;
border-bottom: 1px solid var(--border-color);
font-size: 13px;
color: var(--text-primary);
max-width: 400px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.data-table tbody tr {
transition: var(--transition);
}
.data-table tbody tr:hover {
background: rgba(255, 255, 255, 0.03);
}
.data-table tbody tr:last-child td {
border-bottom: none;
}
/* 分页 */
.pagination {
margin-top: 16px;
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
}
.pagination button,
.pagination select,
.pagination input {
padding: 8px 12px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-primary);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: var(--transition);
}
.pagination button:hover:not(:disabled) {
background: var(--primary);
border-color: var(--primary);
box-shadow: var(--shadow-md);
}
.pagination button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.pagination input[type="number"] {
width: 80px;
text-align: center;
}
.pagination select {
cursor: pointer;
}
/* Manifest / LSM-Tree */
.level-card {
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
padding: 14px;
margin-bottom: 12px;
transition: var(--transition);
}
.level-card:hover {
border-color: var(--border-hover);
box-shadow: var(--shadow-md);
}
.level-header {
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
}
.level-title {
font-size: 16px;
font-weight: 600;
background: linear-gradient(
135deg,
var(--text-primary),
var(--text-secondary)
);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.level-stats {
display: flex;
gap: 16px;
font-size: 12px;
color: var(--text-secondary);
}
.score-badge {
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.score-badge.normal {
background: rgba(16, 185, 129, 0.15);
color: var(--success);
}
.score-badge.warning {
background: rgba(245, 158, 11, 0.15);
color: var(--warning);
}
.score-badge.critical {
background: rgba(239, 68, 68, 0.15);
color: var(--danger);
}
.file-list {
display: none;
margin-top: 12px;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 10px;
padding-top: 8px;
/*border-top: 1px solid var(--border-color);*/
}
.file-card {
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
padding: 12px;
font-size: 12px;
}
.file-header {
display: flex;
align-items: center;
justify-content: space-between;
font-weight: 600;
margin-bottom: 12px;
color: var(--text-primary);
}
.file-detail {
display: flex;
justify-content: space-between;
/*padding: 4px 0;*/
color: var(--text-secondary);
font-size: 12px;
}
/* Modal */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(8px);
z-index: 1000;
justify-content: center;
align-items: center;
animation: fadeIn 0.2s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.modal-content {
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-xl);
max-width: 90%;
max-height: 85%;
display: flex;
flex-direction: column;
box-shadow: var(--shadow-xl);
animation: slideUp 0.3s ease-out;
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.modal-header {
padding: 16px 20px;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
gap: 24px;
}
.modal-header h3 {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.modal-close {
background: transparent;
color: var(--text-secondary);
border: 1px solid var(--border-color);
width: 32px;
height: 32px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
cursor: pointer;
transition: var(--transition);
flex-shrink: 0;
}
.modal-close svg {
width: 18px;
height: 18px;
transition: inherit;
}
.modal-close:hover {
background: rgba(239, 68, 68, 0.1);
border-color: var(--danger);
color: var(--danger);
transform: rotate(90deg);
}
.modal-body {
padding: 16px;
overflow: auto;
font-family: "SF Mono", Monaco, monospace;
font-size: 12px;
line-height: 1.6;
}
.modal-body pre {
white-space: pre-wrap;
word-break: break-word;
margin: 0;
color: var(--text-primary);
}
/* 按钮 */
button {
cursor: pointer;
transition: var(--transition);
font-family: inherit;
}
.row-detail-btn {
background: var(--primary);
color: white;
border: none;
padding: 6px 12px;
border-radius: var(--radius-sm);
font-size: 12px;
font-weight: 600;
transition: var(--transition);
}
.row-detail-btn:hover {
background: var(--primary-dark);
box-shadow: var(--shadow-md);
transform: translateY(-1px);
}
/* 空状态和加载 */
.loading,
.empty,
.error {
text-align: center;
padding: 60px 30px;
}
.empty h2 {
font-size: 20px;
font-weight: 600;
margin-bottom: 10px;
color: var(--text-primary);
}
.empty p {
font-size: 13px;
color: var(--text-secondary);
}
.error {
color: var(--danger);
}
/* Manifest stats */
.manifest-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
margin-bottom: 16px;
}
.stat-card {
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
padding: 14px;
transition: var(--transition);
}
.stat-card:hover {
border-color: var(--border-hover);
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.stat-label {
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 8px;
}
.stat-value {
font-size: 28px;
font-weight: 700;
background: linear-gradient(135deg, var(--primary-light), var(--primary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
/* 响应式设计 */
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.sidebar {
width: 100%;
border-right: none;
border-bottom: 1px solid var(--border-color);
max-height: 40vh;
}
.main {
padding: 16px;
}
.schema-grid {
grid-template-columns: 1fr;
}
.manifest-stats {
grid-template-columns: repeat(2, 1fr);
}
}
/* 列选择器 */
.column-selector {
margin-bottom: 16px;
padding: 14px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
}
.columns-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.column-checkbox {
display: flex;
align-items: center;
padding: 8px 14px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
cursor: pointer;
font-size: 13px;
transition: var(--transition);
}
.column-checkbox:hover {
border-color: var(--border-hover);
}
.column-checkbox.selected {
background: var(--primary-bg);
border-color: var(--primary);
}
.column-checkbox input {
margin-right: 8px;
}
/* 工具按钮 */
.control-buttons {
display: flex;
gap: 8px;
}
.control-buttons button {
padding: 6px 14px;
background: var(--bg-surface);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-primary);
font-size: 12px;
font-weight: 500;
transition: var(--transition);
}
.control-buttons button:hover {
background: var(--bg-hover);
border-color: var(--border-hover);
}
/* 单元格大小指示器 */
.cell-size {
font-size: 11px;
color: var(--text-tertiary);
font-style: italic;
margin-left: 6px;
}
/* 截断指示器 */
.truncated-icon {
color: var(--warning);
margin-left: 6px;
transition: background-color 0.3s ease, color 0.3s ease;
}

View File

@@ -1,5 +1,5 @@
<!doctype html>
<html lang="en">
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -11,59 +11,15 @@
rel="stylesheet"
/>
<link rel="stylesheet" href="/static/css/styles.css" />
<script src="https://npm.onmicrosoft.cn/htmx.org@2.0.7/dist/htmx.min.js"></script>
</head>
<body>
<div class="container">
<!-- 左侧表列表 -->
<div class="sidebar" id="sidebar">
<h1>Tables</h1>
<div
id="table-list"
hx-get="/api/tables-html"
hx-trigger="load"
>
Loading tables...
</div>
</div>
<!-- 右侧主内容区 -->
<div class="main" id="main-content">
<div class="empty">
<h2>Select a table to view data</h2>
<p>Choose a table from the sidebar to get started</p>
</div>
</div>
</div>
<!-- 应用容器 -->
<srdb-app></srdb-app>
<!-- Modal -->
<div id="modal" class="modal" style="display: none">
<div class="modal-content">
<div class="modal-header">
<h3 id="modal-title">Content</h3>
<button class="modal-close" onclick="closeModal()">
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="modal-body">
<pre id="modal-body-content"></pre>
</div>
</div>
</div>
<srdb-modal-dialog></srdb-modal-dialog>
<script src="/static/js/app.js"></script>
<!-- 加载 Lit 组件 -->
<script type="module" src="/static/js/app.js"></script>
</body>
</html>

View File

@@ -1,199 +1,110 @@
// SRDB WebUI - htmx 版本
import './components/app.js';
import './components/table-list.js';
import './components/table-view.js';
import './components/modal-dialog.js';
import './components/theme-toggle.js';
import './components/badge.js';
import './components/field-icon.js';
import './components/data-view.js';
import './components/manifest-view.js';
import './components/page-header.js';
// 全局状态
window.srdbState = {
selectedTable: null,
currentPage: 1,
pageSize: 20,
selectedColumns: [],
expandedTables: new Set(),
expandedLevels: new Set([0, 1]),
};
class App {
constructor() {
// 等待 srdb-app 组件渲染完成
this.appContainer = document.querySelector('srdb-app');
this.modal = document.querySelector('srdb-modal-dialog');
// 等待组件初始化
if (this.appContainer) {
// 使用 updateComplete 等待组件渲染完成
this.appContainer.updateComplete.then(() => {
this.tableList = this.appContainer.shadowRoot.querySelector('srdb-table-list');
this.tableView = this.appContainer.shadowRoot.querySelector('srdb-table-view');
this.pageHeader = this.appContainer.shadowRoot.querySelector('srdb-page-header');
this.setupEventListeners();
});
} else {
// 如果组件还未定义,等待它被定义
customElements.whenDefined('srdb-app').then(() => {
this.appContainer = document.querySelector('srdb-app');
this.appContainer.updateComplete.then(() => {
this.tableList = this.appContainer.shadowRoot.querySelector('srdb-table-list');
this.tableView = this.appContainer.shadowRoot.querySelector('srdb-table-view');
this.pageHeader = this.appContainer.shadowRoot.querySelector('srdb-page-header');
this.setupEventListeners();
});
});
}
}
// 选择表格
function selectTable(tableName) {
window.srdbState.selectedTable = tableName;
window.srdbState.currentPage = 1;
// 高亮选中的表
document.querySelectorAll(".table-item").forEach((el) => {
el.classList.toggle("selected", el.dataset.table === tableName);
});
// 加载表数据
loadTableData(tableName);
}
// 加载表数据
function loadTableData(tableName) {
const mainContent = document.getElementById("main-content");
mainContent.innerHTML = '<div class="loading">Loading...</div>';
fetch(
`/api/tables-view/${tableName}?page=${window.srdbState.currentPage}&pageSize=${window.srdbState.pageSize}`,
)
.then((res) => res.text())
.then((html) => {
mainContent.innerHTML = html;
})
.catch((err) => {
console.error("Failed to load table data:", err);
mainContent.innerHTML =
'<div class="error">Failed to load table data</div>';
setupEventListeners() {
// Listen for table selection
document.addEventListener('table-selected', (e) => {
const tableName = e.detail.tableName;
this.pageHeader.tableName = tableName;
this.pageHeader.view = 'data';
this.tableView.tableName = tableName;
this.tableView.view = 'data';
this.tableView.page = 1;
});
}
// 切换视图 (Data / Manifest)
function switchView(tableName, mode) {
const mainContent = document.getElementById("main-content");
mainContent.innerHTML = '<div class="loading">Loading...</div>';
const endpoint =
mode === "manifest"
? `/api/tables-view/${tableName}/manifest`
: `/api/tables-view/${tableName}?page=${window.srdbState.currentPage}&pageSize=${window.srdbState.pageSize}`;
fetch(endpoint)
.then((res) => res.text())
.then((html) => {
mainContent.innerHTML = html;
// Listen for view change from page-header
document.addEventListener('view-changed', (e) => {
this.tableView.view = e.detail.view;
});
}
// 分页
function changePage(delta) {
window.srdbState.currentPage += delta;
if (window.srdbState.selectedTable) {
loadTableData(window.srdbState.selectedTable);
}
}
function jumpToPage(page) {
window.srdbState.currentPage = parseInt(page);
if (window.srdbState.selectedTable) {
loadTableData(window.srdbState.selectedTable);
}
}
function changePageSize(newSize) {
window.srdbState.pageSize = parseInt(newSize);
window.srdbState.currentPage = 1;
if (window.srdbState.selectedTable) {
loadTableData(window.srdbState.selectedTable);
}
}
// Modal 相关
function showModal(title, content) {
document.getElementById("modal-title").textContent = title;
document.getElementById("modal-body-content").textContent = content;
document.getElementById("modal").style.display = "flex";
}
function closeModal() {
document.getElementById("modal").style.display = "none";
}
function showCellContent(content) {
showModal("Cell Content", content);
}
function showRowDetail(tableName, seq) {
fetch(`/api/tables/${tableName}/data/${seq}`)
.then((res) => res.json())
.then((data) => {
const formatted = JSON.stringify(data, null, 2);
showModal(`Row Detail (Seq: ${seq})`, formatted);
})
.catch((err) => {
console.error("Failed to load row detail:", err);
alert("Failed to load row detail");
// Listen for refresh request from page-header
document.addEventListener('refresh-view', (e) => {
this.tableView.loadData();
});
}
// 折叠展开
function toggleExpand(tableName) {
const item = document.querySelector(`[data-table="${tableName}"]`);
const fieldsDiv = item.querySelector(".schema-fields");
const icon = item.querySelector(".expand-icon");
// Listen for row detail request
document.addEventListener('show-row-detail', async (e) => {
const { tableName, seq } = e.detail;
await this.showRowDetail(tableName, seq);
});
if (window.srdbState.expandedTables.has(tableName)) {
window.srdbState.expandedTables.delete(tableName);
fieldsDiv.style.display = "none";
icon.classList.remove("expanded");
} else {
window.srdbState.expandedTables.add(tableName);
fieldsDiv.style.display = "block";
icon.classList.add("expanded");
// Listen for cell content request
document.addEventListener('show-cell-content', (e) => {
this.showCellContent(e.detail.content);
});
// Close modal on backdrop click
this.modal.addEventListener('click', () => {
this.modal.open = false;
});
}
async showRowDetail(tableName, seq) {
try {
const response = await fetch(`/api/tables/${tableName}/data/${seq}`);
if (!response.ok) throw new Error('Failed to load row detail');
const data = await response.json();
const content = JSON.stringify(data, null, 2);
this.modal.title = `Row Detail - Seq: ${seq}`;
this.modal.content = content;
this.modal.open = true;
} catch (error) {
console.error('Error loading row detail:', error);
this.modal.title = 'Error';
this.modal.content = `Failed to load row detail: ${error.message}`;
this.modal.open = true;
}
}
showCellContent(content) {
this.modal.title = 'Cell Content';
this.modal.content = String(content);
this.modal.open = true;
}
}
function toggleLevel(level) {
const levelCard = document.querySelector(`[data-level="${level}"]`);
const fileList = levelCard.querySelector(".file-list");
const icon = levelCard.querySelector(".expand-icon");
if (window.srdbState.expandedLevels.has(level)) {
window.srdbState.expandedLevels.delete(level);
fileList.style.display = "none";
icon.classList.remove("expanded");
} else {
window.srdbState.expandedLevels.add(level);
fileList.style.display = "grid";
icon.classList.add("expanded");
}
}
// 格式化工具
function formatBytes(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 (bytes / Math.pow(k, i)).toFixed(2) + " " + sizes[i];
}
function formatCount(count) {
if (count >= 1000000) return (count / 1000000).toFixed(1) + "M";
if (count >= 1000) return (count / 1000).toFixed(1) + "K";
return count.toString();
}
// 点击 modal 外部关闭
document.addEventListener("click", (e) => {
const modal = document.getElementById("modal");
if (e.target === modal) {
closeModal();
}
});
// ESC 键关闭 modal
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
closeModal();
}
});
// 切换列显示
function toggleColumn(columnName) {
// 切换 schema-field-card 的选中状态
const card = document.querySelector(
`.schema-field-card[data-column="${columnName}"]`,
);
if (!card) return;
card.classList.toggle("selected");
const isSelected = card.classList.contains("selected");
// 切换表格列的显示/隐藏
const headers = document.querySelectorAll(`th[data-column="${columnName}"]`);
const cells = document.querySelectorAll(`td[data-column="${columnName}"]`);
headers.forEach((header) => {
header.style.display = isSelected ? "" : "none";
});
cells.forEach((cell) => {
cell.style.display = isSelected ? "" : "none";
});
// Initialize app when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => new App());
} else {
new App();
}

View File

@@ -0,0 +1,145 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class AppContainer extends LitElement {
static properties = {
mobileMenuOpen: { type: Boolean }
};
constructor() {
super();
this.mobileMenuOpen = false;
}
toggleMobileMenu() {
this.mobileMenuOpen = !this.mobileMenuOpen;
}
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: block;
height: 100vh;
}
.container {
display: flex;
height: 100%;
overflow: hidden;
}
.sidebar {
width: 280px;
background: var(--bg-surface);
border-right: 1px solid var(--border-color);
overflow-y: auto;
overflow-x: hidden;
padding: 16px 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.sidebar::-webkit-scrollbar {
width: 6px;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 4px;
}
.sidebar h1 {
font-size: 18px;
font-weight: 700;
letter-spacing: -0.02em;
background: linear-gradient(135deg, var(--primary-light), var(--primary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.main {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
background: var(--bg-main);
display: flex;
flex-direction: column;
}
/* 移动端遮罩 */
.mobile-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
@media (max-width: 768px) {
.mobile-overlay.show {
display: block;
}
.container {
flex-direction: column;
}
.sidebar {
position: fixed;
top: 0;
left: 0;
width: 280px;
height: 100vh;
border-right: 1px solid var(--border-color);
border-bottom: none;
transform: translateX(-100%);
transition: transform 0.3s ease;
z-index: 1000;
}
.sidebar.open {
transform: translateX(0);
}
.main {
padding-top: 0;
}
}
`
];
render() {
return html`
<!-- 移动端遮罩 -->
<div class="mobile-overlay ${this.mobileMenuOpen ? 'show' : ''}" @click=${this.toggleMobileMenu}></div>
<div class="container">
<!-- 左侧表列表 -->
<div class="sidebar ${this.mobileMenuOpen ? 'open' : ''}">
<div class="sidebar-header">
<h1>SRDB Tables</h1>
<srdb-theme-toggle></srdb-theme-toggle>
</div>
<srdb-table-list @table-selected=${this.toggleMobileMenu}></srdb-table-list>
</div>
<!-- 右侧主内容区 -->
<div class="main">
<srdb-page-header @toggle-mobile-menu=${this.toggleMobileMenu}></srdb-page-header>
<srdb-table-view></srdb-table-view>
</div>
</div>
`;
}
}
customElements.define('srdb-app', AppContainer);

View File

@@ -0,0 +1,106 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class Badge extends LitElement {
static properties = {
variant: { type: String }, // 'primary', 'success', 'warning', 'danger', 'info'
icon: { type: String },
size: { type: String } // 'sm', 'md'
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: inline-flex;
}
.badge {
position: relative;
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
font-size: 11px;
font-weight: 600;
border-radius: var(--radius-sm);
white-space: nowrap;
}
.badge.size-md {
padding: 4px 10px;
font-size: 12px;
}
/* Primary variant */
.badge.variant-primary {
--badge-border-color: rgba(99, 102, 241, 0.2);
background: rgba(99, 102, 241, 0.15);
color: var(--primary);
}
/* Success variant */
.badge.variant-success {
--badge-border-color: rgba(16, 185, 129, 0.2);
background: rgba(16, 185, 129, 0.15);
color: var(--success);
}
/* Warning variant */
.badge.variant-warning {
--badge-border-color: rgba(245, 158, 11, 0.2);
background: rgba(245, 158, 11, 0.15);
color: var(--warning);
}
/* Danger variant */
.badge.variant-danger {
--badge-border-color: rgba(239, 68, 68, 0.2);
background: rgba(239, 68, 68, 0.15);
color: var(--danger);
}
/* Info variant */
.badge.variant-info {
--badge-border-color: rgba(59, 130, 246, 0.2);
background: rgba(59, 130, 246, 0.15);
color: var(--info);
}
/* Secondary variant */
.badge.variant-secondary {
--badge-border-color: rgba(160, 160, 176, 0.2);
background: rgba(160, 160, 176, 0.15);
color: var(--text-secondary);
}
.icon {
font-size: 12px;
line-height: 1;
}
.badge.size-md .icon {
font-size: 14px;
}
`
];
constructor() {
super();
this.variant = 'primary';
this.icon = '';
this.size = 'sm';
}
render() {
return html`
<span class="badge variant-${this.variant} size-${this.size}">
${this.icon ? html`<span class="icon">${this.icon}</span>` : ''}
<slot></slot>
</span>
`;
}
}
customElements.define('srdb-badge', Badge);

View File

@@ -0,0 +1,351 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class DataView extends LitElement {
static properties = {
tableName: { type: String },
schema: { type: Object },
tableData: { type: Object },
selectedColumns: { type: Array },
loading: { type: Boolean }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: block;
}
h3 {
font-size: 16px;
font-weight: 600;
margin: 20px 0 12px 0;
color: var(--text-primary);
}
.schema-section {
margin-bottom: 24px;
}
.schema-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 12px;
}
.schema-field-card {
padding: 12px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
cursor: pointer;
transition: var(--transition);
}
.schema-field-card:hover {
background: var(--bg-hover);
}
.schema-field-card.selected {
border-color: var(--primary);
background: var(--primary-bg);
}
.field-item {
display: flex;
flex-direction: column;
gap: 4px;
}
.field-item-row {
display: flex;
align-items: center;
gap: 8px;
}
.field-index-icon {
font-size: 14px;
flex-shrink: 0;
}
.field-name {
font-weight: 500;
color: var(--text-primary);
font-size: 13px;
flex: 1;
}
.field-type {
font-family: 'Courier New', monospace;
}
.field-comment {
color: var(--text-tertiary);
font-size: 11px;
margin-top: 4px;
font-style: italic;
min-height: 16px;
}
.field-comment:empty::before {
content: "No comment";
opacity: 0.5;
}
.table-wrapper {
overflow-x: auto;
background: var(--bg-elevated);
border-radius: var(--radius-md);
border: 1px solid var(--border-color);
}
.data-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.data-table th {
background: var(--bg-surface);
color: var(--text-secondary);
font-weight: 600;
text-align: left;
padding: 12px;
border-bottom: 1px solid var(--border-color);
position: sticky;
top: 0;
z-index: 1;
}
.data-table td {
padding: 10px 12px;
border-bottom: 1px solid var(--border-color);
color: var(--text-primary);
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.data-table td:hover {
white-space: normal;
word-break: break-all;
}
.data-table tr:hover {
background: var(--bg-hover);
}
.truncated-icon {
margin-left: 4px;
font-size: 10px;
}
.row-detail-btn {
padding: 4px 12px;
background: var(--primary);
color: white;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 12px;
transition: var(--transition);
}
.row-detail-btn:hover {
background: var(--primary-dark);
}
`
];
constructor() {
super();
this.tableName = '';
this.schema = null;
this.tableData = null;
this.selectedColumns = [];
this.loading = false;
}
updated(changedProperties) {
// 当 tableName 或 schema 改变时,尝试加载保存的列选择
if ((changedProperties.has('tableName') || changedProperties.has('schema')) && this.tableName && this.schema) {
const saved = this.loadSelectedColumns();
if (saved && saved.length > 0) {
// 验证保存的列是否仍然存在于当前 schema 中
const validColumns = saved.filter(col =>
this.schema.fields.some(field => field.name === col)
);
if (validColumns.length > 0) {
this.selectedColumns = validColumns;
}
}
}
}
toggleColumn(columnName) {
const index = this.selectedColumns.indexOf(columnName);
if (index > -1) {
this.selectedColumns = this.selectedColumns.filter(c => c !== columnName);
} else {
this.selectedColumns = [...this.selectedColumns, columnName];
}
// 持久化到 localStorage
this.saveSelectedColumns();
this.dispatchEvent(new CustomEvent('columns-changed', {
detail: { columns: this.selectedColumns },
bubbles: true,
composed: true
}));
}
saveSelectedColumns() {
if (!this.tableName) return;
const key = `srdb_columns_${this.tableName}`;
localStorage.setItem(key, JSON.stringify(this.selectedColumns));
}
loadSelectedColumns() {
if (!this.tableName) return null;
const key = `srdb_columns_${this.tableName}`;
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : null;
}
showRowDetail(seq) {
this.dispatchEvent(new CustomEvent('show-row-detail', {
detail: { tableName: this.tableName, seq },
bubbles: true,
composed: true
}));
}
formatCount(count) {
if (count >= 1000000) return (count / 1000000).toFixed(1) + 'M';
if (count >= 1000) return (count / 1000).toFixed(1) + 'K';
return count.toString();
}
formatTime(nanoTime) {
if (!nanoTime) return '';
// 将纳秒转换为毫秒
const date = new Date(nanoTime / 1000000);
// 格式化为 YYYY-MM-DD HH:mm:ss
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
getColumns() {
let columns = [];
if (this.selectedColumns.length > 0) {
columns = [...this.selectedColumns];
} else {
columns = this.schema?.fields?.map(f => f.name) || [];
}
// 确保系统字段的顺序_seq 在开头_time 在倒数第二
const filtered = columns.filter(c => c !== '_seq' && c !== '_time');
// _seq 放开头
const result = ['_seq', ...filtered];
// _time 放倒数第二Actions 列之前)
result.push('_time');
return result;
}
render() {
if (this.loading || !this.schema || !this.tableData) {
return html`<div class="loading">Loading data...</div>`;
}
const columns = this.getColumns();
return html`
${this.renderSchemaSection()}
<h3>Data (${this.formatCount(this.tableData.totalRows)} rows)</h3>
${this.tableData.data.length === 0 ? html`
<div class="empty"><p>No data available</p></div>
` : html`
<div class="table-wrapper">
<table class="data-table">
<thead>
<tr>
${columns.map(col => html`<th>${col}</th>`)}
<th style="text-align: center;">Actions</th>
</tr>
</thead>
<tbody>
${this.tableData.data.map(row => html`
<tr>
${columns.map(col => html`
<td>
${col === '_time' ? this.formatTime(row[col]) : row[col]}
${row[col + '_truncated'] ? html`<span class="truncated-icon">✂️</span>` : ''}
</td>
`)}
<td style="text-align: center;">
<button
class="row-detail-btn"
@click=${() => this.showRowDetail(row._seq)}
>
Detail
</button>
</td>
</tr>
`)}
</tbody>
</table>
</div>
`}
`;
}
renderSchemaSection() {
if (!this.schema || !this.schema.fields) return '';
return html`
<div class="schema-section">
<h3>Schema <span style="font-size: 12px; font-weight: 400; color: var(--text-secondary);">(点击字段卡片选择要显示的列)</span></h3>
<div class="schema-grid">
${this.schema.fields.map(field => html`
<div
class="schema-field-card ${this.selectedColumns.includes(field.name) ? 'selected' : ''}"
@click=${() => this.toggleColumn(field.name)}
>
<div class="field-item">
<div class="field-item-row">
<srdb-field-icon
?indexed=${field.indexed}
class="field-index-icon"
title="${field.indexed ? 'Indexed field (fast)' : 'Not indexed (slow)'}"
></srdb-field-icon>
<span class="field-name">${field.name}</span>
<srdb-badge variant="primary" class="field-type">
${field.type}
</srdb-badge>
</div>
<div class="field-comment">${field.comment || ''}</div>
</div>
</div>
`)}
</div>
</div>
`;
}
}
customElements.define('srdb-data-view', DataView);

View File

@@ -0,0 +1,59 @@
import { LitElement, html, css, svg } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
export class FieldIcon extends LitElement {
static properties = {
indexed: { type: Boolean }
};
static styles = css`
:host {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
}
svg {
width: 16px;
height: 16px;
}
.indexed {
fill: var(--success);
color: var(--success);
opacity: 1;
}
.not-indexed {
fill: var(--text-secondary);
color: var(--text-secondary);
opacity: 0.6;
}
`;
constructor() {
super();
this.indexed = false;
}
render() {
if (this.indexed) {
// 闪电图标 - 已索引(快速)
return html`
<svg viewBox="0 0 24 24" class="indexed" xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" fill="currentColor" stroke="none"/>
</svg>
`;
} else {
// 圆点图标 - 未索引
return html`
<svg viewBox="0 0 24 24" class="not-indexed" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="4" fill="currentColor"/>
</svg>
`;
}
}
}
customElements.define('srdb-field-icon', FieldIcon);

View File

@@ -0,0 +1,301 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class ManifestView extends LitElement {
static properties = {
manifestData: { type: Object },
loading: { type: Boolean },
expandedLevels: { type: Set }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: block;
}
h3 {
font-size: 16px;
font-weight: 600;
margin: 20px 0 12px 0;
color: var(--text-primary);
}
.manifest-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin-bottom: 24px;
}
.stat-card {
padding: 16px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
}
.stat-label {
font-size: 12px;
color: var(--text-tertiary);
margin-bottom: 8px;
}
.stat-value {
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
}
.level-card {
margin-bottom: 12px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
overflow: hidden;
}
.level-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
cursor: pointer;
transition: var(--transition);
}
.level-header:hover {
background: var(--bg-hover);
}
.level-header-left {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
}
.expand-icon {
font-size: 12px;
color: var(--text-secondary);
transition: transform 0.2s ease;
user-select: none;
}
.expand-icon.expanded {
transform: rotate(90deg);
}
.level-title {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.level-stats {
display: flex;
gap: 16px;
font-size: 13px;
color: var(--text-secondary);
}
.level-files {
padding: 16px;
background: var(--bg-surface);
border-top: 1px solid var(--border-color);
display: none;
}
.level-files.expanded {
display: block;
}
.file-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 12px;
}
.file-item {
padding: 12px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
transition: var(--transition);
}
.file-item:hover {
border-color: var(--primary);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.file-name {
font-family: 'Courier New', monospace;
font-size: 13px;
color: var(--text-primary);
font-weight: 500;
margin-bottom: 8px;
}
.file-detail {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
color: var(--text-secondary);
}
.file-detail-row {
display: flex;
justify-content: space-between;
}
@media (max-width: 768px) {
.file-list {
grid-template-columns: 1fr;
}
}
.empty {
background: var(--bg-elevated);
border-radius: var(--radius-md);
border: 1px dashed var(--border-color);
margin-top: 24px;
}
.empty p {
margin: 0;
}
`
];
constructor() {
super();
this.manifestData = null;
this.loading = false;
this.expandedLevels = new Set();
}
toggleLevel(levelNum) {
if (this.expandedLevels.has(levelNum)) {
this.expandedLevels.delete(levelNum);
} else {
this.expandedLevels.add(levelNum);
}
this.requestUpdate();
}
formatSize(bytes) {
if (bytes >= 1024 * 1024 * 1024) return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
if (bytes >= 1024) return (bytes / 1024).toFixed(2) + ' KB';
return bytes + ' B';
}
getScoreVariant(score) {
if (score >= 0.8) return 'danger'; // 高分 = 需要紧急 compaction
if (score >= 0.5) return 'warning'; // 中分 = 需要关注
return 'success'; // 低分 = 健康状态
}
render() {
if (this.loading || !this.manifestData) {
return html`<div class="loading">Loading manifest...</div>`;
}
const totalFiles = this.manifestData.levels.reduce((sum, l) => sum + l.file_count, 0);
const totalSize = this.manifestData.levels.reduce((sum, l) => sum + l.total_size, 0);
const totalCompactions = this.manifestData.compaction_stats?.total_compactions || 0;
return html`
<h3>LSM-Tree Structure</h3>
<div class="manifest-stats">
<div class="stat-card">
<div class="stat-label">Active Levels</div>
<div class="stat-value">${this.manifestData.levels.filter(l => l.file_count > 0).length}</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Files</div>
<div class="stat-value">${totalFiles}</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Size</div>
<div class="stat-value">${this.formatSize(totalSize)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Compactions</div>
<div class="stat-value">${totalCompactions}</div>
</div>
</div>
${this.manifestData.levels && this.manifestData.levels.length > 0
? this.manifestData.levels.map(level => this.renderLevelCard(level))
: html`
<div class="empty">
<p>No SSTable files in this table yet.</p>
<p style="font-size: 14px; margin-top: 8px;">Insert some data to see the LSM-Tree structure.</p>
</div>
`
}
`;
}
renderLevelCard(level) {
if (level.file_count === 0) return '';
const isExpanded = this.expandedLevels.has(level.level);
return html`
<div class="level-card">
<div class="level-header" @click=${() => this.toggleLevel(level.level)}>
<div class="level-header-left">
<span class="expand-icon ${isExpanded ? 'expanded' : ''}">▶</span>
<div>
<div class="level-title">Level ${level.level}</div>
<div class="level-stats">
<span>${level.file_count} files</span>
<span>${this.formatSize(level.total_size)}</span>
${level.score !== undefined ? html`
<srdb-badge variant="${this.getScoreVariant(level.score)}">
Score: ${(level.score * 100).toFixed(0)}%
</srdb-badge>
` : ''}
</div>
</div>
</div>
</div>
${level.files && level.files.length > 0 ? html`
<div class="level-files ${isExpanded ? 'expanded' : ''}">
<div class="file-list">
${level.files.map(file => html`
<div class="file-item">
<div class="file-name">${file.file_number}.sst</div>
<div class="file-detail">
<div class="file-detail-row">
<span>Size:</span>
<span>${this.formatSize(file.file_size)}</span>
</div>
<div class="file-detail-row">
<span>Rows:</span>
<span>${file.row_count || 0}</span>
</div>
<div class="file-detail-row">
<span>Seq Range:</span>
<span>${file.min_key} - ${file.max_key}</span>
</div>
</div>
</div>
`)}
</div>
</div>
` : ''}
</div>
`;
}
}
customElements.define('srdb-manifest-view', ManifestView);

View File

@@ -0,0 +1,179 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class ModalDialog extends LitElement {
static properties = {
open: { type: Boolean },
title: { type: String },
content: { type: String }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
z-index: 1000;
align-items: center;
justify-content: center;
}
:host([open]) {
display: flex;
}
.modal-content {
background: var(--bg-surface);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-xl);
min-width: 324px;
max-width: 90vw;
max-height: 80vh;
width: fit-content;
display: flex;
flex-direction: column;
border: 1px solid var(--border-color);
}
@media (max-width: 768px) {
.modal-content {
min-width: 300px;
max-width: 95vw;
}
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 24px;
border-bottom: 1px solid var(--border-color);
}
.modal-header h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.modal-close {
background: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-sm);
transition: var(--transition);
}
.modal-close:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.modal-body {
padding: 24px;
overflow-y: auto;
flex: 1;
}
pre {
/*background: var(--bg-elevated);*/
padding: 16px;
border-radius: var(--radius-md);
overflow-x: auto;
color: var(--text-primary);
font-family: 'Courier New', monospace;
font-size: 13px;
line-height: 1.5;
margin: 0;
white-space: pre-wrap;
word-wrap: break-word;
}
`
];
constructor() {
super();
this.open = false;
this.title = 'Content';
this.content = '';
this._handleKeyDown = this._handleKeyDown.bind(this);
}
connectedCallback() {
super.connectedCallback();
document.addEventListener('keydown', this._handleKeyDown);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener('keydown', this._handleKeyDown);
}
updated(changedProperties) {
if (changedProperties.has('open')) {
if (this.open) {
this.setAttribute('open', '');
} else {
this.removeAttribute('open');
}
}
}
_handleKeyDown(e) {
if (this.open && e.key === 'Escape') {
this.close();
}
}
close() {
this.open = false;
this.dispatchEvent(new CustomEvent('modal-close', {
bubbles: true,
composed: true
}));
}
render() {
return html`
<div class="modal-content" @click=${(e) => e.stopPropagation()}>
<div class="modal-header">
<h3>${this.title}</h3>
<button class="modal-close" @click=${this.close}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="modal-body">
<pre>${this.content}</pre>
</div>
</div>
`;
}
}
customElements.define('srdb-modal-dialog', ModalDialog);

View File

@@ -0,0 +1,267 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class PageHeader extends LitElement {
static properties = {
tableName: { type: String },
view: { type: String }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: block;
background: var(--bg-surface);
border-bottom: 1px solid var(--border-color);
position: sticky;
top: 0;
z-index: 10;
}
.header-content {
padding: 16px 24px;
}
.header-top {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 12px;
}
.mobile-menu-btn {
display: none;
width: 40px;
height: 40px;
background: var(--primary);
border: none;
border-radius: var(--radius-md);
color: white;
cursor: pointer;
flex-shrink: 0;
transition: var(--transition);
}
.mobile-menu-btn:hover {
background: var(--primary-dark);
}
.mobile-menu-btn svg {
width: 20px;
height: 20px;
}
h2 {
font-size: 24px;
font-weight: 600;
margin: 0;
color: var(--text-primary);
}
.empty-state {
text-align: center;
padding: 20px;
color: var(--text-secondary);
}
.view-tabs {
display: flex;
align-items: center;
gap: 8px;
border-bottom: 1px solid var(--border-color);
margin: 0 -12px;
padding: 0 24px;
}
.refresh-btn {
margin-left: auto;
padding: 8px 12px;
background: transparent;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
color: var(--text-secondary);
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
}
.refresh-btn:hover {
background: var(--bg-hover);
border-color: var(--border-hover);
color: var(--text-primary);
}
.refresh-btn svg {
width: 16px;
height: 16px;
}
.view-tab {
position: relative;
padding: 16px 20px;
background: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: var(--transition);
}
.view-tab:hover {
color: var(--text-primary);
/*background: var(--bg-hover);*/
}
.view-tab.active {
color: var(--primary);
}
.view-tab::before,
.view-tab::after {
position: absolute;
display: block;
content: "";
z-index: 0;
opacity: 0;
inset-inline: 8px;
}
.view-tab::before {
inset-block: 8px;
border-radius: var(--radius-md);
background: var(--bg-elevated);
}
.view-tab::after {
border-radius: var(--radius-md);
background: var(--primary);
bottom: -2px;
height: 4px;
}
.view-tab.active::before,
.view-tab.active::after,
.view-tab:hover::before {
opacity: 1;
}
.view-tab span {
position: relative;
z-index: 1;
}
@media (max-width: 768px) {
.mobile-menu-btn {
display: flex;
align-items: center;
justify-content: center;
}
.header-content {
padding: 12px 16px;
}
h2 {
font-size: 18px;
flex: 1;
}
.view-tabs {
margin: 0 -16px;
padding: 0 16px;
}
.view-tab {
padding: 8px 16px;
font-size: 13px;
}
}
`
];
constructor() {
super();
this.tableName = '';
this.view = 'data';
}
switchView(newView) {
this.view = newView;
this.dispatchEvent(new CustomEvent('view-changed', {
detail: { view: newView },
bubbles: true,
composed: true
}));
}
toggleMobileMenu() {
this.dispatchEvent(new CustomEvent('toggle-mobile-menu', {
bubbles: true,
composed: true
}));
}
refreshView() {
this.dispatchEvent(new CustomEvent('refresh-view', {
detail: { view: this.view },
bubbles: true,
composed: true
}));
}
render() {
if (!this.tableName) {
return html`
<div class="header-content">
<div class="empty-state">
<p>Select a table from the sidebar</p>
</div>
</div>
`;
}
return html`
<div class="header-content">
<div class="header-top">
<button class="mobile-menu-btn" @click=${this.toggleMobileMenu}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="3" y1="12" x2="21" y2="12"></line>
<line x1="3" y1="6" x2="21" y2="6"></line>
<line x1="3" y1="18" x2="21" y2="18"></line>
</svg>
</button>
<h2>${this.tableName}</h2>
</div>
</div>
<div class="view-tabs">
<button
class="view-tab ${this.view === 'data' ? 'active' : ''}"
@click=${() => this.switchView('data')}
>
<span>Data</span>
</button>
<button
class="view-tab ${this.view === 'manifest' ? 'active' : ''}"
@click=${() => this.switchView('manifest')}
>
<span>Manifest / LSM-Tree</span>
</button>
<button class="refresh-btn" @click=${this.refreshView} title="Refresh current view">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"/>
</svg>
<span>Refresh</span>
</button>
</div>
`;
}
}
customElements.define('srdb-page-header', PageHeader);

View File

@@ -0,0 +1,284 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class TableList extends LitElement {
static properties = {
tables: { type: Array },
selectedTable: { type: String },
expandedTables: { type: Set }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: block;
width: 100%;
}
.table-item {
margin-bottom: 8px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
overflow: hidden;
transition: var(--transition);
}
.table-item:hover {
border-color: var(--border-hover);
}
.table-item.selected {
border-color: var(--primary);
box-shadow: 0 0 0 1px var(--primary);
}
.table-item.selected .table-header {
background: var(--primary-bg);
}
.table-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
cursor: pointer;
transition: var(--transition);
}
.table-header:hover {
background: var(--bg-hover);
}
.table-item.has-expanded .table-header {
border-bottom-color: var(--border-color);
}
.table-header-left {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
min-width: 0;
}
.expand-icon {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
font-size: 12px;
transition: var(--transition);
flex-shrink: 0;
border-radius: var(--radius-sm);
cursor: pointer;
color: var(--text-secondary);
}
.expand-icon:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.expand-icon.expanded {
transform: rotate(90deg);
color: var(--primary);
}
.table-name {
font-weight: 500;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.table-count {
font-size: 12px;
color: var(--text-tertiary);
white-space: nowrap;
flex-shrink: 0;
}
/* Schema 字段列表 */
.schema-fields {
display: none;
flex-direction: column;
border-top: 1px solid transparent;
transition: var(--transition);
position: relative;
}
.schema-fields.expanded {
display: block;
border-top-color: var(--border-color);
}
/* 共享的垂直线 */
.schema-fields.expanded::before {
z-index: 2;
content: "";
position: absolute;
left: 24px;
top: 0;
bottom: 24px;
width: 1px;
background: var(--border-color);
}
.field-item {
z-index: 1;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px 8px 24px;
font-size: 12px;
transition: var(--transition);
position: relative;
}
/* 每个字段的水平线 */
.field-item::before {
content: "";
width: 8px;
height: 1px;
background: var(--border-color);
}
.field-item:hover {
background: var(--bg-hover);
}
.field-item:last-child {
padding-bottom: 12px;
}
.field-index-icon {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
font-size: 14px;
flex-shrink: 0;
}
.field-index-icon.indexed {
color: var(--success);
}
.field-index-icon.not-indexed {
color: var(--text-tertiary);
opacity: 0.5;
}
.field-name {
font-weight: 500;
color: var(--text-secondary);
flex: 1;
}
.field-type {
font-family: 'Courier New', monospace;
}
.loading {
padding: 20px;
}
.error {
text-align: center;
padding: 20px;
color: var(--danger);
}
`
];
constructor() {
super();
this.tables = [];
this.selectedTable = '';
this.expandedTables = new Set();
}
connectedCallback() {
super.connectedCallback();
this.loadTables();
}
async loadTables() {
try {
const response = await fetch('/api/tables');
if (!response.ok) throw new Error('Failed to load tables');
this.tables = await response.json();
} catch (error) {
console.error('Error loading tables:', error);
}
}
toggleExpand(tableName, event) {
event.stopPropagation();
if (this.expandedTables.has(tableName)) {
this.expandedTables.delete(tableName);
} else {
this.expandedTables.add(tableName);
}
this.requestUpdate();
}
selectTable(tableName) {
this.selectedTable = tableName;
this.dispatchEvent(new CustomEvent('table-selected', {
detail: { tableName },
bubbles: true,
composed: true
}));
}
render() {
if (this.tables.length === 0) {
return html`<div class="loading">Loading tables...</div>`;
}
return html`
${this.tables.map(table => html`
<div class="table-item ${this.expandedTables.has(table.name) ? 'has-expanded' : ''} ${this.selectedTable === table.name ? 'selected' : ''}">
<div
class="table-header"
@click=${() => this.selectTable(table.name)}
>
<div class="table-header-left">
<span
class="expand-icon ${this.expandedTables.has(table.name) ? 'expanded' : ''}"
@click=${(e) => this.toggleExpand(table.name, e)}
>
</span>
<span class="table-name">${table.name}</span>
</div>
<span class="table-count">${table.fields.length} fields</span>
</div>
<div class="schema-fields ${this.expandedTables.has(table.name) ? 'expanded' : ''}">
${table.fields.map(field => html`
<div class="field-item">
<srdb-field-icon
?indexed=${field.indexed}
class="field-index-icon"
title="${field.indexed ? 'Indexed field (fast)' : 'Not indexed (slow)'}"
></srdb-field-icon>
<span class="field-name">${field.name}</span>
<srdb-badge variant="primary" class="field-type">
${field.type}
</srdb-badge>
</div>
`)}
</div>
</div>
`)}
`;
}
}
customElements.define('srdb-table-list', TableList);

View File

@@ -0,0 +1,364 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles, cssVariables } from '../styles/shared-styles.js';
export class TableView extends LitElement {
static properties = {
tableName: { type: String },
view: { type: String }, // 'data' or 'manifest'
schema: { type: Object },
tableData: { type: Object },
manifestData: { type: Object },
selectedColumns: { type: Array },
page: { type: Number },
pageSize: { type: Number },
loading: { type: Boolean }
};
static styles = [
sharedStyles,
cssVariables,
css`
:host {
display: flex;
flex-direction: column;
width: 100%;
flex: 1;
position: relative;
overflow: hidden;
}
.content-wrapper {
flex: 1;
overflow-y: auto;
padding: 24px;
padding-bottom: 80px;
}
.pagination {
position: fixed;
bottom: 0;
left: 280px;
right: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 16px 24px;
background: var(--bg-elevated);
border-top: 1px solid var(--border-color);
z-index: 10;
}
@media (max-width: 768px) {
.pagination {
left: 0;
}
}
.pagination button {
padding: 8px 16px;
background: var(--bg-surface);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
cursor: pointer;
transition: var(--transition);
}
.pagination button:hover:not(:disabled) {
background: var(--bg-hover);
border-color: var(--border-hover);
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination select,
.pagination input {
padding: 8px 12px;
background: var(--bg-surface);
color: var(--text-primary);
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
}
.pagination input {
width: 80px;
}
.pagination span {
color: var(--text-primary);
font-size: 14px;
}
`
];
constructor() {
super();
this.tableName = '';
this.view = 'data';
this.schema = null;
this.tableData = null;
this.manifestData = null;
this.selectedColumns = [];
this.page = 1;
this.pageSize = 20;
this.loading = false;
}
updated(changedProperties) {
if (changedProperties.has('tableName') && this.tableName) {
// 切换表时重置选中的列
this.selectedColumns = [];
this.page = 1;
this.loadData();
}
if (changedProperties.has('view') && this.tableName) {
this.loadData();
}
}
async loadData() {
if (!this.tableName) return;
this.loading = true;
try {
// Load schema
const schemaResponse = await fetch(`/api/tables/${this.tableName}/schema`);
if (!schemaResponse.ok) throw new Error('Failed to load schema');
this.schema = await schemaResponse.json();
// Initialize selected columns (all by default)
if (this.schema.fields) {
this.selectedColumns = this.schema.fields.map(f => f.name);
}
if (this.view === 'data') {
await this.loadTableData();
} else if (this.view === 'manifest') {
await this.loadManifestData();
}
} catch (error) {
console.error('Error loading data:', error);
} finally {
this.loading = false;
}
}
async loadTableData() {
const selectParam = this.selectedColumns.join(',');
const url = `/api/tables/${this.tableName}/data?page=${this.page}&pageSize=${this.pageSize}&select=${selectParam}`;
const response = await fetch(url);
if (!response.ok) throw new Error('Failed to load table data');
this.tableData = await response.json();
}
async loadManifestData() {
const response = await fetch(`/api/tables/${this.tableName}/manifest`);
if (!response.ok) throw new Error('Failed to load manifest data');
this.manifestData = await response.json();
}
switchView(newView) {
this.view = newView;
}
toggleColumn(columnName) {
const index = this.selectedColumns.indexOf(columnName);
if (index > -1) {
this.selectedColumns = this.selectedColumns.filter(c => c !== columnName);
} else {
this.selectedColumns = [...this.selectedColumns, columnName];
}
this.loadTableData();
}
changePage(delta) {
this.page = Math.max(1, this.page + delta);
this.loadTableData();
}
changePageSize(newSize) {
this.pageSize = parseInt(newSize);
this.page = 1;
this.loadTableData();
}
jumpToPage(pageNum) {
const num = parseInt(pageNum);
if (num > 0 && this.tableData && num <= this.tableData.totalPages) {
this.page = num;
this.loadTableData();
}
}
showRowDetail(seq) {
this.dispatchEvent(new CustomEvent('show-row-detail', {
detail: { tableName: this.tableName, seq },
bubbles: true,
composed: true
}));
}
toggleLevel(level) {
const levelCard = this.shadowRoot.querySelector(`[data-level="${level}"]`);
if (levelCard) {
const fileList = levelCard.querySelector('.file-list');
const icon = levelCard.querySelector('.expand-icon');
if (fileList.classList.contains('expanded')) {
fileList.classList.remove('expanded');
icon.style.transform = 'rotate(0deg)';
} else {
fileList.classList.add('expanded');
icon.style.transform = 'rotate(90deg)';
}
}
}
formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}
formatCount(count) {
if (count >= 1000000) return (count / 1000000).toFixed(1) + 'M';
if (count >= 1000) return (count / 1000).toFixed(1) + 'K';
return count.toString();
}
render() {
if (!this.tableName) {
return html`
<div class="empty">
<h2>Select a table to view data</h2>
<p>Choose a table from the sidebar to get started</p>
</div>
`;
}
if (this.loading) {
return html`<div class="loading">Loading...</div>`;
}
return html`
<div class="content-wrapper">
${this.view === 'data' ? html`
<srdb-data-view
.tableName=${this.tableName}
.schema=${this.schema}
.tableData=${this.tableData}
.selectedColumns=${this.selectedColumns}
.loading=${this.loading}
@columns-changed=${(e) => {
this.selectedColumns = e.detail.columns;
this.loadTableData();
}}
@show-row-detail=${(e) => this.showRowDetail(e.detail.seq)}
></srdb-data-view>
` : html`
<srdb-manifest-view
.manifestData=${this.manifestData}
.loading=${this.loading}
></srdb-manifest-view>
`}
</div>
${this.view === 'data' && this.tableData ? this.renderPagination() : ''}
`;
}
renderPagination() {
return html`
<div class="pagination">
<select @change=${(e) => this.changePageSize(e.target.value)}>
${[10, 20, 50, 100].map(size => html`
<option value="${size}" ?selected=${size === this.pageSize}>
${size} / page
</option>
`)}
</select>
<button
@click=${() => this.changePage(-1)}
?disabled=${this.page <= 1}
>
Previous
</button>
<span>
Page ${this.page} of ${this.tableData.totalPages}
(${this.formatCount(this.tableData.totalRows)} rows)
</span>
<input
type="number"
min="1"
max="${this.tableData.totalPages}"
placeholder="Jump to"
@keydown=${(e) => e.key === 'Enter' && this.jumpToPage(e.target.value)}
/>
<button @click=${(e) => this.jumpToPage(e.target.previousElementSibling.value)}>
Go
</button>
<button
@click=${() => this.changePage(1)}
?disabled=${this.page >= this.tableData.totalPages}
>
Next
</button>
</div>
`;
}
formatCount(count) {
if (count >= 1000000) return (count / 1000000).toFixed(1) + 'M';
if (count >= 1000) return (count / 1000).toFixed(1) + 'K';
return count.toString();
}
changePage(delta) {
this.page = Math.max(1, this.page + delta);
this.loadTableData();
}
changePageSize(newSize) {
this.pageSize = parseInt(newSize);
this.page = 1;
this.loadTableData();
}
jumpToPage(pageNum) {
const num = parseInt(pageNum);
if (num > 0 && this.tableData && num <= this.tableData.totalPages) {
this.page = num;
this.loadTableData();
}
}
showRowDetail(seq) {
this.dispatchEvent(new CustomEvent('show-row-detail', {
detail: { tableName: this.tableName, seq },
bubbles: true,
composed: true
}));
}
showCellContent(content) {
this.dispatchEvent(new CustomEvent('show-cell-content', {
detail: { content },
bubbles: true,
composed: true
}));
}
}
customElements.define('srdb-table-view', TableView);

View File

@@ -0,0 +1,123 @@
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
import { sharedStyles } from '../styles/shared-styles.js';
export class ThemeToggle extends LitElement {
static properties = {
theme: { type: String }
};
static styles = [
sharedStyles,
css`
:host {
display: inline-block;
}
.theme-toggle {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background: var(--bg-elevated);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
cursor: pointer;
transition: var(--transition);
font-size: 14px;
color: var(--text-primary);
}
.theme-toggle:hover {
background: var(--bg-hover);
border-color: var(--border-hover);
}
.icon {
font-size: 18px;
display: flex;
align-items: center;
}
.label {
font-weight: 500;
}
`
];
constructor() {
super();
// 从 localStorage 读取主题,默认为 dark
this.theme = localStorage.getItem('srdb-theme') || 'dark';
this.applyTheme();
}
toggleTheme() {
this.theme = this.theme === 'dark' ? 'light' : 'dark';
localStorage.setItem('srdb-theme', this.theme);
this.applyTheme();
// 触发主题变化事件
this.dispatchEvent(new CustomEvent('theme-changed', {
detail: { theme: this.theme },
bubbles: true,
composed: true
}));
}
applyTheme() {
const root = document.documentElement;
if (this.theme === 'light') {
// 浅色主题
root.style.setProperty('--srdb-bg-main', '#ffffff');
root.style.setProperty('--srdb-bg-surface', '#f5f5f5');
root.style.setProperty('--srdb-bg-elevated', '#e5e5e5');
root.style.setProperty('--srdb-bg-hover', '#d4d4d4');
root.style.setProperty('--srdb-text-primary', '#1a1a1a');
root.style.setProperty('--srdb-text-secondary', '#666666');
root.style.setProperty('--srdb-text-tertiary', '#999999');
root.style.setProperty('--srdb-border-color', 'rgba(0, 0, 0, 0.1)');
root.style.setProperty('--srdb-border-hover', 'rgba(0, 0, 0, 0.2)');
root.style.setProperty('--srdb-shadow-sm', '0 1px 2px 0 rgba(0, 0, 0, 0.05)');
root.style.setProperty('--srdb-shadow-md', '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)');
root.style.setProperty('--srdb-shadow-lg', '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)');
root.style.setProperty('--srdb-shadow-xl', '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)');
} else {
// 深色主题(默认值)
root.style.setProperty('--srdb-bg-main', '#0f0f1a');
root.style.setProperty('--srdb-bg-surface', '#1a1a2e');
root.style.setProperty('--srdb-bg-elevated', '#222236');
root.style.setProperty('--srdb-bg-hover', '#2a2a3e');
root.style.setProperty('--srdb-text-primary', '#ffffff');
root.style.setProperty('--srdb-text-secondary', '#a0a0b0');
root.style.setProperty('--srdb-text-tertiary', '#6b6b7b');
root.style.setProperty('--srdb-border-color', 'rgba(255, 255, 255, 0.1)');
root.style.setProperty('--srdb-border-hover', 'rgba(255, 255, 255, 0.2)');
root.style.setProperty('--srdb-shadow-sm', '0 1px 2px 0 rgba(0, 0, 0, 0.3)');
root.style.setProperty('--srdb-shadow-md', '0 4px 6px -1px rgba(0, 0, 0, 0.4), 0 2px 4px -1px rgba(0, 0, 0, 0.3)');
root.style.setProperty('--srdb-shadow-lg', '0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3)');
root.style.setProperty('--srdb-shadow-xl', '0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.3)');
}
}
render() {
return html`
<button class="theme-toggle" @click=${this.toggleTheme}>
<span class="icon">
${this.theme === 'dark' ? '🌙' : '☀️'}
</span>
<span class="label">
${this.theme === 'dark' ? 'Dark' : 'Light'}
</span>
</button>
`;
}
}
customElements.define('srdb-theme-toggle', ThemeToggle);

View File

@@ -0,0 +1,89 @@
import { css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
// 共享的基础样式
export const sharedStyles = css`
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* 自定义滚动条样式 */
*::-webkit-scrollbar {
width: 8px;
height: 8px;
}
*::-webkit-scrollbar-track {
background: transparent;
}
*::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
}
*::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
/* 通用状态样式 */
.empty {
text-align: center;
padding: 60px 20px;
color: var(--text-secondary);
}
.loading {
text-align: center;
padding: 60px 20px;
color: var(--text-secondary);
}
`;
// CSS 变量(可以在组件中使用,优先使用外部定义的变量)
export const cssVariables = css`
:host {
/* 主色调 - 优雅的紫蓝色 */
--primary: var(--srdb-primary, #6366f1);
--primary-dark: var(--srdb-primary-dark, #4f46e5);
--primary-light: var(--srdb-primary-light, #818cf8);
--primary-bg: var(--srdb-primary-bg, rgba(99, 102, 241, 0.1));
/* 背景色 */
--bg-main: var(--srdb-bg-main, #0f0f1a);
--bg-surface: var(--srdb-bg-surface, #1a1a2e);
--bg-elevated: var(--srdb-bg-elevated, #222236);
--bg-hover: var(--srdb-bg-hover, #2a2a3e);
/* 文字颜色 */
--text-primary: var(--srdb-text-primary, #ffffff);
--text-secondary: var(--srdb-text-secondary, #a0a0b0);
--text-tertiary: var(--srdb-text-tertiary, #6b6b7b);
/* 边框和分隔线 */
--border-color: var(--srdb-border-color, rgba(255, 255, 255, 0.1));
--border-hover: var(--srdb-border-hover, rgba(255, 255, 255, 0.2));
/* 状态颜色 */
--success: var(--srdb-success, #10b981);
--warning: var(--srdb-warning, #f59e0b);
--danger: var(--srdb-danger, #ef4444);
--info: var(--srdb-info, #3b82f6);
/* 阴影 */
--shadow-sm: var(--srdb-shadow-sm, 0 1px 2px 0 rgba(0, 0, 0, 0.3));
--shadow-md: var(--srdb-shadow-md, 0 4px 6px -1px rgba(0, 0, 0, 0.4), 0 2px 4px -1px rgba(0, 0, 0, 0.3));
--shadow-lg: var(--srdb-shadow-lg, 0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3));
--shadow-xl: var(--srdb-shadow-xl, 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.3));
/* 圆角 */
--radius-sm: var(--srdb-radius-sm, 6px);
--radius-md: var(--srdb-radius-md, 8px);
--radius-lg: var(--srdb-radius-lg, 12px);
--radius-xl: var(--srdb-radius-xl, 16px);
/* 过渡 */
--transition: var(--srdb-transition, all 0.2s cubic-bezier(0.4, 0, 0.2, 1));
}
`;

View File

@@ -5,12 +5,13 @@ import (
"encoding/json"
"fmt"
"io/fs"
"maps"
"net/http"
"sort"
"strconv"
"strings"
"code.tczkiot.com/srdb"
"code.tczkiot.com/srdb/sst"
)
//go:embed static
@@ -33,17 +34,10 @@ func NewWebUI(db *srdb.Database) *WebUI {
func (ui *WebUI) setupHandler() http.Handler {
mux := http.NewServeMux()
// API endpoints - JSON
// API endpoints - JSON API
mux.HandleFunc("/api/tables", ui.handleListTables)
mux.HandleFunc("/api/tables/", ui.handleTableAPI)
// API endpoints - HTML (for htmx)
mux.HandleFunc("/api/tables-html", ui.handleTablesHTML)
mux.HandleFunc("/api/tables-view/", ui.handleTableViewHTML)
// Debug endpoint - list embedded files
mux.HandleFunc("/debug/files", ui.handleDebugFiles)
// 静态文件服务
staticFiles, _ := fs.Sub(staticFS, "static")
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFiles))))
@@ -105,6 +99,11 @@ func (ui *WebUI) handleListTables(w http.ResponseWriter, r *http.Request) {
})
}
// 按表名排序
sort.Slice(tables, func(i, j int) bool {
return tables[i].Name < tables[j].Name
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(tables)
}
@@ -221,11 +220,8 @@ func (ui *WebUI) handleTableManifest(w http.ResponseWriter, r *http.Request, tab
picker := compactionMgr.GetPicker()
levels := make([]LevelInfo, 0)
for level := 0; level < 7; level++ {
for level := range 7 {
files := version.GetLevel(level)
if len(files) == 0 {
continue
}
totalSize := int64(0)
fileInfos := make([]FileInfo, 0, len(files))
@@ -241,7 +237,10 @@ func (ui *WebUI) handleTableManifest(w http.ResponseWriter, r *http.Request, tab
})
}
score := picker.GetLevelScore(version, level)
score := 0.0
if len(files) > 0 {
score = picker.GetLevelScore(version, level)
}
levels = append(levels, LevelInfo{
Level: level,
@@ -294,12 +293,10 @@ func (ui *WebUI) handleTableDataBySeq(w http.ResponseWriter, r *http.Request, ta
}
// 构造响应(不进行剪裁,返回完整数据)
rowData := make(map[string]interface{})
rowData := make(map[string]any)
rowData["_seq"] = row.Seq
rowData["_time"] = row.Time
for k, v := range row.Data {
rowData[k] = v
}
maps.Copy(rowData, row.Data)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(rowData)
@@ -342,26 +339,52 @@ func (ui *WebUI) handleTableData(w http.ResponseWriter, r *http.Request, tableNa
var selectedFields []string
if selectParam != "" {
selectedFields = strings.Split(selectParam, ",")
// 清理字段名(去除空格)
for i := range selectedFields {
selectedFields[i] = strings.TrimSpace(selectedFields[i])
}
}
// 获取 schema 用于字段类型判断
tableSchema := table.GetSchema()
// 使用 Query API 获取所有数据(高效
queryRows, err := table.Query().Rows()
// 使用 Query API 获取数据,如果指定了字段则只查询指定字段(按字段压缩优化
queryBuilder := table.Query()
if len(selectedFields) > 0 {
// 确保 _seq 和 _time 总是被查询(用于构造响应)
fieldsWithMeta := make([]string, 0, len(selectedFields)+2)
hasSeq := false
hasTime := false
for _, field := range selectedFields {
switch field {
case "_seq":
hasSeq = true
case "_time":
hasTime = true
}
}
if !hasSeq {
fieldsWithMeta = append(fieldsWithMeta, "_seq")
}
if !hasTime {
fieldsWithMeta = append(fieldsWithMeta, "_time")
}
fieldsWithMeta = append(fieldsWithMeta, selectedFields...)
queryBuilder = queryBuilder.Select(fieldsWithMeta...)
}
queryRows, err := queryBuilder.Rows()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to query table: %v", err), http.StatusInternalServerError)
return
}
defer queryRows.Close()
// 收集所有 rows 到内存中用于分页(对于大数据集,后续可以优化为流式处理)
allRows := make([]*sst.Row, 0)
// 收集所有 rows 到内存中用于分页
allRows := make([]*srdb.SSTableRow, 0)
for queryRows.Next() {
row := queryRows.Row()
// Row 是 query.Row 类型,需要获取其内部的 sst.Row
// 直接构造 sst.Row
sstRow := &sst.Row{
sstRow := &srdb.SSTableRow{
Seq: row.Data()["_seq"].(int64),
Time: row.Data()["_time"].(int64),
Data: make(map[string]any),
@@ -378,73 +401,43 @@ func (ui *WebUI) handleTableData(w http.ResponseWriter, r *http.Request, tableNa
// 计算分页
totalRows := int64(len(allRows))
offset := (page - 1) * pageSize
end := offset + pageSize
if end > int(totalRows) {
end = int(totalRows)
}
end := min(offset+pageSize, int(totalRows))
// 获取当前页数据
rows := make([]*sst.Row, 0, pageSize)
rows := make([]*srdb.SSTableRow, 0, pageSize)
if offset < int(totalRows) {
rows = allRows[offset:end]
}
// 构造响应,对 string 字段进行剪裁
const maxStringLength = 100 // 最大字符串长度(按字符计数,非字节)
const maxStringLength = 100 // 最大字符串长度
data := make([]map[string]any, 0, len(rows))
for _, row := range rows {
rowData := make(map[string]any)
rowData["_seq"] = row.Seq
rowData["_time"] = row.Time
// 如果指定了字段,只返回选定的字段
if len(selectedFields) > 0 {
for _, field := range selectedFields {
field = strings.TrimSpace(field)
if field == "_seq" {
rowData["_seq"] = row.Seq
} else if field == "_time" {
rowData["_time"] = row.Time
} else if v, ok := row.Data[field]; ok {
// 检查字段类型
fieldDef, err := tableSchema.GetField(field)
if err == nil && fieldDef.Type == srdb.FieldTypeString {
// 对字符串字段进行剪裁
if str, ok := v.(string); ok {
runes := []rune(str)
if len(runes) > maxStringLength {
rowData[field] = string(runes[:maxStringLength]) + "..."
rowData[field+"_truncated"] = true
continue
}
}
}
rowData[field] = v
}
}
} else {
// 返回所有字段
rowData["_seq"] = row.Seq
rowData["_time"] = row.Time
for k, v := range row.Data {
// 检查字段类型
field, err := tableSchema.GetField(k)
if err == nil && field.Type == srdb.FieldTypeString {
// 对字符串字段进行剪裁(按 rune 截取,避免 CJK 等多字节字符乱码)
if str, ok := v.(string); ok {
runes := []rune(str)
if len(runes) > maxStringLength {
rowData[k] = string(runes[:maxStringLength]) + "..."
rowData[k+"_truncated"] = true
continue
}
// 遍历所有字段
for k, v := range row.Data {
// 检查字段类型
field, err := tableSchema.GetField(k)
if err == nil && field.Type == srdb.FieldTypeString {
// 对字符串字段进行剪裁
if str, ok := v.(string); ok {
runes := []rune(str)
if len(runes) > maxStringLength {
rowData[k] = string(runes[:maxStringLength]) + "..."
rowData[k+"_truncated"] = true
continue
}
}
rowData[k] = v
}
rowData[k] = v
}
data = append(data, rowData)
}
response := map[string]interface{}{
response := map[string]any{
"data": data,
"page": page,
"pageSize": pageSize,
@@ -456,25 +449,6 @@ func (ui *WebUI) handleTableData(w http.ResponseWriter, r *http.Request, tableNa
json.NewEncoder(w).Encode(response)
}
// handleDebugFiles 列出所有嵌入的文件(调试用)
func (ui *WebUI) handleDebugFiles(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "Embedded files in staticFS:")
fs.WalkDir(staticFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Fprintf(w, "ERROR walking %s: %v\n", path, err)
return err
}
if d.IsDir() {
fmt.Fprintf(w, "[DIR] %s/\n", path)
} else {
info, _ := d.Info()
fmt.Fprintf(w, "[FILE] %s (%d bytes)\n", path, info.Size())
}
return nil
})
}
// handleIndex 处理首页请求
func (ui *WebUI) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
@@ -493,238 +467,3 @@ func (ui *WebUI) handleIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(content)
}
// handleTablesHTML 处理获取表列表 HTML 请求for htmx
func (ui *WebUI) handleTablesHTML(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
allTables := ui.db.GetAllTablesInfo()
tables := make([]TableListItem, 0, len(allTables))
for name, table := range allTables {
schema := table.GetSchema()
fields := make([]FieldInfo, 0, len(schema.Fields))
for _, field := range schema.Fields {
fields = append(fields, FieldInfo{
Name: field.Name,
Type: field.Type.String(),
Indexed: field.Indexed,
Comment: field.Comment,
})
}
tables = append(tables, TableListItem{
Name: name,
CreatedAt: table.GetCreatedAt(),
Fields: fields,
})
}
html := renderTablesHTML(tables)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(html))
}
// handleTableViewHTML 处理获取表视图 HTML 请求for htmx
func (ui *WebUI) handleTableViewHTML(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 解析路径: /api/tables-view/{name} 或 /api/tables-view/{name}/manifest
path := strings.TrimPrefix(r.URL.Path, "/api/tables-view/")
parts := strings.Split(path, "/")
if len(parts) < 1 || parts[0] == "" {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
tableName := parts[0]
isManifest := len(parts) >= 2 && parts[1] == "manifest"
table, err := ui.db.GetTable(tableName)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if isManifest {
// 返回 Manifest 视图 HTML
ui.renderManifestHTML(w, r, tableName, table)
} else {
// 返回 Data 视图 HTML
ui.renderDataHTML(w, r, tableName, table)
}
}
// renderDataHTML 渲染数据视图 HTML
func (ui *WebUI) renderDataHTML(w http.ResponseWriter, r *http.Request, tableName string, table *srdb.Table) {
// 解析分页参数
pageStr := r.URL.Query().Get("page")
pageSizeStr := r.URL.Query().Get("pageSize")
page := 1
pageSize := 20
if pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
if pageSizeStr != "" {
if ps, err := strconv.Atoi(pageSizeStr); err == nil && ps > 0 && ps <= 1000 {
pageSize = ps
}
}
// 获取 schema
tableSchema := table.GetSchema()
schemaInfo := SchemaInfo{
Name: tableSchema.Name,
Fields: make([]FieldInfo, 0, len(tableSchema.Fields)),
}
for _, field := range tableSchema.Fields {
schemaInfo.Fields = append(schemaInfo.Fields, FieldInfo{
Name: field.Name,
Type: field.Type.String(),
Indexed: field.Indexed,
Comment: field.Comment,
})
}
// 使用 Query API 获取所有数据
queryRows, err := table.Query().Rows()
if err != nil {
http.Error(w, fmt.Sprintf("Failed to query table: %v", err), http.StatusInternalServerError)
return
}
defer queryRows.Close()
// 收集所有 rows
allRows := make([]*sst.Row, 0)
for queryRows.Next() {
row := queryRows.Row()
sstRow := &sst.Row{
Seq: row.Data()["_seq"].(int64),
Time: row.Data()["_time"].(int64),
Data: make(map[string]any),
}
for k, v := range row.Data() {
if k != "_seq" && k != "_time" {
sstRow.Data[k] = v
}
}
allRows = append(allRows, sstRow)
}
// 计算分页
totalRows := int64(len(allRows))
offset := (page - 1) * pageSize
end := offset + pageSize
if end > int(totalRows) {
end = int(totalRows)
}
// 获取当前页数据
rows := make([]*sst.Row, 0, pageSize)
if offset < int(totalRows) {
rows = allRows[offset:end]
}
// 构造 TableDataResponse
const maxStringLength = 100
data := make([]map[string]any, 0, len(rows))
for _, row := range rows {
rowData := make(map[string]any)
rowData["_seq"] = row.Seq
rowData["_time"] = row.Time
for k, v := range row.Data {
field, err := tableSchema.GetField(k)
if err == nil && field.Type == srdb.FieldTypeString {
if str, ok := v.(string); ok {
runes := []rune(str)
if len(runes) > maxStringLength {
rowData[k] = string(runes[:maxStringLength]) + "..."
rowData[k+"_truncated"] = true
continue
}
}
}
rowData[k] = v
}
data = append(data, rowData)
}
tableData := TableDataResponse{
Data: data,
Page: int64(page),
PageSize: int64(pageSize),
TotalRows: totalRows,
TotalPages: (totalRows + int64(pageSize) - 1) / int64(pageSize),
}
html := renderDataViewHTML(tableName, schemaInfo, tableData)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(html))
}
// renderManifestHTML 渲染 Manifest 视图 HTML
func (ui *WebUI) renderManifestHTML(w http.ResponseWriter, r *http.Request, tableName string, table *srdb.Table) {
engine := table.GetEngine()
versionSet := engine.GetVersionSet()
version := versionSet.GetCurrent()
// 获取 Compaction Manager 和 Picker
compactionMgr := engine.GetCompactionManager()
picker := compactionMgr.GetPicker()
levels := make([]LevelInfo, 0)
for level := 0; level < 7; level++ {
files := version.GetLevel(level)
totalSize := int64(0)
fileInfos := make([]FileInfo, 0, len(files))
for _, f := range files {
totalSize += f.FileSize
fileInfos = append(fileInfos, FileInfo{
FileNumber: f.FileNumber,
Level: f.Level,
FileSize: f.FileSize,
MinKey: f.MinKey,
MaxKey: f.MaxKey,
RowCount: f.RowCount,
})
}
score := 0.0
if len(files) > 0 {
score = picker.GetLevelScore(version, level)
}
levels = append(levels, LevelInfo{
Level: level,
FileCount: len(files),
TotalSize: totalSize,
Score: score,
Files: fileInfos,
})
}
stats := compactionMgr.GetStats()
manifest := ManifestResponse{
Levels: levels,
NextFileNumber: versionSet.GetNextFileNumber(),
LastSequence: versionSet.GetLastSequence(),
CompactionStats: stats,
}
html := renderManifestViewHTML(tableName, manifest)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(html))
}