示例工程 25-vue-reactivity-streaming

25-vue-reactivity-streaming/app/src/App.vue

vue · 17 KB

<script setup lang="ts">
import {
  computed,
  isReactive,
  nextTick,
  onMounted,
  onUnmounted,
  ref,
  shallowRef,
} from "vue";
import { version } from "vue";
import type { StreamEvent } from "../shared/ipc";
import { runBenchmark, type BenchmarkResult } from "./lib/benchmark";
import { createStreamStore } from "./lib/stream-store";

const CAP = 2000;
const ROWS = 12;

type Tab = "live" | "bench";

const tab = ref<Tab>("live");
const deepEvents = ref<StreamEvent[]>([]);
const deepUpdates = ref(0);
const store = createStreamStore();
const running = ref(false);
const paused = ref(false);
const received = ref(0);
const emitted = ref(0);
const bench = ref<BenchmarkResult | null>(null);
const frozenDeep = shallowRef<StreamEvent[] | null>(null);
const frozenShallow = shallowRef<StreamEvent[] | null>(null);

const deepRows = computed(() =>
  (frozenDeep.value ?? deepEvents.value).slice(-ROWS),
);
const shallowRows = computed(() =>
  (frozenShallow.value ?? store.events.value).slice(-ROWS),
);
const deepStored = computed(() => deepEvents.value.length);
const shallowStored = computed(() => store.events.value.length);
const pausedCount = computed(() => store.pausedCount.value);

const deepDropped = computed(() =>
  Math.max(0, received.value - deepStored.value),
);

const piniaSnippet = `export const useStream = defineStore("stream", () => {
  const events = shallowRef<StreamEvent[]>([]);
  const received = shallowRef(0);
  function pushBatch(batch: StreamEvent[]) {
    received.value += batch.length;
    events.value = events.value.concat(
      batch.map((event) => markRaw({ ...event })),
    );
  }
  return { events, received, pushBatch };
});
// 组件里:const store = useStream();
// const { events, received } = storeToRefs(store);`;

let unsubscribe: (() => void) | undefined;

function formatTime(ts: number): string {
  const date = new Date(ts);
  const pad = (value: number): string => String(value).padStart(2, "0");
  return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}

function pushDeep(batch: StreamEvent[]): void {
  deepEvents.value.push(...batch);
  if (deepEvents.value.length > CAP) {
    deepEvents.value = deepEvents.value.slice(deepEvents.value.length - CAP);
  }
  deepUpdates.value += 1;
}

function reset(): void {
  deepEvents.value = [];
  deepUpdates.value = 0;
  store.reset();
  received.value = 0;
  emitted.value = 0;
  paused.value = false;
  frozenDeep.value = null;
  frozenShallow.value = null;
}

async function start(): Promise<void> {
  await window.api.stream.start();
  running.value = true;
}

async function stop(): Promise<void> {
  const stats = await window.api.stream.stop();
  running.value = false;
  emitted.value = stats.emitted;
}

function togglePause(): void {
  if (paused.value) {
    paused.value = false;
    frozenDeep.value = null;
    frozenShallow.value = null;
    store.setPaused(false);
    return;
  }
  frozenDeep.value = deepEvents.value.slice();
  frozenShallow.value = store.events.value.slice();
  store.setPaused(true);
  paused.value = true;
}

function runBench(): BenchmarkResult {
  const result = runBenchmark(120, 60);
  bench.value = result;
  return result;
}

function firstId(testid: string): string {
  return (
    document
      .querySelector<HTMLElement>(`[data-testid="${testid}"]`)
      ?.getAttribute("data-id") ?? ""
  );
}

function rowCount(testid: string): number {
  return document.querySelectorAll(`[data-testid="${testid}"]`).length;
}

