Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

15.0 KB
Raw Blame
<script setup lang="ts">
import { computed, defineComponent, h, nextTick, onBeforeUnmount, ref, shallowRef, watch, type VNodeChild } from "vue";
import { DynamicScroller, DynamicScrollerItem } from "vue-virtual-scroller";
import { ChevronDown, ChevronRight } from "@lucide/vue";
import { createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeClosingNode, isJsonTreeContainer, isJsonTreeInitiallyExpanded, jsonTreeContainerKind, jsonTreeContainerSummary, type JsonTreeNode } from "@/lib/common/jsonTree";
import { isLosslessJsonNumber } from "@/lib/common/safeJsonFormat";
import { jsonTreeKeyText, jsonTreeScalarText, type JsonTreeSearchMatch } from "@/lib/common/jsonTreeSearch";
import { renderTextContentMatchesHtml } from "@/lib/common/textContentSearch";

defineOptions({ name: "JsonTree" });

const props = withDefaults(
  defineProps<{
    value: unknown;
    searchMatches?: JsonTreeSearchMatch[];
    activeSearchIndex?: number;
    wordWrap?: boolean;
    /** Optional Shiki-style inline highlighter retained for Redis value views. */
    highlightJson?: (json: string) => string;
    /** Number of expanded container levels, with the root counted as level one. */
    initialExpandedDepth?: number;
    /** Render only viewport rows for large, scrollable JSON responses. */
    virtualized?: boolean;
  }>(),
  {
    wordWrap: true,
    highlightJson: undefined,
    initialExpandedDepth: Number.POSITIVE_INFINITY,
    virtualized: false,
  },
);

type ExpansionMode = "default" | "all" | "none";
type DynamicScrollerHandle = {
  forceUpdate: (clear?: boolean) => void;
  scrollToItem?: (index: number) => void;
  scrollToPosition?: (position: number) => void;
};

const treeRoot = ref<HTMLElement>();
const expansionMode = ref<ExpansionMode>("default");
const expansionOverrides = shallowRef(new Map<string, boolean>());
const virtualScroller = ref<DynamicScrollerHandle>();

const rootNode = computed(() => createJsonTreeRoot(props.value));

function resetExpansion() {
  expansionMode.value = "default";
  expansionOverrides.value = new Map();
}

function expandAll() {
  expansionMode.value = "all";
  expansionOverrides.value = new Map();
}

function collapseAll() {
  expansionMode.value = "none";
  expansionOverrides.value = new Map();
}

function isNodeExpanded(node: JsonTreeNode): boolean {
  const override = expansionOverrides.value.get(node.path);
  if (override !== undefined) return override;

  if (expansionMode.value === "all") return true;
  if (expansionMode.value === "none") return false;
  return isJsonTreeInitiallyExpanded(node.depth, props.initialExpandedDepth);
}

function setNodeExpanded(path: string, expanded: boolean) {
  const next = new Map(expansionOverrides.value);
  next.set(path, expanded);
  expansionOverrides.value = next;
}

function toggleNode(node: JsonTreeNode) {
  setNodeExpanded(node.path, !isNodeExpanded(node));
}

function scalarClass(value: unknown): string {
  if (isLosslessJsonNumber(value) || typeof value === "number") return "json-tree-number";
  if (typeof value === "string") return "json-tree-string";
  if (typeof value === "boolean") return "json-tree-boolean";
  if (value === null) return "json-tree-null";
  return "json-tree-string";
}

const scalarText = jsonTreeScalarText;

const searchParts = computed(() => {
  const parts = new Map<string, { matches: JsonTreeSearchMatch[]; active: number }>();
  for (const [index, match] of (props.searchMatches ?? []).entries()) {
    const key = JSON.stringify([match.path, match.part]);
    const entry = parts.get(key) ?? { matches: [], active: -1 };
    if (index === props.activeSearchIndex) entry.active = entry.matches.length;
    entry.matches.push(match);
    parts.set(key, entry);
  }
  return parts;
});

