@h-ai/ui 0.1.0-alpha.70 → 0.1.0-alpha.72

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.
Files changed (33) hide show
  1. package/README.en.md +19 -6
  2. package/README.ja.md +19 -6
  3. package/README.md +19 -6
  4. package/auto-import.d.ts +1 -0
  5. package/auto-import.js +1 -0
  6. package/dist/components/compounds/JsonViewer.svelte +214 -0
  7. package/dist/components/compounds/JsonViewer.svelte.d.ts +26 -0
  8. package/dist/components/compounds/index.d.ts +1 -0
  9. package/dist/components/compounds/index.js +2 -0
  10. package/dist/components/scenes/ai/index.d.ts +1 -0
  11. package/dist/components/scenes/ai/index.js +2 -0
  12. package/dist/components/scenes/app/FeedbackDetail.svelte +14 -2
  13. package/dist/components/scenes/app/FeedbackDetail.svelte.d.ts +2 -0
  14. package/dist/components/scenes/app/FeedbackForm.svelte +128 -61
  15. package/dist/components/scenes/app/FeedbackForm.svelte.d.ts +14 -3
  16. package/dist/components/scenes/app/FeedbackList.svelte +3 -3
  17. package/dist/components/scenes/app/FeedbackModal.svelte +50 -2
  18. package/dist/components/scenes/app/FeedbackRecorder.svelte +154 -0
  19. package/dist/components/scenes/app/FeedbackRecorder.svelte.d.ts +9 -0
  20. package/dist/components/scenes/app/FeedbackReplay.svelte +142 -0
  21. package/dist/components/scenes/app/FeedbackReplay.svelte.d.ts +7 -0
  22. package/dist/components/scenes/app/FeedbackScreenshot.svelte +37 -23
  23. package/dist/components/scenes/app/feedback-functions.js +1 -0
  24. package/dist/components/scenes/app/feedback-types.d.ts +1 -1
  25. package/dist/components/scenes/iam/auth-error-message.d.ts +1 -1
  26. package/dist/components/scenes/iam/auth-error-message.js +2 -1
  27. package/dist/messages/en-US.json +29 -9
  28. package/dist/messages/ja-JP.json +29 -9
  29. package/dist/messages/zh-CN.json +29 -9
  30. package/dist/toast.svelte.d.ts +9 -0
  31. package/dist/toast.svelte.js +25 -4
  32. package/dist/types.d.ts +27 -0
  33. package/package.json +3 -2
@@ -10,9 +10,10 @@
10
10
  -->
11
11
  <script lang='ts'>
12
12
  import type { DataAttributes, FormLayoutOptions } from '../../../types.js'
13
- import type { FeedbackAnnotation, FeedbackAttachmentView, FeedbackEvidenceSummary, FeedbackFormData, FeedbackReceipt } from './feedback-types.js'
13
+ import type { FeedbackAnnotation, FeedbackAttachmentView, FeedbackEvidenceSummary, FeedbackEvidenceView, FeedbackFormData, FeedbackReceipt } from './feedback-types.js'
14
14
  import { untrack } from 'svelte'
15
15
  import { uiM } from '../../../messages.js'
16
+ import { errorMessage } from '../../../toast.svelte.js'
16
17
  import { getDataAttributes } from '../../../utils.js'
17
18
  import FormField from '../../compounds/FormField.svelte'
18
19
  import FormLayout from '../../compounds/FormLayout.svelte'
@@ -21,7 +22,8 @@
21
22
  import Input from '../../primitives/Input.svelte'
22
23
  import Select from '../../primitives/Select.svelte'
23
24
  import Textarea from '../../primitives/Textarea.svelte'
24
- import { collectionLabel } from './feedback-functions.js'
25
+ import { collectionLabel, evidenceText, feedbackTime } from './feedback-functions.js'
26
+ import FeedbackRecorder from './FeedbackRecorder.svelte'
25
27
  import FeedbackScreenshot from './FeedbackScreenshot.svelte'
26
28
 
27
29
  /**
@@ -51,12 +53,19 @@
51
53
  types?: { bug?: string, feature?: string, question?: string, other?: string }
52
54
  }
53
55
  attachments?: FeedbackAttachmentView[]
56
+ budget?: { maxAttachmentsBytes: number, maxAttachmentBytes: number, maxAttachmentCount: number }
54
57
  evidenceSummary?: FeedbackEvidenceSummary[]
58
+ /** 采集器已脱敏的原始材料,按种类展开查看。 */
59
+ evidence?: FeedbackEvidenceView[]
55
60
  onsubmit?: (input: FeedbackFormData) => Promise<void | FeedbackReceipt>
56
61
  onannotate?: (annotation: FeedbackAnnotation) => Promise<void>
57
62
  /** 宿主准备附件并回填 attachments,使主动添加的图片也可预览、遮挡和标注。 */
