Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | 8x 8x 58x 58x 16x 58x 58x 58x 58x 58x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 8x 8x 16x 8x 16x 8x 16x 8x 16x 8x 16x 16x 16x 16x | /**
* FeedbackLayer.tsx — the mode's overlay (`@@T-462`, `@@T-489`, `@@T-490`).
*
* Mounted once by `App`, above the portal. It owns everything that is transient:
* what the pointer is over, where each callout sits, the region the picture will
* keep, and the one submit that leaves the mode. The draft itself lives in the
* store, because the elements that can be commented on are scattered through the
* tree and must not know about a layer.
*
* Callout boxes are local state rather than draft fields: they are viewport
* pixels while the person is arranging them, and become fractions of the capture
* region only at submit — the moment the region is known.
*/
import type {IFeedbackItem} from '@feasibleone/blong';
import {useCallback, useEffect, useRef, useState} from 'react';
import {useBlong} from '../context/BlongContext.js';
import {useTranslate} from '../hooks/useText.js';
import {useAppStore} from '../state/appStore.js';
import {captureScreen} from './capture.js';
import './feedback.css';
import {FeedbackCallout} from './FeedbackCallout.js';
import {FeedbackCrop} from './FeedbackCrop.js';
import {FeedbackOutline} from './FeedbackOutline.js';
import {FeedbackSubmitBar} from './FeedbackSubmitBar.js';
import {installFeedbackGuard} from './guard.js';
import {closestFeedbackTarget, FEEDBACK_ID_ATTR, isFeedbackUi, rectOf, targetOf} from './ids.js';
import {
arrowHeadPoints,
connectorOf,
moveBox,
placeCallout,
resizeBox,
toFraction,
type IFeedbackRect,
} from './placement.js';
import {appendSpeech, speechSupported} from './speech.js';
import {useFeedbackConfig} from './useFeedbackConfig.js';
import {useFeedbackSpeech} from './useFeedbackSpeech.js';
/** The size a new callout starts at; the person is free to change it. */
// Small on purpose: a callout that covers the element it is about hides the
// problem from the person looking at it (`@@T-494`). A person who wants more room
// drags the corner. It is wide enough for the input-sized text the box now reads
// at (`D-768`).
const CALLOUT_SIZE = {width: 244, height: 156};
/** The distance a new callout keeps from its element, so the arrow has a length. */
const CALLOUT_GAP = 22;
function escapeId(id: string): string {
const css = globalThis.CSS as typeof CSS | undefined;
return css?.escape ? css.escape(id) : id.replace(/["\\]/g, '\\$&');
}
function sameRect(a: IFeedbackRect | undefined, b: IFeedbackRect | undefined): boolean {
if (!a || !b) return a === b;
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
}
function viewportOf(): {width: number; height: number} {
return {width: window.innerWidth, height: window.innerHeight};
}
/** The whole viewport, which is the region a submission keeps unless told otherwise. */
function fullRegion(): IFeedbackRect {
const {width, height} = viewportOf();
return {x: 0, y: 0, width, height};
}
/** The first three segments of an identifier: subject, object and page. */
function pageOf(targetId: string): {subject?: string; object?: string; kind?: string} {
const [subject, object, kind] = targetId.split('/')[0].split('.');
return {subject, object, kind};
}
/**
* The region a fresh crop starts from: everything the submission talks about.
*
* Anchors alone are not enough — a callout can sit far from the element it is
* about, and a crop that leaves it outside the picture would store a box the
* reviewer cannot see. A floor of 40 % of the viewport keeps the first crop
* usable instead of a sliver around one small element.
*/
function initialCrop(
rects: Record<string, IFeedbackRect>,
boxes: Record<string, IFeedbackRect>,
): IFeedbackRect {
const {width, height} = viewportOf();
const boxed = [...Object.values(rects), ...Object.values(boxes)];
if (!boxed.length) {
return {x: width * 0.1, y: height * 0.1, width: width * 0.8, height: height * 0.8};
}
const pad = 32;
const left = Math.min(...boxed.map(box => box.x)) - pad;
const top = Math.min(...boxed.map(box => box.y)) - pad;
const right = Math.max(...boxed.map(box => box.x + box.width)) + pad;
const bottom = Math.max(...boxed.map(box => box.y + box.height)) + pad;
const centreX = (left + right) / 2;
const centreY = (top + bottom) / 2;
const cropWidth = Math.max(right - left, width * 0.4);
const cropHeight = Math.max(bottom - top, height * 0.4);
const x = Math.min(Math.max(0, centreX - cropWidth / 2), Math.max(0, width - cropWidth));
const y = Math.min(Math.max(0, centreY - cropHeight / 2), Math.max(0, height - cropHeight));
return {
x,
y,
width: Math.min(cropWidth, width),
height: Math.min(cropHeight, height),
};
}
export function FeedbackLayer() {
const active = useAppStore(state => state.feedback.active);
const items = useAppStore(state => state.feedback.items);
const feedbackConfig = useFeedbackConfig();
const add = useAppStore(state => state.feedbackAdd);
const update = useAppStore(state => state.feedbackUpdate);
const remove = useAppStore(state => state.feedbackRemove);
const reset = useAppStore(state => state.feedbackReset);
const activate = useAppStore(state => state.feedbackActivate);
const {handler} = useBlong();
const t = useTranslate();
// Dictation (`@@D-758`). The finished phrases land in the draft like typed
// ones; the phrase still being recognised is drawn by the callout and never
// written here.
const speech = useFeedbackSpeech((targetId, transcript) => {
const state = useAppStore.getState();
const existing = state.feedback.items[targetId];
if (!existing) return;
state.feedbackUpdate(targetId, {
commentText: appendSpeech(existing.commentText ?? '', transcript),
});
});
const {start: startSpeech, toggle: toggleSpeech, stop: stopSpeech} = speech;
const listeningTargetId = speech.listeningTargetId;
// Both halves are needed: a suite that declared no speech block gets no
// microphone even where the browser has one, because the switch would
// otherwise appear in every portal (`@@D-758`).
const speechConfig = feedbackConfig?.speech;
const speechAvailable = Boolean(speechConfig) && speechSupported(speechConfig?.engine);
// Read through a ref: the guard below is installed once per mode switch, and
// a configuration object whose identity changes must not reinstall it.
const speechConfigRef = useRef(speechConfig);
speechConfigRef.current = speechConfig;
const [hovered, setHovered] = useState<{
id: string;
rect: IFeedbackRect;
} | null>(null);
const [rects, setRects] = useState<Record<string, IFeedbackRect>>({});
const [boxes, setBoxes] = useState<Record<string, IFeedbackRect>>({});
const [cropping, setCropping] = useState(false);
const [crop, setCrop] = useState<IFeedbackRect | null>(null);
const [busy, setBusy] = useState(false);
// The measure pass reads the draft from a ref so it is not re-created (and the
// scroll listener re-bound) on every keystroke.
const itemsRef = useRef(items);
itemsRef.current = items;
const measure = useCallback(() => {
const next: Record<string, IFeedbackRect> = {};
for (const id of Object.keys(itemsRef.current)) {
const element = document.querySelector(`[${FEEDBACK_ID_ATTR}="${escapeId(id)}"]`);
if (element) next[id] = rectOf(element);
}
// The measurement is the state: the boxes cannot be drawn before the DOM
// has reported where the elements are, so this is not a render that could
// be derived earlier (`@@T-489`).
// eslint-disable-next-line @eslint-react/set-state-in-effect
setRects(previous => {
const keys = Object.keys(next);
if (
keys.length === Object.keys(previous).length &&
keys.every(key => sameRect(previous[key], next[key]))
) {
return previous;
}
return next;
});
}, []);
// Re-measure when the draft changes and whenever the page moves underneath it:
// a tab switch, a table paging, a card collapsing. `ResizeObserver` on the body
// catches the last three, the scroll listener the first two.
useEffect(() => {
Eif (!active) return;
measure();
const onMove = () => measure();
window.addEventListener('scroll', onMove, true);
window.addEventListener('resize', onMove);
const observer =
typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(onMove);
observer?.observe(document.body);
return () => {
window.removeEventListener('scroll', onMove, true);
window.removeEventListener('resize', onMove);
observer?.disconnect();
};
}, [active, items, measure]);
// A new comment gets a box from the solver; an existing one keeps the box the
// person gave it, and a removed comment takes its box with it.
useEffect(() => {
Eif (!active) return;
// Placement depends on where the anchors were measured, which is a DOM fact
// rather than a value the render can compute (`@@T-489`).
// eslint-disable-next-line @eslint-react/set-state-in-effect
setBoxes(previous => {
const next: Record<string, IFeedbackRect> = {};
const taken: IFeedbackRect[] = [];
let changed = false;
for (const id of Object.keys(items)) {
const kept = previous[id];
if (kept) {
next[id] = kept;
taken.push(kept);
continue;
}
const anchor = rects[id];
if (!anchor) continue;
next[id] = placeCallout({
anchor,
size: CALLOUT_SIZE,
viewport: viewportOf(),
taken,
// Room for the arrow to read as one: a box touching its
// element leaves the connector no length at all (`@@T-489`).
gap: CALLOUT_GAP,
}).rect;
taken.push(next[id]);
changed = true;
}
if (Object.keys(previous).length !== Object.keys(next).length) changed = true;
return changed ? next : previous;
});
}, [active, items, rects]);
// Track the pointer. Hover is the only thing that repaints per move; the
// outlines for committed comments come from the measured rects.
useEffect(() => {
Eif (!active || cropping) return;
const onPointerMove = (event: PointerEvent) => {
if (isFeedbackUi(event.target)) {
setHovered(null);
return;
}
const element = closestFeedbackTarget(event.target);
const target = element ? targetOf(element) : null;
if (!element || !target) {
setHovered(null);
return;
}
const rect = rectOf(element);
setHovered(previous =>
previous && previous.id === target.targetId && sameRect(previous.rect, rect)
? previous
: {id: target.targetId, rect},
);
};
document.addEventListener('pointermove', onPointerMove, true);
return () => document.removeEventListener('pointermove', onPointerMove, true);
}, [active, cropping]);
// Freeze the UI and turn a click on an addressable element into a draft item.
useEffect(() => {
Eif (!active || cropping) return;
return installFeedbackGuard({
onTargetClick: element => {
const target = targetOf(element);
if (!target) return;
const state = useAppStore.getState();
const existing = state.feedback.items[target.targetId];
add({
...target,
commentText: existing?.commentText ?? '',
itemIndex: existing?.itemIndex ?? Object.keys(state.feedback.items).length,
} satisfies IFeedbackItem);
// A new box starts listening on its own, which is what lets a
// person dictate a whole review without touching the mic. It
// stays silent unless the microphone is already granted.
void startSpeech(target.targetId, speechConfigRef.current, {auto: true});
},
});
}, [active, cropping, add, startSpeech]);
// Dictation follows the draft: a box that was removed, or a mode that closed,
// must not leave the microphone open.
useEffect(() => {
Eif (!active || (listeningTargetId && !items[listeningTargetId])) stopSpeech();
}, [active, items, listeningTargetId, stopSpeech]);
const onSubmit = useCallback(async () => {
const state = useAppStore.getState();
const comments = Object.values(state.feedback.items).filter(item =>
(item.commentText ?? '').trim(),
);
if (!comments.length) return;
// The microphone has no business being open while the screenshot is taken.
stopSpeech();
const method = feedbackConfig?.submit ?? 'feedback.session.add';
const first = pageOf(comments[0].targetId);
// Both boxes become fractions of what the picture will keep, so the review
// page can lay them over that picture without a scale factor.
const region = crop ?? fullRegion();
const payload = comments.map(item => ({
...item,
...(rects[item.targetId] && {anchor: toFraction(rects[item.targetId], region)}),
...(boxes[item.targetId] && {callout: toFraction(boxes[item.targetId], region)}),
}));
setBusy(true);
try {
const outcome = await captureScreen(feedbackConfig?.maxShotBytes, crop ?? undefined);
await handler[method]?.(
{
session: {
pageUrl: `${window.location.pathname}${window.location.search}`,
pageTitle: document.title,
pageSubject: first.subject,
pageObject: first.object,
pageKind: first.kind,
languageCode: state.language,
viewportJSON: `${window.innerWidth}x${window.innerHeight}@${window.devicePixelRatio || 1}`,
shotStatus: outcome.status,
items: payload,
...(outcome.shot && {shot: outcome.shot}),
},
},
{},
);
reset();
setBoxes({});
setCrop(null);
setCropping(false);
activate(false);
state.showToast({
severity: 'success',
summary: t('Feedback submitted') ?? 'Feedback submitted',
});
} catch {
// The handler proxy already raised the error dialog; staying in the
// mode with the draft intact is the recovery the person needs.
} finally {
setBusy(false);
}
}, [activate, boxes, crop, feedbackConfig, handler, rects, reset, t, stopSpeech]);
const onCrop = useCallback(() => {
setCropping(previous => {
if (previous) return false;
setCrop(current => current ?? initialCrop(rects, boxes));
return true;
});
}, [boxes, rects]);
const onDiscard = useCallback(() => {
stopSpeech();
reset();
setBoxes({});
setCrop(null);
setCropping(false);
}, [reset, stopSpeech]);
Eif (!active) return null;
const connectors = Object.keys(items)
.filter(id => rects[id] && boxes[id])
.map(id => ({id, ...connectorOf(boxes[id], rects[id])}));
return (
<div className="blong-feedback-layer">
{!cropping && hovered && (
<FeedbackOutline
rect={hovered.rect}
targetId={hovered.id}
tone="hover"
/>
)}
{!cropping &&
Object.keys(items).map(id =>
rects[id] ? (
<FeedbackOutline
key={`ring-${id}`}
rect={rects[id]}
targetId={id}
tone="item"
/>
) : null,
)}
{!cropping && connectors.length > 0 && (
<svg
className="blong-feedback-connectors"
aria-hidden
>
{connectors.map(({id, from, to}) => (
<g key={`line-${id}`}>
<line
className="blong-feedback-connector"
x1={from.x}
y1={from.y}
x2={to.x}
y2={to.y}
/>
<polygon
className="blong-feedback-connector__head"
points={arrowHeadPoints(from, to)}
/>
</g>
))}
</svg>
)}
{!cropping &&
Object.entries(items).map(([id, item]) => {
const box = boxes[id];
if (!box) return null;
return (
<FeedbackCallout
key={`callout-${id}`}
targetId={id}
box={box}
comment={item.commentText ?? ''}
onChange={value => update(id, {commentText: value})}
onRemove={() => remove(id)}
speechAvailable={speechAvailable}
listening={listeningTargetId === id}
interimText={listeningTargetId === id ? speech.interimText : undefined}
level={listeningTargetId === id ? speech.level : 'silence'}
waitMs={listeningTargetId === id ? speech.waitMs : 0}
idle={listeningTargetId === id ? speech.idle : 0}
speechError={speech.error}
speechEngine={speechConfigRef.current?.engine}
onListen={() =>
void startSpeech(id, speechConfigRef.current, {auto: true})
}
onToggleListen={() => void toggleSpeech(id, speechConfigRef.current)}
// Taken as spoken, without the punctuation the finished
// phrases get: a phrase cut in half is not a sentence
// (`D-764`).
onAcceptInterim={() => {
const taken = speech.acceptInterim();
if (!taken) return;
const current =
useAppStore.getState().feedback.items[id]?.commentText ?? '';
update(id, {commentText: appendSpeech(current, taken)});
}}
onClearInterim={() => speech.clearInterim()}
onMove={(dx, dy) =>
setBoxes(previous => ({
...previous,
[id]: moveBox(previous[id] ?? box, dx, dy, viewportOf()),
}))
}
onResize={(dx, dy) =>
setBoxes(previous => ({
...previous,
[id]: resizeBox(previous[id] ?? box, dx, dy, viewportOf()),
}))
}
/>
);
})}
{cropping && crop && (
<FeedbackCrop
region={crop}
onMove={(dx, dy) =>
setCrop(previous =>
previous ? moveBox(previous, dx, dy, viewportOf()) : previous,
)
}
onResize={(dx, dy) =>
setCrop(previous =>
previous ? resizeBox(previous, dx, dy, viewportOf()) : previous,
)
}
/>
)}
<FeedbackSubmitBar
count={Object.keys(items).length}
busy={busy}
cropping={cropping}
cropped={Boolean(crop)}
onCrop={onCrop}
onSubmit={() => void onSubmit()}
onDiscard={onDiscard}
/>
</div>
);
}
|