diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index 6a6765d3..11e31498 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -61,3 +61,11 @@ jobs: - name: Test run: flutter test + + - name: Set up Node for feedback checks + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Test feedback recovery + run: node --test web/feedback/test/*.test.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 43954e98..05285452 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -122,6 +122,17 @@ jobs: flutter analyze --no-pub flutter test + + - name: Set up Node for feedback checks + if: steps.plan.outputs.skip == 'false' + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Test feedback recovery + if: steps.plan.outputs.skip == 'false' + run: node --test web/feedback/test/*.test.mjs + tag: name: Tag the release needs: plan diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 6de9c254..9cb5f605 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -23,6 +23,7 @@ import '../widgets/adaptive_switch.dart'; import '../widgets/app_shell/app_shell_metrics.dart'; import '../widgets/blurred_app_bar.dart'; import '../widgets/desktop_popup.dart'; +import '../widgets/feedback_entry.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/update_dialogs.dart'; import 'debug_log_page.dart'; @@ -329,6 +330,7 @@ class _SettingsPageState extends State { ), const Divider(), + const FeedbackEntry(), ListTile( leading: const Icon(Icons.privacy_tip_outlined), title: const Text('隐私政策与使用支持'), diff --git a/lib/widgets/feedback_entry.dart b/lib/widgets/feedback_entry.dart new file mode 100644 index 00000000..dfd8e015 --- /dev/null +++ b/lib/widgets/feedback_entry.dart @@ -0,0 +1,59 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'adaptive_alert_dialog.dart'; + +/// Opens the public feedback page and provides a usable fallback on failure. +class FeedbackEntry extends StatefulWidget { + const FeedbackEntry({super.key, this.launcher}); + + final Future Function(Uri)? launcher; + + @override + State createState() => _FeedbackEntryState(); +} + +class _FeedbackEntryState extends State { + static final _url = Uri.parse('https://techpie-feedback.dzhes.app'); + bool _opening = false; + + Future _open() async { + if (_opening) return; + setState(() => _opening = true); + try { + var opened = false; + try { + opened = await (widget.launcher?.call(_url) ?? + launchUrl(_url, mode: LaunchMode.externalApplication)); + } catch (_) { + // Both a false result and a platform failure need the same recovery. + } + if (opened || !mounted) return; + final copy = await showAdaptiveAlertDialog( + context: context, + title: '无法打开反馈页面', + message: '请复制链接后在浏览器中打开。\n$_url', + actions: const [ + AdaptiveAlertAction(label: '关闭', value: false), + AdaptiveAlertAction(label: '复制链接', value: true, isDefault: true), + ], + ); + if (copy == true) await Clipboard.setData(ClipboardData(text: '$_url')); + } finally { + if (mounted) setState(() => _opening = false); + } + } + + @override + Widget build(BuildContext context) => ListTile( + leading: const Icon(Icons.feedback_outlined), + title: const Text('用户反馈与工单'), + subtitle: const Text('提交问题、建议,或查看工单进度'), + trailing: const Icon(Icons.open_in_new), + enabled: !_opening, + onTap: () => unawaited(_open()), + ); +} diff --git a/test/feedback_entry_test.dart b/test/feedback_entry_test.dart new file mode 100644 index 00000000..19d225de --- /dev/null +++ b/test/feedback_entry_test.dart @@ -0,0 +1,88 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/widgets/feedback_entry.dart'; + +void main() { + testWidgets('successful launch preserves feedback entry without a dialog', + (tester) async { + Uri? opened; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (url) async { + opened = url; + return true; + }, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pumpAndSettle(); + expect(opened.toString(), 'https://techpie-feedback.dzhes.app'); + expect(find.text('无法打开反馈页面'), findsNothing); + }); + + for (final throws in [false, true]) { + testWidgets('launch ${throws ? 'exception' : 'false'} offers copyable link', + (tester) async { + String? copied; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (_) async { + if (throws) throw PlatformException(code: 'unavailable'); + return false; + }, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pumpAndSettle(); + expect(find.text('无法打开反馈页面'), findsOneWidget); + await tester.tap(find.text('复制链接')); + await tester.pumpAndSettle(); + expect(copied, 'https://techpie-feedback.dzhes.app'); + }); + } + + testWidgets('late launch failure after navigation does not display a dialog', + (tester) async { + final pending = Completer(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FeedbackEntry( + launcher: (_) => pending.future, + ), + ), + ), + ); + await tester.tap(find.text('用户反馈与工单')); + await tester.pump(); + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + pending.complete(false); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('无法打开反馈页面'), findsNothing); + }); +} diff --git a/web/feedback/.gitignore b/web/feedback/.gitignore new file mode 100644 index 00000000..6d9d5d79 --- /dev/null +++ b/web/feedback/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.vercel/ +.env* +!.env.example +.data/ diff --git a/web/feedback/README.md b/web/feedback/README.md new file mode 100644 index 00000000..5dd6a9ed --- /dev/null +++ b/web/feedback/README.md @@ -0,0 +1,9 @@ +# TechPie 反馈入口 + +本目录只包含反馈表单与工单查询界面。API、存储、后台管理、测试和部署配置独立放在 E:\Projects\techpie-feedback-api。 + +接口地址:https://techpie-feedback.dzhes.app/api/feedback。API 项目部署时同步这里的公开界面到 public/,因此该域名也提供反馈入口,后台地址为 /miku。 + +表单包含 GeekPie-UniAuth 用户名(非学号)、反馈类型、平台与版本、使用场景、标题、具体问题、复现步骤、期望结果与联系方式。用户名自行填写,未做 SSO 身份验证,不传递 SSO Token。提交后生成工单 ID,可下载凭证并查看公开回复与处理进度。 + +Flutter 设置页通过“用户反馈与工单”打开入口。API 的账户密码、存储凭据及运行数据均不在本目录。 \ No newline at end of file diff --git a/web/feedback/public/app.js b/web/feedback/public/app.js new file mode 100644 index 00000000..55799e44 --- /dev/null +++ b/web/feedback/public/app.js @@ -0,0 +1,93 @@ +import { api, el, details } from "./common.js"; +let receipt; +function tab(mode) { + for (const name of ["new", "lookup"]) { + el(`${name}-panel`).hidden = name !== mode; + el(`${name}-tab`).setAttribute("aria-selected", String(name === mode)); + } +} +el("new-tab").onclick = () => tab("new"); +el("lookup-tab").onclick = () => tab("lookup"); +document.querySelector(".tabs").onkeydown = (event) => { + if (["ArrowLeft", "ArrowRight"].includes(event.key)) { + event.preventDefault(); + const mode = el("new-panel").hidden ? "new" : "lookup"; + tab(mode); + el(`${mode}-tab`).focus(); + } +}; +const form = el("feedback-form"); +el("another-feedback").onclick = () => { + receipt = null; + form.reset(); + form.hidden = false; + el("receipt").hidden = true; + form.elements.contact.type = "email"; + form.elements.contact.autocomplete = "email"; + el("receipt-id").textContent = ""; + form.elements.userId.focus(); +}; +form.elements.contactType.onchange = () => { + form.elements.contact.type = + form.elements.contactType.value === "邮箱" ? "email" : "text"; + form.elements.contact.autocomplete = + form.elements.contactType.value === "邮箱" ? "email" : "off"; +}; +form.onsubmit = async (event) => { + event.preventDefault(); + const button = form.querySelector("button"); + button.disabled = true; + el("form-message").textContent = ""; + try { + receipt = await api("create", { + ...Object.fromEntries(new FormData(form)), + consent: form.elements.consent.checked, + }); + el("receipt-id").textContent = receipt.id; + form.hidden = true; + el("receipt").hidden = false; + el("receipt").focus(); + } catch (error) { + el("form-message").textContent = error.message; + } finally { + button.disabled = false; + } +}; +el("save-receipt").onclick = () => { + const file = new Blob( + [ + `TechPie 工单凭证\n工单 ID:${receipt.id}\n查询入口:${location.origin}/\n请妥善保存工单 ID。\n`, + ], + { type: "text/plain;charset=utf-8" }, + ); + const url = URL.createObjectURL(file); + const a = document.createElement("a"); + a.href = url; + a.download = `${receipt.id}.txt`; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +}; +el("view-receipt").onclick = () => { + el("lookup-form").elements.id.value = receipt.id; + tab("lookup"); + el("lookup-form").requestSubmit(); +}; +el("lookup-form").onsubmit = async (event) => { + event.preventDefault(); + const form = event.currentTarget; + const button = form.querySelector("button"); + button.disabled = true; + el("lookup-message").textContent = ""; + el("lookup-result").replaceChildren(); + try { + const { ticket } = await api("lookup", { + ...Object.fromEntries(new FormData(form)), + id: form.elements.id.value.trim().toUpperCase(), + }); + details(ticket, el("lookup-result")); + } catch (error) { + el("lookup-message").textContent = error.message; + } finally { + button.disabled = false; + } +}; diff --git a/web/feedback/public/common.js b/web/feedback/public/common.js new file mode 100644 index 00000000..ba4f041d --- /dev/null +++ b/web/feedback/public/common.js @@ -0,0 +1,145 @@ +const TIMEOUT_MS = 15000; +const NETWORK_MESSAGE = "网络连接失败,请检查网络后重试"; +const timeoutMessage = (action) => + action === "create" + ? "请求超时,提交结果尚未确认,请勿连续重复提交" + : "请求超时,请稍后重试"; +function withTimeout(action, run) { + let timer; + const controller = + typeof AbortController === "function" ? new AbortController() : null; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error(timeoutMessage(action))); + if (controller) controller.abort(); + }, TIMEOUT_MS); + }); + const work = Promise.resolve().then(() => run(controller)); + return Promise.race([work, timeout]).finally(() => clearTimeout(timer)); +} +export async function api(action, data = {}) { + const endpoint = + location.hostname === "techpie-feedback.dzhes.app" || + location.hostname === "localhost" + ? "/api/feedback" + : "https://techpie-feedback.dzhes.app/api/feedback"; + let result; + try { + // No automatic retry: create must not risk duplicate submissions. + const outcome = await withTimeout(action, async (controller) => { + const response = await fetch(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...data, action }), + ...(controller ? { signal: controller.signal } : {}), + }); + let json; + try { + json = await response.json(); + } catch { + throw new Error("服务暂时不可用,请稍后重试"); + } + return { response, json }; + }); + result = outcome.json; + if (!outcome.response.ok) { + const error = new Error(result.error || "请求失败"); + error.status = outcome.response.status; + throw error; + } + return result; + } catch (error) { + if (error && (error.name === "AbortError" || error.name === "TimeoutError")) { + throw new Error(timeoutMessage(action)); + } + if (error instanceof TypeError) { + throw new Error(NETWORK_MESSAGE); + } + throw error; + } +} +export const el = (id) => document.getElementById(id); +export const date = (value) => + new Date(value).toLocaleString("zh-CN", { hour12: false }); +export function node(tag, text, className) { + const result = document.createElement(tag); + if (text !== undefined) result.textContent = text; + if (className) result.className = className; + return result; +} +export function details(ticket, target, admin = false) { + target.replaceChildren(); + const heading = node("div", undefined, "split"); + heading.append( + node("h2", ticket.title), + node("span", ticket.status, "badge"), + ); + target.append( + heading, + node("p", `${ticket.id} · ${date(ticket.createdAt)}`, "muted"), + ); + for (const [label, value] of [ + ["反馈类型", ticket.category], + ["使用场景", ticket.scenario], + ["平台 / 版本", `${ticket.platform} / ${ticket.version || "未填写"}`], + ["具体问题", ticket.problem], + ["复现步骤", ticket.steps], + ["期望结果", ticket.expected], + ...(admin + ? [ + ["用户 ID", ticket.userId], + ["联系方式", `${ticket.contactType}:${ticket.contact}`], + ["优先级", ticket.priority], + ["负责人", ticket.assignee || "未分配"], + ["归档", ticket.archived ? "已归档" : "未归档"], + ] + : []), + ]) { + if (!value) continue; + const section = node("section", undefined, "section"); + section.append(node("h3", label), node("p", value)); + target.append(section); + } + const timeline = node( + "div", + undefined, + admin ? "timeline admin-history" : "timeline", + ); + const labels = { + reply: "公开回复", + note: "内部备注", + status: "修改状态", + priority: "设置优先级", + category: "修改分类", + assign: "分配负责人", + archive: "归档操作", + }; + for (const event of ticket.history) { + const item = node( + "article", + undefined, + event.action === "note" ? "internal" : "", + ); + item.append( + node("div", labels[event.action], "history-label"), + node("small", date(event.at)), + node( + "p", + event.action === "archive" + ? event.value === "true" + ? "已归档" + : "已恢复" + : event.value, + ), + ); + timeline.append(item); + } + const section = node("section", undefined, "section"); + section.append( + node("h3", admin ? "操作记录" : "处理记录"), + ticket.history.length + ? timeline + : node("p", "工单已提交,状态为待处理。", "muted"), + ); + target.append(section); +} diff --git a/web/feedback/public/icon.png b/web/feedback/public/icon.png new file mode 100644 index 00000000..04c8cbc9 Binary files /dev/null and b/web/feedback/public/icon.png differ diff --git a/web/feedback/public/index.html b/web/feedback/public/index.html new file mode 100644 index 00000000..bad15873 --- /dev/null +++ b/web/feedback/public/index.html @@ -0,0 +1,239 @@ + + + + + + + + 用户反馈 · TechPie + + + + + + +
+
+

用户反馈

+

提交使用问题或功能建议,或通过工单 ID 查询处理结果。用户群:1130168501

+
+
+ +
+

提交反馈

+

带 * 的项目为必填项。提交成功后将生成工单 ID。

+
+
+

用户与使用环境

+
+ + + + + +
+
+
+

反馈内容

+
+ + + + +
+
+
+

联系方式

+
+ +
+
+ + +
+ +
+
+ +
+ +
+
+ + + diff --git a/web/feedback/public/style.css b/web/feedback/public/style.css new file mode 100644 index 00000000..5545bd4c --- /dev/null +++ b/web/feedback/public/style.css @@ -0,0 +1,404 @@ +:root { + color-scheme: light; + --ink: #172b45; + --muted: #526680; + --blue: #087ff5; + --line: #dce7f1; + --paper: #f7fbff; + --soft: #eaf4ff; + font-family: + -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", + sans-serif; + color: var(--ink); + background: #fff; + font-synthesis: none; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + font-size: 17px; + line-height: 1.8; +} +a { + color: #096ace; + text-underline-offset: 4px; +} +a:hover { + color: #064d99; +} +button, +input, +textarea, +select { + font: inherit; +} +button { + cursor: pointer; +} +button:disabled { + opacity: 0.55; + cursor: wait; +} +a:focus-visible, +button:focus-visible { + outline: 3px solid #1181ee; + outline-offset: 5px; +} +[hidden] { + display: none !important; +} +.wrap { + max-width: 1320px; + margin: auto; + padding: 0 36px; +} +.nav { + min-height: 92px; + border-bottom: 1px solid var(--line); + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; +} +.brand { + display: flex; + align-items: center; + gap: 12px; + font-size: 22px; + font-weight: 740; + letter-spacing: -0.7px; + text-decoration: none; + color: var(--ink); +} +.brand img { + width: 48px; + height: 48px; + border-radius: 9px; +} +.navlinks { + display: flex; + align-items: center; + gap: 28px; +} +.navlinks a { + font-size: 15px; + text-decoration: none; + color: var(--muted); +} +.navlinks a[aria-current="page"] { + color: var(--blue); +} +.feedback-page { + max-width: 920px; + margin: auto; + padding: 56px 36px 80px; +} +.page-heading h1 { + font-size: 40px; + font-weight: 760; + line-height: 1.35; + letter-spacing: -0.04em; + margin: 12px 0 16px; +} +.page-heading p { + color: var(--muted); + margin: 0 0 36px; + font-size: 16px; +} +.tabs { + display: flex; + gap: 32px; + border-bottom: 1px solid var(--line); + margin-bottom: 32px; +} +.tabs button { + position: relative; + border: 0; + background: none; + padding: 12px 0; + color: var(--muted); + font-size: 16px; +} +.tabs button[aria-selected="true"] { + color: var(--blue); + font-weight: 600; +} +.tabs button[aria-selected="true"]:after { + content: ""; + height: 2px; + position: absolute; + bottom: -1px; + left: 0; + right: 0; + background: var(--blue); +} +.card { + min-width: 0; +} +h2 { + font-size: 24px; + line-height: 1.5; + margin: 0 0 8px; +} +h3 { + font-size: 18px; + font-weight: 600; + margin: 0 0 20px; +} +.muted { + color: var(--muted); + font-size: 14px; + margin: 8px 0 24px; +} +.section { + border-top: 1px solid var(--line); + padding-top: 24px; + margin-top: 32px; +} +.fields { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 22px 28px; +} +.full { + grid-column: 1/-1; +} +label { + display: block; + font-size: 15px; + font-weight: 500; +} +.required { + color: #b3261e; +} +.hint { + display: block; + font-size: 13px; + color: var(--muted); + font-weight: 400; + margin-top: 6px; +} +input:not([type="checkbox"]), +textarea, +select { + display: block; + width: 100%; + margin-top: 8px; + padding: 10px 12px; + border: 1px solid #bccdde; + border-radius: 6px; + background: #fff; + color: var(--ink); + font-size: 15px; + line-height: 1.6; + outline: none; +} +textarea { + resize: vertical; + min-height: 110px; +} +input:focus, +textarea:focus, +select:focus { + border-color: var(--blue); + box-shadow: 0 0 0 2px var(--soft); +} +.check { + display: flex; + gap: 10px; + color: var(--muted); + font-size: 13px; + font-weight: 400; + margin-top: 28px; + line-height: 1.7; +} +.check input { + margin-top: 5px; + accent-color: var(--blue); +} +.actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 20px; + margin-top: 24px; +} +.primary { + display: inline-block; + background: var(--blue); + color: #fff; + border: 0; + border-radius: 11px; + padding: 11px 22px; + font-size: 16px; + font-weight: 600; + text-decoration: none; +} +.primary:hover { + background: #066acb; + color: #fff; +} +.quiet { + border: 1px solid var(--line); + background: #fff; + color: var(--ink); + border-radius: 6px; + padding: 9px 16px; + font-size: 14px; +} +.message { + color: #b3261e; + background: #fff3f2; + border-left: 3px solid #b3261e; + padding: 12px 16px; + font-size: 14px; + white-space: pre-wrap; + margin-top: 20px; +} +.message:empty { + display: none; +} +.success { + border-top: 1px solid var(--line); + margin-top: 28px; + padding-top: 28px; +} +.credential { + display: block; + font: + 15px/1.8 ui-monospace, + Consolas, + monospace; + background: var(--paper); + border: 1px solid var(--line); + padding: 12px 16px; + overflow-wrap: anywhere; + margin: 8px 0 20px; + border-radius: 6px; +} +.badge { + display: inline-block; + background: var(--soft); + color: #096ace; + border-radius: 4px; + font-size: 13px; + line-height: 1.6; + padding: 3px 10px; + white-space: nowrap; +} +.split { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} +.detail { + margin-top: 32px; +} +.detail p { + font-size: 15px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.detail h3 { + margin-bottom: 12px; +} +.timeline { + border-left: 2px solid var(--line); + padding-left: 20px; +} +.timeline article { + margin: 0 0 24px; +} +.timeline small { + font-size: 12px; + color: var(--muted); +} +.history-label { + font-size: 14px; + font-weight: 600; +} +.trap { + position: absolute; + left: -10000px; +} +.footer { + display: flex; + gap: 28px; + border-top: 1px solid var(--line); + padding: 24px 0 34px; + font-size: 13px; + color: #667991; +} +.footer a { + color: inherit; + text-decoration: none; +} +@media (max-width: 800px) { + .wrap { + padding: 0 24px; + } + .nav { + min-height: 78px; + } + .navlinks { + gap: 16px; + } + .feedback-page { + padding: 34px 23px 55px; + } + .page-heading h1 { + font-size: 32px; + } + .page-heading p { + margin-bottom: 24px; + } + .fields { + gap: 20px; + } + .section { + margin-top: 26px; + } + .navlinks a { + font-size: 13px; + } +} +@media (max-width: 520px) { + .fields { + grid-template-columns: 1fr; + } + .brand { + font-size: 20px; + } + .brand img { + width: 40px; + height: 40px; + } + .nav { + gap: 14px; + flex-wrap: wrap; + padding: 16px 0; + } + .navlinks { + gap: 18px; + } + .navlinks a:first-child { + display: none; + } + .actions { + gap: 12px; + } + .split { + align-items: flex-start; + } + .feedback-page { + padding-top: 28px; + } +} +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } +} diff --git a/web/feedback/test/app.test.mjs b/web/feedback/test/app.test.mjs new file mode 100644 index 00000000..24639438 --- /dev/null +++ b/web/feedback/test/app.test.mjs @@ -0,0 +1,96 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +function element() { + return { + hidden: false, disabled: false, value: '', textContent: '', + setAttribute() {}, focus() {}, replaceChildren() {}, reset() {}, + querySelector() { return this.button ||= element(); }, + }; +} + +async function fixture(fetchImpl) { + const elements = new Map(); + const get = (id) => { + if (!elements.has(id)) elements.set(id, element()); + return elements.get(id); + }; + const form = get('feedback-form'); + form.elements = { + userId: { value: 'student' }, + problem: { value: '请保留已经填写的反馈内容' }, + consent: { checked: true }, contact: {}, contactType: {}, + }; + get('lookup-form').elements = { id: { value: 'TP-TEST' } }; + const timers = new Map(); + let nextTimer = 0, calls = 0; + const context = vm.createContext({ + location: { hostname: 'localhost', origin: 'http://localhost' }, + document: { getElementById: get, querySelector: () => element() }, + FormData: class { + constructor(form) { this.form = form; } + *[Symbol.iterator]() { + for (const [key, value] of Object.entries(this.form.elements)) { + yield [key, value.value]; + } + } + }, + TypeError, AbortController, + fetch: (...args) => { calls++; return fetchImpl(...args); }, + setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, + clearTimeout(id) { timers.delete(id); }, + }); + const common = await readFile(new URL('../public/common.js', import.meta.url), 'utf8'); + const app = await readFile(new URL('../public/app.js', import.meta.url), 'utf8'); + vm.runInContext(common.replace(/^export /gm, ''), context); + vm.runInContext(app.replace(/^import .*$/m, ''), context); + return { + get, form, calls: () => calls, + expire() { for (const fn of [...timers.values()]) fn(); }, + pendingTimers: () => timers.size, + }; +} + +test('successful submission reveals its receipt and releases the button', async () => { + const f = await fixture(async () => ({ ok: true, json: async () => ({ id: 'TP-9' }) })); + await f.form.onsubmit({ preventDefault() {} }); + assert.equal(f.get('receipt-id').textContent, 'TP-9'); + assert.equal(f.get('receipt').hidden, false); + assert.equal(f.form.hidden, true); + assert.equal(f.form.querySelector().disabled, false); + assert.equal(f.pendingTimers(), 0); +}); + +test('network failure keeps inputs and releases the submit button', async () => { + const f = await fixture(async () => { throw new TypeError('Failed to fetch'); }); + await f.form.onsubmit({ preventDefault() {} }); + assert.match(f.get('form-message').textContent, /网络连接失败/); + assert.equal(f.form.elements.problem.value, '请保留已经填写的反馈内容'); + assert.equal(f.form.hidden, false); + assert.equal(f.form.querySelector().disabled, false); + assert.equal(f.calls(), 1); +}); + +for (const mode of ['create', 'lookup']) { + test(`${mode} timeout releases button without automatic retries`, async () => { + let signal; + const f = await fixture((_url, options) => { + signal = options.signal; + return new Promise(() => {}); + }); + const form = mode === 'create' ? f.form : f.get('lookup-form'); + const task = form.onsubmit({ preventDefault() {}, currentTarget: form }); + await Promise.resolve(); await Promise.resolve(); + assert.equal(form.querySelector().disabled, true); + f.expire(); + await task; + assert.equal(signal.aborted, true); + assert.equal(form.querySelector().disabled, false); + assert.equal(f.calls(), 1); + assert.equal(f.pendingTimers(), 0); + assert.match(f.get(mode === 'create' ? 'form-message' : 'lookup-message').textContent, /请求超时/); + assert.equal(f.form.elements.problem.value, '请保留已经填写的反馈内容'); + }); +} diff --git a/web/feedback/test/common.test.mjs b/web/feedback/test/common.test.mjs new file mode 100644 index 00000000..287ea4fd --- /dev/null +++ b/web/feedback/test/common.test.mjs @@ -0,0 +1,156 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; + +test.beforeEach((t) => { + const original = globalThis.location; + globalThis.location = { hostname: 'localhost' }; + t.after(() => { + if (original === undefined) delete globalThis.location; + else globalThis.location = original; + }); +}); + +async function loadCommon() { + const source = await readFile( + new URL("../public/common.js", import.meta.url), + "utf8", + ); + const dataUrl = + "data:text/javascript;base64," + Buffer.from(source).toString("base64"); + return import(dataUrl); +} + +function mockFetch(t, impl) { + const original = globalThis.fetch; + const calls = []; + globalThis.fetch = (url, options) => { + calls.push({ url, options }); + return impl(url, options); + }; + t.after(() => { + globalThis.fetch = original; + }); + return calls; +} + +function mockTimers(t) { + const originalSet = globalThis.setTimeout; + const originalClear = globalThis.clearTimeout; + const pending = new Map(); + let nextId = 1; + globalThis.setTimeout = (fn, ms) => { + const id = nextId++; + pending.set(id, { fn, ms }); + return id; + }; + globalThis.clearTimeout = (id) => { + pending.delete(id); + }; + t.after(() => { + globalThis.setTimeout = originalSet; + globalThis.clearTimeout = originalClear; + }); + return { + fire() { + const entries = [...pending.values()]; + pending.clear(); + for (const { fn } of entries) fn(); + }, + get size() { + return pending.size; + }, + }; +} + +test("success resolves parsed result and clears timer", async (t) => { + const timers = mockTimers(t); + const calls = mockFetch(t, () => + Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ id: "TP-1" }), + }), + ); + const { api } = await loadCommon(); + const result = await api("lookup", { id: "TP-1" }); + assert.deepEqual(result, { id: "TP-1" }); + assert.equal(calls.length, 1); + assert.equal(timers.size, 0); +}); + +test("http error surfaces server message and status", async (t) => { + mockTimers(t); + mockFetch(t, () => + Promise.resolve({ + ok: false, + status: 400, + json: () => Promise.resolve({ error: "无效工单" }), + }), + ); + const { api } = await loadCommon(); + await assert.rejects(api("lookup", {}), (error) => { + assert.equal(error.message, "无效工单"); + assert.equal(error.status, 400); + return true; + }); +}); + +test("invalid body json yields friendly message", async (t) => { + mockTimers(t); + mockFetch(t, () => + Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.reject(new SyntaxError("bad json")), + }), + ); + const { api } = await loadCommon(); + await assert.rejects(api("lookup", {}), { message: "服务暂时不可用,请稍后重试" }); +}); + +test("network TypeError maps to translated message", async (t) => { + mockTimers(t); + mockFetch(t, () => Promise.reject(new TypeError("Failed to fetch"))); + const { api } = await loadCommon(); + await assert.rejects(api("create", {}), { + message: "网络连接失败,请检查网络后重试", + }); +}); + +test("hanging fetch aborts on timeout with create wording", async (t) => { + const timers = mockTimers(t); + let aborted = false; + mockFetch(t, (_url, options) => { + options.signal.addEventListener("abort", () => { + aborted = true; + }); + return new Promise(() => {}); + }); + const { api } = await loadCommon(); + const pending = api("create", {}); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(timers.size, 1); + timers.fire(); + await assert.rejects(pending, { + message: "请求超时,提交结果尚未确认,请勿连续重复提交", + }); + assert.equal(aborted, true); +}); + +test("hanging body parse timeouts and clears timer", async (t) => { + const timers = mockTimers(t); + mockFetch(t, () => + Promise.resolve({ ok: true, status: 200, json: () => new Promise(() => {}) }), + ); + const { api } = await loadCommon(); + const pending = api("lookup", {}); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + assert.equal(timers.size, 1); + timers.fire(); + await assert.rejects(pending, { message: "请求超时,请稍后重试" }); + assert.equal(timers.size, 0); +});