@jskit-ai/uploads-image-web 0.2.39 → 0.2.41

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `createImageUploadRuntime` takes the phone's sources inside an app: `nativeSources` lists them and `pickFrom(source)` adds the chosen files to the same Uppy, so the field's checks, editor and upload are unchanged; `nativeSource` defaults to the page's.
5
6
  - The image dialog (Uppy's dashboard and image editor) takes the app's Material 3 roles and typeface, in light and dark: its panel is `surface-container-high` with 28dp corners and no outline, text `on-surface`, "browse files" a `primary` link underlined only under the pointer, filled buttons primary and full-shape, all in the theme's `--v-font-body`, instead of Uppy's light grey panel, blue underlined link and system font in both schemes. `@jskit-ai/uploads-image-web/client/styles` loads it after Uppy's stylesheets.
6
7
  - The image dialog is modal over the whole app: its `scrim` covers the top app bar, navigation and Vuetify's own overlays (Uppy's z-index 1001 sat under the app bar), and its close button sits inside the dialog in a 56dp header row, an `on-surface-variant` 48dp icon button, instead of above the container (hidden under the app bar at 390 and 768) or beside it (at 1280). At compact width (below 600dp) it is a full-screen dialog with the close button at the leading edge; at medium width it keeps 24dp from every edge. Its hint text is `on-surface-variant` (Uppy's #757575 on its grey panel was 4.2:1).
7
8
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/uploads-image-web",
3
- "version": "0.2.39",
3
+ "version": "0.2.41",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -15,7 +15,7 @@
15
15
  "./locales/en.json": "./locales/en.json"
16
16
  },
17
17
  "dependencies": {
18
- "@jskit-ai/uploads-runtime": "0.2.39",
18
+ "@jskit-ai/uploads-runtime": "0.2.41",
19
19
  "@uppy/compressor": "^3.1.0",
20
20
  "@uppy/core": "^5.2.0",
21
21
  "@uppy/dashboard": "^5.1.1",
@@ -23,7 +23,7 @@
23
23
  "@uppy/xhr-upload": "^5.1.1"
24
24
  },
25
25
  "peerDependencies": {
26
- "@jskit-ai/kernel": "0.2.39",
26
+ "@jskit-ai/kernel": "0.2.41",
27
27
  "vue": "^3.5.13"
28
28
  },
29
29
  "description": "Reusable client-side image upload runtime with pre-upload image editing.",
@@ -12,7 +12,8 @@ import {
12
12
  DEFAULT_IMAGE_UPLOAD_MAX_BYTES
13
13
  } from "../../shared/imageUploadDefaults.js";
14
14
  import { parseUploadResponse } from "../support/parseUploadResponse.js";
15
- import { closeDashboard, stopImageEditor } from "../support/uppyPlugins.js";
15
+ import { getNativeSource } from "@jskit-ai/uploads-runtime/client";
16
+ import { addNativeFiles, closeDashboard, stopImageEditor } from "../support/uppyPlugins.js";
16
17
  import { useJskitText } from "../i18n.js";
17
18
 
18
19
  function ignoreUploadEvent() {}
