@hosty-sdk/app 0.39.0 → 0.41.1

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 (43) hide show
  1. package/README.md +4 -2
  2. package/dist/feedback-capture.d.ts +5 -1
  3. package/dist/feedback-capture.js +41 -2
  4. package/dist/feedback-channel.d.ts +91 -0
  5. package/dist/feedback-channel.js +187 -0
  6. package/dist/feedback-client.d.ts +8 -0
  7. package/dist/feedback-client.js +26 -0
  8. package/dist/feedback-draft.d.ts +1 -5
  9. package/dist/feedback-draft.js +0 -31
  10. package/dist/feedback-react.d.ts +6 -2
  11. package/dist/feedback-react.js +235 -357
  12. package/dist/feedback-rpc.d.ts +7 -0
  13. package/dist/feedback-rpc.js +42 -0
  14. package/dist/feedback-workspace.d.ts +13 -0
  15. package/dist/feedback-workspace.js +28 -0
  16. package/dist/sdk-chrome.d.ts +1 -1
  17. package/dist/sdk-chrome.js +4 -0
  18. package/dist/ui-embedded.d.ts +10 -0
  19. package/dist/ui-embedded.js +61 -0
  20. package/dist/ui-frame.js +1 -0
  21. package/dist/ui-host.d.ts +15 -2
  22. package/dist/ui-host.js +128 -27
  23. package/dist/ui-navigation-react.js +9 -4
  24. package/dist/ui-react.d.ts +5 -1
  25. package/dist/ui-react.js +59 -15
  26. package/dist/ui-server.d.ts +2 -0
  27. package/dist/ui-server.js +28 -3
  28. package/dist/ui-standalone-context.d.ts +8 -0
  29. package/dist/ui-standalone-context.js +3 -0
  30. package/dist/ui-standalone-preferences.d.ts +17 -0
  31. package/dist/ui-standalone-preferences.js +77 -0
  32. package/dist/ui-standalone-react.d.ts +24 -0
  33. package/dist/ui-standalone-react.js +47 -0
  34. package/dist/ui-transport.js +1 -1
  35. package/dist/ui-types.d.ts +5 -0
  36. package/dist/ui-workspaces.d.ts +7 -0
  37. package/dist/ui-workspaces.js +1 -1
  38. package/dist/ui.d.ts +1 -0
  39. package/package.json +5 -1
  40. package/dist/feedback-audio.d.ts +0 -3
  41. package/dist/feedback-audio.js +0 -40
  42. package/dist/feedback-speech.d.ts +0 -6
  43. package/dist/feedback-speech.js +0 -119
@@ -1,390 +1,268 @@
1
1
  "use client";
2
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { useEffect, useRef, useState } from "react";
4
- import { createPortal } from "react-dom";
5
- import { APP_SESSION_RESTORED, appFetch } from "./browser-auth.js";
6
- import { SdkChromeStyles } from "./sdk-chrome.js";
7
- import { blankDraft, deleteDraft, draftKey, makeNote, readDraft, saveDraft, submission } from "./feedback-draft.js";
8
- import { FeedbackSpeech } from "./feedback-speech.js";
9
- import { captureStill, cropStill } from "./feedback-capture.js";
10
- function useBlobUrl(blob) {
11
- const [url, setUrl] = useState("");
12
- useEffect(() => { if (!blob) {
13
- setUrl("");
14
- return;
15
- } const value = URL.createObjectURL(blob); setUrl(value); return () => URL.revokeObjectURL(value); }, [blob]);
16
- return url;
17
- }
18
- function ImagePreview({ blob }) { const url = useBlobUrl(blob); return url ? _jsx("img", { src: url, alt: "Included screenshot" }) : null; }
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { createPortal } from 'react-dom';
5
+ import { APP_SESSION_RESTORED, appFetch } from './browser-auth.js';
6
+ import { FEEDBACK_ROOT, feedbackScope, validCapabilities, validDraft } from './feedback-channel.js';
7
+ import { readDraft, deleteDraft, submission } from './feedback-draft.js';
19
8
  const rect = (b) => ({ x: b.x, y: b.y, width: b.width, height: b.height });
20
9
  const viewport = () => ({ width: innerWidth, height: innerHeight, scale: devicePixelRatio });