onMounted(() => {
  unsubscribe = window.api.stream.onBatch((batch) => {
    received.value += batch.events.length;
    emitted.value = batch.emitted;
    pushDeep(batch.events);
    store.pushBatch(batch.events);
  });

  window.__pause = togglePause;
  window.__setTab = (next) => {
    tab.value = next;
  };
  window.__runBenchmark = () => {
    runBench();
    tab.value = "bench";
  };
  window.__prepareShots = async () => {
    reset();
    tab.value = "live";
    await start();
  };
  window.__smoke = async () => {
    const wait = (ms: number) =>
      new Promise((resolve) => setTimeout(resolve, ms));

    await window.api.stream.stop();
    reset();
    await wait(120);
    await start();
    await wait(700);

    const deepUpdatesBefore = deepUpdates.value;
    const shallowFlushesBefore = store.flushes.value;

    togglePause();
    await nextTick();
    const deepIdAtPause = firstId("deep-row");
    const shallowIdAtPause = firstId("shallow-row");
    await wait(500);
    const frozenStable =
      firstId("deep-row") === deepIdAtPause &&
      firstId("shallow-row") === shallowIdAtPause;
    const pausedBuffered = store.pausedCount.value;

    togglePause();
    await nextTick();
    await wait(320);
    const resumedChanged =
      firstId("deep-row") !== deepIdAtPause ||
      firstId("shallow-row") !== shallowIdAtPause;
    const resumedRowCount = rowCount("shallow-row");

    const stats = await window.api.stream.stop();
    await wait(250);
    const receivedCount = received.value;

    const deepProxy =
      deepEvents.value.length > 0 && isReactive(deepEvents.value[0]);
    const shallowProxy =
      store.events.value.length > 0 && isReactive(store.events.value[0]);

    const result = runBench();
    tab.value = "bench";
    await nextTick();
    const benchVisible =
      document.querySelector('[data-testid="bench-table"]') !== null;
    tab.value = "live";
    await nextTick();

    return {
      vueVersion: version,
      received: receivedCount,
      emitted: stats.emitted,
      deepUpdates: deepUpdatesBefore,
      shallowFlushes: shallowFlushesBefore,
      pausedBuffered,
      frozenStable,
      resumedChanged,
      deepProxy,
      shallowProxy,
      benchDeepMs: result.deepMs,
      benchShallowMs: result.shallowMs,
      benchRounds: result.rounds,
      benchVisible,
      resumedRowCount,
    };
  };
});

onUnmounted(() => {
  unsubscribe?.();
});
</script>