@@ -38,6 +39,7 @@ function createImageUploadRuntime({
38
39
  onUploadError,
39
40
  onRestrictionFailed,
40
41
  onUnavailable = ignoreUploadEvent,
42
+ nativeSource = getNativeSource(),
41
43
  dependencies: {
42
44
  UppyClass = Uppy,
43
45
  DashboardPlugin = Dashboard,
@@ -212,6 +214,24 @@ function createImageUploadRuntime({
212
214
  }
213
215
  }
214
216
 
217
+ /**
218
+ * Inside a phone app, chooses the image from one of the phone's own sources (`nativeSource.sources`: "camera",
219
+ * "photos", "scan", "files") and opens the same editor and upload the web's picker leads to. Nothing is added when the
220
+ * person cancels.
221
+ * @param {import("@jskit-ai/uploads-runtime/client").NativeSourceKind} source
222
+ */
223
+ async function pickFrom(source) {
224
+ setup();
225
+ if (!uploadUppy) {
226
+ onUnavailable();
227
+ return 0;
228
+ }
229
+ const files = await nativeSource.pick(source, { accept: normalizedAllowedMimeTypes, multiple: maxNumberOfFiles > 1 });
230
+ const added = files.length ? addNativeFiles(uploadUppy, files) : 0;
231
+ if (added) uploadUppy.getPlugin("Dashboard")?.openModal();
232
+ return added;
233
+ }
234
+
215
235
  function destroy() {
216
236
  if (!uploadUppy) {
217
237
  return;
@@ -224,6 +244,9 @@ function createImageUploadRuntime({
224
244
  return Object.freeze({
225
245
  destroy,
226
246
  openEditor,
247
+ // The phone's own sources inside an app, none on the web: a field offers a button for each.
248
+ nativeSources: nativeSource.sources,
249
+ pickFrom,
227
250
  setup
228
251
  });
229
252
  }
@@ -16,4 +16,24 @@ function stopImageEditor(uppy) {
16
16
  }
17
17
  }
18
18
 
19
- export { closeDashboard, stopImageEditor };
19
+ /**
20
+ * Adds files a native source answered (the camera, the photo picker, a scan, the document picker) to the field's
21
+ * Uppy, which checks them against the field's restrictions as it checks a file chosen on the web. Answers how many it
22
+ * took: one refused (too large, the wrong type, one too many) is reported through "restriction-failed".
23
+ * @param {import("../types.js").ImageUppy} uppy
24
+ * @param {ReadonlyArray<File>} files
25
+ */
26
+ function addNativeFiles(uppy, files) {
27
+ let added = 0;
28
+ for (const file of files) {
29
+ try {
30
+ uppy.addFile({ name: file.name, type: file.type, data: file, source: "native" });
31
+ added += 1;
32
+ } catch {
33
+ // Uppy has emitted "restriction-failed" for it, which the field shows.
34
+ }
35
+ }
36
+ return added;
37
+ }
38
+
39
+ export { addNativeFiles, closeDashboard, stopImageEditor };
@@ -52,6 +52,8 @@
52
52
  * @property {(failure: { file: unknown, error: Error, response: unknown, uppy: ImageUppy }) => void} onUploadError
53
53
  * @property {(failure: { file: unknown, error: Error, uppy: ImageUppy }) => void} onRestrictionFailed
54
54
  * @property {() => void} [onUnavailable] Called when the editor is opened outside a browser.
55
+ * @property {import("@jskit-ai/uploads-runtime/client").NativeSource} [nativeSource] Where files come from inside a phone
56
+ * app (the camera, the photo picker, a scan, the document picker); the page's own by default, none on the web.
55
57
  * @property {ImageUploadDependencies} [dependencies]
56
58
  */
57
59
 
@@ -0,0 +1,105 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createNativeSource } from "@jskit-ai/uploads-runtime/client";
4
+ import { createImageUploadRuntime } from "../src/client/composables/createImageUploadRuntime.js";
5
+
6
+ /** An Uppy that enforces the field's restrictions on addFile, as Uppy does, and records the dashboard opening. */
7
+ class RestrictingUppy {
8
+ constructor(options) {
9
+ this.options = options;
10
+ this.files = [];
11
+ this.handlers = new Map();
12
+ this.dashboard = { opened: 0, openModal: () => { this.dashboard.opened += 1; }, closeModal() {} };
13
+ }
14
+
15
+ use() { return this; }
16
+ on(event, handler) { this.handlers.set(event, handler); return this; }
17
+ getPlugin(name) { return name === "Dashboard" ? this.dashboard : null; }
18
+ destroy() {}
19
+
20
+ addFile(file) {
21
+ const { allowedFileTypes, maxFileSize, maxNumberOfFiles } = this.options.restrictions;
22
+ const error = !allowedFileTypes.includes(file.type) ? "type" : file.data.size > maxFileSize ? "size" : this.files.length >= maxNumberOfFiles ? "count" : "";
23
+ if (error) {
24
+ this.handlers.get("restriction-failed")?.(file, new Error(error));
25
+ throw new Error(error);
26
+ }
27
+ this.files.push(file);
28
+ }
29
+ }
30
+
31
+ /** The runtime sets up only in a browser: a window for the test, removed after it. */
32
+ function withWindow(t) {
33
+ const had = Object.hasOwn(globalThis, "window");
34
+ const previous = globalThis.window;
35
+ globalThis.window = {};
36
+ t.after(() => {
37
+ if (had) globalThis.window = previous;
38
+ else delete globalThis.window;
39
+ });
40
+ }
41
+
42
+ const plugins = (overrides = {}) => ({ camera: null, scanner: null, filePicker: null, ...overrides });
43
+ const read = async (url) => new Response(new Blob([url.includes("big") ? "x".repeat(2048) : "jpeg"], { type: url.endsWith(".png") ? "image/png" : "image/jpeg" }));
44
+
45
+ function runtimeWith(nativeSource, refused, options = {}) {
46
+ let uppy = null;
47
+ const runtime = createImageUploadRuntime({
48
+ endpoint: "/api/avatar",
49
+ maxUploadBytes: 1024,
50
+ allowedMimeTypes: ["image/jpeg"],
51
+ nativeSource,
52
+ resolveRequestHeaders: async () => ({}),
53
+ onUploadSuccess() {},
54
+ onUploadError() {},
55
+ onRestrictionFailed: ({ error }) => refused.push(error.message),
56
+ ...options,
57
+ dependencies: { UppyClass: class extends RestrictingUppy { constructor(o) { super(o); uppy = this; } }, DashboardPlugin: {}, ImageEditorPlugin: {}, CompressorPlugin: {}, XHRUploadPlugin: {} }
58
+ });
59
+ return { runtime, uppy: () => uppy };
60
+ }
61
+
62
+ test("inside an app the image field offers the phone's sources and checks their files as it checks the web's", async (t) => {
63
+ withWindow(t);
64
+ const nativeSource = createNativeSource({
65
+ plugins: plugins({
66
+ camera: {
67
+ takePhoto: async () => ({ webPath: "capacitor://localhost/_capacitor_file_/tmp/photo.jpg" }),
68
+ chooseFromGallery: async () => ({ results: [{ webPath: "capacitor://localhost/_capacitor_file_/tmp/big.jpg" }] })
69
+ },
70
+ scanner: { scanDocument: async () => ({ status: "cancel" }) }
71
+ }),
72
+ fileUrl: (path) => `capacitor://localhost/_capacitor_file_${path}`,
73
+ fetchImpl: read,
74
+ now: () => 7
75
+ });
76
+ const refused = [];
77
+ const { runtime, uppy } = runtimeWith(nativeSource, refused);
78
+ assert.deepEqual(runtime.nativeSources, ["camera", "photos", "scan"], "no document picker: its plugin is not installed");
79
+
80
+ assert.equal(await runtime.pickFrom("camera"), 1);
81
+ assert.deepEqual(uppy().files.map((file) => [file.name, file.type, file.source]), [["photo-7.jpg", "image/jpeg", "native"]]);
82
+ assert.equal(uppy().dashboard.opened, 1, "the same editor and upload follow");
83
+
84
+ assert.equal(await runtime.pickFrom("photos"), 0);
85
+ assert.deepEqual(refused, ["size"], "a photo over the field's limit is refused as on the web");
86
+ assert.equal(await runtime.pickFrom("scan"), 0, "a cancelled scan adds nothing");
87
+ assert.equal(uppy().dashboard.opened, 1);
88
+ });
89
+
90
+ test("on the web the field has no native sources, and the document picker reads a picked file's own data", async (t) => {
91
+ withWindow(t);
92
+ assert.deepEqual(runtimeWith(undefined, []).runtime.nativeSources, []);
93
+ const picked = [];
94
+ const nativeSource = createNativeSource({
95
+ plugins: plugins({ filePicker: { pickFiles: async (options) => { picked.push(options); return { files: [{ name: "id.jpg", mimeType: "image/jpeg", size: 4, blob: new Blob(["jpeg"], { type: "image/jpeg" }) }] }; } } }),
96
+ fileUrl: String,
97
+ fetchImpl: read,
98
+ now: () => 1
99
+ });
100
+ const { runtime, uppy } = runtimeWith(nativeSource, []);
101
+ assert.equal(await runtime.pickFrom("files"), 1);
102
+ assert.deepEqual(picked, [{ types: ["image/jpeg"], limit: 1 }], "only the types the field takes, one file");
103
+ assert.equal(uppy().files[0].name, "id.jpg");
104
+ assert.deepEqual(await nativeSource.pick("camera"), [], "a source the app lacks picks nothing");
105
+ });