58
- onfileschange?: (files: File[]) => Promise<void>
59
- onexport?: (input: FeedbackFormData) => Promise<void>
63
+ onfileschange?: (files: File[], removedAttachmentIds?: readonly string[]) => Promise<void>
64
+ /** 不传 ID 补充页面截图,传 ID 替换原截图;弹窗组件负责换页选取交互。 */
65
+ oncapture?: (attachmentId?: string) => void | Promise<void>
66
+ /** 录屏期间宿主可隐藏反馈表单,停止后重新显示。 */
67
+ onrecordingchange?: (active: boolean) => void
68
+ onexport?: (input: FeedbackFormData) => Promise<void | boolean>
60
69
  oncancel?: () => void
61
70
  oncomplete?: () => void
62
71
  /** 准备新现场后更新,关闭弹窗不会丢失未提交内容。 */
@@ -68,10 +77,14 @@
68
77
  let {
69
78
  labels = {},
70
79
  attachments = [],
80
+ budget,
71
81
  evidenceSummary = [],
82
+ evidence = [],
72
83
  onsubmit,
73
84
  onannotate,
74
85
  onfileschange,
86
+ oncapture,
87
+ onrecordingchange,
75
88
  onexport,
76
89
  oncancel,
77
90
  oncomplete,
@@ -96,9 +109,22 @@
96
109
  let staging = $state(false)
97
110
  let filesError = $state(false)
98
111
  let exporting = $state(false)
112
+ let recording = $state(false)
113
+ let exported = $state(false)
114
+ let expandedMaterials = $state<string[]>([])
99
115
  let error = $state('')
100
116
  let previousKey = $state(untrack(() => resetKey))
101
117
  const visibleAttachments = $derived(attachments.filter(item => !removedAttachmentIds.includes(item.id)))
118
+ const attachmentBytes = $derived(visibleAttachments.reduce((total, file) => total + (file.size ?? 0), 0))
119
+ const recordingBytes = $derived(budget ? Math.max(0, Math.min(budget.maxAttachmentBytes, budget.maxAttachmentsBytes - attachmentBytes)) : undefined)
120
+ const attachmentLimitReached = $derived(budget ? visibleAttachments.length >= budget.maxAttachmentCount || attachmentBytes >= budget.maxAttachmentsBytes : false)
121
+ const materialGroups = $derived([
122
+ { label: uiM('feedback_environment'), kinds: ['environment'] },
123
+ { label: uiM('feedback_logs'), kinds: ['log', 'error', 'request'] },
124
+ { label: uiM('feedback_scene'), kinds: ['interaction', 'snapshot', 'business'] },
125
+ { label: uiM('feedback_replay'), kinds: ['replay'] },
126
+ { label: uiM('feedback_missing'), kinds: ['missing'] },
127
+ ].map(group => ({ ...group, items: evidence.filter(item => group.kinds.includes(item.kind)) })).filter(group => group.items.length))
102
128
  const typeOptions = $derived([
103
129
  { value: 'bug', label: labels.types?.bug ?? uiM('feedback_type_bug') },
104
130
  { value: 'feature', label: labels.types?.feature ?? uiM('feedback_type_feature') },
@@ -115,6 +141,7 @@
115
141
  filesError = false
116
142
  removedAttachmentIds = []
117
143
  receipt = undefined
144
+ exported = false
118
145
  error = ''
119
146
  }
120
147
  })
@@ -125,7 +152,7 @@
125
152
 