<template>
  <div class="app">
    <header class="header">
      <div class="brand">
        <h1>Vue 响应式调优实验台</h1>
        <span class="pill">Vue {{ version }}</span>
        <span
          v-if="tab === 'live'"
          class="pill"
          :class="running ? 'ok' : ''"
          data-testid="running-badge"
        >
          {{ running ? "运行中" : "已停止" }}
        </span>
        <span v-if="tab === 'live'" class="muted" data-testid="paused-badge">
          <template v-if="paused">
            已暂停 · 新增
            <span data-testid="paused-count">{{ pausedCount }}</span>
            条
          </template>
          <template v-else>实时跟随</template>
        </span>
      </div>
      <nav class="tabs">
        <button
          class="tab"
          :class="tab === 'live' ? 'active' : ''"
          data-testid="tab-live"
          @click="tab = 'live'"
        >
          实时
        </button>
        <button
          class="tab"
          :class="tab === 'bench' ? 'active' : ''"
          data-testid="tab-bench"
          @click="tab = 'bench'"
        >
          基准
        </button>
      </nav>
    </header>

    <template v-if="tab === 'live'">
      <div class="stats">
        <div class="card stat">
          <div class="muted">接收</div>
          <div class="value" data-testid="received">{{ received }}</div>
        </div>
        <div class="card stat">
          <div class="muted">深响应式更新</div>
          <div class="value" data-testid="deep-updates">{{ deepUpdates }}</div>
        </div>
        <div class="card stat">
          <div class="muted">shallow 快照</div>
          <div class="value" data-testid="shallow-flushes">
            {{ store.flushes.value }}
          </div>
        </div>
        <div class="card stat">
          <div class="muted">暂停新增</div>
          <div class="value" data-testid="paused-count-stat">
            {{ pausedCount }}
          </div>
        </div>
        <div class="card stat">
          <div class="muted">主进程已发</div>
          <div class="value" data-testid="emitted">{{ emitted }}</div>
        </div>
      </div>

      <div class="controls card pad">
        <button
          class="btn primary"
          data-testid="start"
          :disabled="running"
          @click="start"
        >
          开始
        </button>
        <button
          class="btn"
          data-testid="stop"
          :disabled="!running"
          @click="stop"
        >
          停止
        </button>
        <button class="btn" data-testid="pause-toggle" @click="togglePause">
          {{ paused ? "继续" : "暂停" }}
        </button>
        <button class="btn" data-testid="clear" @click="reset">清空</button>
        <button class="btn" data-testid="run-bench" @click="runBench">
          运行基准
        </button>
        <span class="muted small">
          每 50ms 推送 8 条;shallow 端每 150ms 合并发布一次。
        </span>
      </div>

      <div class="lanes">
        <section class="card lane">
          <div class="lane-head">
            <div>
              <h2>ref([]) 深响应式</h2>
              <p class="muted small">
                每批都改数组;读取时逐项代理,computed 随之失效。
              </p>
            </div>
            <span class="tag warn">每批更新</span>
          </div>
          <div class="rows">
            <div
              v-for="event in deepRows"
              :key="event.id"
              class="row"
              data-testid="deep-row"
              :data-id="event.id"
            >
              <span class="muted">{{ formatTime(event.ts) }}</span>
              <span :class="`src-${event.source}`">{{ event.source }}</span>
              <span class="text">{{ event.text }}</span>
            </div>
          </div>
          <div class="lane-foot muted">
            更新 {{ deepUpdates }} 次 · 保留 {{ deepStored }} · 丢弃
            {{ deepDropped }} · 行 {{ Math.min(ROWS, deepRows.length) }}
          </div>
        </section>

        <section class="card lane">
          <div class="lane-head">
            <div>
              <h2>shallowRef + markRaw</h2>
              <p class="muted small">
                原始数组累积;每 150ms 发布快照,只让列表引用变一次。
              </p>
            </div>
            <span class="tag ok">合并发布</span>
          </div>
          <div class="rows">
            <div
              v-for="event in shallowRows"
              :key="event.id"
              class="row"
              data-testid="shallow-row"
              :data-id="event.id"
            >
              <span class="muted">{{ formatTime(event.ts) }}</span>
              <span :class="`src-${event.source}`">{{ event.source }}</span>
              <span class="text">{{ event.text }}</span>
            </div>
          </div>
          <div class="lane-foot muted">
            快照 {{ store.flushes.value }} 次 · 保留 {{ shallowStored }} ·
            待发布 {{ store.pending.value }} · 丢弃 {{ store.dropped.value }} ·
            行
            {{ Math.min(ROWS, shallowRows.length) }}
          </div>
        </section>
      </div>

      <p class="hint muted">
        两栏吃同一批事件:左边每次批次都触发渲染,右边把批次合并成快照;暂停只冻结视图,计数继续。
      </p>
    </template>

    <section v-else class="bench">
      <div class="card pad">
        <div class="bench-head">
          <div>
            <h2>深响应式 vs shallowRef</h2>
            <p class="muted small">
              120 轮 × 60 条 = 7,200
              条事件;两种方式都读完求和,保证代理被触发。
            </p>
          </div>
          <button
            class="btn primary"
            data-testid="run-bench-again"
            @click="runBench"
          >
            再跑一次
          </button>
        </div>

        <table v-if="bench" class="bench-table" data-testid="bench-table">
          <thead>
            <tr>
              <th>实现</th>
              <th>耗时</th>
              <th>事件数</th>
              <th>校验和</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>ref([]) 深响应式</td>
              <td>{{ bench.deepMs }} ms</td>
              <td>{{ bench.rounds * bench.size }}</td>
              <td>{{ bench.deepSum }}</td>
            </tr>
            <tr>
              <td>shallowRef</td>
              <td>{{ bench.shallowMs }} ms</td>
              <td>{{ bench.rounds * bench.size }}</td>
              <td>{{ bench.shallowSum }}</td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted empty">尚未运行基准</p>

        <p v-if="bench" class="speedup" data-testid="bench-speedup">
          约 {{ bench.speedup }}× 差距({{ bench.rounds }} 轮 / 每轮
          {{ bench.size }} 条)
        </p>
      </div>

      <div class="card pad">
        <h3>为什么快</h3>
        <ul class="list">
          <li>数据只读:事件进入后不再修改,不需要深层代理。</li>
          <li>发布合并:批次先进普通数组,150ms 才替换一次引用。</li>
          <li>边界清晰:IPC 传普通对象,渲染层自己决定响应式深度。</li>
        </ul>
      </div>

      <div class="card pad">
        <h3>Pinia 对照(本章不引入依赖)</h3>
        <p class="muted small">
          单窗口、单 store 时,数十行组合式 store 足够;需要跨面板共享、devtools
          与插件时再上 Pinia。下面的 setup store 与本章写法一一对应。
        </p>
        <pre class="code">{{ piniaSnippet }}</pre>
      </div>
    </section>
  </div>
