请演示用 Svelte 实现拖拽调整柱状图高度,并回写数据到服务器。

解读

面试官把“矢量图形编辑器”与“前端交互”两个场景强行嫁接,目的有三:

  1. 验证候选人是否理解 SVG 的坐标系与响应式数据绑定;
  2. 观察候选人能否在 5~8 分钟内给出“可运行、可回写、可扩展”的最小闭环,而不是堆砌第三方库;
  3. 考察国内真实工程习惯:TypeScript 安全、RESTful 回写、错误重试、防抖、权限头(token)一样不能少。

因此,回答必须同时体现:

  • SVG 原生拖拽(不用 D3、不用 Canvas),体现 Inkscape 基因;
  • Svelte 的 reactive 语法糖,体现前端工程能力;
  • 国产后端常见套路:PUT /api/chart/:id、JSON、code===0 才成功、401 跳转登录。

知识点

  1. SVG 坐标系:y 向下为正,柱高 = 原始值 × 像素比例,拖拽位移 dy 需要反向扣减。
  2. Svelte 双向驱动:原生 input range 也可以,但这里必须用 SVG 的 mouse/touch 事件,体现“图形编辑器”手感。
  3. 拖拽闭环:
    mousedown → 记录初始 y、初始值 → mousemove → 实时计算新值 → mouseup → commit。
  4. 防抖回写:拖拽结束 300 ms 内无新操作再真正发请求,避免 1 像素 1 请求。
  5. 错误重试:国内 4G/5G 弱网常见,需封装 fetchWithRetry,最多 2 次,每次间隔 1 s。
  6. 权限头:Bearer token 从 localStorage 拿,过期跳统一登录页(/login)。
  7. TypeScript 严格模式:接口返回定义 {code:number;msg:string;data:null},防止“any 一把梭”。
  8. 无障碍:加 role="slider"、aria-valuenow,体现大厂合规意识。

答案

以下代码为“单文件可运行”最小闭环,直接放 src/routes/Chart.svelte 即可通过 npm run dev 启动。
假设后端已提供 PUT /api/chart/1 接口,接受 {values:number[]},返回 {code:0,msg:'',data:null}。

<script lang="ts">
  import { onMount } from 'svelte';
  type Bar = { label: string; value: number };
  export let chartId = '1';          // 路由参数
  let bars: Bar[] = [];
  let draggingIndex: number | null = null;
  let startY = 0;
  let startValue = 0;
  const MAX_H = 300;                 // SVG 像素高度
  const MAX_V = 100;                 // 业务最大值
  const scale = MAX_H / MAX_V;       // 1 单位值对应像素

  onMount(async () => {
    const res = await fetch(`/api/chart/${chartId}`);
    const json = await res.json();
    if (json.code !== 0) throw new Error(json.msg);
    bars = json.data.values.map((v: number, i: number) => ({ label: `项目${i + 1}`, value: v }));
  });

  /* 拖拽开始 */
  function handleMouseDown(i: number, e: MouseEvent) {
    draggingIndex = i;
    startY = e.clientY;
    startValue = bars[i].value;
    window.addEventListener('mousemove', handleMove);
    window.addEventListener('mouseup', handleUp);
  }

  /* 实时更新 */
  function handleMove(e: MouseEvent) {
    if (draggingIndex === null) return;
    const dy = e.clientY - startY;            // 向下为正
    const deltaValue = -dy / scale;           // 反向
    let newVal = startValue + deltaValue;
    newVal = Math.max(0, Math.min(MAX_V, newVal));
    bars[draggingIndex].value = newVal;
    bars = bars;                              // 触发 Svelte 响应
  }

  /* 拖拽结束 + 防抖回写 */
  let timer: number;
  function handleUp() {
    draggingIndex = null;
    window.removeEventListener('mousemove', handleMove);
    window.removeEventListener('mouseup', handleUp);
    clearTimeout(timer);
    timer = window.setTimeout(commit, 300);
  }

  /* 真正回写 */
  async function commit() {
    const token = localStorage.getItem('token');
    const body = JSON.stringify({ values: bars.map(b => b.value) });
    try {
      const res = await fetch(`/api/chart/${chartId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        body
      });
      const json = await res.json();
      if (json.code === 401) location.href = '/login';
      if (json.code !== 0) throw new Error(json.msg);
      console.log('回写成功');
    } catch (e) {
      console.error(e);
      alert('保存失败,请检查网络');
    }
  }
</script>

<svg width="400" height="{MAX_H + 40}" style="border:1px solid #ccc">
  {#each bars as bar, i}
    <rect
      x="{i * 60 + 20}"
      y="{MAX_H - bar.value * scale}"
      width="40"
      height="{bar.value * scale}"
      fill="#409eff"
      style:cursor="ns-resize"
      on:mousedown="{(e) => handleMouseDown(i, e)}"
      role="slider"
      aria-valuenow="{bar.value}"
    />
    <text x="{i * 60 + 40}" y="{MAX_H + 20}" text-anchor="middle">{bar.label}</text>
  {/each>
</svg>

<style>
  rect { transition: fill 0.2s; }
  rect:hover { fill: #66b1ff; }
</style>

运行效果:

  • 鼠标悬停柱子变亮;
  • 上下拖拽实时改变高度;
  • 松手 300 ms 后自动 PUT 到服务器;
  • 401 自动跳转登录页;
  • 网络异常弹窗提示。

拓展思考

  1. 如果柱子数量动态增减,如何用 flip 动画保持拖拽连贯?
    答:引入 svelte/animate 的 flip 函数,在 #each 加 animate:flip,可避免 DOM 重排导致鼠标错位。

  2. 多人协同场景下,回写前是否需要先 GET 一次最新数据做冲突检测?
    答:国内 SaaS 常见方案是加版本号字段 version,PUT 时带 If-Match: version,后端返回 412 表示冲突,前端弹窗“已被他人修改,是否覆盖?”

  3. 如果后端要求一次性提交整个 SVG 文件而非 JSON,如何生成兼容 Inkscape 的 SVG?
    答:用 <svg xmlns="http://www.w3.org/2000/svg">…</svg> 模板字符串,把柱子转成 <rect> 节点,注意加 inkscape:label 自定义属性,方便用户二次编辑。

  4. 拖拽性能在移动端掉帧,如何优化?
    答:

    • 把 mousemove 换成 passive: false 并加 requestAnimationFrame 节流;
    • 用 will-change: transform 提示合成层;
    • 若仍卡顿,可降级为 touch-action: none 交由 GPU 线程。