@stefan.inc/feedback-engine 0.0.0-stage → 0.0.0
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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/package.json +57 -5
- package/src/core/annotations.ts +104 -0
- package/src/core/cardLayout.ts +82 -0
- package/src/core/describe.ts +143 -0
- package/src/core/index.ts +9 -0
- package/src/core/model.ts +133 -0
- package/src/core/problem.ts +51 -0
- package/src/core/report.ts +74 -0
- package/src/core/session.ts +184 -0
- package/src/core/taskTitle.ts +35 -0
- package/src/core/tree.ts +117 -0
- package/src/dom/capture.ts +78 -0
- package/src/dom/image.ts +316 -0
- package/src/dom/procrastimate.ts +205 -0
- package/src/dom/scene.ts +286 -0
- package/src/dom/screenshot.ts +118 -0
- package/src/dom/share.ts +71 -0
- package/src/dom/tags.ts +21 -0
- package/src/dom/webhook.ts +80 -0
- package/src/dom/zip.ts +52 -0
- package/src/editor/Button.svelte +125 -0
- package/src/editor/Editor.svelte +1078 -0
- package/src/editor/Host.svelte +31 -0
- package/src/editor/ItemsSheet.svelte +233 -0
- package/src/editor/Pill.svelte +65 -0
- package/src/editor/ProblemCard.svelte +67 -0
- package/src/editor/ProcrastimateSheet.svelte +304 -0
- package/src/editor/WebhookSheet.svelte +132 -0
- package/src/editor/engine.ts +154 -0
- package/src/editor/setup.ts +106 -0
- package/src/next/index.d.ts +13 -0
- package/src/next/index.js +69 -0
- package/src/next/loader.js +23 -0
- package/src/react/components.ts +101 -0
- package/src/react/index.ts +44 -0
- package/src/react/public.d.ts +101 -0
- package/src/svelte/index.ts +32 -0
- package/src/vite/index.d.ts +44 -0
- package/src/vite/index.js +207 -0
- package/src/vite/react.js +172 -0
package/src/dom/image.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import {
|
|
2
|
+
cards as metrics,
|
|
3
|
+
line,
|
|
4
|
+
nearestSource,
|
|
5
|
+
paletteColor,
|
|
6
|
+
place,
|
|
7
|
+
tag,
|
|
8
|
+
title,
|
|
9
|
+
type Annotations,
|
|
10
|
+
type Frame,
|
|
11
|
+
type Point,
|
|
12
|
+
} from '../core/index.ts';
|
|
13
|
+
import type { Screen } from './capture.ts';
|
|
14
|
+
|
|
15
|
+
/** Keeps a tall full-length capture shareable. */
|
|
16
|
+
const pixelBudget = 40_000_000;
|
|
17
|
+
const secondary = '#6b6b6b';
|
|
18
|
+
const primary = '#141414';
|
|
19
|
+
const sans = 'system-ui, -apple-system, "Segoe UI", sans-serif';
|
|
20
|
+
const mono = 'ui-monospace, "SF Mono", Menlo, Consolas, monospace';
|
|
21
|
+
|
|
22
|
+
type Run = { text: string; font: string; color: string; background?: string; spacing?: number };
|
|
23
|
+
type Piece = Run & { x: number; width: number };
|
|
24
|
+
type Line = { pieces: Piece[]; height: number; gap: number };
|
|
25
|
+
|
|
26
|
+
const fontSize = (font: string) => Number(/(\d+(?:\.\d+)?)px/.exec(font)![1]);
|
|
27
|
+
|
|
28
|
+
/** Breaks runs of styled text into lines no wider than `width`. A paragraph ends at each newline, with `gap` points after it. */
|
|
29
|
+
function layout(context: CanvasRenderingContext2D, paragraphs: { runs: Run[]; gap?: number }[], width: number): Line[] {
|
|
30
|
+
const lines: Line[] = [];
|
|
31
|
+
for (const paragraph of paragraphs) {
|
|
32
|
+
let current: Line = { pieces: [], height: 0, gap: 0 };
|
|
33
|
+
let x = 0;
|
|
34
|
+
const wrap = () => {
|
|
35
|
+
lines.push(current);
|
|
36
|
+
current = { pieces: [], height: 0, gap: 0 };
|
|
37
|
+
x = 0;
|
|
38
|
+
};
|
|
39
|
+
for (const run of paragraph.runs) {
|
|
40
|
+
context.font = run.font;
|
|
41
|
+
context.letterSpacing = `${run.spacing ?? 0}px`;
|
|
42
|
+
const height = Math.ceil(fontSize(run.font) * 1.3);
|
|
43
|
+
// A highlighted token stays whole. Other text breaks between words, and a word wider than the line breaks inside.
|
|
44
|
+
const words = run.background ? [run.text] : (run.text.match(/\n|[^\S\n]+|[^\s]+/g) ?? []);
|
|
45
|
+
for (let word of words) {
|
|
46
|
+
if (word === '\n') {
|
|
47
|
+
current.height ||= height;
|
|
48
|
+
wrap();
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
let wordWidth = context.measureText(word).width;
|
|
52
|
+
if (x + wordWidth > width && x > 0) {
|
|
53
|
+
wrap();
|
|
54
|
+
if (!word.trim()) continue;
|
|
55
|
+
}
|
|
56
|
+
while (wordWidth > width && word.length > 1) {
|
|
57
|
+
let count = word.length - 1;
|
|
58
|
+
while (count > 1 && context.measureText(word.slice(0, count)).width > width) count -= 1;
|
|
59
|
+
const head = word.slice(0, count);
|
|
60
|
+
current.pieces.push({ ...run, text: head, x: 0, width: context.measureText(head).width });
|
|
61
|
+
current.height = Math.max(current.height, height);
|
|
62
|
+
wrap();
|
|
63
|
+
word = word.slice(count);
|
|
64
|
+
wordWidth = context.measureText(word).width;
|
|
65
|
+
}
|
|
66
|
+
current.pieces.push({ ...run, text: word, x, width: wordWidth });
|
|
67
|
+
current.height = Math.max(current.height, height);
|
|
68
|
+
x += wordWidth;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (current.pieces.length) lines.push(current);
|
|
72
|
+
if (lines.length) lines.at(-1)!.gap = paragraph.gap ?? 0;
|
|
73
|
+
}
|
|
74
|
+
context.letterSpacing = '0px';
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const heightOf = (lines: Line[]) => Math.ceil(lines.reduce((sum, row) => sum + row.height + row.gap, 0));
|
|
79
|
+
|
|
80
|
+
function drawText(context: CanvasRenderingContext2D, lines: Line[], origin: Point) {
|
|
81
|
+
let y = origin.y;
|
|
82
|
+
context.textBaseline = 'middle';
|
|
83
|
+
for (const row of lines) {
|
|
84
|
+
for (const piece of row.pieces) {
|
|
85
|
+
context.font = piece.font;
|
|
86
|
+
context.letterSpacing = `${piece.spacing ?? 0}px`;
|
|
87
|
+
if (piece.background) {
|
|
88
|
+
context.fillStyle = piece.background;
|
|
89
|
+
context.fillRect(origin.x + piece.x, y, piece.width, row.height);
|
|
90
|
+
}
|
|
91
|
+
context.fillStyle = piece.color;
|
|
92
|
+
context.fillText(piece.text, origin.x + piece.x, y + row.height / 2);
|
|
93
|
+
}
|
|
94
|
+
y += row.height + row.gap;
|
|
95
|
+
}
|
|
96
|
+
context.letterSpacing = '0px';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function roundedRect(context: CanvasRenderingContext2D, frame: Frame, radius: number) {
|
|
100
|
+
context.beginPath();
|
|
101
|
+
context.roundRect(frame.x, frame.y, frame.width, frame.height, Math.min(radius, frame.width / 2, frame.height / 2));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function withAlpha(color: string, alpha: number) {
|
|
105
|
+
const value = Number.parseInt(color.slice(1), 16);
|
|
106
|
+
return `rgb(${value >> 16} ${(value >> 8) & 255} ${value & 255} / ${alpha})`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The card's border and its footer's fill: the item's color at 45% over white, opaque so the two match exactly. */
|
|
110
|
+
function tint(color: string) {
|
|
111
|
+
const value = Number.parseInt(color.slice(1), 16);
|
|
112
|
+
const mix = (channel: number) => Math.round(channel * 0.45 + 255 * 0.55);
|
|
113
|
+
return `rgb(${mix(value >> 16)} ${mix((value >> 8) & 255)} ${mix(value & 255)})`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const footerPadding = 6;
|
|
117
|
+
|
|
118
|
+
const clamp = (value: number, low: number, high: number) => Math.min(Math.max(value, low), high);
|
|
119
|
+
|
|
120
|
+
function dashedBox(context: CanvasRenderingContext2D, target: Frame, color: string) {
|
|
121
|
+
roundedRect(context, { x: target.x - 1, y: target.y - 1, width: target.width + 2, height: target.height + 2 }, 4);
|
|
122
|
+
context.lineWidth = 1.5;
|
|
123
|
+
context.setLineDash([6, 4]);
|
|
124
|
+
context.strokeStyle = withAlpha(color, 0.9);
|
|
125
|
+
context.stroke();
|
|
126
|
+
context.setLineDash([]);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function label(context: CanvasRenderingContext2D, text: string, center: Point) {
|
|
130
|
+
context.font = `700 11px ${sans}`;
|
|
131
|
+
context.fillStyle = 'white';
|
|
132
|
+
context.textAlign = 'center';
|
|
133
|
+
context.textBaseline = 'middle';
|
|
134
|
+
context.fillText(text, center.x, center.y + 0.5);
|
|
135
|
+
context.textAlign = 'left';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function badge(context: CanvasRenderingContext2D, number: number, color: string, center: Point) {
|
|
139
|
+
context.beginPath();
|
|
140
|
+
context.arc(center.x, center.y, metrics.badge / 2, 0, Math.PI * 2);
|
|
141
|
+
context.fillStyle = color;
|
|
142
|
+
context.fill();
|
|
143
|
+
context.lineWidth = 1.5;
|
|
144
|
+
context.strokeStyle = 'white';
|
|
145
|
+
context.stroke();
|
|
146
|
+
label(context, String(number), center);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A reference's `@N`, in a square centered on the box's top-right corner. */
|
|
150
|
+
function referenceTag(context: CanvasRenderingContext2D, text: string, color: string, corner: Point, shot: Frame) {
|
|
151
|
+
context.font = `700 11px ${sans}`;
|
|
152
|
+
const width = Math.max(context.measureText(text).width + 8, metrics.badge);
|
|
153
|
+
const center = {
|
|
154
|
+
x: clamp(corner.x, shot.x + width / 2 + 2, shot.x + shot.width - width / 2 - 2),
|
|
155
|
+
y: clamp(corner.y, shot.y + metrics.badge / 2 + 2, shot.y + shot.height - metrics.badge / 2 - 2),
|
|
156
|
+
};
|
|
157
|
+
roundedRect(context, { x: center.x - width / 2, y: center.y - metrics.badge / 2, width, height: metrics.badge }, 3);
|
|
158
|
+
context.fillStyle = color;
|
|
159
|
+
context.fill();
|
|
160
|
+
context.lineWidth = 1.5;
|
|
161
|
+
context.strokeStyle = 'white';
|
|
162
|
+
context.stroke();
|
|
163
|
+
label(context, text, center);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The image export: the screenshot with numbered boxes, each item's text and code location in a card beside it, a
|
|
168
|
+
* tagged box for each referenced node, and the capture's environment, so the one file is enough on its own.
|
|
169
|
+
*/
|
|
170
|
+
export function annotatedImage({ capture, image, scale }: Screen, annotations: Annotations): HTMLCanvasElement {
|
|
171
|
+
const { column, padding, badge: badgeSize } = metrics;
|
|
172
|
+
const textWidth = column - padding * 3 - badgeSize;
|
|
173
|
+
const canvas = document.createElement('canvas');
|
|
174
|
+
const context = canvas.getContext('2d')!;
|
|
175
|
+
|
|
176
|
+
const app = capture.environment.find(entry => entry.name === 'App')?.value ?? 'App';
|
|
177
|
+
const environment = layout(
|
|
178
|
+
context,
|
|
179
|
+
[
|
|
180
|
+
{ runs: [{ text: `Feedback: ${app}`, font: `700 16px ${sans}`, color: primary }], gap: 6 },
|
|
181
|
+
...capture.environment.flatMap(entry =>
|
|
182
|
+
entry.name === 'App'
|
|
183
|
+
? []
|
|
184
|
+
: [
|
|
185
|
+
{ runs: [{ text: entry.name.toUpperCase(), font: `600 10px ${sans}`, color: secondary, spacing: 0.5 }] },
|
|
186
|
+
{ runs: [{ text: entry.value, font: `12.5px ${sans}`, color: primary }], gap: 6 },
|
|
187
|
+
],
|
|
188
|
+
),
|
|
189
|
+
],
|
|
190
|
+
column,
|
|
191
|
+
);
|
|
192
|
+
const environmentHeight = heightOf(environment);
|
|
193
|
+
|
|
194
|
+
const items = annotations.items.map(item => {
|
|
195
|
+
const node = capture.nodes[item.target]!;
|
|
196
|
+
const source = nearestSource(capture, item.target);
|
|
197
|
+
const text = layout(
|
|
198
|
+
context,
|
|
199
|
+
[
|
|
200
|
+
{
|
|
201
|
+
runs: annotations.segments(item.text).map(segment =>
|
|
202
|
+
segment.reference
|
|
203
|
+
? {
|
|
204
|
+
text: ` ${segment.text} `,
|
|
205
|
+
font: `600 14px ${sans}`,
|
|
206
|
+
color: 'white',
|
|
207
|
+
background: paletteColor(annotations.colorIndex(segment.reference.target)),
|
|
208
|
+
}
|
|
209
|
+
: { text: segment.text, font: `14px ${sans}`, color: primary },
|
|
210
|
+
),
|
|
211
|
+
},
|
|
212
|
+
],
|
|
213
|
+
textWidth,
|
|
214
|
+
);
|
|
215
|
+
const footer = layout(
|
|
216
|
+
context,
|
|
217
|
+
[
|
|
218
|
+
{ runs: [{ text: title(node), font: `600 11px ${sans}`, color: primary }] },
|
|
219
|
+
...(source ? [{ runs: [{ text: source, font: `11px ${mono}`, color: primary }] }] : []),
|
|
220
|
+
],
|
|
221
|
+
column - padding * 2,
|
|
222
|
+
);
|
|
223
|
+
const body = Math.max(heightOf(text), badgeSize) + padding * 2;
|
|
224
|
+
const footerHeight = heightOf(footer) + footerPadding * 2;
|
|
225
|
+
return {
|
|
226
|
+
number: annotations.number(item.target),
|
|
227
|
+
color: paletteColor(annotations.colorIndex(item.target)),
|
|
228
|
+
text,
|
|
229
|
+
footer,
|
|
230
|
+
body,
|
|
231
|
+
height: body + footerHeight,
|
|
232
|
+
frame: node.frame,
|
|
233
|
+
};
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const placed = place(
|
|
237
|
+
items.map(item => item.frame),
|
|
238
|
+
items.map(item => item.height),
|
|
239
|
+
capture.size,
|
|
240
|
+
environmentHeight,
|
|
241
|
+
capture.visible.height,
|
|
242
|
+
annotations.used.map(reference => capture.nodes[reference.target]!.frame),
|
|
243
|
+
);
|
|
244
|
+
const { shot, size } = placed;
|
|
245
|
+
const exportScale = Math.min(scale, Math.sqrt(pixelBudget / (size.width * size.height)));
|
|
246
|
+
canvas.width = Math.round(size.width * exportScale);
|
|
247
|
+
canvas.height = Math.round(size.height * exportScale);
|
|
248
|
+
context.scale(exportScale, exportScale);
|
|
249
|
+
|
|
250
|
+
context.fillStyle = '#f2f2f2';
|
|
251
|
+
context.fillRect(0, 0, size.width, size.height);
|
|
252
|
+
context.save();
|
|
253
|
+
roundedRect(context, shot, 12);
|
|
254
|
+
context.clip();
|
|
255
|
+
context.drawImage(image, shot.x, shot.y, capture.size.width, capture.size.height);
|
|
256
|
+
context.restore();
|
|
257
|
+
roundedRect(context, shot, 12);
|
|
258
|
+
context.lineWidth = 1;
|
|
259
|
+
context.strokeStyle = '#cccccc';
|
|
260
|
+
context.stroke();
|
|
261
|
+
|
|
262
|
+
const inShot = (frame: Frame) => ({ ...frame, x: frame.x + shot.x, y: frame.y + shot.y });
|
|
263
|
+
for (const [index, item] of items.entries()) {
|
|
264
|
+
const target = inShot(item.frame);
|
|
265
|
+
dashedBox(context, target, item.color);
|
|
266
|
+
const { start, end } = line(placed.cards[index]!, target);
|
|
267
|
+
context.beginPath();
|
|
268
|
+
context.moveTo(start.x, start.y);
|
|
269
|
+
context.lineTo(end.x, end.y);
|
|
270
|
+
context.lineWidth = 1.25;
|
|
271
|
+
context.strokeStyle = withAlpha(item.color, 0.6);
|
|
272
|
+
context.stroke();
|
|
273
|
+
context.beginPath();
|
|
274
|
+
context.arc(end.x, end.y, 2.5, 0, Math.PI * 2);
|
|
275
|
+
context.fillStyle = item.color;
|
|
276
|
+
context.fill();
|
|
277
|
+
badge(context, item.number, item.color, {
|
|
278
|
+
x: clamp(target.x, shot.x + badgeSize / 2 + 2, shot.x + shot.width - badgeSize / 2 - 2),
|
|
279
|
+
y: clamp(target.y, shot.y + badgeSize / 2 + 2, shot.y + shot.height - badgeSize / 2 - 2),
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const flagged = new Set(annotations.items.map(item => item.target));
|
|
284
|
+
for (const reference of annotations.used) {
|
|
285
|
+
const color = paletteColor(annotations.colorIndex(reference.target));
|
|
286
|
+
const target = inShot(capture.nodes[reference.target]!.frame);
|
|
287
|
+
if (!flagged.has(reference.target)) dashedBox(context, target, color);
|
|
288
|
+
referenceTag(context, tag(reference), color, { x: target.x + target.width, y: target.y }, shot);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
for (const [index, item] of items.entries()) {
|
|
292
|
+
const { origin } = placed.cards[index]!;
|
|
293
|
+
const border = tint(item.color);
|
|
294
|
+
roundedRect(context, { ...origin, width: column, height: item.height }, 10);
|
|
295
|
+
context.fillStyle = 'white';
|
|
296
|
+
context.fill();
|
|
297
|
+
context.save();
|
|
298
|
+
context.clip();
|
|
299
|
+
context.fillStyle = border;
|
|
300
|
+
context.fillRect(origin.x, origin.y + item.body, column, item.height - item.body);
|
|
301
|
+
context.restore();
|
|
302
|
+
roundedRect(context, { ...origin, width: column, height: item.height }, 10);
|
|
303
|
+
context.lineWidth = 1;
|
|
304
|
+
context.strokeStyle = border;
|
|
305
|
+
context.stroke();
|
|
306
|
+
badge(context, item.number, item.color, {
|
|
307
|
+
x: origin.x + padding + badgeSize / 2,
|
|
308
|
+
y: origin.y + padding + badgeSize / 2,
|
|
309
|
+
});
|
|
310
|
+
drawText(context, item.text, { x: origin.x + padding * 2 + badgeSize, y: origin.y + padding });
|
|
311
|
+
drawText(context, item.footer, { x: origin.x + padding, y: origin.y + item.body + footerPadding });
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
drawText(context, environment, placed.environment);
|
|
315
|
+
return canvas;
|
|
316
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { Problem } from '../core/problem.ts';
|
|
2
|
+
|
|
3
|
+
export type ProcrastimateConfig = {
|
|
4
|
+
/** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
|
|
5
|
+
url: string;
|
|
6
|
+
/** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
|
|
7
|
+
token?: string;
|
|
8
|
+
/** The ProcrastiMate web app, for the link to a posted task. */
|
|
9
|
+
app?: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type Section = { id: string; name: string };
|
|
13
|
+
export type Project = { id: string; name: string; sections: Section[] };
|
|
14
|
+
/** Where a task goes: the Inbox without a project, and the project's top, above its sections, without a section. */
|
|
15
|
+
export type Place = { projectId?: string; sectionId?: string };
|
|
16
|
+
|
|
17
|
+
/** ProcrastiMate's `FILE_PART_BYTES` and `FILE_MAX_BYTES` (`shared/images.ts` there). */
|
|
18
|
+
const filePartBytes = 1_500_000;
|
|
19
|
+
const fileMaxBytes = 25_000_000;
|
|
20
|
+
const defaultApp = 'https://procrastimate.stf.lol';
|
|
21
|
+
|
|
22
|
+
const projectsKey = 'feedback.procrastimate.projects';
|
|
23
|
+
const lastProjectKey = 'feedback.procrastimate.project';
|
|
24
|
+
|
|
25
|
+
function stored<T>(key: string): T | undefined {
|
|
26
|
+
try {
|
|
27
|
+
const value = localStorage.getItem(key);
|
|
28
|
+
return value === null ? undefined : (JSON.parse(value) as T);
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const store = (key: string, value: unknown) => {
|
|
35
|
+
try {
|
|
36
|
+
if (value === undefined) localStorage.removeItem(key);
|
|
37
|
+
else localStorage.setItem(key, JSON.stringify(value));
|
|
38
|
+
} catch {
|
|
39
|
+
// Storage can be off, as in a private window. The picker then opens empty.
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** The projects from the last time the picker loaded them, so it opens filled. */
|
|
44
|
+
export const cachedProjects = () => stored<Project[]>(projectsKey) ?? [];
|
|
45
|
+
/** The project of the last post. Its section is not kept, so a new post starts at the project's top. */
|
|
46
|
+
export const lastProject = () => stored<string>(lastProjectKey);
|
|
47
|
+
|
|
48
|
+
export const taskLink = (config: ProcrastimateConfig, id: string) =>
|
|
49
|
+
`${(config.app ?? defaultApp).replace(/\/$/, '')}/inbox?task=${encodeURIComponent(id)}`;
|
|
50
|
+
|
|
51
|
+
async function send(
|
|
52
|
+
config: ProcrastimateConfig,
|
|
53
|
+
method: string,
|
|
54
|
+
path: string,
|
|
55
|
+
query: Record<string, string> = {},
|
|
56
|
+
body?: BodyInit,
|
|
57
|
+
type?: string,
|
|
58
|
+
) {
|
|
59
|
+
const search = new URLSearchParams(Object.entries(query).toSorted(([a], [b]) => a.localeCompare(b)));
|
|
60
|
+
const url = `${config.url.replace(/\/$/, '')}/${path}${search.size ? `?${search}` : ''}`;
|
|
61
|
+
let response: Response;
|
|
62
|
+
try {
|
|
63
|
+
response = await fetch(url, {
|
|
64
|
+
method,
|
|
65
|
+
body,
|
|
66
|
+
headers: {
|
|
67
|
+
...(config.token ? { Authorization: `Bearer ${config.token}` } : {}),
|
|
68
|
+
...(type ? { 'Content-Type': type } : {}),
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw Problem.request(method, url, undefined, undefined, error);
|
|
73
|
+
}
|
|
74
|
+
if (response.ok) return response;
|
|
75
|
+
const text = await response.text().catch(() => '');
|
|
76
|
+
if (response.status === 401) {
|
|
77
|
+
throw Problem.request(
|
|
78
|
+
method,
|
|
79
|
+
url,
|
|
80
|
+
response.status,
|
|
81
|
+
text,
|
|
82
|
+
new Error('ProcrastiMate rejected the token. Check the token Feedback was set up with.'),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
let message: string | undefined;
|
|
86
|
+
try {
|
|
87
|
+
message = (JSON.parse(text) as { message?: string }).message;
|
|
88
|
+
} catch {
|
|
89
|
+
// A proxy's HTML error page, which the details show as it came.
|
|
90
|
+
}
|
|
91
|
+
throw Problem.request(
|
|
92
|
+
method,
|
|
93
|
+
url,
|
|
94
|
+
response.status,
|
|
95
|
+
text,
|
|
96
|
+
new Error(message ? `ProcrastiMate: ${message}` : `ProcrastiMate answered ${response.status}.`),
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type Row = { id: string; name: string; order: number; createdAt: number };
|
|
101
|
+
const inOrder = <T extends Row>(rows: T[]) => rows.toSorted((a, b) => a.order - b.order || a.createdAt - b.createdAt);
|
|
102
|
+
|
|
103
|
+
/** The space's projects and their sections in the app's order. `/api/view` is the only route that lists them. */
|
|
104
|
+
export async function loadProjects(config: ProcrastimateConfig): Promise<Project[]> {
|
|
105
|
+
const view = (await (await send(config, 'GET', 'api/view')).json()) as {
|
|
106
|
+
projects: Row[];
|
|
107
|
+
sections: (Row & { projectId: string })[];
|
|
108
|
+
};
|
|
109
|
+
const projects = inOrder(view.projects).map(project => ({
|
|
110
|
+
id: project.id,
|
|
111
|
+
name: project.name,
|
|
112
|
+
sections: inOrder(view.sections.filter(section => section.projectId === project.id)).map(({ id, name }) => ({
|
|
113
|
+
id,
|
|
114
|
+
name,
|
|
115
|
+
})),
|
|
116
|
+
}));
|
|
117
|
+
store(projectsKey, projects);
|
|
118
|
+
return projects;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
type Encoded = { blob: Blob; width: number; height: number };
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A JPEG of the image no wider than `width` and no larger than `maxBytes`. ProcrastiMate's own clients fit the long
|
|
125
|
+
* side. A full-length capture is many times taller than wide, so this fits the width, which keeps its text readable.
|
|
126
|
+
*/
|
|
127
|
+
async function jpeg(image: HTMLCanvasElement, width: number, maxBytes: number): Promise<Encoded> {
|
|
128
|
+
for (let target = Math.min(width, image.width); target >= 64; target = Math.floor((target * 3) / 4)) {
|
|
129
|
+
const scaled = document.createElement('canvas');
|
|
130
|
+
scaled.width = target;
|
|
131
|
+
scaled.height = Math.max(1, Math.round((image.height * target) / image.width));
|
|
132
|
+
const context = scaled.getContext('2d')!;
|
|
133
|
+
context.imageSmoothingQuality = 'high';
|
|
134
|
+
context.drawImage(image, 0, 0, scaled.width, scaled.height);
|
|
135
|
+
for (const quality of [0.8, 0.65, 0.5]) {
|
|
136
|
+
const blob = await new Promise<Blob | null>(resolve => scaled.toBlob(resolve, 'image/jpeg', quality));
|
|
137
|
+
if (blob && blob.size <= maxBytes) return { blob, width: scaled.width, height: scaled.height };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
throw new Error('The image could not be made small enough to upload.');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Creates one task with the image export and `feedback.json` attached, and returns its id. The attachments upload
|
|
145
|
+
* before the task that lists them, as ProcrastiMate's own clients do, so the task never names bytes the server
|
|
146
|
+
* cannot serve.
|
|
147
|
+
*/
|
|
148
|
+
export async function postTask(
|
|
149
|
+
config: ProcrastimateConfig,
|
|
150
|
+
title: string,
|
|
151
|
+
place: Place,
|
|
152
|
+
image: HTMLCanvasElement,
|
|
153
|
+
report: string,
|
|
154
|
+
step: (text: string) => void,
|
|
155
|
+
) {
|
|
156
|
+
const bytes = new TextEncoder().encode(report);
|
|
157
|
+
if (bytes.length > fileMaxBytes) throw new Error("The JSON report is over ProcrastiMate's 25 MB file limit.");
|
|
158
|
+
step('Encoding the image');
|
|
159
|
+
const full = await jpeg(image, 2048, 1_500_000);
|
|
160
|
+
const thumb = await jpeg(image, 320, 200_000);
|
|
161
|
+
const imageId = crypto.randomUUID();
|
|
162
|
+
const reportId = crypto.randomUUID();
|
|
163
|
+
step('Uploading the image');
|
|
164
|
+
await send(config, 'PUT', 'api/images', { id: imageId, size: 'full' }, full.blob, 'image/jpeg');
|
|
165
|
+
step('Uploading the thumbnail');
|
|
166
|
+
await send(config, 'PUT', 'api/images', { id: imageId, size: 'thumb' }, thumb.blob, 'image/jpeg');
|
|
167
|
+
const parts = Math.max(1, Math.ceil(bytes.length / filePartBytes));
|
|
168
|
+
for (let start = 0, part = 0; start < bytes.length; start += filePartBytes, part++) {
|
|
169
|
+
step(parts === 1 ? 'Uploading feedback.json' : `Uploading feedback.json, part ${part + 1} of ${parts}`);
|
|
170
|
+
const chunk = bytes.slice(start, start + filePartBytes);
|
|
171
|
+
await send(config, 'PUT', 'api/images', { id: reportId, size: `part${part}` }, chunk, 'application/octet-stream');
|
|
172
|
+
}
|
|
173
|
+
step('Creating the task');
|
|
174
|
+
const created = await send(
|
|
175
|
+
config,
|
|
176
|
+
'POST',
|
|
177
|
+
'api/tasks',
|
|
178
|
+
{},
|
|
179
|
+
JSON.stringify({ title, projectId: place.projectId ?? null, sectionId: place.sectionId ?? null }),
|
|
180
|
+
'application/json',
|
|
181
|
+
);
|
|
182
|
+
const { id } = (await created.json()) as { id: string };
|
|
183
|
+
// The agent API cannot create a task with attachments, so a failed attach would leave a task without them, and a retry would add a second one.
|
|
184
|
+
step('Attaching the files');
|
|
185
|
+
try {
|
|
186
|
+
await send(
|
|
187
|
+
config,
|
|
188
|
+
'PATCH',
|
|
189
|
+
'api/tasks',
|
|
190
|
+
{ id },
|
|
191
|
+
JSON.stringify({
|
|
192
|
+
attachments: [
|
|
193
|
+
{ id: imageId, width: full.width, height: full.height },
|
|
194
|
+
{ id: reportId, name: 'feedback.json', type: 'application/json', bytes: bytes.length },
|
|
195
|
+
],
|
|
196
|
+
}),
|
|
197
|
+
'application/json',
|
|
198
|
+
);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
await send(config, 'DELETE', 'api/tasks', { id }).catch(() => {});
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
store(lastProjectKey, place.projectId);
|
|
204
|
+
return id;
|
|
205
|
+
}
|