@gateweb/react-utils 2.4.0 → 2.6.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.
@@ -269,6 +269,8 @@ type TValueOptions<T> = AtLeastOne<{
269
269
  * const [currentValue, setCurrentValue] = useValue({ value });
270
270
  * };
271
271
  * ```
272
+ *
273
+ * @deprecated This hook is deprecated in favor of `useControllableState`, which provides more features and better performance. Please use `useControllableState` instead.
272
274
  */
273
275
  declare const useValue: <T>({ value, defaultValue }: TValueOptions<T>) => readonly [T, (newValue: T) => void];
274
276
 
@@ -286,6 +288,35 @@ declare function mergeRefs<T = any>(refs: Array<React__default.MutableRefObject<
286
288
  * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
287
289
  */
288
290
  declare const downloadFile: (source: string | Blob, filename?: string, fileExtension?: string) => void;
291
+ type DownloadFileOptions = {
292
+ /**
293
+ * The url string to download.
294
+ */
295
+ url: string;
296
+ /**
297
+ * The filename to use for the downloaded file (without extension)
298
+ *
299
+ * @default The current timestamp as a string (e.g. "1686789123456")
300
+ */
301
+ filename?: string;
302
+ /**
303
+ * The file extension to append to the filename (e.g. "txt", "pdf").
304
+ */
305
+ fileExtension?: string;
306
+ /**
307
+ * `fetch` init options (e.g. `credentials`, `headers`).
308
+ *
309
+ * Note: the URL must allow CORS (or be same-origin) for the browser to read the response.
310
+ */
311
+ fetchInit?: RequestInit;
312
+ };
313
+ /**
314
+ * Downloads a file by fetching the URL into a Blob first, then triggering a blob download.
315
+ *
316
+ * This is useful when a URL returns a previewable Content-Type (e.g. `application/pdf`) and
317
+ * the browser would otherwise open a new tab to preview instead of downloading.
318
+ */
319
+ declare const downloadFileWithFetch: ({ url, filename, fileExtension, fetchInit, }: DownloadFileOptions) => Promise<void>;
289
320
 
290
321
  /**
291
322
  * 從 localStorage 取得資料,支援槽狀取值(Json 物件)
@@ -307,5 +338,5 @@ declare const getLocalStorage: <T>(key: string, deCode?: boolean) => T | undefin
307
338
  */
308
339
  declare const setLocalStorage: (key: string, value: Record<string, any>, enCode?: boolean) => void;
309
340
 
310
- export { QueryProvider, createDataContext, createStoreContext, downloadFile, getLocalStorage, mergeRefs, setLocalStorage, useCountdown, useDisclosure, useHorizontalWheel, useQueryContext, useValue };
311
- export type { TCountdownActions, UseDisclosureReturn };
341
+ export { QueryProvider, createDataContext, createStoreContext, downloadFile, downloadFileWithFetch, getLocalStorage, mergeRefs, setLocalStorage, useCountdown, useDisclosure, useHorizontalWheel, useQueryContext, useValue };
342
+ export type { DownloadFileOptions, TCountdownActions, UseDisclosureReturn };
@@ -6,7 +6,7 @@ var React = require('react');
6
6
  var useCountdown12s = require('./useCountdown-12s-uiqhgllY.js');
7
7
  var useDisclosure12s = require('./useDisclosure-12s-SZtbSE4A.js');
8
8
  var useHorizontalWheel12s = require('./useHorizontalWheel-12s-bwbWVJeM.js');
9
- var download12s = require('./download-12s-DKxkL92w.js');
9
+ var download12s = require('./download-12s-C5yIKqRX.js');
10
10
  var webStorage12s = require('./webStorage-12s-0RtNO_uc.js');
11
11
 
12
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -74,6 +74,8 @@ var React__default = /*#__PURE__*/_interopDefault(React);
74
74
  * const [currentValue, setCurrentValue] = useValue({ value });
75
75
  * };
76
76
  * ```
