emdash-plugin-retouche 0.1.0 → 0.2.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/CHANGELOG.md +35 -10
- package/README.md +96 -85
- package/dist/index.d.mts +8 -8
- package/dist/index.mjs +66 -81
- package/package.json +5 -3
- package/src/admin/BeforeAfter.tsx +7 -5
- package/src/admin/ImageField.tsx +80 -0
- package/src/admin/RetouchePage.tsx +26 -28
- package/src/admin/api.ts +11 -15
- package/src/admin/errors.ts +34 -0
- package/src/admin/i18n/en.ts +35 -0
- package/src/admin/i18n/fr.ts +35 -0
- package/src/admin/i18n/messages.ts +37 -0
- package/src/admin/i18n/useMessages.ts +24 -0
- package/src/admin/usePreview.ts +11 -10
- package/src/shared/api.ts +2 -7
- package/src/shared/errors.ts +8 -0
- package/src/shared/filename.ts +2 -2
- package/src/shared/formats.ts +6 -0
- package/src/shared/presets.ts +1 -11
- package/src/admin/ImagePicker.tsx +0 -122
package/dist/index.mjs
CHANGED
|
@@ -3,21 +3,21 @@ import { z } from "astro/zod";
|
|
|
3
3
|
import sharp from "sharp";
|
|
4
4
|
// package.json
|
|
5
5
|
var name = "emdash-plugin-retouche";
|
|
6
|
-
var version = "0.
|
|
6
|
+
var version = "0.2.0";
|
|
7
7
|
// src/shared/presets.ts
|
|
8
|
-
const PRESETS = ["
|
|
8
|
+
const PRESETS = ["pencil", "color"];
|
|
9
9
|
// src/image/pixels.ts
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* Operations on raw interleaved 8-bit pixels (1 channel for grayscale,
|
|
12
|
+
* 3 channels for RGB). Input arrays are never modified.
|
|
13
13
|
*/
|
|
14
14
|
const MAX = 255;
|
|
15
|
-
/**
|
|
15
|
+
/** Divides each pixel by the blurred background: paper tends towards `gain`. */
|
|
16
16
|
function flattenIllumination(pixels, background, gain) {
|
|
17
|
-
if (pixels.length !== background.length) throw new RangeError("
|
|
17
|
+
if (pixels.length !== background.length) throw new RangeError("The image and its background differ in size.");
|
|
18
18
|
return new Uint8Array(pixels.length).map((_, i) => Math.min(MAX, Math.round(pixels[i] * gain / Math.max(1, background[i]))));
|
|
19
19
|
}
|
|
20
|
-
/**
|
|
20
|
+
/** Rec. 601 luma, like PIL `Image.convert("L")`. */
|
|
21
21
|
function luminance(pixels, channels) {
|
|
22
22
|
if (channels === 1) return pixels;
|
|
23
23
|
return new Uint8Array(pixels.length / channels).map((_, i) => {
|
|
@@ -32,9 +32,9 @@ function histogram(values) {
|
|
|
32
32
|
}, /* @__PURE__ */ new Uint32Array(256));
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
|
-
*
|
|
36
|
-
* `ImageOps.autocontrast(cutoff=...)
|
|
37
|
-
*
|
|
35
|
+
* Autocontrast bounds, following PIL
|
|
36
|
+
* `ImageOps.autocontrast(cutoff=...)`: drop `dark` of the pixels from the
|
|
37
|
+
* bottom and `light` from the top, then read the remaining extreme values.
|
|
38
38
|
*/
|
|
39
39
|
function contrastBounds(counts, cutoff) {
|
|
40
40
|
const total = counts.reduce((sum, count) => sum + count, 0);
|
|
@@ -47,7 +47,7 @@ function firstAbove(counts, skipped) {
|
|
|
47
47
|
const index = counts.findIndex((_, i) => counts.subarray(0, i + 1).reduce((sum, count) => sum + count, 0) > skipped);
|
|
48
48
|
return index === -1 ? 0 : index;
|
|
49
49
|
}
|
|
50
|
-
/**
|
|
50
|
+
/** Linear stretch table from `[low, high]` to `[0, 255]`. */
|
|
51
51
|
function stretchTable(low, high) {
|
|
52
52
|
const identity = (/* @__PURE__ */ new Uint8Array(256)).map((_, v) => v);
|
|
53
53
|
if (high <= low) return identity;
|
|
@@ -57,27 +57,27 @@ function stretchTable(low, high) {
|
|
|
57
57
|
function applyTable(pixels, table) {
|
|
58
58
|
return pixels.map((v) => table[v]);
|
|
59
59
|
}
|
|
60
|
-
/**
|
|
60
|
+
/** Linear blend: 0 returns `from`, 1 returns `to`. */
|
|
61
61
|
function blend(from, to, amount) {
|
|
62
|
-
if (from.length !== to.length) throw new RangeError("
|
|
62
|
+
if (from.length !== to.length) throw new RangeError("The two images differ in size.");
|
|
63
63
|
const t = Math.min(1, Math.max(0, amount));
|
|
64
64
|
if (t === 1) return to;
|
|
65
65
|
return new Uint8Array(from.length).map((_, i) => Math.round(from[i] + (to[i] - from[i]) * t));
|
|
66
66
|
}
|
|
67
|
-
// src/image/
|
|
68
|
-
/**
|
|
67
|
+
// src/image/retouch.ts
|
|
68
|
+
/** Maximum width of the image saved to the media library. */
|
|
69
69
|
const OUTPUT_MAX_WIDTH = 2e3;
|
|
70
|
-
/**
|
|
70
|
+
/** Target paper level after the lighting correction. */
|
|
71
71
|
const PAPER_GAIN = 235;
|
|
72
72
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
73
|
+
* The reference setting blurs a 600 px wide image by 40 px: the blur is
|
|
74
|
+
* therefore 1/15 of the width, whatever the processed size.
|
|
75
75
|
*/
|
|
76
76
|
const BLUR_RATIO = 40 / 600;
|
|
77
77
|
/**
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
78
|
+
* The background is estimated on a reduced copy, then enlarged: a 130 px
|
|
79
|
+
* Gaussian blur at 2000 px would cost far more for the same result, since
|
|
80
|
+
* the background only holds low frequencies.
|
|
81
81
|
*/
|
|
82
82
|
const BACKGROUND_WIDTH = 240;
|
|
83
83
|
const CUTOFF = {
|
|
@@ -85,7 +85,7 @@ const CUTOFF = {
|
|
|
85
85
|
light: .13
|
|
86
86
|
};
|
|
87
87
|
const JPEG_QUALITY = 86;
|
|
88
|
-
async function
|
|
88
|
+
async function retouch(input, options) {
|
|
89
89
|
const base = await decode(input, options);
|
|
90
90
|
const background = await estimateBackground(base);
|
|
91
91
|
const flattened = flattenIllumination(base.pixels, background, PAPER_GAIN);
|
|
@@ -103,17 +103,17 @@ async function retoucher(input, options) {
|
|
|
103
103
|
};
|
|
104
104
|
}
|
|
105
105
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
106
|
+
* Applies the EXIF orientation of phone photos, flattens transparency onto
|
|
107
|
+
* white and scales the image down to the requested width. Metadata, GPS
|
|
108
|
+
* position included, is not carried over to the output JPEG.
|
|
109
109
|
*/
|
|
110
110
|
async function decode(input, options) {
|
|
111
111
|
const { data, info } = await sharp(input).rotate().flatten({ background: "#ffffff" }).resize({
|
|
112
112
|
width: options.maxWidth,
|
|
113
113
|
withoutEnlargement: true
|
|
114
|
-
}).toColourspace(colourspace(options.preset === "
|
|
114
|
+
}).toColourspace(colourspace(options.preset === "color" ? 3 : 1)).raw().toBuffer({ resolveWithObject: true });
|
|
115
115
|
const channels = info.channels;
|
|
116
|
-
if (channels !== 1 && channels !== 3) throw new Error(`
|
|
116
|
+
if (channels !== 1 && channels !== 3) throw new Error(`Unexpected channel count after decoding: ${String(channels)}.`);
|
|
117
117
|
return {
|
|
118
118
|
pixels: new Uint8Array(data),
|
|
119
119
|
width: info.width,
|
|
@@ -122,9 +122,9 @@ async function decode(input, options) {
|
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
125
|
+
* Within one pipeline sharp always resizes before blurring, whatever the
|
|
126
|
+
* call order: reduction, blur and enlargement therefore run as three
|
|
127
|
+
* separate pipelines.
|
|
128
128
|
*/
|
|
129
129
|
async function estimateBackground(image) {
|
|
130
130
|
const smallWidth = Math.min(BACKGROUND_WIDTH, image.width);
|
|
@@ -143,7 +143,7 @@ async function transform(image, operation) {
|
|
|
143
143
|
channels: image.channels
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
|
-
/**
|
|
146
|
+
/** Without an explicit colourspace, sharp outputs a 1-channel raw input as RGB. */
|
|
147
147
|
function colourspace(channels) {
|
|
148
148
|
return channels === 1 ? "b-w" : "srgb";
|
|
149
149
|
}
|
|
@@ -156,40 +156,32 @@ function rawInfo(image) {
|
|
|
156
156
|
}
|
|
157
157
|
// src/shared/filename.ts
|
|
158
158
|
const EXTENSION = /\.[^./\\]+$/;
|
|
159
|
-
const
|
|
159
|
+
const RETOUCHED_SUFFIX = "-retouched";
|
|
160
160
|
function retouchedFilename(original) {
|
|
161
161
|
const base = original.trim().replace(EXTENSION, "");
|
|
162
|
-
return `${base.length > 0 ? base : "image"}${
|
|
162
|
+
return `${base.length > 0 ? base : "image"}${RETOUCHED_SUFFIX}.jpg`;
|
|
163
163
|
}
|
|
164
|
-
// src/
|
|
165
|
-
/**
|
|
166
|
-
const
|
|
167
|
-
/** Formats que sharp sait décoder parmi ceux qu'accepte la médiathèque. */
|
|
168
|
-
const DECODABLE = /* @__PURE__ */ new Set([
|
|
164
|
+
// src/shared/formats.ts
|
|
165
|
+
/** Media library formats that sharp can decode. */
|
|
166
|
+
const DECODABLE_TYPES = [
|
|
169
167
|
"image/jpeg",
|
|
170
168
|
"image/png",
|
|
171
169
|
"image/webp",
|
|
172
170
|
"image/avif",
|
|
173
171
|
"image/gif"
|
|
174
|
-
]
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
mimeType: "image/",
|
|
178
|
-
limit: 48,
|
|
179
|
-
...cursor === void 0 ? {} : { cursor }
|
|
180
|
-
});
|
|
181
|
-
return {
|
|
182
|
-
items: page.items.filter((item) => DECODABLE.has(item.mimeType)).map((item) => ({
|
|
183
|
-
id: item.id,
|
|
184
|
-
filename: item.filename,
|
|
185
|
-
url: item.url,
|
|
186
|
-
width: item.width ?? null,
|
|
187
|
-
height: item.height ?? null
|
|
188
|
-
})),
|
|
189
|
-
nextCursor: page.hasMore ? page.cursor ?? null : null
|
|
190
|
-
};
|
|
172
|
+
];
|
|
173
|
+
function isDecodable(mimeType) {
|
|
174
|
+
return DECODABLE_TYPES.some((type) => type === mimeType);
|
|
191
175
|
}
|
|
192
|
-
|
|
176
|
+
// src/plugin/errors.ts
|
|
177
|
+
/** The English message is for logs and API clients; the admin translates `code`. */
|
|
178
|
+
function routeError(code, message, status) {
|
|
179
|
+
return new PluginRouteError(code, message, status);
|
|
180
|
+
}
|
|
181
|
+
// src/plugin/actions.ts
|
|
182
|
+
/** Cap that EmDash enforces on `ctx.media.readBytes()`. */
|
|
183
|
+
const MAX_INPUT_BYTES = 16777216;
|
|
184
|
+
async function previewRetouch(media, request) {
|
|
193
185
|
const result = await render(await readSource(media, request.mediaId), request, 900);
|
|
194
186
|
return {
|
|
195
187
|
dataUrl: `data:image/jpeg;base64,${Buffer.from(result.jpeg.buffer).toString("base64")}`,
|
|
@@ -197,9 +189,9 @@ async function previewRetouche(media, request) {
|
|
|
197
189
|
height: result.height
|
|
198
190
|
};
|
|
199
191
|
}
|
|
200
|
-
/**
|
|
201
|
-
async function
|
|
202
|
-
if (!media.upload) throw
|
|
192
|
+
/** Always creates a new media item: the original is neither replaced nor modified. */
|
|
193
|
+
async function saveRetouch(media, request) {
|
|
194
|
+
if (!media.upload) throw routeError("MEDIA_UNAVAILABLE", "Uploading to the media library is not allowed.", 500);
|
|
203
195
|
const source = await readSource(media, request.mediaId);
|
|
204
196
|
const result = await render(source, request, OUTPUT_MAX_WIDTH);
|
|
205
197
|
const filename = retouchedFilename(source.filename);
|
|
@@ -212,9 +204,9 @@ async function saveRetouche(media, request) {
|
|
|
212
204
|
}
|
|
213
205
|
async function readSource(media, mediaId) {
|
|
214
206
|
const item = await media.get(mediaId);
|
|
215
|
-
if (!item) throw
|
|
216
|
-
if (!
|
|
217
|
-
if (!media.readBytes) throw
|
|
207
|
+
if (!item) throw routeError("IMAGE_NOT_FOUND", "Image not found in the media library.", 404);
|
|
208
|
+
if (!isDecodable(item.mimeType)) throw routeError("UNSUPPORTED_FORMAT", `Unsupported format: ${item.mimeType}.`, 400);
|
|
209
|
+
if (!media.readBytes) throw routeError("MEDIA_UNAVAILABLE", "Reading files is not allowed.", 500);
|
|
218
210
|
const file = await media.readBytes(mediaId, { maxBytes: MAX_INPUT_BYTES });
|
|
219
211
|
return {
|
|
220
212
|
filename: item.filename,
|
|
@@ -223,46 +215,39 @@ async function readSource(media, mediaId) {
|
|
|
223
215
|
}
|
|
224
216
|
async function render(source, request, maxWidth) {
|
|
225
217
|
try {
|
|
226
|
-
return await
|
|
218
|
+
return await retouch(source.bytes, {
|
|
227
219
|
preset: request.preset,
|
|
228
220
|
intensity: request.intensity / 100,
|
|
229
221
|
maxWidth
|
|
230
222
|
});
|
|
231
223
|
} catch {
|
|
232
|
-
throw
|
|
224
|
+
throw routeError("UNDECODABLE_IMAGE", "This image could not be decoded.", 400);
|
|
233
225
|
}
|
|
234
226
|
}
|
|
235
227
|
// src/plugin/routes.ts
|
|
236
|
-
const
|
|
228
|
+
const retouchInput = z.object({
|
|
237
229
|
mediaId: z.string().min(1).max(200),
|
|
238
230
|
preset: z.enum(PRESETS),
|
|
239
231
|
intensity: z.number().min(0).max(100)
|
|
240
232
|
});
|
|
241
|
-
const imagesInput = z.object({ cursor: z.string().min(1).max(500).optional() });
|
|
242
233
|
function requireMedia(ctx) {
|
|
243
|
-
if (!ctx.media) throw
|
|
234
|
+
if (!ctx.media) throw routeError("MEDIA_UNAVAILABLE", "The media library is not available to the plugin.", 500);
|
|
244
235
|
return ctx.media;
|
|
245
236
|
}
|
|
246
237
|
const routes = {
|
|
247
|
-
images: {
|
|
248
|
-
methods: ["GET"],
|
|
249
|
-
permission: "media:read",
|
|
250
|
-
input: imagesInput,
|
|
251
|
-
handler: (ctx) => listImages(requireMedia(ctx), ctx.input.cursor)
|
|
252
|
-
},
|
|
253
238
|
preview: {
|
|
254
239
|
methods: ["POST"],
|
|
255
240
|
permission: "media:read",
|
|
256
|
-
input:
|
|
257
|
-
handler: (ctx) =>
|
|
241
|
+
input: retouchInput,
|
|
242
|
+
handler: (ctx) => previewRetouch(requireMedia(ctx), ctx.input)
|
|
258
243
|
},
|
|
259
244
|
save: {
|
|
260
245
|
methods: ["POST"],
|
|
261
246
|
permission: "media:upload",
|
|
262
|
-
input:
|
|
247
|
+
input: retouchInput,
|
|
263
248
|
handler: async (ctx) => {
|
|
264
|
-
const saved = await
|
|
265
|
-
ctx.log.info("
|
|
249
|
+
const saved = await saveRetouch(requireMedia(ctx), ctx.input);
|
|
250
|
+
ctx.log.info("Retouched image saved", {
|
|
266
251
|
source: ctx.input.mediaId,
|
|
267
252
|
created: saved.mediaId,
|
|
268
253
|
preset: ctx.input.preset,
|
|
@@ -276,7 +261,7 @@ const routes = {
|
|
|
276
261
|
const PLUGIN_ID = "retouche";
|
|
277
262
|
// src/index.ts
|
|
278
263
|
const ADMIN_ENTRY = `${name}/admin`;
|
|
279
|
-
/**
|
|
264
|
+
/** Add to `plugins: []` of the `emdash()` integration in `astro.config.mjs`. */
|
|
280
265
|
function retouchePlugin() {
|
|
281
266
|
return {
|
|
282
267
|
id: PLUGIN_ID,
|
|
@@ -290,7 +275,7 @@ function createPlugin() {
|
|
|
290
275
|
return definePlugin({
|
|
291
276
|
id: PLUGIN_ID,
|
|
292
277
|
displayName: "Retouche",
|
|
293
|
-
description: "
|
|
278
|
+
description: "Automatic retouching of drawing photos: white paper, contrast, sensible size.",
|
|
294
279
|
version,
|
|
295
280
|
capabilities: [
|
|
296
281
|
"media:read",
|
|
@@ -308,4 +293,4 @@ function createPlugin() {
|
|
|
308
293
|
}
|
|
309
294
|
});
|
|
310
295
|
}
|
|
311
|
-
export { createPlugin,
|
|
296
|
+
export { createPlugin, retouch, retouchePlugin };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "emdash-plugin-retouche",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Native EmDash plugin that retouches phone photos of drawings: white paper, stronger contrast, sensible size.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Wallerand Delevacq",
|
|
7
7
|
"repository": {
|
|
@@ -47,12 +47,14 @@
|
|
|
47
47
|
"astro": ">=6.0.0",
|
|
48
48
|
"emdash": ">=1.6.0 <2.0.0",
|
|
49
49
|
"react": "^18.0.0 || ^19.0.0",
|
|
50
|
-
"sharp": ">=0.34.0"
|
|
50
|
+
"sharp": ">=0.34.0",
|
|
51
|
+
"@emdash-cms/admin": ">=1.6.0 <2.0.0"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
54
|
"@cloudflare/kumo": "2.19.0",
|
|
54
55
|
"@commitlint/cli": "^21.3.0",
|
|
55
56
|
"@commitlint/config-conventional": "^21.3.0",
|
|
57
|
+
"@emdash-cms/admin": "1.6.0",
|
|
56
58
|
"@eslint/js": "^9.39.5",
|
|
57
59
|
"@types/node": "^24.0.0",
|
|
58
60
|
"@types/react": "^19.3.3",
|
|
@@ -2,6 +2,7 @@ import { Loader } from "@cloudflare/kumo";
|
|
|
2
2
|
import type * as React from "react";
|
|
3
3
|
|
|
4
4
|
import type { ImageSummary } from "../shared/api.js";
|
|
5
|
+
import { useMessages } from "./i18n/useMessages.js";
|
|
5
6
|
import type { PreviewState } from "./usePreview.js";
|
|
6
7
|
|
|
7
8
|
interface BeforeAfterProps {
|
|
@@ -29,21 +30,22 @@ const pending: React.CSSProperties = { ...picture, minHeight: "12rem", display:
|
|
|
29
30
|
|
|
30
31
|
export function BeforeAfter({ source, state }: BeforeAfterProps) {
|
|
31
32
|
const { preview, loading, error } = state;
|
|
33
|
+
const messages = useMessages();
|
|
32
34
|
return (
|
|
33
35
|
<div className="space-y-4">
|
|
34
36
|
<div style={layout}>
|
|
35
37
|
<figure style={frame}>
|
|
36
|
-
<figcaption className="text-sm font-medium">
|
|
37
|
-
<img src={source.url} alt={
|
|
38
|
+
<figcaption className="text-sm font-medium">{messages.before}</figcaption>
|
|
39
|
+
<img src={source.url} alt={messages.originalAlt(source.filename)} style={picture} />
|
|
38
40
|
</figure>
|
|
39
41
|
<figure style={frame} aria-busy={loading}>
|
|
40
|
-
<figcaption className="text-sm font-medium">
|
|
42
|
+
<figcaption className="text-sm font-medium">{messages.after}</figcaption>
|
|
41
43
|
{preview === null ? (
|
|
42
44
|
<div style={pending}>{loading ? <Loader /> : null}</div>
|
|
43
45
|
) : (
|
|
44
46
|
<img
|
|
45
47
|
src={preview.dataUrl}
|
|
46
|
-
alt=
|
|
48
|
+
alt={messages.previewAlt}
|
|
47
49
|
style={{ ...picture, opacity: loading ? 0.6 : 1 }}
|
|
48
50
|
/>
|
|
49
51
|
)}
|
|
@@ -51,7 +53,7 @@ export function BeforeAfter({ source, state }: BeforeAfterProps) {
|
|
|
51
53
|
</div>
|
|
52
54
|
{error === null ? null : (
|
|
53
55
|
<p role="alert" className="text-kumo-danger">
|
|
54
|
-
{error}
|
|
56
|
+
{messages.errors[error]}
|
|
55
57
|
</p>
|
|
56
58
|
)}
|
|
57
59
|
</div>
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type MediaItem, MediaPickerModal } from "@emdash-cms/admin";
|
|
2
|
+
import { Button } from "@cloudflare/kumo";
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
|
|
5
|
+
import type { ImageSummary } from "../shared/api.js";
|
|
6
|
+
import { DECODABLE_TYPES } from "../shared/formats.js";
|
|
7
|
+
import { useMessages } from "./i18n/useMessages.js";
|
|
8
|
+
|
|
9
|
+
interface ImageFieldProps {
|
|
10
|
+
readonly selected: ImageSummary | null;
|
|
11
|
+
readonly onSelect: (image: ImageSummary) => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const row: React.CSSProperties = { display: "flex", alignItems: "center", gap: "0.75rem" };
|
|
15
|
+
|
|
16
|
+
const thumbnail: React.CSSProperties = {
|
|
17
|
+
width: "4rem",
|
|
18
|
+
height: "4rem",
|
|
19
|
+
flexShrink: 0,
|
|
20
|
+
objectFit: "cover",
|
|
21
|
+
borderRadius: "0.375rem",
|
|
22
|
+
background: "rgba(127, 127, 127, 0.15)",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const details: React.CSSProperties = { display: "flex", flexDirection: "column", minWidth: 0, flex: 1 };
|
|
26
|
+
|
|
27
|
+
const ellipsis: React.CSSProperties = { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" };
|
|
28
|
+
|
|
29
|
+
function toSummary(item: MediaItem): ImageSummary {
|
|
30
|
+
return { id: item.id, filename: item.filename, url: item.url, width: item.width ?? null, height: item.height ?? null };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Selected image on one line; the EmDash media picker opens on demand. */
|
|
34
|
+
export function ImageField({ selected, onSelect }: ImageFieldProps) {
|
|
35
|
+
const [open, setOpen] = React.useState(false);
|
|
36
|
+
const messages = useMessages();
|
|
37
|
+
|
|
38
|
+
return (
|
|
39
|
+
<div style={row}>
|
|
40
|
+
{selected === null ? null : (
|
|
41
|
+
<>
|
|
42
|
+
<img src={selected.url} alt="" style={thumbnail} />
|
|
43
|
+
<div style={details}>
|
|
44
|
+
<span className="font-medium" style={ellipsis} title={selected.filename}>
|
|
45
|
+
{selected.filename}
|
|
46
|
+
</span>
|
|
47
|
+
{selected.width === null || selected.height === null ? null : (
|
|
48
|
+
<span className="text-sm text-kumo-subtle">
|
|
49
|
+
{selected.width} × {selected.height}
|
|
50
|
+
</span>
|
|
51
|
+
)}
|
|
52
|
+
</div>
|
|
53
|
+
</>
|
|
54
|
+
)}
|
|
55
|
+
<Button
|
|
56
|
+
type="button"
|
|
57
|
+
variant={selected === null ? "primary" : "secondary"}
|
|
58
|
+
onClick={() => {
|
|
59
|
+
setOpen(true);
|
|
60
|
+
}}
|
|
61
|
+
>
|
|
62
|
+
{selected === null ? messages.chooseImage : messages.changeImage}
|
|
63
|
+
</Button>
|
|
64
|
+
<MediaPickerModal
|
|
65
|
+
open={open}
|
|
66
|
+
onOpenChange={setOpen}
|
|
67
|
+
onSelect={(item) => {
|
|
68
|
+
onSelect(toSummary(item));
|
|
69
|
+
setOpen(false);
|
|
70
|
+
}}
|
|
71
|
+
mediaKind="image"
|
|
72
|
+
mimeTypeFilters={[...DECODABLE_TYPES]}
|
|
73
|
+
localOnly
|
|
74
|
+
hideUrlInput
|
|
75
|
+
title={messages.pickerTitle}
|
|
76
|
+
confirmLabel={messages.pickerConfirm}
|
|
77
|
+
/>
|
|
78
|
+
</div>
|
|
79
|
+
);
|
|
80
|
+
}
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import { Banner, Button, Radio, Slider } from "@cloudflare/kumo";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
|
|
4
|
-
import type { ImageSummary,
|
|
5
|
-
import { DEFAULT_INTENSITY,
|
|
6
|
-
import {
|
|
4
|
+
import type { ImageSummary, RetouchRequest, SaveResponse } from "../shared/api.js";
|
|
5
|
+
import { DEFAULT_INTENSITY, PRESETS, type Preset } from "../shared/presets.js";
|
|
6
|
+
import { saveRetouch } from "./api.js";
|
|
7
7
|
import { BeforeAfter } from "./BeforeAfter.js";
|
|
8
|
-
import {
|
|
8
|
+
import { type ErrorKey, errorKey } from "./errors.js";
|
|
9
|
+
import { useMessages } from "./i18n/useMessages.js";
|
|
10
|
+
import { ImageField } from "./ImageField.js";
|
|
9
11
|
import { requestKey, usePreview } from "./usePreview.js";
|
|
10
12
|
|
|
11
13
|
type SaveOutcome =
|
|
12
14
|
| { readonly status: "idle" }
|
|
13
15
|
| { readonly status: "saving" }
|
|
14
16
|
| { readonly status: "saved"; readonly result: SaveResponse }
|
|
15
|
-
| { readonly status: "error"; readonly
|
|
17
|
+
| { readonly status: "error"; readonly error: ErrorKey };
|
|
16
18
|
|
|
17
|
-
/**
|
|
19
|
+
/** A save result only applies to the settings that produced it. */
|
|
18
20
|
interface SaveState {
|
|
19
21
|
readonly key: string | null;
|
|
20
22
|
readonly outcome: SaveOutcome;
|
|
@@ -31,14 +33,14 @@ function firstValue(value: number | readonly number[]): number {
|
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
export function RetouchePage() {
|
|
36
|
+
const messages = useMessages();
|
|
34
37
|
const [source, setSource] = React.useState<ImageSummary | null>(null);
|
|
35
|
-
const [preset, setPreset] = React.useState<Preset>("
|
|
38
|
+
const [preset, setPreset] = React.useState<Preset>("pencil");
|
|
36
39
|
const [sliderValue, setSliderValue] = React.useState(DEFAULT_INTENSITY);
|
|
37
40
|
const [intensity, setIntensity] = React.useState(DEFAULT_INTENSITY);
|
|
38
41
|
const [saveState, setSaveState] = React.useState<SaveState>({ key: null, outcome: IDLE });
|
|
39
|
-
const [refreshKey, setRefreshKey] = React.useState(0);
|
|
40
42
|
|
|
41
|
-
const request = React.useMemo<
|
|
43
|
+
const request = React.useMemo<RetouchRequest | null>(
|
|
42
44
|
() => (source === null ? null : { mediaId: source.id, preset, intensity }),
|
|
43
45
|
[source, preset, intensity],
|
|
44
46
|
);
|
|
@@ -50,35 +52,31 @@ export function RetouchePage() {
|
|
|
50
52
|
if (request === null) return;
|
|
51
53
|
setSaveState({ key, outcome: { status: "saving" } });
|
|
52
54
|
try {
|
|
53
|
-
const result = await
|
|
55
|
+
const result = await saveRetouch(request);
|
|
54
56
|
setSaveState({ key, outcome: { status: "saved", result } });
|
|
55
|
-
setRefreshKey((current) => current + 1);
|
|
56
57
|
} catch (cause) {
|
|
57
|
-
setSaveState({ key, outcome: { status: "error",
|
|
58
|
+
setSaveState({ key, outcome: { status: "error", error: errorKey(cause, "SAVE_FAILED") } });
|
|
58
59
|
}
|
|
59
60
|
};
|
|
60
61
|
|
|
61
62
|
return (
|
|
62
63
|
<div className="space-y-6">
|
|
63
64
|
<header className="space-y-2">
|
|
64
|
-
<h1 className="text-2xl font-semibold">Retouche
|
|
65
|
-
<p className="text-kumo-subtle">
|
|
66
|
-
Choisissez la photo d'un dessin, puis un préréglage. L'image retouchée est ajoutée à la médiathèque comme
|
|
67
|
-
une nouvelle image : l'original n'est jamais modifié.
|
|
68
|
-
</p>
|
|
65
|
+
<h1 className="text-2xl font-semibold">Retouche</h1>
|
|
66
|
+
<p className="text-kumo-subtle">{messages.intro}</p>
|
|
69
67
|
</header>
|
|
70
68
|
|
|
71
69
|
<section className="space-y-3">
|
|
72
|
-
<h2 className="text-lg font-semibold">
|
|
73
|
-
<
|
|
70
|
+
<h2 className="text-lg font-semibold">{messages.imageStep}</h2>
|
|
71
|
+
<ImageField selected={source} onSelect={setSource} />
|
|
74
72
|
</section>
|
|
75
73
|
|
|
76
74
|
{source === null ? null : (
|
|
77
75
|
<>
|
|
78
76
|
<section className="space-y-4">
|
|
79
|
-
<h2 className="text-lg font-semibold">
|
|
77
|
+
<h2 className="text-lg font-semibold">{messages.settingsStep}</h2>
|
|
80
78
|
<Radio.Group
|
|
81
|
-
legend=
|
|
79
|
+
legend={messages.presetLegend}
|
|
82
80
|
appearance="card"
|
|
83
81
|
orientation="horizontal"
|
|
84
82
|
value={preset}
|
|
@@ -87,11 +85,11 @@ export function RetouchePage() {
|
|
|
87
85
|
}}
|
|
88
86
|
>
|
|
89
87
|
{PRESETS.map((id) => (
|
|
90
|
-
<Radio.Item key={id} value={id} label={
|
|
88
|
+
<Radio.Item key={id} value={id} label={messages.presets[id].label} description={messages.presets[id].description} />
|
|
91
89
|
))}
|
|
92
90
|
</Radio.Group>
|
|
93
91
|
<Slider
|
|
94
|
-
label=
|
|
92
|
+
label={messages.intensity}
|
|
95
93
|
min={0}
|
|
96
94
|
max={100}
|
|
97
95
|
step={5}
|
|
@@ -107,7 +105,7 @@ export function RetouchePage() {
|
|
|
107
105
|
</section>
|
|
108
106
|
|
|
109
107
|
<section className="space-y-4">
|
|
110
|
-
<h2 className="text-lg font-semibold">
|
|
108
|
+
<h2 className="text-lg font-semibold">{messages.previewStep}</h2>
|
|
111
109
|
<BeforeAfter source={source} state={preview} />
|
|
112
110
|
</section>
|
|
113
111
|
|
|
@@ -119,16 +117,16 @@ export function RetouchePage() {
|
|
|
119
117
|
disabled={preview.preview === null || preview.error !== null}
|
|
120
118
|
onClick={() => void handleSave()}
|
|
121
119
|
>
|
|
122
|
-
|
|
120
|
+
{messages.save}
|
|
123
121
|
</Button>
|
|
124
122
|
{save.status === "saved" ? (
|
|
125
123
|
<Banner
|
|
126
|
-
title=
|
|
127
|
-
description={
|
|
124
|
+
title={messages.savedTitle}
|
|
125
|
+
description={messages.savedDescription(save.result.filename)}
|
|
128
126
|
/>
|
|
129
127
|
) : null}
|
|
130
128
|
{save.status === "error" ? (
|
|
131
|
-
<Banner variant="error" title=
|
|
129
|
+
<Banner variant="error" title={messages.saveFailedTitle} description={messages.errors[save.error]} />
|
|
132
130
|
) : null}
|
|
133
131
|
</section>
|
|
134
132
|
</>
|
package/src/admin/api.ts
CHANGED
|
@@ -2,19 +2,19 @@ import { apiFetch, parseApiResponse } from "emdash/plugin-utils";
|
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
4
|
API_BASE,
|
|
5
|
-
type ImageListResponse,
|
|
6
5
|
type PreviewResponse,
|
|
7
|
-
type
|
|
6
|
+
type RetouchRequest,
|
|
8
7
|
type SaveResponse,
|
|
9
8
|
} from "../shared/api.js";
|
|
9
|
+
import { apiError } from "./errors.js";
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return parseApiResponse<
|
|
11
|
+
/** `parseApiResponse` reduces a failure to its message; `apiError` keeps `error.code` for translation. */
|
|
12
|
+
async function parse<T>(response: Response): Promise<T> {
|
|
13
|
+
if (!response.ok) throw await apiError(response);
|
|
14
|
+
return parseApiResponse<T>(response);
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
function post(route: string, request:
|
|
17
|
+
function post(route: string, request: RetouchRequest, signal?: AbortSignal): Promise<Response> {
|
|
18
18
|
return apiFetch(`${API_BASE}/${route}`, {
|
|
19
19
|
method: "POST",
|
|
20
20
|
headers: { "Content-Type": "application/json" },
|
|
@@ -23,14 +23,10 @@ function post(route: string, request: RetoucheRequest, signal?: AbortSignal): Pr
|
|
|
23
23
|
});
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
export async function fetchPreview(request:
|
|
27
|
-
return
|
|
26
|
+
export async function fetchPreview(request: RetouchRequest, signal: AbortSignal): Promise<PreviewResponse> {
|
|
27
|
+
return parse<PreviewResponse>(await post("preview", request, signal));
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
export async function
|
|
31
|
-
return
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function errorMessage(cause: unknown): string {
|
|
35
|
-
return cause instanceof Error ? cause.message : String(cause);
|
|
30
|
+
export async function saveRetouch(request: RetouchRequest): Promise<SaveResponse> {
|
|
31
|
+
return parse<SaveResponse>(await post("save", request));
|
|
36
32
|
}
|