@jx3box/jx3box-ui 2.4.26 → 2.4.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -322,6 +322,7 @@ export default {
322
322
  publish: "Post Comment",
323
323
  },
324
324
  commentWithReply: {
325
+ refreshAfterSubmitFailed: "Your reply was posted, but the list could not be refreshed. Refresh the page to view it; do not submit again.",
325
326
  defaultName: "Anonymous Wanderer",
326
327
  top: "Pinned",
327
328
  star: "Featured",
@@ -354,6 +355,7 @@ export default {
354
355
  zlpBy: { all: "All", default: "Expansion" },
355
356
  collection: { included: "This post has been included in the author's JX3 booklet" },
356
357
  comment: {
358
+ refreshAfterSubmitFailed: "Your comment was posted, but the list could not be refreshed. Refresh the page to view it; do not submit again.",
357
359
  sortMode: "Sort:",
358
360
  desc: "Newest first",
359
361
  asc: "Oldest first",
@@ -321,7 +321,15 @@ export default {
321
321
  secretTip: "Bình luận bí mật chỉ hiển thị với bạn và tác giả, và không thể thay đổi sau đó",
322
322
  publish: "Đăng bình luận",
323
323
  },
324
- commentWithReply: { defaultName: "Hiệp khách vô danh", top: "Ghim", star: "Nổi bật", secret: "Bí mật", commentSuccess: "Bình luận thành công!", deleteSuccess: "Xóa thành công!" },
324
+ commentWithReply: {
325
+ refreshAfterSubmitFailed: "Phản hồi đã được gửi nhưng không thể tải lại danh sách. Hãy tải lại trang để xem, không cần gửi lại.",
326
+ defaultName: "Hiệp khách vô danh",
327
+ top: "Ghim",
328
+ star: "Nổi bật",
329
+ secret: "Bí mật",
330
+ commentSuccess: "Bình luận thành công!",
331
+ deleteSuccess: "Xóa thành công!",
332
+ },
325
333
  commentUpload: {
326
334
  tip: "Tải tối đa {count} ảnh định dạng {types}, mỗi ảnh không quá {size} MB",
327
335
  tipWithVideo: "Tải tối đa {count} tệp đính kèm. Hỗ trợ: {types}. Ảnh không quá {imageSize} MB, video không quá {videoSize} MB",
@@ -347,6 +355,7 @@ export default {
347
355
  zlpBy: { all: "Tất cả", default: "Bản mở rộng" },
348
356
  collection: { included: "Tác phẩm này đã được đưa vào sổ tay JX3 của tác giả" },
349
357
  comment: {
358
+ refreshAfterSubmitFailed: "Bình luận đã được gửi nhưng không thể tải lại danh sách. Hãy tải lại trang để xem, không cần gửi lại.",
350
359
  sortMode: "Sắp xếp:",
351
360
  desc: "Mới nhất trước",
352
361
  asc: "Cũ nhất trước",
@@ -380,6 +380,7 @@ export default {
380
380
  publish: "发表评论",
381
381
  },
382
382
  commentWithReply: {
383
+ refreshAfterSubmitFailed: "回复已提交,列表刷新失败,请刷新页面查看,无需重复提交。",
383
384
  defaultName: "人字榜800线无名小侠",
384
385
  top: "置顶",
385
386
  star: "精华",
@@ -459,6 +460,7 @@ export default {
459
460
  included: "该作品已被收录至作者的剑三小册",
460
461
  },
461
462
  comment: {
463
+ refreshAfterSubmitFailed: "评论已提交,列表刷新失败,请刷新页面查看,无需重复提交。",
462
464
  sortMode: "排序模式:",
463
465
  desc: "最后靠前",
464
466
  asc: "最早靠前",
@@ -321,7 +321,15 @@ export default {
321
321
  secretTip: "勾選悄悄話後僅作者和你可見,且不可再變更狀態",
322
322
  publish: "發表評論",
323
323
  },
324
- commentWithReply: { defaultName: "無名小俠", top: "置頂", star: "精華", secret: "悄悄話", commentSuccess: "評論成功!", deleteSuccess: "刪除成功!" },
324
+ commentWithReply: {
325
+ refreshAfterSubmitFailed: "回覆已提交,列表重新整理失敗,請重新整理頁面查看,無需重複提交。",
326
+ defaultName: "無名小俠",
327
+ top: "置頂",
328
+ star: "精華",
329
+ secret: "悄悄話",
330
+ commentSuccess: "評論成功!",
331
+ deleteSuccess: "刪除成功!",
332
+ },
325
333
  commentUpload: {
326
334
  tip: "最多上傳 {count} 張 {types} 格式圖片,單張圖片不能超過 {size} MB",
327
335
  tipWithVideo: "最多上傳 {count} 個附件,支援 {types},圖片不超過 {imageSize} MB,影片不超過 {videoSize} MB",
@@ -347,6 +355,7 @@ export default {
347
355
  zlpBy: { all: "全部", default: "資料片" },
348
356
  collection: { included: "該作品已被收錄至作者的劍三小冊" },
349
357
  comment: {
358
+ refreshAfterSubmitFailed: "評論已提交,列表重新整理失敗,請重新整理頁面查看,無需重複提交。",
350
359
  sortMode: "排序模式:",
351
360
  desc: "最後靠前",
352
361
  asc: "最早靠前",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jx3box/jx3box-ui",
3
- "version": "2.4.26",
3
+ "version": "2.4.28",
4
4
  "description": "JX3BOX Vue3 UI",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -57,13 +57,12 @@ export async function setOrderMode(val) {
57
57
  }
58
58
  }
59
59
 
60
- export const GET = function (url, queryParams) {
61
- return $
62
- .get(url, {
63
- params: queryParams,
64
- })
60
+ export const GET = function (url, queryParams, options = {}) {
61
+ return $.get(url, {
62
+ params: queryParams,
63
+ })
65
64
  .then((res) => res.data)
66
- .catch((err) => __handleError(err));
65
+ .catch((err) => __handleError(err, options));
67
66
  };
68
67
 
69
68
  const postRecord = {};
@@ -95,10 +94,9 @@ export const POST = function (url, queryParams, body) {
95
94
  count: 0,
96
95
  };
97
96
  }
98
- return $
99
- .post(url, body, {
100
- params: queryParams,
101
- })
97
+ return $.post(url, body, {
98
+ params: queryParams,
99
+ })
102
100
  .then((res) => res.data)
103
101
  .catch((err) => __handleError(err));
104
102
  };
@@ -120,10 +118,10 @@ export const DELETE = function (url, queryParams) {
120
118
  .catch((err) => __handleError(err));
121
119
  };
122
120
 
123
- function __handleError(err) {
121
+ function __handleError(err, options = {}) {
124
122
  const status = err?.response?.status;
125
123
  const statusText = err?.response?.statusText || "Request Error";
126
- const message = err?.response?.data?.msg || err?.response?.data || "";
124
+ const message = options.errorMessage || err?.response?.data?.msg || err?.response?.data || "";
127
125
  switch (status) {
128
126
  case 401:
129
127
  case 403:
@@ -141,8 +139,8 @@ function __handleError(err) {
141
139
  });
142
140
  break;
143
141
  default:
144
- Notification.error({
145
- title: "系统:" + statusText,
142
+ Notification[options.errorMessage ? "warning" : "error"]({
143
+ title: options.errorMessage ? "" : "系统:" + statusText,
146
144
  message: message || "系统错误,请稍后重试!",
147
145
  duration: 3000,
148
146
  position: "bottom-right",
@@ -340,21 +340,34 @@ export default {
340
340
  return count > 0 ? count : "";
341
341
  },
342
342
  attachmentUploadFinish(data) {
343
- this.disableSubmitBtn = false;
344
- this.$emit("addNewReply", {
345
- content: this.newComment.content,
346
- attachmentList: data,
347
- });
343
+ this.disableSubmitBtn = true;
344
+ const submittedContent = this.newComment.content;
345
+ this.$emit(
346
+ "addNewReply",
347
+ {
348
+ content: submittedContent,
349
+ attachmentList: data,
350
+ },
351
+ () => this.clearSubmittedContent(submittedContent),
352
+ () => {
353
+ this.disableSubmitBtn = false;
354
+ }
355
+ );
348
356
  this.showUploader = false;
357
+ },
358
+ clearSubmittedContent(submittedContent) {
359
+ if (this.newComment.content !== submittedContent) return false;
349
360
  this.newComment = {
350
361
  content: "",
351
362
  };
363
+ return true;
352
364
  },
353
365
  attachmentUplodError() {
354
366
  this.disableSubmitBtn = false;
355
367
  },
356
368
 
357
369
  submit() {
370
+ if (this.disableSubmitBtn) return;
358
371
  this.disableSubmitBtn = true;
359
372
  if (this.$refs.uploader) {
360
373
  this.$refs.uploader.upload();
@@ -97,6 +97,7 @@ export default {
97
97
  },
98
98
  methods: {
99
99
  onSubmit() {
100
+ if (this.disableSubmitBtn) return;
100
101
  this.disableSubmitBtn = true;
101
102
  if (this.$refs.uploader) {
102
103
  this.$refs.uploader.upload();
@@ -105,14 +106,24 @@ export default {
105
106
  }
106
107
  },
107
108
  onQuickReply(item) {
108
- this.$emit("submit", {
109
- content: item,
110
- attachmentList: [],
111
- is_template: 1,
112
- });
109
+ if (this.disableSubmitBtn) return;
110
+ this.disableSubmitBtn = true;
111
+ this.$emit(
112
+ "submit",
113
+ {
114
+ content: item,
115
+ attachmentList: [],
116
+ is_template: 1,
117
+ },
118
+ undefined,
119
+ () => {
120
+ this.disableSubmitBtn = false;
121
+ }
122
+ );
113
123
  },
114
124
  // 文件上传完成后,进行数据提交
115
125
  attachmentUploadFinish(data) {
126
+ this.disableSubmitBtn = true;
116
127
  const submittedContent = this.newComment.content;
117
128
  this.$emit(
118
129
  "submit",
@@ -121,19 +132,20 @@ export default {
121
132
  is_secret: this.is_secret ? 1 : 0,
122
133
  attachmentList: data,
123
134
  },
124
- () => this.clearSubmittedContent(submittedContent)
135
+ () => this.clearSubmittedContent(submittedContent),
136
+ () => {
137
+ this.disableSubmitBtn = false;
138
+ }
125
139
  );
126
140
  this.showUploader = false;
127
-
128
- this.disableSubmitBtn = false;
129
141
  },
130
142
  clearSubmittedContent(submittedContent) {
131
143
  // 请求成功后才清空;若等待响应期间用户已修改内容,则保留新草稿。
132
- if (this.newComment.content === submittedContent) {
133
- this.newComment = {
134
- content: "",
135
- };
136
- }
144
+ if (this.newComment.content !== submittedContent) return false;
145
+ this.newComment = {
146
+ content: "",
147
+ };
148
+ return true;
137
149
  },
138
150
  attachmentUploadError() {
139
151
  this.disableSubmitBtn = false;
@@ -214,8 +214,8 @@ export default {
214
214
  setWhiteComment(white) {
215
215
  this.$emit("setWhiteComment", this.item.id, white);
216
216
  },
217
- addNewReply(data) {
218
- POST(`${this.baseApi}/comment/${this.item.id}/reply`, null, data)
217
+ addNewReply(data, clearSubmittedContent, onSettled) {
218
+ return POST(`${this.baseApi}/comment/${this.item.id}/reply`, null, data)
219
219
  .then(() => {
220
220
  this.$notify({
221
221
  title: "",
@@ -224,10 +224,15 @@ export default {
224
224
  duration: 3000,
225
225
  position: "bottom-right",
226
226
  });
227
-
228
- this.loadReplyList(this.pager.index);
227
+ if (typeof clearSubmittedContent === "function") {
228
+ clearSubmittedContent();
229
+ }
230
+ return this.loadReplyList(this.pager.index, undefined, true);
229
231
  })
230
- .catch(() => {});
232
+ .catch(() => {})
233
+ .finally(() => {
234
+ if (typeof onSettled === "function") onSettled();
235
+ });
231
236
  },
232
237
  deleteReply(id) {
233
238
  DELETE(`${this.baseApi}/comment/${id}`)
@@ -246,8 +251,15 @@ export default {
246
251
  gotoReplyListIndex(index) {
247
252
  this.loadReplyList(index, 6);
248
253
  },
249
- loadReplyList(index, pageSize) {
250
- GET(`${this.baseApi}/comment/${this.item.id}/reply/page/${index}?pageSize=${pageSize}`)
254
+ loadReplyList(index, pageSize, afterSubmit = false) {
255
+ return GET(`${this.baseApi}/comment/${this.item.id}/reply/page/${index}?pageSize=${pageSize}`, null, {
256
+ errorMessage: afterSubmit
257
+ ? this.$jx3boxT(
258
+ "jx3boxUi.commentWithReply.refreshAfterSubmitFailed",
259
+ "回复已提交,列表刷新失败,请刷新页面查看,无需重复提交。"
260
+ )
261
+ : undefined,
262
+ })
251
263
  .then((resp) => {
252
264
  if (index == 1 && pageSize == 3) {
253
265
  // eslint-disable-next-line vue/no-mutating-props
@@ -89,6 +89,7 @@ export default {
89
89
  },
90
90
  methods: {
91
91
  submitReply() {
92
+ if (this.disableSubmitBtn) return;
92
93
  this.disableSubmitBtn = true;
93
94
  if (this.$refs.uploader) {
94
95
  this.$refs.uploader.upload();
@@ -100,14 +101,26 @@ export default {
100
101
  this.$emit("hideForm");
101
102
  },
102
103
  attachmentUploadFinish(data) {
103
- this.disableSubmitBtn = false;
104
- this.$emit("doReply", {
105
- content: this.content,
106
- attachmentList: data,
107
- });
108
- this.content = "";
104
+ this.disableSubmitBtn = true;
105
+ const submittedContent = this.content;
106
+ this.$emit(
107
+ "doReply",
108
+ {
109
+ content: submittedContent,
110
+ attachmentList: data,
111
+ },
112
+ () => this.clearSubmittedContent(submittedContent),
113
+ () => {
114
+ this.disableSubmitBtn = false;
115
+ }
116
+ );
109
117
  this.showUploader = false;
110
118
  },
119
+ clearSubmittedContent(submittedContent) {
120
+ if (this.content !== submittedContent) return false;
121
+ this.content = "";
122
+ return true;
123
+ },
111
124
  attachmentUploadError() {
112
125
  this.disableSubmitBtn = false;
113
126
  },
@@ -95,11 +95,20 @@ export default {
95
95
  setLikeComment(setLike) {
96
96
  this.$emit("setLikeComment", this.reply.id, setLike);
97
97
  },
98
- doReply(replyData) {
99
- (replyData.replyForUID = this.reply.userId),
100
- (replyData.replyForCommentId = this.reply.id),
101
- this.$emit("addReply", replyData);
102
- this.showReplyForReplyFrom = false;
98
+ doReply(replyData, clearSubmittedContent, onSettled) {
99
+ replyData.replyForUID = this.reply.userId;
100
+ replyData.replyForCommentId = this.reply.id;
101
+ this.$emit(
102
+ "addReply",
103
+ replyData,
104
+ () => {
105
+ const contentCleared = clearSubmittedContent?.();
106
+ if (contentCleared !== false) {
107
+ this.showReplyForReplyFrom = false;
108
+ }
109
+ },
110
+ onSettled
111
+ );
103
112
  },
104
113
  },
105
114
  };
@@ -95,8 +95,8 @@ export default {
95
95
  setLikeComment(id, isLike) {
96
96
  this.$emit("setLikeComment", id, isLike);
97
97
  },
98
- addReply(data) {
99
- this.$emit("addNewReply", data);
98
+ addReply(data, clearSubmittedContent, onSettled) {
99
+ this.$emit("addNewReply", data, clearSubmittedContent, onSettled);
100
100
  },
101
101
  },
102
102
  };
@@ -11,7 +11,7 @@
11
11
  }}</el-button
12
12
  >
13
13
  </div>
14
- <AuthorLink class="u-block u-links" :data="data" />
14
+ <!-- <AuthorLink class="u-block u-links" :data="data" /> -->
15
15
  <AuthorRole class="u-block u-roles" :data="data" />
16
16
  <AuthorMedals class="u-block u-trophy" :medals="activeMedals" />
17
17
  <!-- <AuthorTeams class="u-block u-teams" :uid="uid" /> -->
@@ -24,7 +24,7 @@
24
24
 
25
25
  <script>
26
26
  import AuthorInfo from "../author/AuthorInfo.vue";
27
- import AuthorLink from "../author/AuthorLink.vue";
27
+ // import AuthorLink from "../author/AuthorLink.vue";
28
28
  // import AuthorFollow from "../author/AuthorFollow.vue";
29
29
  // import AuthorGift from "../author/AuthorGift.vue";
30
30
  // import AuthorFans from "../author/AuthorFans.vue";
@@ -161,7 +161,7 @@ export default {
161
161
  },
162
162
  components: {
163
163
  AuthorInfo,
164
- AuthorLink,
164
+ // AuthorLink,
165
165
  // AuthorFollow,
166
166
  // AuthorGift,
167
167
  AuthorRole,
@@ -232,14 +232,21 @@ export default {
232
232
  })
233
233
  .catch(() => {});
234
234
  },
235
- reloadCommentList(index) {
235
+ reloadCommentList(index, afterSubmit = false) {
236
236
  this.loading = true;
237
237
  let orderQuery = {};
238
238
  if (this.isDesc === "DESC") {
239
239
  orderQuery["desc"] = true;
240
240
  }
241
241
  orderQuery["orderby_likes"] = this.orderByLikes;
242
- GET(`${this.baseAPI}/comment/page/${index}`, orderQuery)
242
+ return GET(`${this.baseAPI}/comment/page/${index}`, orderQuery, {
243
+ errorMessage: afterSubmit
244
+ ? this.$jx3boxT(
245
+ "jx3boxUi.comment.refreshAfterSubmitFailed",
246
+ "评论已提交,列表刷新失败,请刷新页面查看,无需重复提交。"
247
+ )
248
+ : undefined,
249
+ })
243
250
  .then((resp) => {
244
251
  this.commentList = resp.data || [];
245
252
  this.pager = resp.page;
@@ -253,19 +260,9 @@ export default {
253
260
  handleCurrentChange(gotoIndex) {
254
261
  this.reloadCommentList(gotoIndex);
255
262
  },
256
- userSubmitInputForm(data, clearSubmittedContent) {
257
- POST(`${this.baseAPI}/comment`, null, data)
258
- .then((responseJSON) => {
259
- if (!responseJSON || Number(responseJSON.code) !== 0) {
260
- this.$notify({
261
- title: this.$jx3boxT("jx3boxUi.comment.commentFailed", "评论失败"),
262
- message: responseJSON?.msg || "",
263
- type: "error",
264
- duration: 3000,
265
- position: "bottom-right",
266
- });
267
- return;
268
- }
263
+ userSubmitInputForm(data, clearSubmittedContent, onSettled) {
264
+ return POST(`${this.baseAPI}/comment`, null, data)
265
+ .then(() => {
269
266
  this.$notify({
270
267
  title: "",
271
268
  message: this.$jx3boxT("jx3boxUi.comment.commentSuccess", "评论成功!"),
@@ -278,10 +275,13 @@ export default {
278
275
  }
279
276
  // 位于第一页时才去更新数据,否则没必要,等用户自己触发
280
277
  if (this.pager.index == 1) {
281
- this.reloadCommentList(this.pager.index);
278
+ return this.reloadCommentList(this.pager.index, true);
282
279
  }
283
280
  })
284
- .catch(() => {});
281
+ .catch(() => {})
282
+ .finally(() => {
283
+ if (typeof onSettled === "function") onSettled();
284
+ });
285
285
  },
286
286
  profileLink: function (uid) {
287
287
  return authorLink(uid);
@@ -0,0 +1,335 @@
1
+ const assert = require("node:assert/strict");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const vm = require("node:vm");
5
+ const { test } = require("node:test");
6
+ const axios = require("axios");
7
+
8
+ function createService(status, data) {
9
+ const notifications = [];
10
+ // Exercise the service's actual Axios status validation without a live write.
11
+ const client = axios.create({
12
+ adapter: async (config) => {
13
+ const response = { status, statusText: String(status), data, config, headers: {} };
14
+ if (!config.validateStatus || config.validateStatus(status)) return response;
15
+ throw new axios.AxiosError("Request failed", undefined, config, undefined, response);
16
+ },
17
+ });
18
+ const source = fs
19
+ .readFileSync(path.join(__dirname, "../service/comment.js"), "utf8")
20
+ .replace(/^import .*;\n/gm, "")
21
+ .replace(/export /g, "");
22
+ const context = vm.createContext({
23
+ JX3BOX: { __Links: { account: { login: "/login", email_verify: "/verify" } } },
24
+ Notification: {
25
+ warning: (value) => notifications.push({ ...value, type: "warning" }),
26
+ error: (value) => notifications.push({ ...value, type: "error" }),
27
+ },
28
+ $next: () => client,
29
+ window: { location: { href: "/article" } },
30
+ });
31
+ vm.runInContext(source + "\nglobalThis.submit = POST; globalThis.get = GET;", context);
32
+ return { submit: context.submit, get: context.get, notifications };
33
+ }
34
+
35
+ for (const endpoint of ["/comment", "/comment/1/reply"]) {
36
+ for (const status of [200, 201, 202, 204]) {
37
+ test(`${endpoint} accepts HTTP ${status}`, async () => {
38
+ const data = status === 204 ? "" : { id: 123 };
39
+ const { submit, notifications } = createService(status, data);
40
+ assert.deepEqual(await submit(endpoint, null, { content: "test" }), data);
41
+ assert.equal(notifications.length, 0);
42
+ });
43
+ }
44
+ for (const status of [400, 401, 403, 406, 423, 500]) {
45
+ test(`${endpoint} rejects HTTP ${status}`, async () => {
46
+ const { submit } = createService(status, { msg: "failed" });
47
+ await assert.rejects(submit(endpoint, null, { content: "test" }), (err) => err.response.status === status);
48
+ });
49
+ }
50
+ }
51
+
52
+ // Load the real Options API methods, replacing only external imports.
53
+ function loadMethods(file, overrides = {}) {
54
+ const babel = require("@babel/core");
55
+ const bindings = {};
56
+ const source = fs.readFileSync(path.join(__dirname, "..", file), "utf8").match(/<script>([\s\S]*?)<\/script>/)[1];
57
+ const result = babel.transformSync(source, {
58
+ configFile: false,
59
+ babelrc: false,
60
+ plugins: [
61
+ ({ types: t }) => ({
62
+ visitor: {
63
+ ImportDeclaration(node) {
64
+ for (const specifier of node.node.specifiers) bindings[specifier.local.name] = {};
65
+ node.remove();
66
+ },
67
+ ExportDefaultDeclaration(node) {
68
+ node.replaceWith(
69
+ t.expressionStatement(
70
+ t.assignmentExpression(
71
+ "=",
72
+ t.memberExpression(t.identifier("globalThis"), t.identifier("component")),
73
+ node.node.declaration
74
+ )
75
+ )
76
+ );
77
+ },
78
+ },
79
+ }),
80
+ ],
81
+ });
82
+ const context = vm.createContext({ ...bindings, ...overrides });
83
+ vm.runInContext(result.code, context);
84
+ return context.component.methods;
85
+ }
86
+
87
+ for (const data of [{ code: 0 }, { code: "0" }, { code: 200 }, { id: 123 }, null, ""]) {
88
+ test(`successful response body ${JSON.stringify(data)} is passed through`, async () => {
89
+ const { submit, notifications } = createService(200, data);
90
+ assert.deepEqual(await submit("/comment", null, {}), data);
91
+ assert.equal(notifications.length, 0);
92
+ });
93
+ }
94
+
95
+ for (const [file, method, refresh] of [
96
+ ["src/single/Comment.vue", "userSubmitInputForm", "reloadCommentList"],
97
+ ["src/comment/CommentWithReply.vue", "addNewReply", "loadReplyList"],
98
+ ]) {
99
+ for (const succeeds of [true, false]) {
100
+ test(`${file}: ${succeeds ? "success clears draft and refreshes" : "failure preserves draft"}`, async () => {
101
+ const notifications = [];
102
+ let cleared = 0;
103
+ let refreshed = 0;
104
+ const methods = loadMethods(file, {
105
+ POST: () => (succeeds ? Promise.resolve({ code: 200 }) : Promise.reject(new Error("failed"))),
106
+ });
107
+ const instance = {
108
+ baseAPI: "/api",
109
+ baseApi: "/api",
110
+ item: { id: 1 },
111
+ pager: { index: 1 },
112
+ $notify: (value) => notifications.push(value),
113
+ $jx3boxT: (key, fallback) => fallback,
114
+ [refresh]: () => {
115
+ refreshed++;
116
+ },
117
+ };
118
+ methods[method].call(instance, { content: "draft" }, () => {
119
+ cleared++;
120
+ });
121
+ await new Promise((resolve) => setImmediate(resolve));
122
+ assert.equal(cleared, Number(succeeds));
123
+ assert.equal(refreshed, Number(succeeds));
124
+ assert.equal(notifications.length, Number(succeeds));
125
+ if (succeeds) assert.equal(notifications[0].type, "success");
126
+ });
127
+ }
128
+ }
129
+
130
+ for (const file of ["CommentInputForm", "CommentContent", "ReplyForReply"]) {
131
+ test(`${file}: upload completion waits for submit success and preserves edited draft`, () => {
132
+ const methods = loadMethods(`src/comment/${file}.vue`);
133
+ let clear;
134
+ const instance = {
135
+ ...methods,
136
+ newComment: { content: "draft" },
137
+ content: "draft",
138
+ $emit: (event, payload, callback) => {
139
+ clear = callback;
140
+ },
141
+ };
142
+ methods.attachmentUploadFinish.call(instance, ["https://example.com/image.png"]);
143
+ const read = () => (file === "ReplyForReply" ? instance.content : instance.newComment.content);
144
+ assert.equal(read(), "draft");
145
+ if (file === "ReplyForReply") instance.content = "new draft";
146
+ else instance.newComment.content = "new draft";
147
+ assert.equal(clear(), false);
148
+ assert.equal(read(), "new draft");
149
+ methods.attachmentUploadFinish.call(instance, []);
150
+ assert.equal(clear(), true);
151
+ assert.equal(read(), "");
152
+ });
153
+ }
154
+
155
+ test("nested reply forwards success callback through ReplyItem and ReplyList", () => {
156
+ const itemMethods = loadMethods("src/comment/ReplyItem.vue");
157
+ const listMethods = loadMethods("src/comment/ReplyList.vue");
158
+ let onSuccess;
159
+ const instance = {
160
+ reply: { id: 2, userId: 3 },
161
+ showReplyForReplyFrom: true,
162
+ $emit: (event, data, callback) =>
163
+ listMethods.addReply.call(
164
+ {
165
+ $emit: (name, payload, forwarded) => {
166
+ assert.equal(payload.replyForUID, 3);
167
+ assert.equal(payload.replyForCommentId, 2);
168
+ onSuccess = forwarded;
169
+ },
170
+ },
171
+ data,
172
+ callback
173
+ ),
174
+ };
175
+ itemMethods.doReply.call(instance, {}, () => false);
176
+ assert.equal(instance.showReplyForReplyFrom, true);
177
+ onSuccess();
178
+ assert.equal(instance.showReplyForReplyFrom, true);
179
+ itemMethods.doReply.call(instance, {}, () => true);
180
+ onSuccess();
181
+ assert.equal(instance.showReplyForReplyFrom, false);
182
+ });
183
+
184
+ for (const [file, method, uploadError] of [
185
+ ["CommentInputForm", "onSubmit", "attachmentUploadError"],
186
+ ["CommentContent", "submit", "attachmentUplodError"],
187
+ ["ReplyForReply", "submitReply", "attachmentUploadError"],
188
+ ]) {
189
+ test(`${file}: blocks duplicate submissions until settled and unlocks on upload failure`, () => {
190
+ const methods = loadMethods(`src/comment/${file}.vue`);
191
+ let submits = 0;
192
+ let settle;
193
+ const instance = {
194
+ ...methods,
195
+ $refs: {},
196
+ disableSubmitBtn: false,
197
+ newComment: { content: "draft" },
198
+ content: "draft",
199
+ $emit: (name, data, clear, onSettled) => {
200
+ submits++;
201
+ settle = onSettled;
202
+ },
203
+ };
204
+ instance[method]();
205
+ assert.equal(instance.disableSubmitBtn, true);
206
+ instance[method]();
207
+ assert.equal(submits, 1);
208
+ settle();
209
+ assert.equal(instance.disableSubmitBtn, false);
210
+ instance[method]();
211
+ assert.equal(submits, 2);
212
+ instance[uploadError]();
213
+ assert.equal(instance.disableSubmitBtn, false);
214
+ });
215
+ }
216
+
217
+ test("quick reply shares the submission lock and releases it on settlement", () => {
218
+ const methods = loadMethods("src/comment/CommentInputForm.vue");
219
+ let submits = 0;
220
+ let settle;
221
+ const instance = {
222
+ ...methods,
223
+ disableSubmitBtn: false,
224
+ $emit: (event, data, clear, callback) => {
225
+ submits++;
226
+ settle = callback;
227
+ assert.equal(clear, undefined);
228
+ },
229
+ };
230
+ instance.onQuickReply("hello");
231
+ instance.onQuickReply("hello");
232
+ instance.onSubmit();
233
+ assert.equal(submits, 1);
234
+ settle();
235
+ assert.equal(instance.disableSubmitBtn, false);
236
+ });
237
+
238
+ for (const [file, method, refresh] of [
239
+ ["src/single/Comment.vue", "userSubmitInputForm", "reloadCommentList"],
240
+ ["src/comment/CommentWithReply.vue", "addNewReply", "loadReplyList"],
241
+ ]) {
242
+ for (const succeeds of [true, false]) {
243
+ test(`${file}: submission settlement always unlocks, success=${succeeds}`, async () => {
244
+ let resolve;
245
+ let reject;
246
+ let settled = 0;
247
+ const pending = new Promise((res, rej) => {
248
+ resolve = res;
249
+ reject = rej;
250
+ });
251
+ const methods = loadMethods(file, { POST: () => pending });
252
+ const instance = {
253
+ baseAPI: "/api",
254
+ baseApi: "/api",
255
+ item: { id: 1 },
256
+ pager: { index: 1 },
257
+ $notify() {},
258
+ $jx3boxT: (key, text) => text,
259
+ [refresh]: () => Promise.resolve(),
260
+ };
261
+ const request = methods[method].call(instance, {}, undefined, () => {
262
+ settled++;
263
+ });
264
+ assert.equal(settled, 0);
265
+ if (succeeds) resolve({});
266
+ else reject(new Error("network failed"));
267
+ await request;
268
+ assert.equal(settled, 1);
269
+ });
270
+ }
271
+ test(`${file}: POST succeeds and GET fails with a contextual warning only`, async () => {
272
+ const service = createService(500, { msg: "server error" });
273
+ const notifications = [];
274
+ let cleared = 0;
275
+ let settled = 0;
276
+ const methods = loadMethods(file, { POST: () => Promise.resolve({}), GET: service.get });
277
+ const instance = {
278
+ ...methods,
279
+ baseAPI: "/api",
280
+ baseApi: "/api",
281
+ item: { id: 1 },
282
+ pager: { index: 1 },
283
+ $notify: (value) => notifications.push(value),
284
+ $jx3boxT: (key, text) => text,
285
+ };
286
+ await instance[method](
287
+ {},
288
+ () => {
289
+ cleared++;
290
+ },
291
+ () => {
292
+ settled++;
293
+ }
294
+ );
295
+ assert.equal(cleared, 1);
296
+ assert.equal(settled, 1);
297
+ assert.equal(notifications.length, 1);
298
+ assert.equal(notifications[0].type, "success");
299
+ assert.equal(service.notifications.length, 1);
300
+ assert.equal(service.notifications[0].type, "warning");
301
+ assert.match(service.notifications[0].message, /已提交.*列表刷新失败.*无需重复提交/);
302
+ assert.equal(instance.loading, file.includes("single") ? false : undefined);
303
+ });
304
+ }
305
+
306
+ test("nested reply forwards settlement even when submission fails", () => {
307
+ const item = loadMethods("src/comment/ReplyItem.vue");
308
+ const list = loadMethods("src/comment/ReplyList.vue");
309
+ let settled = 0;
310
+ const instance = {
311
+ reply: { id: 2, userId: 3 },
312
+ showReplyForReplyFrom: true,
313
+ $emit: (event, data, clear, onSettled) =>
314
+ list.addReply.call(
315
+ {
316
+ $emit: (name, payload, onSuccess, callback) => callback(),
317
+ },
318
+ data,
319
+ clear,
320
+ onSettled
321
+ ),
322
+ };
323
+ item.doReply.call(
324
+ instance,
325
+ {},
326
+ () => {
327
+ throw new Error("must not clear");
328
+ },
329
+ () => {
330
+ settled++;
331
+ }
332
+ );
333
+ assert.equal(settled, 1);
334
+ assert.equal(instance.showReplyForReplyFrom, true);
335
+ });