function highlightedJson(value: string, node: JsonTreeNode, part: "key" | "value"): string {
  const entry = searchParts.value.get(JSON.stringify([node.path, part]));
  if (entry) return renderTextContentMatchesHtml(value, entry.matches, { activeMatchIndex: entry.active });
  return props.highlightJson?.(value) ?? escapeHtml(value);
}

let searchNavigationRevision = 0;
const pendingSearchFrames = new Map<number, () => void>();
onBeforeUnmount(() => {
  searchNavigationRevision++;
  for (const [frame, resolve] of pendingSearchFrames) {
    cancelAnimationFrame(frame);
    resolve();
  }
  pendingSearchFrames.clear();
});

function nextSearchFrame(): Promise<void> {
  return new Promise((resolve) => {
    const frame = requestAnimationFrame(() => {
      pendingSearchFrames.delete(frame);
      resolve();
    });
    pendingSearchFrames.set(frame, resolve);
  });
}

async function revealSearchMatch() {
  const revision = ++searchNavigationRevision;
  const match = props.searchMatches?.[props.activeSearchIndex ?? -1];
  if (!match) return;
  const overrides = new Map(expansionOverrides.value);
  overrides.set("", true);
  const segments = match.path.split("/");
  for (let i = 1; i < segments.length; i++) overrides.set(segments.slice(0, i).join("/"), true);
  expansionOverrides.value = overrides;
  await nextTick();
  if (revision !== searchNavigationRevision) return;
  const index = visibleNodes.value.findIndex((node) => node.path === match.path);
  if (props.virtualized && index >= 0) virtualScroller.value?.scrollToItem?.(index);
  // Virtual rows are published on animation frames, after scroll events and size
  // measurements. A Vue tick alone can still observe the old recycled rows.
  let visibleFrames = 0;
  for (let attempt = 0; attempt < 20; attempt++) {
    await nextSearchFrame();
    await nextTick();
    if (revision !== searchNavigationRevision) return;
    const target = treeRoot.value?.querySelector<HTMLElement>('[data-document-search-active="true"]');
    if (target && target.closest<HTMLElement>("[data-json-path]")?.dataset.jsonPath === match.path && target.getClientRects().length) {
      target.scrollIntoView({ block: "nearest", inline: "nearest" });
      // Correct again after dynamic row measurement has had time to settle.
      if (++visibleFrames >= 3) return;
    } else {
      visibleFrames = 0;
      if (props.virtualized && index >= 0) virtualScroller.value?.scrollToItem?.(index);
    }
  }
}