77
+ *
78
+ * @deprecated This hook is deprecated in favor of `useControllableState`, which provides more features and better performance. Please use `useControllableState` instead.
77
79
  */ const useValue = ({ value, defaultValue })=>{
78
80
  if (value === undefined && defaultValue === undefined) {
79
81
  throw new Error('Either `value` or `defaultValue` must be provided.');
@@ -114,6 +116,7 @@ exports.useCountdown = useCountdown12s.useCountdown;
114
116
  exports.useDisclosure = useDisclosure12s.useDisclosure;
115
117
  exports.useHorizontalWheel = useHorizontalWheel12s.useHorizontalWheel;
116
118
  exports.downloadFile = download12s.downloadFile;
119
+ exports.downloadFileWithFetch = download12s.downloadFileWithFetch;
117
120
  exports.getLocalStorage = webStorage12s.getLocalStorage;
118
121
  exports.setLocalStorage = webStorage12s.setLocalStorage;
119
122
  exports.createDataContext = createDataContext;
@@ -0,0 +1,65 @@
1
+ 'use client';
2
+ const sanitizeUrlForError = (input)=>{
3
+ try {
4
+ const parsed = new URL(input);
5
+ return `${parsed.origin}${parsed.pathname}`;
6
+ } catch {
7
+ return input.split('#')[0].split('?')[0];
8
+ }
9
+ };
10
+ /**
11
+ * Downloads a file from a given source.
12
+ *
13
+ * @param source - The source of the file to be downloaded. It can be a URL string or a Blob object.
14
+ * @param filename - The name of the file to be downloaded. Defaults to the current timestamp if not provided.
15
+ * @param fileExtension - The file extension to be appended to the filename. Optional.
16
+ *
17
+ * @example
18
+ * downloadFile('http://example.com/file.txt', 'testfile', 'txt');
19
+ * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
20
+ */ const downloadFile = (source, filename = new Date().getTime().toString(), fileExtension)=>{
21
+ const shouldRevokeObjectUrl = typeof source !== 'string';
22
+ const url = shouldRevokeObjectUrl ? URL.createObjectURL(source) : source;
23
+ const link = document.createElement('a');
24
+ link.id = `download-${new Date().getTime()}`;
25
+ document.body.appendChild(link);
26
+ if (!fileExtension) {
27
+ link.download = filename;
28
+ } else {
29
+ link.download = `${filename}.${fileExtension}`;
30
+ }
31
+ link.href = url;
32
+ link.target = '_blank';
33
+ link.click();
34
+ link.remove();
35
+ if (shouldRevokeObjectUrl) {
36
+ // Defer revocation to avoid interfering with the download in some browsers.
37
+ setTimeout(()=>{
38
+ URL.revokeObjectURL(url);
39
+ }, 0);
40
+ }
41
+ };
42
+ /**
43
+ * Downloads a file by fetching the URL into a Blob first, then triggering a blob download.
44
+ *
45
+ * This is useful when a URL returns a previewable Content-Type (e.g. `application/pdf`) and
46
+ * the browser would otherwise open a new tab to preview instead of downloading.
47
+ */ const downloadFileWithFetch = async ({ url, filename = new Date().getTime().toString(), fileExtension, fetchInit })=>{
48
+ const safeUrl = sanitizeUrlForError(url);
49
+ let response;
50
+ try {
51
+ response = await fetch(url, fetchInit);
52
+ } catch (error) {
53
+ throw new Error(`downloadFileWithFetch: fetch failed for ${safeUrl}`, {
54
+ cause: error
55
+ });
56
+ }
57
+ if (!response.ok) {
58
+ throw new Error(`downloadFileWithFetch: failed to fetch ${safeUrl} (status ${response.status} ${response.statusText})`);
59
+ }
60
+ const blob = await response.blob();
61
+ downloadFile(blob, filename, fileExtension);
62
+ };
63
+
64
+ exports.downloadFile = downloadFile;
65
+ exports.downloadFileWithFetch = downloadFileWithFetch;
@@ -269,6 +269,8 @@ type TValueOptions<T> = AtLeastOne<{
269
269
  * const [currentValue, setCurrentValue] = useValue({ value });
270
270
  * };
271
271
  * ```
272
+ *
273
+ * @deprecated This hook is deprecated in favor of `useControllableState`, which provides more features and better performance. Please use `useControllableState` instead.
272
274
  */
273
275
  declare const useValue: <T>({ value, defaultValue }: TValueOptions<T>) => readonly [T, (newValue: T) => void];
274
276
 
@@ -286,6 +288,35 @@ declare function mergeRefs<T = any>(refs: Array<React__default.MutableRefObject<
286
288
  * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
287
289
  */
288
290
  declare const downloadFile: (source: string | Blob, filename?: string, fileExtension?: string) => void;
291
+ type DownloadFileOptions = {
292
+ /**
293
+ * The url string to download.
294
+ */
295
+ url: string;
296
+ /**
297
+ * The filename to use for the downloaded file (without extension)
298
+ *
299
+ * @default The current timestamp as a string (e.g. "1686789123456")
300
+ */
301
+ filename?: string;
302
+ /**
303
+ * The file extension to append to the filename (e.g. "txt", "pdf").
304
+ */
305
+ fileExtension?: string;
306
+ /**
307
+ * `fetch` init options (e.g. `credentials`, `headers`).
308
+ *
309
+ * Note: the URL must allow CORS (or be same-origin) for the browser to read the response.
310
+ */
311
+ fetchInit?: RequestInit;
312
+ };
313
+ /**
314
+ * Downloads a file by fetching the URL into a Blob first, then triggering a blob download.
315
+ *
316
+ * This is useful when a URL returns a previewable Content-Type (e.g. `application/pdf`) and
317
+ * the browser would otherwise open a new tab to preview instead of downloading.
318
+ */
319
+ declare const downloadFileWithFetch: ({ url, filename, fileExtension, fetchInit, }: DownloadFileOptions) => Promise<void>;
289
320
 
290
321
  /**
291
322
  * 從 localStorage 取得資料,支援槽狀取值(Json 物件)
@@ -307,5 +338,5 @@ declare const getLocalStorage: <T>(key: string, deCode?: boolean) => T | undefin
307
338
  */
308
339
  declare const setLocalStorage: (key: string, value: Record<string, any>, enCode?: boolean) => void;
309
340
 
310
- export { QueryProvider, createDataContext, createStoreContext, downloadFile, getLocalStorage, mergeRefs, setLocalStorage, useCountdown, useDisclosure, useHorizontalWheel, useQueryContext, useValue };
311
- export type { TCountdownActions, UseDisclosureReturn };
341
+ export { QueryProvider, createDataContext, createStoreContext, downloadFile, downloadFileWithFetch, getLocalStorage, mergeRefs, setLocalStorage, useCountdown, useDisclosure, useHorizontalWheel, useQueryContext, useValue };
342
+ export type { DownloadFileOptions, TCountdownActions, UseDisclosureReturn };
@@ -4,7 +4,7 @@ import React, { useMemo, createContext, useContext, useState, useCallback } from
4
4
  export { u as useCountdown } from './useCountdown-12s-t52WIHfq.mjs';
5
5
  export { u as useDisclosure } from './useDisclosure-12s-BQAHpAXK.mjs';
6
6
  export { u as useHorizontalWheel } from './useHorizontalWheel-12s-D3IfutV9.mjs';
7
- export { d as downloadFile } from './download-12s-CnaJ0p_f.mjs';
7
+ export { d as downloadFile, a as downloadFileWithFetch } from './download-12s-DtxLfLpr.mjs';
8
8
  export { g as getLocalStorage, s as setLocalStorage } from './webStorage-12s-Bo7x8q5t.mjs';
9
9
 
10
10
  /**
@@ -68,6 +68,8 @@ export { g as getLocalStorage, s as setLocalStorage } from './webStorage-12s-Bo7
68
68
  * const [currentValue, setCurrentValue] = useValue({ value });
69
69
  * };
70
70
  * ```
71
+ *
72
+ * @deprecated This hook is deprecated in favor of `useControllableState`, which provides more features and better performance. Please use `useControllableState` instead.
71
73
  */ const useValue = ({ value, defaultValue })=>{
72
74
  if (value === undefined && defaultValue === undefined) {
73
75
  throw new Error('Either `value` or `defaultValue` must be provided.');
@@ -0,0 +1,64 @@
1
+ 'use client';
2
+ const sanitizeUrlForError = (input)=>{
3
+ try {
4
+ const parsed = new URL(input);
5
+ return `${parsed.origin}${parsed.pathname}`;
6
+ } catch {
7
+ return input.split('#')[0].split('?')[0];
8
+ }
9
+ };
10
+ /**
11
+ * Downloads a file from a given source.
12
+ *
13
+ * @param source - The source of the file to be downloaded. It can be a URL string or a Blob object.
14
+ * @param filename - The name of the file to be downloaded. Defaults to the current timestamp if not provided.
15
+ * @param fileExtension - The file extension to be appended to the filename. Optional.
16
+ *
17
+ * @example
18
+ * downloadFile('http://example.com/file.txt', 'testfile', 'txt');
19
+ * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
20
+ */ const downloadFile = (source, filename = new Date().getTime().toString(), fileExtension)=>{
21
+ const shouldRevokeObjectUrl = typeof source !== 'string';
22
+ const url = shouldRevokeObjectUrl ? URL.createObjectURL(source) : source;
23
+ const link = document.createElement('a');
24
+ link.id = `download-${new Date().getTime()}`;
25
+ document.body.appendChild(link);
26
+ if (!fileExtension) {
27
+ link.download = filename;
28
+ } else {
29
+ link.download = `${filename}.${fileExtension}`;
30
+ }
31
+ link.href = url;
32
+ link.target = '_blank';
33
+ link.click();
34
+ link.remove();
35
+ if (shouldRevokeObjectUrl) {
36
+ // Defer revocation to avoid interfering with the download in some browsers.
37
+ setTimeout(()=>{
38
+ URL.revokeObjectURL(url);
39
+ }, 0);
40
+ }
41
+ };
42
+ /**
43
+ * Downloads a file by fetching the URL into a Blob first, then triggering a blob download.
44
+ *
45
+ * This is useful when a URL returns a previewable Content-Type (e.g. `application/pdf`) and
46
+ * the browser would otherwise open a new tab to preview instead of downloading.
47
+ */ const downloadFileWithFetch = async ({ url, filename = new Date().getTime().toString(), fileExtension, fetchInit })=>{
48
+ const safeUrl = sanitizeUrlForError(url);
49
+ let response;
50
+ try {
51
+ response = await fetch(url, fetchInit);
52
+ } catch (error) {
53
+ throw new Error(`downloadFileWithFetch: fetch failed for ${safeUrl}`, {
54
+ cause: error
55
+ });
56
+ }
57
+ if (!response.ok) {
58
+ throw new Error(`downloadFileWithFetch: failed to fetch ${safeUrl} (status ${response.status} ${response.statusText})`);
59
+ }
60
+ const blob = await response.blob();
61
+ downloadFile(blob, filename, fileExtension);
62
+ };
63
+
64
+ export { downloadFileWithFetch as a, downloadFile as d };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gateweb/react-utils",
3
- "version": "2.4.0",
3
+ "version": "2.6.0",
4
4
  "description": "React Utils for GateWeb",
5
5
  "homepage": "https://github.com/GW-VAT-BPSP-Team/react-utils",
6
6
  "repository": {
@@ -1,27 +0,0 @@
1
- 'use client';
2
- /**
3
- * Downloads a file from a given source.
4
- *
5
- * @param source - The source of the file to be downloaded. It can be a URL string or a Blob object.
6
- * @param filename - The name of the file to be downloaded. Defaults to the current timestamp if not provided.
7
- * @param fileExtension - The file extension to be appended to the filename. Optional.
8
- *
9
- * @example
10
- * downloadFile('http://example.com/file.txt', 'testfile', 'txt');
11
- * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
12
- */ const downloadFile = (source, filename = new Date().getTime().toString(), fileExtension)=>{
13
- const url = typeof source === 'string' ? source : URL.createObjectURL(source);
14
- const link = document.createElement('a');
15
- link.id = `download-${new Date().getTime()}`;
16
- document.body.appendChild(link);
17
- if (!fileExtension) {
18
- link.download = filename;
19
- } else {
20
- link.download = `${filename}.${fileExtension}`;
21
- }
22
- link.href = url;
23
- link.target = '_blank';
24
- link.click();
25
- };
26
-
27
- exports.downloadFile = downloadFile;
@@ -1,27 +0,0 @@
1
- 'use client';
2
- /**
3
- * Downloads a file from a given source.
4
- *
5
- * @param source - The source of the file to be downloaded. It can be a URL string or a Blob object.
6
- * @param filename - The name of the file to be downloaded. Defaults to the current timestamp if not provided.
7
- * @param fileExtension - The file extension to be appended to the filename. Optional.
8
- *
9
- * @example
10
- * downloadFile('http://example.com/file.txt', 'testfile', 'txt');
11
- * downloadFile(new Blob(['test content'], { type: 'text/plain' }), 'testfile', 'txt');
12
- */ const downloadFile = (source, filename = new Date().getTime().toString(), fileExtension)=>{
13
- const url = typeof source === 'string' ? source : URL.createObjectURL(source);
14
- const link = document.createElement('a');
15
- link.id = `download-${new Date().getTime()}`;
16
- document.body.appendChild(link);
17
- if (!fileExtension) {
18
- link.download = filename;
19
- } else {
20
- link.download = `${filename}.${fileExtension}`;
21
- }
22
- link.href = url;
23
- link.target = '_blank';
24
- link.click();
25
- };
26
-
27
- export { downloadFile as d };