21
- const errorMessage = (e) => e instanceof Error ? e.message : "Feedback could not be saved.";
22
- export function FeedbackCapture({ active, uiPath = "/api/hosty/ui" }) {
23
- const [capabilities, setCapabilities] = useState(null);
24
- const [unavailable, setUnavailable] = useState("");
25
- const [retry, setRetry] = useState(0);
10
+ function note(target) { return { id: crypto.randomUUID(), text: '', route: location.pathname + location.search, capturedAt: new Date().toISOString(), target }; }
11
+ /** Selection and source-authenticated intake only. The tool application owns all form UI/storage. */
12
+ export function FeedbackCapture({ active, uiPath = '/api/hosty/ui', client }) {
13
+ const [capabilities, setCapabilities] = useState(null), [retry, setRetry] = useState(0);
14
+ const pickMode = useRef(null), priorCursor = useRef(null), resetPick = useRef(() => { });
15
+ const pinned = useRef(false), highlightExpiry = useRef(undefined);
16
+ const outlineFrame = useRef(undefined);
17
+ const selections = useRef(new Map());
18
+ const remember = (chosen, element) => {
19
+ selections.current.set(chosen.id, { element, route: location.href });
20
+ if (selections.current.size > 20)
21
+ selections.current.delete(selections.current.keys().next().value);
22
+ return chosen;
23
+ };
24
+ const clearPinned = () => { pinned.current = false; clearTimeout(highlightExpiry.current); if (outlineFrame.current !== undefined)
25
+ cancelAnimationFrame(outlineFrame.current); };
26
+ const [highlight, setHighlight] = useState(null);
27
+ const pending = useRef(null);
28
+ const path = uiPath.replace(/\/$/, '') + '/feedback';
29
+ const finish = (value) => { clearPinned(); const done = pending.current; pending.current = null; pickMode.current = null; resetPick.current(); if (priorCursor.current !== null)
30
+ document.documentElement.style.cursor = priorCursor.current; priorCursor.current = null; setHighlight(null); done?.(value); };
26
31
  useEffect(() => { const refresh = () => setRetry(r => r + 1); window.addEventListener(APP_SESSION_RESTORED, refresh); return () => window.removeEventListener(APP_SESSION_RESTORED, refresh); }, []);
27
- const path = uiPath.replace(/\/$/, "") + "/feedback";
28
32
  useEffect(() => {
29
33
  setCapabilities(null);
30
- setUnavailable("");
31
34
  if (!active)
32
35
  return;
33
36
  const controller = new AbortController();
34
- void appFetch(path, { signal: controller.signal }).then(async (response) => {
35
- if (!response.ok)
36
- throw new Error(response.status === 404 ? "Update Core and this app to enable feedback." : "Feedback is unavailable. Retry when access is restored.");
37
- const value = await response.json();
38
- if (value.version !== 1 || !value.userId || !value.appId || !value.installation || !value.coreId)
39
- throw new Error("Feedback capability response is incompatible.");
40
- if (!controller.signal.aborted)
41
- setCapabilities(value);
42
- }).catch(e => { if (!controller.signal.aborted)
43
- setUnavailable(errorMessage(e)); });
37
+ void appFetch(path, { signal: controller.signal }).then(async (r) => {
38
+ if (r.ok) {
39
+ const c = await r.json();
40
+ if (validCapabilities(c) && !controller.signal.aborted)
41
+ setCapabilities(c);
42
+ }
43
+ }).catch(() => { });
44
44
  return () => controller.abort();
45
45
  }, [active, path, retry]);
46
- if (!active || typeof document === "undefined")
47
- return null;
48
- return capabilities ? _jsx(FeedbackEditor, { capabilities: capabilities, path: path }, draftKey(capabilities))
49
- : unavailable ? createPortal(_jsxs("div", { "data-hosty-feedback": true, "data-hosty-sdk": true, className: "hosty-feedback-launch", children: [_jsx(SdkChromeStyles, {}), _jsx("button", { title: unavailable, onClick: () => setRetry(r => r + 1), children: "Retry feedback" })] }), document.body) : null;
50
- }
51
- function FeedbackEditor({ capabilities, path }) {
52
- const [dictating, setDictating] = useState(false);
53
- const [reviewTargets, setReviewTargets] = useState([]);
54
- const key = draftKey(capabilities);
55
- const [draft, setDraft] = useState(() => blankDraft(key));
56
- const current = useRef(draft), savedRevision = useRef(0), savedRequestId = useRef(null), queue = useRef(Promise.resolve()), saveFailure = useRef(null);
57
- const live = useRef(true);
58
- const [ready, setReady] = useState(false), [open, setOpen] = useState(false), [saving, setSaving] = useState(false);
59
- const [error, setError] = useState(""), [notice, setNotice] = useState(""), [busy, setBusy] = useState(false);
60
- const [picking, setPicking] = useState(null);
61
- const [highlight, setHighlight] = useState(null);
62
- const [edit, setEdit] = useState(null);
63
- const [hidden, setHidden] = useState(false), [capturing, setCapturing] = useState(false);
64
- const [preview, setPreview] = useState(null);
65
- const elements = useRef(new Map());
66
- const capture = useRef(null);
67
- const root = useRef(null);
68
46
  useEffect(() => {
69
- live.current = true;
70
- void readDraft(key).then(value => {
71
- if (!live.current)
72
- return;
73
- if (value) {
74
- current.current = value;
75
- savedRevision.current = value.revision;
76
- savedRequestId.current = value.requestId;
77
- setDraft(value);
78
- setNotice("Saved draft restored.");
79
- }
80
- }).catch(e => { if (live.current)
81
- setError(errorMessage(e)); }).finally(() => { if (live.current)
82
- setReady(true); });
83
- return () => { live.current = false; capture.current?.abort(); };
84
- }, [key]);
85
- function update(change) {
86
- const next = { ...current.current, ...change, revision: current.current.revision + 1 };
87
- current.current = next;
88
- setDraft(next);
89
- setSaving(true);
90
- setNotice("");
91
- queue.current = queue.current.then(async () => {
92
- try {
93
- await saveDraft(next, savedRevision.current, savedRequestId.current);
94
- savedRevision.current = next.revision;
95
- savedRequestId.current = next.requestId;
96
- saveFailure.current = null;
97
- if (live.current) {
98
- setError("");
99
- setSaving(current.current.revision !== next.revision);
47
+ if (!active || !capabilities || !client)
48
+ return;
49
+ let live = true;
50
+ const invoke = async (o) => {
51
+ if (!live)
52
+ throw new Error('The source document is no longer active.');
53
+ const key = feedbackScope(capabilities), route = location.href;
54
+ switch (o.action) {
55
+ case 'pick':
56
+ finish(null);
57
+ pickMode.current = o.mode ?? 'element';
58
+ priorCursor.current = document.documentElement.style.cursor;
59
+ document.documentElement.style.cursor = 'crosshair';
60
+ return new Promise(resolve => { pending.current = resolve; });
61
+ case 'cancel':
62
+ finish(null);
63
+ return null;
64
+ case 'page': return note({ kind: 'page', label: 'Page comment', viewport: viewport() });
65
+ case 'highlight': {
66
+ clearPinned();
67
+ const selected = o.requestId ? selections.current.get(o.requestId) : undefined;
68
+ if (o.target?.bounds && o.requestId && (!selected || selected.route !== location.href || selected.element?.isConnected === false))
69
+ throw new Error('The selected element is no longer visible. Select it again to capture a screenshot.');
70
+ pinned.current = !!o.target?.bounds;
71
+ setHighlight(o.target?.bounds ?? null);
72
+ if (pinned.current) {
73
+ // Follow layout changes until the frame is captured instead of outlining
74
+ // the selected element's former position.
75
+ const follow = () => {
76
+ if (!pinned.current || !selected?.element)
77
+ return;
78
+ if (!selected.element.isConnected) {
79
+ clearPinned();
80
+ setHighlight(null);
81
+ return;
82
+ }
83
+ const bounds = rect(selected.element.getBoundingClientRect());
84
+ setHighlight(current => current && Object.keys(bounds).every(k => current[k] === bounds[k]) ? current : bounds);
85
+ outlineFrame.current = requestAnimationFrame(follow);
86
+ };
87
+ follow();
88
+ highlightExpiry.current = setTimeout(() => { clearPinned(); setHighlight(null); }, 10000);
89
+ }
90
+ return null;
100
91
  }
101
- }
102
- catch (e) {
103
- saveFailure.current = new Error(errorMessage(e));
104
- if (live.current) {
105
- setSaving(false);
106
- setError("Not saved locally: " + errorMessage(e));
92
+ case 'crop-target': {
93
+ clearPinned();
94
+ setHighlight(null);
95
+ const api = globalThis;
96
+ return api.CropTarget?.fromElement(document.documentElement) ?? null;
97
+ }
98
+ case 'legacy-read': {
99
+ const d = await readDraft(key);
100
+ return d && validDraft(d) ? d : null;
101
+ }
102
+ case 'legacy-delete':
103
+ if (o.requestId && o.revision !== undefined)
104
+ await deleteDraft(key, o.requestId, o.revision);
105
+ return null;
106
+ case 'submit': {
107
+ if (!o.draft || !validDraft(o.draft) || o.draft.key !== key)
108
+ throw new Error('Feedback belongs to a different source or account.');
109
+ const body = JSON.stringify(await submission(o.draft));
110
+ if (!live || route !== location.href)
111
+ throw new Error('The source document changed before submission.');
112
+ const response = await appFetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body });
113
+ const result = await response.json().catch(() => null);
114
+ let reviewTargets = [];
115
+ if (response.ok && capabilities.administrator && result?.status === 'submitted' && typeof result.id === 'string') {
116
+ try {
117
+ const review = await appFetch(path + '/' + encodeURIComponent(result.id) + '/review-targets');
118
+ if (review.ok)
119
+ reviewTargets = (await review.json()).targets ?? [];
120
+ }
121
+ catch { /* Submission is already durable; review links are optional. */ }
122
+ }
123
+ return { ok: response.ok, status: response.status, result, reviewTargets };
107
124
  }
125
+ default: throw new Error('Unsupported capture operation.');
108
126
  }
127
+ };
128
+ const register = () => {
129
+ if ('feedback' in client) {
130
+ const bootstrap = client.getSnapshot().bootstrap;
131
+ const own = bootstrap?.app;
132
+ if (bootstrap?.userId !== capabilities.userId || own?.appId !== capabilities.appId || own.installationId !== capabilities.installation)
133
+ return;
134
+ client.feedback.register({ id: FEEDBACK_ROOT, capabilities, label: document.title || capabilities.appId, route: location.pathname, workspaceId: 'default', visible: () => live, invoke });
135
+ }
136
+ else
137
+ client.registerFeedbackSource(capabilities, invoke);
138
+ };
139
+ let registeredRoute = location.href;
140
+ const stopNavigation = client.subscribeNavigation(() => {
141
+ if (location.href !== registeredRoute) {
142
+ registeredRoute = location.href;
143
+ selections.current.clear();
144
+ finish(null);
145
+ }
146
+ register();
109
147
  });
110
- }
111
- async function flush() { await queue.current; if (saveFailure.current)
112
- throw saveFailure.current; }
113
- function noteChange(id, change) {
114
- if (current.current.submitting)
115
- return;
116
- update({ annotations: current.current.annotations.map(n => n.id === id ? { ...n, ...change } : n) });
117
- }
118
- function add(target, element) {
119
- if (current.current.annotations.length >= capabilities.maxAnnotations) {
120
- setError("A report can contain at most 20 annotations.");
121
- return;
122
- }
123
- const note = makeNote(target);
124
- if (element)
125
- elements.current.set(note.id, element);
126
- update({ annotations: [...current.current.annotations, note] });
127
- setEdit({ id: note.id, where: "anchor" });
128
- setPicking(null);
129
- setHighlight(target.bounds ?? null);
130
- }
148
+ register();
149
+ const unsubscribe = client.subscribe(event => {
150
+ if (event.type === 'environment' && event.value.connection === 'connected')
151
+ register();
152
+ });
153
+ return () => {
154
+ live = false;
155
+ finish(null);
156
+ stopNavigation();
157
+ unsubscribe();
158
+ if ('feedback' in client)
159
+ client.feedback.remove(FEEDBACK_ROOT);
160
+ else
161
+ client.unregisterFeedbackSource();
162
+ };
163
+ }, [active, capabilities, client, path]);
131
164
  useEffect(() => {
132
- if (!picking || draft.submitting || !open)
165
+ if (!active)
133
166
  return;
134
167
  let start = null;
135
- const inside = (event) => event.composedPath().some(node => node instanceof Element && node.hasAttribute("data-hosty-feedback"));
136
- const move = (event) => {
137
- if (inside(event))
168
+ const inside = (event) => event.composedPath().some(n => n instanceof Element && n.hasAttribute('data-hosty-feedback-control'));
169
+ const clearHover = () => { start = null; if (!pinned.current)
170
+ setHighlight(null); };
171
+ resetPick.current = clearHover;
172
+ const leaves = (e) => {
173
+ if (!(e.relatedTarget instanceof Element) || e.relatedTarget instanceof HTMLIFrameElement || e.relatedTarget.ownerDocument !== document)
174
+ clearHover();
175
+ };
176
+ const move = (e) => {
177
+ if (!pickMode.current)
178
+ return;
179
+ if (inside(e)) {
180
+ clearHover();
138
181
  return;
139
- if (picking === "region" && start)
140
- setHighlight({ x: Math.min(start.x, event.clientX), y: Math.min(start.y, event.clientY),
141
- width: Math.abs(event.clientX - start.x), height: Math.abs(event.clientY - start.y) });
142
- else if (picking === "element") {
143
- const element = document.elementFromPoint(event.clientX, event.clientY);
144
- if (element)
145
- setHighlight(rect(element.getBoundingClientRect()));
182
+ }
183
+ if (pickMode.current === 'region' && start)
184
+ setHighlight({ x: Math.min(start.x, e.clientX), y: Math.min(start.y, e.clientY), width: Math.abs(start.x - e.clientX), height: Math.abs(start.y - e.clientY) });
185
+ else if (pickMode.current === 'element') {
186
+ const element = document.elementFromPoint(e.clientX, e.clientY);
187
+ setHighlight(element && !(element instanceof HTMLIFrameElement) ? rect(element.getBoundingClientRect()) : null);
146
188
  }
147
189
  };
148
- const down = (event) => {
149
- if (inside(event))
190
+ let stopClickGuard = () => { };
191
+ const down = (e) => {
192
+ stopClickGuard();
193
+ if (!pickMode.current)
150
194
  return;
151
- event.preventDefault();
152
- event.stopImmediatePropagation();
153
- // React may remove the picker effect before the native click follows pointerup.
154
- const swallow = (click) => { click.preventDefault(); click.stopImmediatePropagation(); cleanup(); };
155
- const cleanup = () => { document.removeEventListener("click", swallow, true); clearTimeout(timer); };
156
- const timer = setTimeout(cleanup, 1500);
157
- document.addEventListener("click", swallow, { capture: true, once: true });
158
- if (picking === "region") {
159
- start = { x: event.clientX, y: event.clientY };
195
+ if (inside(e))
160
196
  return;
161
- }
162
- const element = document.elementFromPoint(event.clientX, event.clientY);
163
- if (!element)
197
+ const element = document.elementFromPoint(e.clientX, e.clientY);
198
+ if (!element || element instanceof HTMLIFrameElement)
199
+ return;
200
+ e.preventDefault();
201
+ e.stopImmediatePropagation();
202
+ let released = false;
203
+ let timer;
204
+ const swallow = (click) => {
205
+ // A region drag may click the common ancestor of its down/up targets. The next
206
+ // pointerdown clears this guard, so a later unrelated gesture is never swallowed.
207
+ if (released || click.composedPath().includes(element)) {
208
+ click.preventDefault();
209
+ click.stopImmediatePropagation();
210
+ }
211
+ cleanup();
212
+ };
213
+ const releasedPointer = () => { released = true; timer = setTimeout(cleanup, 0); };
214
+ const cleanup = () => {
215
+ document.removeEventListener('click', swallow, true);
216
+ window.removeEventListener('pointerup', releasedPointer, true);
217
+ document.removeEventListener('pointercancel', cleanup, true);
218
+ clearTimeout(timer);
219
+ };
220
+ stopClickGuard = cleanup;
221
+ document.addEventListener('click', swallow, { capture: true, once: true });
222
+ window.addEventListener('pointerup', releasedPointer, { capture: true, once: true });
223
+ document.addEventListener('pointercancel', cleanup, { capture: true, once: true });
224
+ if (pickMode.current === 'region') {
225
+ start = { x: e.clientX, y: e.clientY };
164
226
  return;
165
- // Never read input values, text content, or arbitrary data attributes into evidence.
166
- const label = element.getAttribute("aria-label")?.slice(0, 200) || element.tagName.toLowerCase();
167
- const selector = element.id ? "#" + CSS.escape(element.id) : element.tagName.toLowerCase();
168
- add({ kind: "element", label, selector, bounds: rect(element.getBoundingClientRect()), viewport: viewport() }, element);
227
+ }
228
+ const chosen = note({ kind: 'element', label: element.getAttribute('aria-label')?.slice(0, 200) || element.tagName.toLowerCase(), selector: element.id ? '#' + CSS.escape(element.id) : element.tagName.toLowerCase(), bounds: rect(element.getBoundingClientRect()), viewport: viewport() });
229
+ finish(remember(chosen, element));
169
230
  };
170
- const up = (event) => {
171
- if (!start)
231
+ const up = (e) => {
232
+ if (!pickMode.current || !start)
172
233
  return;
173
- event.preventDefault();
174
- event.stopImmediatePropagation();
175
- const b = { x: Math.min(start.x, event.clientX), y: Math.min(start.y, event.clientY),
176
- width: Math.abs(event.clientX - start.x), height: Math.abs(event.clientY - start.y) };
234
+ e.preventDefault();
235
+ e.stopImmediatePropagation();
236
+ const b = { x: Math.min(start.x, e.clientX), y: Math.min(start.y, e.clientY), width: Math.abs(start.x - e.clientX), height: Math.abs(start.y - e.clientY) };
177
237
  start = null;
178
238
  if (b.width > 3 && b.height > 3)
179
- add({ kind: "region", label: "Selected region", bounds: b, viewport: viewport() });
239
+ finish(remember(note({ kind: 'region', label: 'Selected region', bounds: b, viewport: viewport() })));
180
240
  };
181
- const click = (event) => { if (!inside(event)) {
182
- event.preventDefault();
183
- event.stopImmediatePropagation();
184
- } };
185
- const escape = (event) => { if (event.key === "Escape") {
186
- setPicking(null);
187
- setHighlight(null);
188
- } };
189
- document.addEventListener("pointermove", move, true);
190
- document.addEventListener("pointerdown", down, true);
191
- document.addEventListener("pointerup", up, true);
192
- document.addEventListener("click", click, true);
193
- document.addEventListener("keydown", escape, true);
194
- const old = document.documentElement.style.cursor;
195
- document.documentElement.style.cursor = "crosshair";
196
- return () => {
197
- document.removeEventListener("pointermove", move, true);
198
- document.removeEventListener("pointerdown", down, true);
199
- document.removeEventListener("pointerup", up, true);
200
- document.removeEventListener("click", click, true);
201
- document.removeEventListener("keydown", escape, true);
202
- document.documentElement.style.cursor = old;
241
+ const click = (e) => {
242
+ if (pickMode.current && !inside(e)) {
243
+ e.preventDefault();
244
+ e.stopImmediatePropagation();
245
+ }
203
246
  };
204
- }, [picking, draft.submitting, open]);
205
- const selected = draft.annotations.find(n => n.id === edit?.id);
206
- useEffect(() => {
207
- if (picking || !edit || !open)
208
- return;
209
- const refresh = () => {
210
- const element = elements.current.get(edit.id);
211
- setHighlight(element?.isConnected ? rect(element.getBoundingClientRect()) : current.current.annotations.find(n => n.id === edit.id)?.target?.bounds ?? null);
247
+ const key = (e) => { if (pickMode.current && e.key === 'Escape') {
248
+ e.preventDefault();
249
+ e.stopPropagation();
250
+ finish(null);
251
+ } };
252
+ const visibility = () => {
253
+ if (document.visibilityState !== 'visible')
254
+ clearHover();
212
255
  };
213
- refresh();
214
- window.addEventListener("scroll", refresh, true);
215
- window.addEventListener("resize", refresh);
216
- return () => { window.removeEventListener("scroll", refresh, true); window.removeEventListener("resize", refresh); };
217
- }, [edit, picking, open]);
218
- async function done() {
219
- setEdit(null);
220
- setHighlight(null);
221
- try {
222
- await flush();
223
- }
224
- catch (e) {
225
- setError(errorMessage(e));
226
- }
227
- }
228
- async function screenshot(id) {
229
- if (capture.current || draft.submitting)
230
- return;
231
- const operation = new AbortController();
232
- capture.current = operation;
233
- setCapturing(true);
234
- setError("");
235
- try {
236
- const blob = await captureStill(value => { if (root.current)
237
- root.current.style.visibility = value ? "hidden" : ""; setHidden(value); }, operation.signal);
238
- if (live.current && !operation.signal.aborted)
239
- setPreview({ id, blob });
240
- }
241
- catch (e) {
242
- if (live.current && !operation.signal.aborted)
243
- setError(errorMessage(e));
244
- }
245
- finally {
246
- if (capture.current === operation)
247
- capture.current = null;
248
- if (live.current)
249
- setCapturing(false);
250
- }
251
- }
252
- async function acceptImage(blob) {
253
- if (!preview)
254
- return;
255
- if (blob.size > capabilities.maxImageBytes) {
256
- setError("Crop a smaller area: each screenshot must fit within 2 MiB.");
257
- return;
258
- }
259
- const total = current.current.annotations.filter(n => n.id !== preview.id).reduce((sum, n) => sum + (n.image?.size ?? 0), 0) + blob.size;
260
- if (total > capabilities.maxTotalImageBytes) {
261
- setError("Screenshots may total at most 8 MiB. Remove or crop an existing image.");
262
- return;
263
- }
264
- noteChange(preview.id, { image: blob });
265
- setPreview(null);
266
- }
267
- async function send() {
268
- if (busy || !current.current.annotations.length || current.current.annotations.some(n => !n.text.trim()))
269
- return;
270
- setBusy(true);
271
- setError("");
272
- try {
273
- update({ submitting: true });
274
- await flush();
275
- const frozen = current.current;
276
- const response = await appFetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(await submission(frozen)) });
277
- const result = await response.json().catch(() => null);
278
- if (!response.ok) {
279
- if ([400, 413, 415].includes(response.status))
280
- update({ submitting: false, requestId: crypto.randomUUID() });
281
- throw new Error(result?.message ?? "Submission was not confirmed. Retry the same feedback; your draft is retained.");
282
- }
283
- if (!result || !["submitted", "deleted"].includes(result.status ?? ""))
284
- throw new Error("Submission was not confirmed. Retry the same feedback.");
285
- await deleteDraft(key, frozen.requestId, frozen.revision);
286
- const fresh = blankDraft(key);
287
- savedRevision.current = 0;
288
- savedRequestId.current = null;
289
- current.current = fresh;
290
- setDraft(fresh);
291
- setReviewTargets([]);
292
- if (capabilities.administrator && result.status === "submitted" && result.id) {
293
- void appFetch(path + "/" + encodeURIComponent(result.id) + "/review-targets").then(async (response) => {
294
- if (!response.ok)
295
- return;
296
- const value = await response.json();
297
- if (live.current)
298
- setReviewTargets(value.targets ?? []);
299
- }).catch(() => undefined);
300
- }
301
- setEdit(null);
302
- setHighlight(null);
303
- setNotice(result.status === "deleted" ? "This feedback was already submitted and subsequently removed with its workspace." : "Feedback submitted.");
304
- }
305
- catch (e) {
306
- setError(errorMessage(e));
307
- }
308
- finally {
309
- if (live.current)
310
- setBusy(false);
311
- }
312
- }
313
- async function discard() {
314
- if (!window.confirm(current.current.submitting ? "This submission may already exist. Discard its local retry record? This does not delete a submitted feedback." : "Discard this local feedback draft and its screenshots?"))
315
- return;
316
- try {
317
- await queue.current;
318
- await deleteDraft(key, current.current.requestId, savedRevision.current);
319
- const fresh = blankDraft(key);
320
- savedRevision.current = 0;
321
- savedRequestId.current = null;
322
- saveFailure.current = null;
323
- current.current = fresh;
324
- setDraft(fresh);
325
- setEdit(null);
326
- setHighlight(null);
327
- setError("");
328
- setNotice("Draft discarded.");
329
- }
330
- catch (e) {
331
- setError(errorMessage(e));
332
- }
333
- }
334
- function editor(note) {
335
- return _jsxs(_Fragment, { children: [_jsxs("label", { children: ["Comment", _jsx("textarea", { "aria-label": "Comment", autoFocus: true, maxLength: 2000, value: note.text, disabled: draft.submitting, onChange: event => noteChange(note.id, { text: event.target.value }), placeholder: "What should change here?" })] }), _jsx(FeedbackSpeech, { path: path, disabled: draft.submitting, onBusyChange: setDictating, onText: text => {
336
- const old = current.current.annotations.find(n => n.id === note.id);
337
- if (!old)
338
- return;
339
- const next = [old.text, text].filter(Boolean).join(" ");
340
- if (next.length > 2000) {
341
- setError("Dictation exceeds the comment limit. Shorten the comment before dictating again.");
342
- return;
343
- }
344
- noteChange(note.id, { text: next });
345
- } }), _jsxs("div", { className: "hf-actions", children: [_jsx("button", { onClick: () => void screenshot(note.id), disabled: capturing || draft.submitting, children: "Add screenshot" }), _jsx("button", { disabled: dictating, onClick: () => void done(), children: "Done" })] })] });
346
- }
347
- const popup = { left: Math.max(12, Math.min(highlight?.x ?? 24, innerWidth - 340)),
348
- top: Math.max(12, Math.min((highlight?.y ?? 40) + (highlight?.height ?? 0) + 12, innerHeight - 250)) };
349
- if (!ready)
350
- return null;
351
- return createPortal(_jsxs("div", { ref: root, "data-hosty-feedback": true, "data-hosty-sdk": true, style: { visibility: hidden ? "hidden" : undefined }, children: [_jsx(SdkChromeStyles, {}), _jsx("style", { children: feedbackStyles }), !open && _jsxs("button", { className: "hosty-feedback-launch", onClick: () => setOpen(true), children: ["Annotate", draft.annotations.length ? " · " + draft.annotations.length : ""] }), open && _jsxs(_Fragment, { children: [picking && _jsxs("div", { className: "hosty-feedback-launch", role: "status", children: [picking === "element" ? "Select an element" : "Drag a region", " \u00B7 Escape cancels ", _jsx("button", { onClick: () => { setPicking(null); setHighlight(null); }, children: "Cancel selection" })] }), _jsxs("aside", { className: "hf-panel", "aria-label": "Feedback draft", style: { visibility: picking ? "hidden" : undefined,
352
- ...(edit?.where === "anchor" && highlight && highlight.x > innerWidth - 400 ? { left: 12, right: "auto" } : {}) }, children: [_jsxs("header", { children: [_jsxs("div", { children: [_jsx("strong", { children: "Feedback" }), _jsx("small", { children: saving ? "Saving…" : saveFailure.current ? "Not saved locally" : draft.revision ? "Saved locally" : "New report" })] }), _jsx("button", { "aria-label": "Close feedback", onClick: () => { setOpen(false); setPicking(null); capture.current?.abort(); }, children: "\u00D7" })] }), _jsx("p", { children: "Collect related comments, then send them as one feedback." }), _jsxs("div", { className: "hf-actions", children: [_jsx("button", { disabled: draft.submitting, "aria-pressed": picking === "element", onClick: () => { setEdit(null); setPicking("element"); }, children: "Select element" }), _jsx("button", { disabled: draft.submitting, "aria-pressed": picking === "region", onClick: () => { setEdit(null); setPicking("region"); }, children: "Select region" }), _jsx("button", { disabled: draft.submitting, onClick: () => add({ kind: "page", label: "This page", viewport: viewport() }), children: "Page comment" })] }), picking && _jsxs("p", { role: "status", children: [picking === "element" ? "Click an element to annotate it." : "Drag over the area to annotate.", " Escape cancels selection."] }), _jsx("ol", { children: draft.annotations.map((note, index) => _jsxs("li", { children: [_jsxs("div", { className: "hf-note-heading", children: [_jsxs("button", { onClick: () => { setPicking(null); setEdit({ id: note.id, where: "anchor" }); elements.current.get(note.id)?.scrollIntoView({ block: "nearest" }); }, children: [index + 1, ". ", note.target?.label ?? "Annotation"] }), _jsx("button", { disabled: draft.submitting, onClick: () => { update({ annotations: current.current.annotations.filter(n => n.id !== note.id) }); if (edit?.id === note.id)
353
- setEdit(null); }, children: "Remove" })] }), edit?.id === note.id && edit.where === "side" ? editor(note) : _jsxs(_Fragment, { children: [_jsx("p", { children: note.text || "Add a comment…" }), _jsx("button", { onClick: () => { setPicking(null); setEdit({ id: note.id, where: "side" }); }, children: "Edit" })] }), note.image && _jsxs(_Fragment, { children: [_jsx(ImagePreview, { blob: note.image }), _jsx("button", { disabled: draft.submitting, onClick: () => noteChange(note.id, { image: undefined }), children: "Remove screenshot" })] })] }, note.id)) }), _jsxs("label", { children: ["Overall comment (optional)", _jsx("textarea", { maxLength: 5000, value: draft.comment, disabled: draft.submitting, onChange: event => update({ comment: event.target.value }) })] }), error && _jsx("p", { role: "alert", className: "hf-error", children: error }), notice && _jsx("p", { role: "status", children: notice }), reviewTargets.map(target => _jsx("p", { children: _jsxs("a", { href: target.href, target: "_blank", rel: "noopener noreferrer", children: ["Send to chat in ", target.label] }) }, target.href)), draft.submitting && !busy && _jsx("p", { children: "The submission may already have reached Core. Retry to recover its confirmation." }), _jsxs("footer", { children: [_jsx("button", { onClick: () => void discard(), disabled: busy, children: "Discard draft" }), _jsx("button", { className: "hf-primary", disabled: busy || dictating || capturing || !draft.annotations.length || draft.annotations.some(n => !n.text.trim()), onClick: () => void send(), children: busy ? "Sending…" : draft.submitting ? "Retry submission" : "Submit feedback" })] })] }), highlight && _jsx("div", { className: "hf-highlight", "aria-hidden": true, style: { left: highlight.x, top: highlight.y, width: highlight.width, height: highlight.height } }), selected && edit?.where === "anchor" && !picking && _jsxs("section", { className: "hf-popover", role: "dialog", "aria-label": "Annotation comment", style: popup, children: [_jsx("strong", { children: selected.target?.label ?? "Annotation" }), editor(selected)] }), preview && _jsx(CropPreview, { blob: preview.blob, onCancel: () => setPreview(null), onAccept: acceptImage })] })] }), document.body);
354
- }
355
- function CropPreview({ blob, onCancel, onAccept }) {
356
- const url = useBlobUrl(blob);
357
- const [crop, setCrop] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState("");
358
- const dialog = useRef(null);
359
- useEffect(() => {
360
- const node = dialog.current;
361
- node?.showModal();
362
- return () => { node?.close(); };
363
- }, []);
364
- const start = useRef(null);
365
- const point = (event) => {
366
- const bounds = event.currentTarget.getBoundingClientRect();
367
- return { x: Math.max(0, Math.min(1, (event.clientX - bounds.x) / bounds.width)), y: Math.max(0, Math.min(1, (event.clientY - bounds.y) / bounds.height)) };
368
- };
369
- return _jsxs("dialog", { ref: dialog, className: "hf-crop", "aria-label": "Review screenshot", onCancel: event => { event.preventDefault(); if (!busy)
370
- onCancel(); }, children: [_jsx("h2", { children: "Review screenshot" }), _jsx("p", { children: "Check the selected source. Drag to crop, or adjust the percentages below. Only the approved image is included." }), _jsxs("div", { className: "hf-crop-image", onPointerDown: event => { start.current = point(event); event.currentTarget.setPointerCapture(event.pointerId); }, onPointerMove: event => {
371
- if (!start.current)
372
- return;
373
- const p = point(event);
374
- setCrop({ x: Math.min(p.x, start.current.x), y: Math.min(p.y, start.current.y),
375
- width: Math.abs(p.x - start.current.x), height: Math.abs(p.y - start.current.y) });
376
- }, onPointerUp: () => { start.current = null; }, children: [url && _jsx("img", { src: url, alt: "Captured screen for review", draggable: false }), crop && _jsx("div", { className: "hf-crop-selection", style: { left: crop.x * 100 + "%", top: crop.y * 100 + "%", width: crop.width * 100 + "%", height: crop.height * 100 + "%" } })] }), _jsx("div", { className: "hf-actions", children: ["x", "y", "width", "height"].map(field => _jsxs("label", { children: [field === "x" ? "Left %" : field === "y" ? "Top %" : field === "width" ? "Width %" : "Height %", _jsx("input", { type: "number", min: 0, max: 100, value: Math.round((crop?.[field] ?? (field === "width" || field === "height" ? 1 : 0)) * 100), onChange: event => setCrop({ ...(crop ?? { x: 0, y: 0, width: 1, height: 1 }), [field]: Math.max(0, Math.min(1, Number(event.target.value) / 100)) }) })] }, field)) }), error && _jsx("p", { role: "alert", children: error }), _jsxs("footer", { children: [_jsx("button", { onClick: onCancel, disabled: busy, children: "Cancel" }), _jsx("button", { onClick: () => setCrop(null), children: "Use full image" }), _jsx("button", { className: "hf-primary", disabled: busy || !!crop && (!crop.width || !crop.height), onClick: () => { setBusy(true); void cropStill(blob, crop).then(onAccept).catch(e => setError(errorMessage(e))).finally(() => setBusy(false)); }, children: "Include screenshot" })] })] });
256
+ document.addEventListener('pointermove', move, true);
257
+ document.addEventListener('pointerdown', down, true);
258
+ document.addEventListener('pointerup', up, true);
259
+ document.addEventListener('click', click, true);
260
+ document.addEventListener('keydown', key, true);
261
+ document.addEventListener('pointerout', leaves, true);
262
+ document.addEventListener('pointercancel', clearHover, true);
263
+ document.addEventListener('visibilitychange', visibility);
264
+ window.addEventListener('blur', clearHover);
265
+ return () => { stopClickGuard(); document.removeEventListener('pointermove', move, true); document.removeEventListener('pointerdown', down, true); document.removeEventListener('pointerup', up, true); document.removeEventListener('click', click, true); document.removeEventListener('keydown', key, true); document.removeEventListener('pointerout', leaves, true); document.removeEventListener('pointercancel', clearHover, true); document.removeEventListener('visibilitychange', visibility); window.removeEventListener('blur', clearHover); resetPick.current = () => { }; };
266
+ }, [active]);
267
+ return active && highlight ? createPortal(_jsx("div", { "data-hosty-feedback-highlight": true, "aria-hidden": true, style: { position: 'fixed', pointerEvents: 'none', zIndex: 2147483646, left: highlight.x, top: highlight.y, width: highlight.width, height: highlight.height, border: '2px solid #65a30d', background: 'rgba(163,230,53,.12)', boxSizing: 'border-box' } }), document.body) : null;
377
268
  }
378
- const feedbackStyles = [
379
- "[data-hosty-feedback]{font-family:var(--hs-font);font-size:14px;color:#0f1b2d;line-height:1.45}",
380
- ".hosty-feedback-launch{position:fixed;left:16px;bottom:16px;z-index:2147481000;background:#fff;border:1px solid #bdc8d6;border-radius:20px;padding:10px 16px;box-shadow:0 3px 14px #0f1b2d20}",
381
- "[data-hosty-feedback] button{font:inherit;cursor:pointer;border:1px solid #cbd5e1;border-radius:7px;background:#fff;padding:6px 10px;color:#0f1b2d}",
382
- "[data-hosty-feedback] button:disabled{opacity:.5;cursor:not-allowed}[data-hosty-feedback] button:focus-visible,[data-hosty-feedback] textarea:focus{outline:2px solid #65a30d;outline-offset:2px}",
383
- "[data-hosty-feedback] textarea{box-sizing:border-box;display:block;width:100%;min-height:90px;font:inherit;color:#0f1b2d;background:#fff;border:1px solid #cbd5e1;border-radius:7px;padding:8px;resize:vertical;margin:6px 0}",
384
- "[data-hosty-feedback] .hf-primary{background:#a3e635;border-color:#84cc16}[data-hosty-feedback] .hf-error{color:#b91c1c}",
385
- ".hf-panel{box-sizing:border-box;position:fixed;right:12px;top:12px;bottom:12px;width:min(360px,calc(100vw - 24px));background:#fff;border:1px solid #cbd5e1;border-radius:12px;padding:16px;box-shadow:0 10px 45px #0f1b2d30;overflow:auto;z-index:2147481001}",
386
- ".hf-panel header,.hf-note-heading,.hf-panel footer,.hf-crop footer{display:flex;justify-content:space-between;align-items:center;gap:8px}.hf-panel small{display:block;color:#64748b}.hf-panel ol{padding:0;list-style:none}.hf-panel li{border:1px solid #e2e8f0;border-radius:9px;padding:10px;margin:12px 0}.hf-panel p{white-space:pre-wrap;overflow-wrap:anywhere}.hf-panel img{max-width:100%;border-radius:6px;margin:8px 0}.hf-panel footer{margin-top:14px}",
387
- ".hf-actions{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}.hf-highlight{position:fixed;border:2px solid #65a30d;box-shadow:0 0 0 2px #ecfccb;pointer-events:none;z-index:2147481000;background:#a3e63518;box-sizing:border-box}",
388
- ".hf-popover>strong{display:block;margin-bottom:6px}.hf-popover{position:fixed;width:min(310px,calc(100vw - 32px));box-sizing:border-box;z-index:2147481002;background:#fff;border:1px solid #84cc16;border-radius:10px;padding:12px;box-shadow:0 8px 28px #0f1b2d35}",
389
- ".hf-backdrop{position:fixed;inset:0;background:#0f1b2d88;display:grid;place-items:center;z-index:2147481003;padding:16px}.hf-crop::backdrop{background:#0f1b2d88}.hf-crop{border:0;color:#0f1b2d;background:#fff;border-radius:12px;padding:20px;width:min(760px,90vw);max-height:90vh;overflow:auto}.hf-crop-image{position:relative;display:table;max-width:100%;touch-action:none}.hf-crop-image img{display:block;max-width:100%;max-height:55vh;user-select:none}.hf-crop-selection{position:absolute;border:2px solid #65a30d;background:#a3e63530;pointer-events:none;box-sizing:border-box}.hf-crop input{display:block;width:70px}"
390
- ].join("\n");