function escapeHtml(value: string): string {
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function nodeAccessibleLabel(node: JsonTreeNode): string {
  // JSON Pointer paths are language-neutral and uniquely identify each toggle.
  return node.path || "$";
}

function highlightedJsonSpan(className: string, text: string, node: JsonTreeNode, part: "key" | "value"): VNodeChild {
  return h("span", { class: className, innerHTML: highlightedJson(text, node, part) });
}

function renderJsonNode(node: JsonTreeNode): VNodeChild {
  const containerValue = isJsonTreeContainer(node.value) ? node.value : undefined;
  const expanded = containerValue !== undefined && isNodeExpanded(node);
  const indent = `${node.depth * 16}px`;
  const rowChildren: VNodeChild[] = [];

  if (containerValue !== undefined) {
    const accessibleLabel = nodeAccessibleLabel(node);
    rowChildren.push(
      h(
        "button",
        {
          type: "button",
          class: "json-tree-toggle",
          "aria-expanded": expanded,
          "aria-label": accessibleLabel,
          title: accessibleLabel,
          onClick: () => toggleNode(node),
        },
        [expanded ? h(ChevronDown, { class: "h-3.5 w-3.5", "aria-hidden": "true" }) : h(ChevronRight, { class: "h-3.5 w-3.5", "aria-hidden": "true" })],
      ),
    );
  } else {
    rowChildren.push(h("span", { class: "json-tree-spacer", "aria-hidden": "true" }));
  }

  if (node.parentKind !== "root") {
    rowChildren.push(highlightedJsonSpan(node.parentKind === "array" ? "json-tree-index" : "json-tree-key", jsonTreeKeyText(node), node, "key"), h("span", { class: "json-tree-punctuation" }, ":"));
  }

  if (containerValue !== undefined) {
    const kind = jsonTreeContainerKind(containerValue);
    rowChildren.push(h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "[" : "{"));
    if (!expanded) {
      rowChildren.push(h("span", { class: "json-tree-summary" }, jsonTreeContainerSummary(containerValue)), h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "]" : "}"));
    }
  } else {
    rowChildren.push(highlightedJsonSpan(scalarClass(node.value), scalarText(node.value), node, "value"));
  }

  const children =
    containerValue !== undefined && expanded
      ? h("div", { class: "json-tree-children" }, [
          ...getJsonTreeChildren(node).map(renderJsonNode),
          h("div", { class: "json-tree-row", style: { paddingInlineStart: indent } }, [h("span", { class: `json-tree-bracket json-tree-closing is-${jsonTreeContainerKind(containerValue)}` }, jsonTreeContainerKind(containerValue) === "array" ? "]" : "}")]),
        ])
      : null;

  return h("div", { key: node.path, class: "json-tree-node", "data-json-path": node.path }, [h("div", { class: "json-tree-row", style: { paddingInlineStart: indent } }, rowChildren), children]);
}

const JsonTreeRoot = defineComponent({
  name: "JsonTreeRoot",
  setup() {
    return () => renderJsonNode(rootNode.value);
  },
});

const visibleNodes = computed(() => getVisibleJsonTreeNodes(rootNode.value, isNodeExpanded, props.virtualized));

function refresh(resetScroll = false) {
  if (!props.virtualized) return;
  void nextTick(() => {
    virtualScroller.value?.forceUpdate(true);
    if (resetScroll) virtualScroller.value?.scrollToPosition?.(0);
  });
}

watch([() => props.value, () => props.initialExpandedDepth], () => {
  resetExpansion();
  refresh(true);
});

watch([() => props.searchMatches, () => props.activeSearchIndex], revealSearchMatch, { flush: "post", immediate: true });

defineExpose({ expandAll, collapseAll, resetExpansion, refresh, revealSearchMatch });
</script>

<template>
  <div ref="treeRoot" class="json-tree" :class="{ 'is-nowrap': !wordWrap, 'is-virtualized': virtualized }">
    <!-- Virtual rows keep a fully expanded response responsive even when it has thousands of nodes. -->
    <DynamicScroller v-if="virtualized" ref="virtualScroller" :items="visibleNodes" :min-item-size="24" :buffer="600" key-field="path" class="json-tree-scroller">
      <template #default="{ item: node, active, index }">
        <DynamicScrollerItem :item="node" :active="active" :size-dependencies="[wordWrap, node.path, node.label, scalarText(node.value), isNodeExpanded(node), searchMatches, activeSearchIndex]" :data-index="index">
          <div class="json-tree-node" :data-json-path="node.path">
            <div class="json-tree-row" :style="{ paddingInlineStart: `${node.depth * 16}px` }">
              <template v-if="isJsonTreeClosingNode(node)">
                <span class="json-tree-bracket json-tree-closing" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span>
              </template>
              <template v-else>
                <button v-if="isJsonTreeContainer(node.value)" type="button" class="json-tree-toggle" :aria-expanded="isNodeExpanded(node)" :aria-label="nodeAccessibleLabel(node)" :title="nodeAccessibleLabel(node)" @click="toggleNode(node)">
                  <ChevronDown v-if="isNodeExpanded(node)" class="h-3.5 w-3.5" aria-hidden="true" />
                  <ChevronRight v-else class="h-3.5 w-3.5" aria-hidden="true" />
                </button>
                <span v-else class="json-tree-spacer" aria-hidden="true" />

                <template v-if="node.parentKind !== 'root'">
                  <span :class="node.parentKind === 'array' ? 'json-tree-index' : 'json-tree-key'" v-html="highlightedJson(jsonTreeKeyText(node), node, 'key')" />
                  <span class="json-tree-punctuation">:</span>
                </template>

                <template v-if="isJsonTreeContainer(node.value)">
                  <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "[" : "{" }}</span>
                  <template v-if="!isNodeExpanded(node)">
                    <span class="json-tree-summary">{{ jsonTreeContainerSummary(node.value) }}</span>
                    <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span>
                  </template>
                </template>
                <span v-else :class="scalarClass(node.value)" v-html="highlightedJson(scalarText(node.value), node, 'value')" />
              </template>
            </div>
          </div>
        </DynamicScrollerItem>
      </template>
    </DynamicScroller>
    <JsonTreeRoot v-else />
  </div>