</template>

<style scoped>
.app {
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 20px;
  border-bottom: 1px solid var(--border);
}

.brand {
  display: flex;
  align-items: center;
  gap: 10px;
}

.brand h1 {
  margin: 0;
  font-size: 15px;
}

.pill {
  padding: 2px 8px;
  border: 1px solid var(--border);
  border-radius: 999px;
  font-size: 11px;
  color: var(--muted);
}

.pill.ok {
  border-color: #bbf7d0;
  background: #dcfce7;
  color: #166534;
}

.tabs {
  display: flex;
  gap: 4px;
  padding: 3px;
  border: 1px solid var(--border);
  border-radius: 999px;
}

.tab {
  padding: 4px 12px;
  border: 0;
  border-radius: 999px;
  background: transparent;
  font-size: 12px;
  color: var(--muted);
}

.tab.active {
  background: var(--primary);
  color: var(--primary-fg);
}

.stats {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 12px;
  padding: 12px 20px;
}

.stat {
  padding: 8px 12px;
}

.value {
  font-size: 20px;
  font-weight: 600;
}

.controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 20px;
}

.lanes {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
  padding: 16px 20px 0;
}

.lane {
  padding: 12px;
  min-width: 0;
}

.lane-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 8px;
}

.lane-head h2 {
  margin: 0;
  font-size: 13px;
}

.tag {
  padding: 2px 8px;
  border-radius: 999px;
  font-size: 10px;
  white-space: nowrap;
}

.tag.warn {
  background: #fef3c7;
  color: #92400e;
}

.tag.ok {
  background: #dcfce7;
  color: #166534;
}

.rows {
  margin-top: 8px;
  border: 1px solid var(--border);
  border-radius: 6px;
  overflow: hidden;
}

.row {
  display: grid;
  grid-template-columns: 64px 56px minmax(0, 1fr);
  align-items: center;
  gap: 8px;
  height: 26px;
  padding: 0 8px;
  border-bottom: 1px solid color-mix(in srgb, var(--border) 60%, transparent);
  font-family: var(--font-mono);
  font-size: 10.5px;
}

.row:last-child {
  border-bottom: 0;
}

.text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.src-build {
  color: #7c3aed;
}

.src-network {
  color: #0f766e;
}

.src-tools {
  color: #b45309;
}

.lane-foot {
  margin-top: 8px;
  font-size: 11px;
}

.hint {
  margin: 10px 20px 20px;
  font-size: 11px;
}

.bench {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px 20px 24px;
}

.bench-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.bench h2,
.bench h3 {
  margin: 0 0 8px;
  font-size: 14px;
}

.bench-table {
  width: 100%;
  margin-top: 12px;
  border-collapse: collapse;
  font-size: 12px;
}

.bench-table th,
.bench-table td {
  padding: 8px;
  border-bottom: 1px solid var(--border);
  text-align: left;
}

.bench-table th {
  color: var(--muted);
  font-weight: 500;
}

.speedup {
  margin: 12px 0 0;
  color: var(--primary);
  font-size: 12px;
}

.list {
  margin: 8px 0 0;
  padding-left: 20px;
  color: var(--muted);
  font-size: 12px;
}

.list li {
  margin: 4px 0;
}

.code {
  margin: 8px 0 0;
  overflow: auto;
  font-family: var(--font-mono);
  font-size: 11px;
  line-height: 1.7;
}

.empty {
  margin: 12px 0 0;
}

.small {
  font-size: 11px;
}
</style>