126
153
  async function submit(event: SubmitEvent) {
127
154
  event.preventDefault()
128
- if (loading || annotating || staging || (onfileschange && filesError) || receipt)
155
+ if (loading || annotating || staging || exporting || recording || (onfileschange && filesError) || receipt)
129
156
  return
130
157
  if (!onsubmit) {
131
158
  error = labels.errorSubmit ?? uiM('feedback_error_submit')
@@ -141,7 +168,7 @@
141
168
  oncomplete?.()
142
169
  }
143
170
  catch (cause) {
144
- error = cause instanceof Error ? cause.message : labels.errorSubmit ?? uiM('feedback_error_submit')
171
+ error = errorMessage(cause, labels.errorSubmit ?? uiM('feedback_error_submit'))
145
172
  }
146
173
  finally {
147
174
  loading = false
@@ -152,11 +179,12 @@
152
179
  if (!onexport || exporting || annotating || staging)
153
180
  return
154
181
  exporting = true
182
+ error = ''
155
183
  try {
156
- await onexport(values())
184
+ exported = await onexport(values()) !== false
157
185
  }
158
186
  catch (cause) {
159
- error = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
187
+ error = errorMessage(cause, uiM('feedback_action_failed'))
160
188
  }
161
189
  finally {
162
190
  exporting = false
@@ -182,12 +210,12 @@
182
210
  filesError = false
183
211
  error = ''
184
212
  try {
185
- await onfileschange([...files])
213
+ await onfileschange([...files], removedAttachmentIds)
186
214
  files = []
187
215
  }
188
216
  catch (cause) {
189
217
  filesError = true
190
- error = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
218
+ error = errorMessage(cause, uiM('feedback_action_failed'))
191
219
  }
192
220
  finally {
193
221
  staging = false
@@ -207,65 +235,104 @@
207
235
  if (!files.length)
208
236
  filesError = false
209
237
  }
238
+ function recordingChanged(active: boolean) {
239
+ recording = active
240
+ onrecordingchange?.(active)
241
+ }
242
+ async function recorded(file: File) {
243
+ files = [...files, file]
244
+ await stageFiles()
245
+ }
210
246
  </script>
211
247
 
212
- <form {...dataAttributes} class={`feedback-form min-w-0 space-y-4 ${className}`} onsubmit={submit} data-feedback-ui='true' data-feedback-ignore='true'>
213
- {#if error}<div class='alert alert-error break-words' role='alert'>{error}</div>{/if}
214
- {#if receipt}
215
- <div role='status' class='alert alert-success block space-y-2 break-words'>
216
- <p class='font-medium'>{uiM('feedback_accepted', { number: receipt.number })}</p>
217
- <p>{collectionLabel(receipt.collectionStatus)}</p>
218
- <p class='text-sm'>{uiM('feedback_accepted_hint')}</p>
219
- </div>
220
- {:else}
221
- <p class='text-sm text-base-content/65'>{labels.description ?? uiM('feedback_quick_hint')}</p>
222
- <FormLayout {columns} {labelPosition} {labelWidth}>
223
- <FormField for={`${instanceId}-description`} label={labels.contentLabel ?? uiM('feedback_optional_description')}>
224
- <Textarea id={`${instanceId}-description`} name='description' class='h-28' maxlength={10000} placeholder={labels.contentPlaceholder ?? uiM('feedback_content_placeholder')} bind:value={description} disabled={loading} />
225
- </FormField>
226
- </FormLayout>
227
- {#if visibleAttachments.length}
228
- <section class='space-y-3' aria-label={uiM('feedback_screenshots')}>
229
- {#each visibleAttachments as attachment (attachment.id)}
230
- <div class='rounded-lg border border-base-content/10 p-3 min-w-0 space-y-2'>
231
- <div class='flex items-center justify-between gap-3'>
232
- <span class='min-w-0 text-sm break-all'>{attachment.name}</span>
233
- <Button size='xs' variant='ghost' disabled={loading} ariaLabel={`${uiM('feedback_remove')} ${attachment.name}`} onclick={() => removedAttachmentIds = [...removedAttachmentIds, attachment.id]}>{uiM('feedback_remove')}</Button>
234
- </div>
235
- {#if attachment.mimeType?.startsWith('image/') && attachment.url}<FeedbackScreenshot {attachment} onannotate={!loading && onannotate ? annotate : undefined} />{/if}
236
- {#if attachment.missingReason}<p class='text-warning text-sm break-words'>{uiM('feedback_missing')}: {attachment.missingReason}</p>{/if}
237
- </div>
238
- {/each}
239
- </section>
248
+ <form {...dataAttributes} class={`feedback-form flex min-h-0 min-w-0 flex-1 flex-col gap-4 ${className}`} onsubmit={submit} data-feedback-ui='true' data-feedback-ignore='true'>
249
+ <div class='min-h-0 flex-1 space-y-4 overflow-y-auto'>
250
+ {#if budget}
251
+ <p class='text-xs text-base-content/60'>{uiM('feedback_capacity_hint', { used: (attachments.filter(item => !removedAttachmentIds.includes(item.id)).reduce((sum, item) => sum + (item.size ?? 0), 0) / 1048576).toFixed(1), total: (budget.maxAttachmentsBytes / 1048576).toFixed(1), single: (budget.maxAttachmentBytes / 1048576).toFixed(1), count: budget.maxAttachmentCount })}</p>
240
252
  {/if}
241
- <details class='rounded-lg border border-base-content/10 p-3'>
242
- <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_more')}</summary>
243
- <div class='pt-3 space-y-4'>
244
- <FormLayout {columns} {labelPosition} {labelWidth}>
245
- <FormField for={`${instanceId}-type`} label={labels.typeLabel ?? uiM('feedback_type_label')}><Select id={`${instanceId}-type`} options={typeOptions} bind:value={feedbackType} disabled={loading} /></FormField>
246
- <FormField for={`${instanceId}-contact`} label={labels.contactLabel ?? uiM('feedback_contact_label')}><Input id={`${instanceId}-contact`} placeholder={labels.contactPlaceholder ?? uiM('feedback_contact_placeholder')} bind:value={contact} maxlength={254} autocomplete='email' disabled={loading} /></FormField>
247
- <FormField for={`${instanceId}-files`} label={uiM('feedback_add_files')}><BareInput id={`${instanceId}-files`} type='file' accept='.png,.jpg,.jpeg,.webp,.txt,.log,.json,image/png,image/jpeg,image/webp,text/plain,application/json' multiple disabled={loading || staging} class='file-input file-input-bordered w-full' onchange={selectFiles} /></FormField>
248
- </FormLayout>
249
- {#each files as file, index (`${file.name}:${file.lastModified}:${index}`)}
250
- <div class='flex items-center gap-2 min-w-0 text-sm'><span class='min-w-0 flex-1 break-all'>{file.name}</span><Button size='xs' variant='ghost' disabled={loading || staging} ariaLabel={`${uiM('feedback_remove')} ${file.name}`} onclick={() => removeFile(index)}>{uiM('feedback_remove')}</Button></div>
251
- {/each}
252
- {#if onfileschange && filesError}<Button size='sm' loading={staging} onclick={stageFiles}>{uiM('feedback_retry')}</Button>{/if}
253
+ {#if error}<div class='alert alert-error break-words' role='alert'>{error}</div>{/if}
254
+ {#if receipt}
255
+ <div role='status' class='alert alert-success block space-y-2 break-words'>
256
+ <p class='font-medium'>{uiM('feedback_accepted', { number: receipt.number })}</p>
257
+ <p>{collectionLabel(receipt.collectionStatus)}</p>
258
+ <p class='text-sm'>{uiM('feedback_accepted_hint')}</p>
253
259
  </div>
254
- </details>
255
- {#if evidenceSummary.length}
256
- <details class='rounded-lg border border-base-content/10 p-3'>
257
- <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_materials')}</summary>
258
- <dl class='space-y-2 pt-3 text-sm'>
259
- {#each evidenceSummary as item, index (`${item.label}:${index}`)}
260
- <div class='min-w-0'><dt class='font-medium'>{item.label}{item.count === undefined ? '' : ` · ${item.count}`}</dt><dd class='text-base-content/65 break-words'>{item.status === 'missing' ? uiM('feedback_missing') : item.status === 'not-applicable' ? uiM('feedback_not_applicable') : item.status === 'partial' ? uiM('feedback_partial') : uiM('feedback_complete')}{item.detail ? ` · ${item.detail}` : ''}</dd></div>
260
+ {:else}
261
+ <p class='text-sm text-base-content/65'>{labels.description ?? uiM('feedback_quick_hint')}</p>
262
+ <FormLayout {columns} {labelPosition} {labelWidth}>
263
+ <FormField for={`${instanceId}-description`} label={labels.contentLabel ?? uiM('feedback_optional_description')}>
264
+ <Textarea id={`${instanceId}-description`} name='description' class='h-28' maxlength={10000} placeholder={labels.contentPlaceholder ?? uiM('feedback_content_placeholder')} bind:value={description} disabled={loading} />
265
+ </FormField>
266
+ </FormLayout>
267
+ <div class='flex flex-wrap gap-2'>
268
+ {#if oncapture}<Button size='sm' variant='outline' disabled={loading || annotating || staging || exporting} onclick={() => oncapture()}>{uiM('feedback_capture_add')}</Button>{/if}
269
+ <label class='btn btn-sm btn-ghost focus-within:outline focus-within:outline-primary'>
270
+ {uiM('feedback_add_files')}
271
+ <BareInput id={`${instanceId}-files`} type='file' aria-label={uiM('feedback_add_files')} accept='.png,.jpg,.jpeg,.webp,.webm,.mp4,.txt,.log,.json,.pdf,image/png,image/jpeg,image/webp,video/webm,video/mp4,text/plain,application/json,application/pdf' multiple disabled={loading || staging || exporting} class='sr-only' onchange={selectFiles} />
272
+ </label>
273
+ {#if onfileschange}<FeedbackRecorder maxBytes={recordingBytes} disabled={loading || annotating || staging || exporting || attachmentLimitReached} onactive={recordingChanged} onrecord={recorded} />{/if}
274
+ </div>
275
+ {#each files as file, index (`${file.name}:${file.lastModified}:${index}`)}
276
+ <div class='flex items-center gap-2 min-w-0 text-sm'><span class='min-w-0 flex-1 break-all'>{file.name}</span><Button size='xs' variant='ghost' disabled={loading || staging} ariaLabel={`${uiM('feedback_remove')} ${file.name}`} onclick={() => removeFile(index)}>{uiM('feedback_remove')}</Button></div>
277
+ {/each}
278
+ {#if onfileschange && filesError}<Button size='sm' loading={staging} onclick={stageFiles}>{uiM('feedback_retry')}</Button>{/if}
279
+ {#if visibleAttachments.length}
280
+ <section class='space-y-3' aria-label={uiM('feedback_screenshots')}>
281
+ {#each visibleAttachments as attachment (attachment.id)}
282
+ <div class='rounded-lg border border-base-content/10 p-3 min-w-0 space-y-2'>
283
+ <div class='flex items-center justify-between gap-3'>
284
+ <span class='min-w-0 text-sm break-all'>{attachment.name}</span>
285
+ <div class='flex shrink-0 gap-1'>
286
+ {#if oncapture && attachment.mimeType?.startsWith('image/')}<Button size='xs' variant='ghost' disabled={loading || annotating || staging || exporting} onclick={() => oncapture(attachment.id)}>{uiM('feedback_capture_replace')}</Button>{/if}
287
+ <Button size='xs' variant='ghost' disabled={loading || annotating || exporting} ariaLabel={`${uiM('feedback_remove')} ${attachment.name}`} onclick={() => removedAttachmentIds = [...removedAttachmentIds, attachment.id]}>{uiM('feedback_remove')}</Button>
288
+ </div>
289
+ </div>
290
+ {#if attachment.mimeType?.startsWith('image/') && attachment.url}<FeedbackScreenshot {attachment} onannotate={!loading && !exporting && !staging && onannotate ? annotate : undefined} />{/if}
291
+ {#if attachment.mimeType?.startsWith('video/') && attachment.url}<!-- svelte-ignore a11y_media_has_caption (用户上传的无声录屏) -->
292
+ <video src={attachment.url} controls preload='metadata' class='max-w-full rounded' aria-label={attachment.name}></video>{/if}
293
+ {#if attachment.missingReason}<p class='text-warning text-sm break-words'>{uiM('feedback_missing')}: {attachment.missingReason}</p>{/if}
294
+ </div>
261
295
  {/each}
262
- </dl>
296
+ </section>
297
+ {/if}
298
+ <details class='rounded-lg border border-base-content/10 p-3'>
299
+ <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_more')}</summary>
300
+ <div class='pt-3 space-y-4'>
301
+ <FormLayout {columns} {labelPosition} {labelWidth}>
302
+ <FormField for={`${instanceId}-type`} label={labels.typeLabel ?? uiM('feedback_type_label')}><Select id={`${instanceId}-type`} options={typeOptions} bind:value={feedbackType} disabled={loading} /></FormField>
303
+ <FormField for={`${instanceId}-contact`} label={labels.contactLabel ?? uiM('feedback_contact_label')}><Input id={`${instanceId}-contact`} placeholder={labels.contactPlaceholder ?? uiM('feedback_contact_placeholder')} bind:value={contact} maxlength={254} autocomplete='email' disabled={loading} /></FormField>
304
+ </FormLayout>
305
+ </div>
263
306
  </details>
307
+ {#if evidenceSummary.length || evidence.length}
308
+ <details class='rounded-lg border border-base-content/10 p-3'>
309
+ <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_materials')}</summary>
310
+ <dl class='space-y-2 pt-3 text-sm'>
311
+ {#each materialGroups as group (group.label)}
312
+ <div class='min-w-0'>
313
+ <dt class='font-medium'>{group.label} · {group.items.length}</dt>
314
+ <dd class='space-y-2 pt-2'>
315
+ {#each group.items as item (item.id)}
316
+ <details class='rounded bg-base-200 p-2' ontoggle={event => expandedMaterials = event.currentTarget.open ? [...expandedMaterials, item.id] : expandedMaterials.filter(id => id !== item.id)}>
317
+ <summary class='cursor-pointer break-all text-xs'>{feedbackTime(item.timestamp)} · {item.kind} · {item.source} #{item.sequence}</summary>
318
+ {#if expandedMaterials.includes(item.id)}<pre class='mt-2 max-h-64 max-w-full overflow-auto whitespace-pre-wrap break-all text-xs'>{evidenceText(item.data)}</pre>{/if}
319
+ </details>
320
+ {/each}
321
+ </dd>
322
+ </div>
323
+ {/each}
324
+ {#each evidenceSummary as item, index (`${item.label}:${index}`)}
325
+ <div class='min-w-0'><dt class='font-medium'>{item.label}{item.count === undefined ? '' : ` · ${item.count}`}</dt><dd class='text-base-content/65 break-words'>{item.status === 'missing' ? uiM('feedback_missing') : item.status === 'not-applicable' ? uiM('feedback_not_applicable') : item.status === 'partial' ? uiM('feedback_partial') : uiM('feedback_complete')}{item.detail ? ` · ${item.detail}` : ''}</dd></div>
326
+ {/each}
327
+ </dl>
328
+ </details>
329
+ {/if}
264
330
  {/if}
265
- {/if}
266
- <div class='flex flex-wrap justify-end gap-2 border-t border-base-content/10 pt-4'>
331
+ {#if exported}<p class='text-sm text-success' role='status'>{uiM('feedback_local_saved')}</p>{/if}
332
+ </div>
333
+ <div class='shrink-0 flex flex-wrap justify-end gap-2 border-t border-base-content/10 bg-base-100 pt-4 pb-2'>
267
334
  {#if onexport}<Button variant='ghost' loading={exporting} disabled={annotating || staging} onclick={saveLocal}>{uiM('feedback_local_export')}</Button>{/if}
268
335
  {#if oncancel}<Button variant='ghost' onclick={oncancel}>{receipt ? uiM('feedback_close') : labels.cancel ?? uiM('feedback_cancel')}</Button>{/if}
269
- {#if !receipt}<Button type='submit' variant='primary' loading={loading || staging} disabled={annotating || Boolean(onfileschange && filesError)}>{labels.submit ?? uiM('feedback_submit')}</Button>{/if}
336
+ {#if !receipt}<Button type='submit' variant='primary' loading={loading || staging} disabled={annotating || exporting || recording || Boolean(onfileschange && filesError)}>{labels.submit ?? uiM('feedback_submit')}</Button>{/if}
270
337
  </div>
271
338
  </form>
@@ -1,5 +1,5 @@
1
1
  import type { DataAttributes, FormLayoutOptions } from '../../../types.js';
2
- import type { FeedbackAnnotation, FeedbackAttachmentView, FeedbackEvidenceSummary, FeedbackFormData, FeedbackReceipt } from './feedback-types.js';
2
+ import type { FeedbackAnnotation, FeedbackAttachmentView, FeedbackEvidenceSummary, FeedbackEvidenceView, FeedbackFormData, FeedbackReceipt } from './feedback-types.js';
3
3
  /**
4
4
  * 反馈表单的宿主注入契约,网络和采集服务通过动作回调接入。
5
5
  * @example
@@ -32,12 +32,23 @@ interface Props extends FormLayoutOptions {
32
32
  };
33
33
  };
34
34
  attachments?: FeedbackAttachmentView[];
35
+ budget?: {
36
+ maxAttachmentsBytes: number;
37
+ maxAttachmentBytes: number;
38
+ maxAttachmentCount: number;
39
+ };
35
40
  evidenceSummary?: FeedbackEvidenceSummary[];
41
+ /** 采集器已脱敏的原始材料,按种类展开查看。 */
42
+ evidence?: FeedbackEvidenceView[];
36
43
  onsubmit?: (input: FeedbackFormData) => Promise<void | FeedbackReceipt>;
37
44
  onannotate?: (annotation: FeedbackAnnotation) => Promise<void>;
38
45
  /** 宿主准备附件并回填 attachments,使主动添加的图片也可预览、遮挡和标注。 */
39
- onfileschange?: (files: File[]) => Promise<void>;
40
- onexport?: (input: FeedbackFormData) => Promise<void>;
46
+ onfileschange?: (files: File[], removedAttachmentIds?: readonly string[]) => Promise<void>;
47
+ /** 不传 ID 补充页面截图,传 ID 替换原截图;弹窗组件负责换页选取交互。 */
48
+ oncapture?: (attachmentId?: string) => void | Promise<void>;
49
+ /** 录屏期间宿主可隐藏反馈表单,停止后重新显示。 */
50
+ onrecordingchange?: (active: boolean) => void;
51
+ onexport?: (input: FeedbackFormData) => Promise<void | boolean>;
41
52
  oncancel?: () => void;
42
53
  oncomplete?: () => void;
43
54
  /** 准备新现场后更新,关闭弹窗不会丢失未提交内容。 */
@@ -12,6 +12,7 @@
12
12
  import type { DataAttributes } from '../../../types.js'
13
13
  import type { FeedbackListQuery, FeedbackPage, FeedbackPermissions, FeedbackReportView, FeedbackStatusChange } from './feedback-types.js'
14
14
  import { uiM } from '../../../messages.js'
15
+ import { errorMessage } from '../../../toast.svelte.js'
15
16
  import { getDataAttributes } from '../../../utils.js'
16
17
  import DataTable from '../../compounds/DataTable.svelte'
17
18
  import Pagination from '../../compounds/Pagination.svelte'
@@ -81,7 +82,7 @@
81
82
  await onquerychange?.(query)
82
83
  }
83
84
  catch (cause) {
84
- actionError = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
85
+ actionError = errorMessage(cause, uiM('feedback_action_failed'))
85
86
  }
86
87
  }
87
88
  function filter(values: Record<string, unknown>) {
@@ -98,7 +99,7 @@
98
99
  await action()
99
100
  }
100
101
  catch (cause) {
101
- actionError = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
102
+ actionError = errorMessage(cause, uiM('feedback_action_failed'))
102
103
  }
103
104
  finally {
104
105
  busyId = ''
@@ -111,7 +112,6 @@
111
112
  <p role='alert' class='alert alert-warning'>{uiM('feedback_permission_denied')}</p>
112
113
  {:else}
113
114
  <TableToolbar bind:searchValue={search} {filterFields} bind:filterValues sortableColumns={[{ key: 'createdAt', label: uiM('feedback_created_at') }]} sortBy='createdAt' bind:sortDirection searchPlaceholder={uiM('feedback_search')} onsearch={value => update({ page: 1, search: value || undefined })} onfilterchange={filter} onclearfilters={() => update({ page: 1, status: undefined, collectionStatus: undefined, appId: undefined, appVersion: undefined, from: undefined, to: undefined })} onsort={(_, direction) => update({ page: 1, sortDirection: direction })}>
114
- {#snippet leading()}<h2 class='font-semibold text-lg'>{uiM('feedback_list_title')}</h2>{/snippet}
115
115
  </TableToolbar>
116
116
  {#if error || actionError}<p role='alert' class='alert alert-error break-words'>{error || actionError}</p>{/if}
117
117
  <div class='min-h-0 min-w-0 flex-1 overflow-hidden'>
@@ -15,19 +15,67 @@
15
15
  <script lang='ts'>
16
16
  import type { ComponentProps } from 'svelte'
17
17
  import { uiM } from '../../../messages.js'
18
+ import { errorMessage } from '../../../toast.svelte.js'
18
19
  import { getDataAttributes, portal } from '../../../utils.js'
19
20
  import Modal from '../../compounds/Modal.svelte'
21
+ import Button from '../../primitives/Button.svelte'
20
22
  import FeedbackForm from './FeedbackForm.svelte'
21
23
 
22
24
  let { open = $bindable(false), ...restProps }: ComponentProps<typeof FeedbackForm> & { open?: boolean } = $props()
23
25
  const dataAttributes = $derived(getDataAttributes(restProps))
24
26
  const formProps = $derived(Object.fromEntries(Object.entries(restProps).filter(([key]) => !key.startsWith('data-'))) as ComponentProps<typeof FeedbackForm>)
27
+ let selectingPage = $state(false)
28
+ let captureTarget = $state<string>()
29
+ let capturing = $state(false)
30
+ let captureError = $state('')
31
+
32
+ function selectPage(attachmentId?: string) {
33
+ captureTarget = attachmentId
34
+ captureError = ''
35
+ selectingPage = true
36
+ open = false
37
+ }
38
+ function returnToFeedback() {
39
+ selectingPage = false
40
+ open = true
41
+ }
42
+ function recordingChanged(active: boolean) {
43
+ open = !active
44
+ formProps.onrecordingchange?.(active)
45
+ }
46
+ async function capture() {
47
+ if (capturing)
48
+ return
49
+ capturing = true
50
+ captureError = ''
51
+ try {
52
+ await formProps.oncapture?.(captureTarget)
53
+ selectingPage = false
54
+ open = true
55
+ }
56
+ catch (cause) {
57
+ captureError = errorMessage(cause, uiM('feedback_action_failed'))
58
+ }
59
+ finally {
60
+ capturing = false
61
+ }
62
+ }
25
63
  </script>
26
64
 
27
65
  <!-- 脱离顶栏的 fixed 包含块与层叠上下文;包装层不参与布局,卸载由 portal 清理。 -->
28
66
  <div use:portal class='contents'>
29
- <Modal {...dataAttributes} bind:open title={formProps.labels?.title ?? uiM('feedback_title')} size='lg' data-feedback-ui='true' data-feedback-ignore='true'>
30
- <FeedbackForm {...formProps} oncancel={() => {
67
+ {#if selectingPage && !open}
68
+ <aside class='fixed inset-x-4 bottom-4 z-[1200] mx-auto max-w-xl rounded-xl border border-base-content/15 bg-base-100 p-4 shadow-xl space-y-3' data-feedback-ignore='true' aria-label={uiM('feedback_capture_add')}>
69
+ <p class='text-sm' role='status'>{uiM('feedback_capture_hint')}</p>
70
+ {#if captureError}<p class='text-error text-sm break-words' role='alert'>{captureError}</p>{/if}
71
+ <div class='flex flex-wrap justify-end gap-2'>
72
+ <Button size='sm' variant='ghost' disabled={capturing} onclick={returnToFeedback}>{uiM('feedback_capture_return')}</Button>
73
+ <Button size='sm' variant='primary' loading={capturing} onclick={capture}>{uiM('feedback_capture_now')}</Button>
74
+ </div>
75
+ </aside>
76
+ {/if}
77
+ <Modal {...dataAttributes} bind:open title={formProps.labels?.title ?? uiM('feedback_title')} size='lg' bodyOverflow='hidden' bodyClass='flex flex-col' data-feedback-ui='true' data-feedback-ignore='true'>
78
+ <FeedbackForm {...formProps} onrecordingchange={recordingChanged} oncapture={formProps.oncapture ? selectPage : undefined} oncancel={() => {
31
79
  open = false
32
80
  formProps.oncancel?.()
33
81
  }} oncomplete={() => {
@@ -0,0 +1,154 @@
1
+ <!-- 浏览器原生短录屏;用户主动授权,无声音,停止后交给宿主准备附件。 -->
2
+ <script lang='ts'>
3
+ import { onMount } from 'svelte'
4
+ import { uiM } from '../../../messages.js'
5
+ import { errorMessage } from '../../../toast.svelte.js'
6
+ import { portal } from '../../../utils.js'
7
+ import Button from '../../primitives/Button.svelte'
8
+
9
+ const { disabled = false, maxBytes = 5 * 1024 * 1024, onrecord, onactive }: {
10
+ disabled?: boolean
11
+ maxBytes?: number
12
+ onrecord: (file: File) => Promise<void>
13
+ onactive: (active: boolean) => void
14
+ } = $props()
15
+ let supported = $state(false)
16
+ let expanded = $state(false)
17
+ let active = $state(false)
18
+ let busy = $state(false)
19
+ let seconds = $state(0)
20
+ let error = $state('')
21
+ let recorder: MediaRecorder | undefined
22
+ let stream: MediaStream | undefined
23
+ let timer: ReturnType<typeof setInterval> | undefined
24
+ let mounted = true
25
+ let cancelled = false
26
+
27
+ function release() {
28
+ clearInterval(timer)
29
+ timer = undefined
30
+ for (const track of stream?.getTracks() ?? [])
31
+ track.stop()
32
+ stream = undefined
33
+ }
34
+ function stop(discard = false) {
35
+ cancelled ||= discard
36
+ if (recorder?.state === 'recording') {
37
+ recorder.stop()
38
+ // 正常停止先让编码器发送最终数据;取消/卸载立即释放,正常路径由 onstop 释放。
39
+ if (!discard)
40
+ return
41
+ }
42
+ release()
43
+ }
44
+ async function start() {
45
+ if (busy || active || disabled)
46
+ return
47
+ busy = true
48
+ error = ''
49
+ cancelled = false
50
+ try {
51
+ // 必须直接来自点击事件,保留浏览器的用户激活授权。
52
+ const selected = await navigator.mediaDevices.getDisplayMedia({ video: { width: 1280, height: 720, frameRate: 10 }, audio: false })
53
+ if (!mounted) {
54
+ selected.getTracks().forEach(track => track.stop())
55
+ return
56
+ }
57
+ stream = selected
58
+ const mimeType = ['video/webm;codecs=vp8', 'video/webm', 'video/mp4'].find(type => MediaRecorder.isTypeSupported(type))
59
+ if (!mimeType)
60
+ throw new Error('No supported recording format')
61
+ const current = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 500_000 })
62
+ recorder = current
63
+ const chunks: Blob[] = []
64
+ let size = 0
65
+ current.ondataavailable = (event) => {
66
+ if (event.data.size) {
67
+ chunks.push(event.data)
68
+ size += event.data.size
69
+ if (size >= maxBytes * 0.9)
70
+ stop()
71
+ }
72
+ }
73
+ current.onerror = (event) => {
74
+ cancelled = true
75
+ error = errorMessage('error' in event ? event.error : new Error('MediaRecorder failed'), uiM('feedback_record_failed'))
76
+ stop(true)
77
+ }
78
+ current.onstart = () => {
79
+ // 原生编码器可能延迟启动;录制时长必须从实际开始采集时计算。
80
+ if (!mounted || cancelled || current.state !== 'recording')
81
+ return
82
+ const started = Date.now()
83
+ timer = setInterval(() => {
84
+ seconds = Math.floor((Date.now() - started) / 1000)
85
+ if (seconds >= 60)
86
+ stop()
87
+ }, 250)
88
+ }
89
+ current.onstop = async () => {
90
+ release()
91
+ active = false
92
+ busy = true
93
+ try {
94
+ if (!mounted || cancelled)
95
+ return
96
+ if (!size || size > maxBytes) {
97
+ error = errorMessage(new Error('Recording output was empty or exceeded budget', { cause: { size, maxBytes, seconds, mimeType } }), uiM('feedback_record_empty'))
98
+ return
99
+ }
100
+ const type = mimeType.split(';')[0]!
101
+ await onrecord(new File(chunks, `recording-${Date.now()}.${type === 'video/mp4' ? 'mp4' : 'webm'}`, { type }))
102
+ expanded = false
103
+ }
104
+ catch (cause) {
105
+ error = errorMessage(cause, uiM('feedback_record_failed'))
106
+ }
107
+ finally {
108
+ busy = false
109
+ if (mounted)
110
+ onactive(false)
111
+ }
112
+ }
113
+ for (const track of stream.getVideoTracks())
114
+ track.addEventListener('ended', () => stop(), { once: true })
115
+ current.start(1000)
116
+ seconds = 0
117
+ active = true
118
+ onactive(true)
119
+ }
120
+ catch (cause) {
121
+ release()
122
+ error = errorMessage(cause, uiM('feedback_record_failed'))
123
+ }
124
+ finally {
125
+ busy = false
126
+ }
127
+ }
128
+
129
+ onMount(() => {
130
+ supported = typeof MediaRecorder !== 'undefined' && typeof navigator.mediaDevices?.getDisplayMedia === 'function'
131
+ return () => {
132
+ mounted = false
133
+ stop(true)
134
+ }
135
+ })
136
+ </script>
137
+
138
+ <div class='space-y-2 min-w-0'>
139
+ <Button size='sm' variant='ghost' disabled={disabled || active || busy} onclick={() => expanded = !expanded}>{uiM('feedback_record')}</Button>
140
+ {#if expanded}
141
+ <p class='text-xs text-base-content/65'>{supported ? uiM('feedback_record_hint', { size: (maxBytes / 1048576).toFixed(1) }) : uiM('feedback_record_unsupported')}</p>
142
+ {#if supported}<Button size='sm' loading={busy} disabled={disabled || active} onclick={start}>{uiM('feedback_record_start')}</Button>{/if}
143
+ {/if}
144
+ {#if error}<p class='text-error text-sm break-words' role='alert'>{error}</p>{/if}
145
+ </div>
146
+ {#if active}
147
+ <div use:portal class='fixed bottom-4 inset-x-4 z-[1200] mx-auto flex max-w-xl flex-wrap items-center justify-between gap-3 rounded-xl border border-error/25 bg-base-100 p-4 shadow-xl' data-feedback-ignore='true'>
148
+ <p class='text-sm' role='status'>{uiM('feedback_recording', { seconds })}</p>
149
+ <div class='flex gap-2'>
150
+ <Button size='sm' variant='ghost' onclick={() => stop(true)}>{uiM('feedback_record_cancel')}</Button>
151
+ <Button size='sm' variant='error' onclick={() => stop()}>{uiM('feedback_record_stop')}</Button>
152
+ </div>
153
+ </div>
154
+ {/if}
@@ -0,0 +1,9 @@
1
+ type $$ComponentProps = {
2
+ disabled?: boolean;
3
+ maxBytes?: number;
4
+ onrecord: (file: File) => Promise<void>;
5
+ onactive: (active: boolean) => void;
6
+ };
7
+ declare const FeedbackRecorder: import("svelte").Component<$$ComponentProps, {}, "">;
8
+ type FeedbackRecorder = ReturnType<typeof FeedbackRecorder>;
9
+ export default FeedbackRecorder;