</template>

<style>
.json-tree {
  --json-tree-key: var(--info);
  --json-tree-string: var(--success);
  --json-tree-number: var(--warning);
  --json-tree-boolean: color-mix(in srgb, var(--primary) 70%, var(--info));
  --json-tree-null: var(--muted-foreground);

  color: var(--foreground);
  white-space: pre-wrap;
  overflow-wrap: anywhere;
}

.json-tree.is-virtualized {
  height: 100%;
  min-height: 0;
}

.json-tree-scroller {
  height: 100%;
  min-height: 0;
  overflow: auto;
}

.json-tree.is-nowrap {
  white-space: pre;
  overflow-wrap: normal;
}

.json-tree-row {
  display: flex;
  min-height: 24px;
  align-items: flex-start;
  gap: 4px;
  padding-block: 2px;
  /* Fixed line box so the hover background wraps the glyphs symmetrically. */
  line-height: 20px;
  border-radius: var(--dbx-radius-fixed-4);
}

.json-tree-row:hover {
  background: color-mix(in srgb, var(--muted) 50%, transparent);
}

.json-tree-toggle {
  align-self: center;
  display: inline-flex;
  height: 18px;
  width: 18px;
  flex: 0 0 auto;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
  color: var(--muted-foreground);
}

.json-tree-toggle:hover {
  background: var(--accent);
  color: var(--foreground);
}

.json-tree-toggle:focus-visible {
  outline: 2px solid var(--ring);
  outline-offset: 1px;
}

.json-tree-spacer {
  width: 18px;
  flex: 0 0 auto;
}

/* Closing brackets sit in the toggle's slot so they line up with the chevron above. */
.json-tree-closing {
  display: inline-flex;
  width: 18px;
  flex: 0 0 auto;
  justify-content: center;
}

.json-tree-key {
  color: var(--json-tree-key);
}

.json-tree-string {
  color: var(--json-tree-string);
}

.json-tree-number {
  color: var(--json-tree-number);
}

.json-tree-boolean {
  color: var(--json-tree-boolean);
}

.json-tree-null {
  color: var(--json-tree-null);
  font-style: italic;
}

.json-tree-index,
.json-tree-punctuation,
.json-tree-summary {
  color: var(--muted-foreground);
}

.json-tree-bracket {
  color: var(--foreground);
  font-weight: 650;
}

.json-tree-key,
.json-tree-index,
.json-tree-punctuation,
.json-tree-bracket {
  flex: 0 0 auto;
}

.json-tree-string,
.json-tree-number,
.json-tree-boolean,
.json-tree-null {
  flex: 1 1 auto;
  min-width: 0;
}

.json-tree-summary {
  flex: 0 1 auto;
  min-width: 0;
}

.dark .json-tree {
  --json-tree-key: #93c5fd;
  --json-tree-string: #86efac;
  --json-tree-number: #fbbf24;
  --json-tree-boolean: #c4b5fd;
  --json-tree-null: #94a3b8;
}
</style>