antd-crud-table 0.4.0 → 0.7.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.
Files changed (41) hide show
  1. package/README.md +293 -783
  2. package/dist/CrudTable-Btf58zof.js +610 -0
  3. package/dist/CrudTable-DRN70sET.cjs +1 -0
  4. package/dist/CrudTable.cjs +1 -1
  5. package/dist/CrudTable.d.ts +85 -18
  6. package/dist/CrudTable.js +3 -306
  7. package/dist/CrudTableLazy.cjs +1 -1
  8. package/dist/CrudTableLazy.d.ts +4 -3
  9. package/dist/CrudTableLazy.js +8 -7
  10. package/dist/core/CustomDataSource.d.ts +35 -0
  11. package/dist/core/InMemoryDataSource.d.ts +30 -0
  12. package/dist/core/LocalStorageDataSource.d.ts +30 -0
  13. package/dist/core/RestDataSource.d.ts +120 -0
  14. package/dist/core/StaticDataSource.d.ts +20 -0
  15. package/dist/core/identity.d.ts +28 -0
  16. package/dist/core/inMemoryQuery.d.ts +26 -0
  17. package/dist/core/index.d.ts +11 -0
  18. package/dist/core/types.d.ts +86 -0
  19. package/dist/en_US-D3Kl6g3n.cjs +1 -0
  20. package/dist/en_US-DGCMDOdX.js +41 -0
  21. package/dist/exportData.cjs +13 -13
  22. package/dist/exportData.js +48 -39
  23. package/dist/fields/registry.d.ts +38 -0
  24. package/dist/fields/types.d.ts +29 -0
  25. package/dist/hooks/useCrudTable.d.ts +114 -57
  26. package/dist/hooks/useLocalStorageCrud.d.ts +14 -9
  27. package/dist/index.cjs +1 -0
  28. package/dist/index.d.ts +14 -6
  29. package/dist/index.js +7 -0
  30. package/dist/locale/en_US.d.ts +10 -0
  31. package/dist/locale/index.d.ts +4 -0
  32. package/dist/locale/types.d.ts +89 -0
  33. package/dist/locale/useResolvedLocale.d.ts +35 -0
  34. package/dist/useCrudTable-40jpmCkr.cjs +1 -0
  35. package/dist/useCrudTable-DxjnXVlQ.js +460 -0
  36. package/dist/useCrudTable.cjs +1 -1
  37. package/dist/useCrudTable.js +2 -235
  38. package/dist/useLocalStorageCrud.cjs +1 -1
  39. package/dist/useLocalStorageCrud.js +12 -198
  40. package/dist/utils/exportData.d.ts +37 -12
  41. package/package.json +52 -16
@@ -1,69 +1,126 @@
1
1
  import { ActionType } from '@ant-design/pro-components';
2
- export type CrudOperation<T> = {
3
- getList: (params: CrudParams) => Promise<CrudResponse<T>>;
4
- create: (data: Partial<T>) => Promise<T>;
5
- update: (id: any, data: Partial<T>) => Promise<T>;
6
- delete: (id: any) => Promise<void>;
7
- };
8
- export type CrudParams = {
9
- current?: number;
10
- pageSize?: number;
11
- sortBy?: string;
12
- sortOrder?: 'ascend' | 'descend';
13
- [key: string]: any;
14
- };
15
- export type CrudResponse<T> = {
16
- data: T[];
17
- total: number;
18
- success?: boolean;
19
- };
20
- export type CrudState<T> = {
2
+ import { CrudDataSource, CrudDraft, IdGenerator, RestDataSourceOptions } from '../core';
3
+ import { CrudOperations } from '../core/CustomDataSource';
4
+ import { PartialCrudTableLocale } from '../locale/types';
5
+ /** The operations a table performs, used to tag success and error callbacks. */
6
+ export type CrudOperationName = 'list' | 'create' | 'update' | 'delete';
7
+ /**
8
+ * Coerce a thrown value into an Error.
9
+ *
10
+ * Callbacks receive a real Error rather than `unknown`, so consumers can read
11
+ * `.message` without narrowing at every call site. Non-Error throws are wrapped
12
+ * rather than stringified into the message, keeping the original as `cause`.
13
+ */
14
+ export declare const toError: (thrown: unknown) => Error;
15
+ /** Everything the hook tracks about the current view of the data. */
16
+ export interface CrudTableState<T> {
17
+ /** Whether a read or write is in flight. */
21
18
  loading: boolean;
22
- error: string | null;
23
- data: T[];
19
+ /** The most recent failure, cleared when a read succeeds. */
20
+ error: Error | null;
21
+ /** Records from the last read. Empty until `refresh` has run. */
22
+ data: readonly T[];
23
+ /** Records matching the filters, across all pages. */
24
24
  total: number;
25
- current: number;
25
+ /** Current 1-based page. */
26
+ page: number;
27
+ /** Current rows per page. */
26
28
  pageSize: number;
27
- };
28
- type UseCrudTableConfigBase = {
29
+ }
30
+ /** Options shared by every strategy. */
31
+ interface UseCrudTableOptionsBase<T, K extends keyof T> {
32
+ /** Rows per page for the hook's own reads. Defaults to 10. */
29
33
  defaultPageSize?: number;
30
- enableCache?: boolean;
34
+ /**
35
+ * Apply mutations to local state immediately instead of re-reading.
36
+ *
37
+ * Trades consistency for responsiveness: server-assigned fields will not be
38
+ * reflected until the next list.
39
+ */
31
40
  optimisticUpdates?: boolean;
32
- onSuccess?: (operation: 'create' | 'update' | 'delete' | 'fetch', data: any) => void;
33
- onError?: (operation: 'create' | 'update' | 'delete' | 'fetch', error: any) => void;
34
- };
35
- interface UseCrudTableConfigStatic<T> extends UseCrudTableConfigBase {
36
- staticData: T[];
41
+ /**
42
+ * Re-read the list after a successful mutation.
43
+ *
44
+ * Defaults to true for standalone hook consumers, which render from
45
+ * `state.data`. `CrudTable` sets it false: it renders from ProTable's own
46
+ * request pipeline and reloads through `actionRef`, so leaving this on
47
+ * issued two list requests for every write.
48
+ */
49
+ refreshAfterMutation?: boolean;
50
+ /** Replaces the built-in identity policy for the in-memory strategies. */
51
+ generateId?: IdGenerator<T, K>;
52
+ /** Show antd toasts for the outcome of each operation. */
53
+ notifications?: boolean;
54
+ /**
55
+ * Overrides for the toast wording.
56
+ *
57
+ * `CrudTable` passes its own resolved locale down, so this is only needed
58
+ * when the hook is used on its own.
59
+ */
60
+ locale?: PartialCrudTableLocale;
61
+ /** Called after an operation succeeds, with whatever it produced. */
62
+ onSuccess?: (operation: CrudOperationName, payload: unknown) => void;
63
+ /** Called when an operation fails, with a real Error rather than the raw throw. */
64
+ onError?: (operation: CrudOperationName, error: Error) => void;
65
+ }
66
+ /** Serves records from an in-process array. */
67
+ export interface StaticStrategy<T, K extends keyof T> extends UseCrudTableOptionsBase<T, K> {
68
+ /** Seed records. Copied once; later changes to the array are not picked up. */
69
+ staticData: readonly T[];
37
70
  }
38
- interface UseCrudTableConfigApi<T> extends UseCrudTableConfigBase {
39
- api: {
40
- baseUrl?: string;
41
- endpoints?: {
42
- list?: string;
43
- create?: string;
44
- update?: string;
45
- delete?: string;
46
- };
47
- headers?: Record<string, string>;
48
- transform?: {
49
- request?: (data: any) => any;
50
- response?: (data: any) => CrudResponse<T>;
51
- };
52
- };
71
+ /** Serves records from a REST API. */
72
+ export interface RestStrategy<T, K extends keyof T> extends UseCrudTableOptionsBase<T, K> {
73
+ /** Endpoints, parameter names, verbs and payload mapping. */
74
+ api: RestDataSourceOptions<T>;
53
75
  }
54
- interface UseCrudTableConfigCustom<T> extends UseCrudTableConfigBase {
55
- operations: Partial<CrudOperation<T>>;
76
+ /** Serves records persisted to `localStorage`. */
77
+ export interface LocalStorageStrategy<T, K extends keyof T> extends UseCrudTableOptionsBase<T, K> {
78
+ /** The `localStorage` key records are stored under. */
79
+ storageKey: string;
80
+ /** Records used when the key holds nothing readable. */
81
+ initialData?: readonly T[];
56
82
  }
57
- export type UseCrudTableConfig<T> = UseCrudTableConfigStatic<T> | UseCrudTableConfigApi<T> | UseCrudTableConfigCustom<T>;
58
- export type CrudTableActions<T> = {
83
+ /** Serves records through consumer-supplied operations. */
84
+ export interface OperationsStrategy<T, K extends keyof T> extends UseCrudTableOptionsBase<T, K> {
85
+ /** Your own implementations. Omitted operations fail with a named error. */
86
+ operations: CrudOperations<T, K>;
87
+ }
88
+ /** Serves records from a source the consumer constructs and owns. */
89
+ export interface DataSourceStrategy<T, K extends keyof T> extends UseCrudTableOptionsBase<T, K> {
90
+ /** A source the consumer constructs and owns outright. */
91
+ dataSource: CrudDataSource<T, K>;
92
+ }
93
+ /** Exactly one strategy must be supplied. */
94
+ export type UseCrudTableOptions<T, K extends keyof T> = StaticStrategy<T, K> | RestStrategy<T, K> | LocalStorageStrategy<T, K> | OperationsStrategy<T, K> | DataSourceStrategy<T, K>;
95
+ /** What {@link useCrudTable} returns. */
96
+ export interface CrudTableActions<T, K extends keyof T> {
97
+ /** Re-read the current page into `state`. */
59
98
  refresh: () => Promise<void>;
60
- create: (data: Partial<T>) => Promise<T | null>;
61
- update: (id: any, data: Partial<T>) => Promise<T | null>;
62
- delete: (id: any) => Promise<boolean>;
99
+ /** Create a record. Resolves to the stored result, or `null` on failure. */
100
+ create: (draft: CrudDraft<T>) => Promise<T | null>;
101
+ /** Update a record. Resolves to the stored result, or `null` on failure. */
102
+ update: (id: T[K], draft: CrudDraft<T>) => Promise<T | null>;
103
+ /** Delete a record. Resolves to whether it succeeded. */
104
+ remove: (id: T[K]) => Promise<boolean>;
105
+ /** The live source, for wiring a table's own request pipeline directly. */
106
+ dataSource: CrudDataSource<T, K>;
107
+ /** Move to a 1-based page. */
108
+ setPage: (page: number) => void;
109
+ /** Change the page size, returning to the first page. */
63
110
  setPageSize: (size: number) => void;
64
- setCurrentPage: (page: number) => void;
65
- state: CrudState<T>;
66
- actionRef: React.RefObject<ActionType | null>;
67
- };
68
- export declare const useCrudTable: <T extends Record<string, any>>(rowKey: keyof T, config: UseCrudTableConfig<T>) => CrudTableActions<T>;
111
+ /** Current loading, error, data and pagination state. */
112
+ state: CrudTableState<T>;
113
+ /** ProTable's imperative handle, for reloading the table's own pipeline. */
114
+ actionRef: React.RefObject<ActionType | undefined>;
115
+ }
116
+ /**
117
+ * React state and mutation orchestration over a `CrudDataSource`.
118
+ *
119
+ * All I/O lives in the source; this hook owns only React concerns. The source
120
+ * is constructed once per hook instance and held in a ref, so its lifetime is
121
+ * tied to the component rather than to the identity of the arguments that
122
+ * described it - passing an inline `staticData` literal no longer discards the
123
+ * dataset on every parent render.
124
+ */
125
+ export declare const useCrudTable: <T extends object, K extends keyof T>(rowKey: K, options: UseCrudTableOptions<T, K>) => CrudTableActions<T, K>;
69
126
  export {};
@@ -1,9 +1,14 @@
1
- import { CrudTableActions } from './useCrudTable';
2
- export type UseLocalStorageCrudConfig = {
3
- defaultPageSize?: number;
4
- optimisticUpdates?: boolean;
5
- onSuccess?: (operation: 'create' | 'update' | 'delete' | 'fetch', data: any) => void;
6
- onError?: (operation: 'create' | 'update' | 'delete' | 'fetch', error: any) => void;
7
- };
8
- export declare const useLocalStorageCrud: <T extends Record<string, any>>(rowKey: keyof T, storageKey: string, initialData?: T[], config?: UseLocalStorageCrudConfig) => CrudTableActions<T>;
9
- export default useLocalStorageCrud;
1
+ import { CrudTableActions, LocalStorageStrategy } from './useCrudTable';
2
+ /**
3
+ * Options for the localStorage strategy, minus the strategy selector itself.
4
+ */
5
+ /** Options for the localStorage strategy, minus the strategy selector itself. */
6
+ export type UseLocalStorageCrudOptions<T, K extends keyof T> = Omit<LocalStorageStrategy<T, K>, 'storageKey' | 'initialData'>;
7
+ /**
8
+ * A localStorage-backed CRUD hook.
9
+ *
10
+ * A thin wrapper that selects the localStorage strategy and performs the
11
+ * initial read. Standalone consumers render from `state.data`, so unlike the
12
+ * table - which drives its own request pipeline - this needs a load on mount.
13
+ */
14
+ export declare const useLocalStorageCrud: <T extends object, K extends keyof T>(rowKey: K, storageKey: string, initialData?: readonly T[], options?: UseLocalStorageCrudOptions<T, K>) => CrudTableActions<T, K>;
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./CrudTable-DRN70sET.cjs"),t=require("./useCrudTable-40jpmCkr.cjs"),n=require("./en_US-D3Kl6g3n.cjs"),r=require("./exportData.cjs"),i=require("./CrudTableLazy.cjs"),a=require("./useLocalStorageCrud.cjs");exports.CrudTable=e.t,exports.default=e.t,exports.CrudTableLazy=i.default,exports.CustomDataSource=t.r,exports.InMemoryDataSource=t.l,exports.LocalStorageDataSource=t.s,exports.RestDataSource=t.a,exports.RestError=t.o,exports.StaticDataSource=t.c,exports.UnsupportedOperationError=t.i,exports.defaultFieldLocale=e.r,exports.defaultIdGenerator=t.m,exports.enUS=n.t,exports.exportAllData=r.exportAllData,exports.exportData=r.exportData,exports.exportToCSV=r.exportToCSV,exports.exportToExcel=r.exportToExcel,exports.exportToJSON=r.exportToJSON,exports.fieldRegistry=e.i,exports.filterRecords=t.u,exports.getFieldDefinition=e.a,exports.paginateRecords=t.d,exports.queryRecords=t.f,exports.randomUuid=t.h,exports.sortRecords=t.p,exports.toError=t.t,exports.useCrudTable=t.n,exports.useLocalStorageCrud=a.useLocalStorageCrud,exports.useResolvedLocale=e.n;
package/dist/index.d.ts CHANGED
@@ -1,9 +1,17 @@
1
1
  export { default as CrudTable } from './CrudTable';
2
2
  export { default as CrudTableLazy } from './CrudTableLazy';
3
- export { useCrudTable } from './hooks/useCrudTable';
3
+ export { default } from './CrudTable';
4
+ export type { CrudTableConfig, CrudColumn, CrudColumnFor } from './CrudTable';
5
+ export { useCrudTable, toError } from './hooks/useCrudTable';
4
6
  export { useLocalStorageCrud } from './hooks/useLocalStorageCrud';
5
- export { exportData, exportToCSV, exportToJSON, exportToXLSX, exportAllData } from './utils/exportData';
6
- export type { CrudTableConfig, CrudColumn, DataType } from './CrudTable';
7
- export type { UseCrudTableConfig, CrudTableActions, CrudOperation, CrudParams, CrudResponse, CrudState } from './hooks/useCrudTable';
8
- export type { UseLocalStorageCrudConfig } from './hooks/useLocalStorageCrud';
9
- export type { ExportFormat } from './utils/exportData';
7
+ export type { CrudOperationName, CrudTableActions, CrudTableState, UseCrudTableOptions, StaticStrategy, RestStrategy, LocalStorageStrategy, OperationsStrategy, DataSourceStrategy, } from './hooks/useCrudTable';
8
+ export type { UseLocalStorageCrudOptions } from './hooks/useLocalStorageCrud';
9
+ export { CustomDataSource, InMemoryDataSource, LocalStorageDataSource, RestDataSource, RestError, StaticDataSource, UnsupportedOperationError, defaultIdGenerator, filterRecords, paginateRecords, queryRecords, randomUuid, sortRecords, } from './core';
10
+ export type { CrudDataSource, CrudDraft, CrudFilters, CrudFilterValue, CrudOperations, CrudPage, CrudQuery, CrudSort, IdGenerator, RestDataSourceOptions, RestEndpoints, RestMethods, RestParamNames, SortDirection, Timestamped, } from './core';
11
+ export { enUS, useResolvedLocale } from './locale';
12
+ export type { CrudTableLocale, PartialCrudTableLocale, ResolvedLocale } from './locale';
13
+ export { fieldRegistry, getFieldDefinition, defaultFieldLocale } from './fields/registry';
14
+ export type { FieldType, FieldTypeDefinition } from './fields/registry';
15
+ export type { EnumOption, FieldColumn } from './fields/types';
16
+ export { exportData, exportToCSV, exportToJSON, exportToExcel, exportAllData, } from './utils/exportData';
17
+ export type { ColumnOption, ExportFormat, ExportOptions } from './utils/exportData';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { a as e, i as t, n, r, t as i } from "./CrudTable-Btf58zof.js";
2
+ import { a, c as o, d as s, f as c, h as l, i as u, l as d, m as f, n as p, o as m, p as h, r as g, s as _, t as v, u as y } from "./useCrudTable-DxjnXVlQ.js";
3
+ import { t as b } from "./en_US-DGCMDOdX.js";
4
+ import { exportAllData as x, exportData as S, exportToCSV as C, exportToExcel as w, exportToJSON as T } from "./exportData.js";
5
+ import E from "./CrudTableLazy.js";
6
+ import { useLocalStorageCrud as D } from "./useLocalStorageCrud.js";
7
+ export { i as CrudTable, i as default, E as CrudTableLazy, g as CustomDataSource, d as InMemoryDataSource, _ as LocalStorageDataSource, a as RestDataSource, m as RestError, o as StaticDataSource, u as UnsupportedOperationError, r as defaultFieldLocale, f as defaultIdGenerator, b as enUS, x as exportAllData, S as exportData, C as exportToCSV, w as exportToExcel, T as exportToJSON, t as fieldRegistry, y as filterRecords, e as getFieldDefinition, s as paginateRecords, c as queryRecords, l as randomUuid, h as sortRecords, v as toError, p as useCrudTable, D as useLocalStorageCrud, n as useResolvedLocale };
@@ -0,0 +1,10 @@
1
+ import { CrudTableLocale } from './types';
2
+ /**
3
+ * The built-in default.
4
+ *
5
+ * English is the fallback everywhere, including when no antd `ConfigProvider`
6
+ * is present - which is the case that previously left antd's own components
7
+ * rendering their built-in Chinese defaults.
8
+ */
9
+ export declare const enUS: CrudTableLocale;
10
+ export default enUS;
@@ -0,0 +1,4 @@
1
+ export { enUS } from './en_US';
2
+ export { useResolvedLocale } from './useResolvedLocale';
3
+ export type { ResolvedLocale } from './useResolvedLocale';
4
+ export type { CrudTableLocale, PartialCrudTableLocale } from './types';
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Every user-visible string the library produces.
3
+ *
4
+ * Interpolated strings are functions rather than templates with placeholders,
5
+ * so a translation cannot silently drop a value or get the argument order
6
+ * wrong - the compiler checks it.
7
+ *
8
+ * antd's own chrome (pagination, empty states, date pickers) is localised
9
+ * through antd's `ConfigProvider`, and ProTable's chrome through its `intl`.
10
+ * `CrudTable` derives both from the surrounding `ConfigProvider` when there is
11
+ * one, so a consumer usually sets their app locale once and this object only
12
+ * needs supplying to override the library's own wording.
13
+ */
14
+ export interface CrudTableLocale {
15
+ /** Header of the per-row actions column. */
16
+ actions: string;
17
+ /** Row action opening the edit form. */
18
+ edit: string;
19
+ /** Row action deleting a record. */
20
+ delete: string;
21
+ /** Toolbar button opening the create form. */
22
+ create: string;
23
+ /** Toolbar menu entry re-reading the current page. */
24
+ refresh: string;
25
+ /** Title of the create form. */
26
+ createTitle: string;
27
+ /** Title of the edit form. */
28
+ editTitle: string;
29
+ /** Confirm button in the create/edit form. */
30
+ ok: string;
31
+ /** Dismiss button in the create/edit form. */
32
+ cancel: string;
33
+ /** Validation message for a required field. */
34
+ requiredField: (label: string) => string;
35
+ /** Title of the single-delete confirmation. */
36
+ confirmDeleteTitle: string;
37
+ /** Body of both delete confirmations. */
38
+ confirmDeleteContent: string;
39
+ /** Confirm button of the single-delete confirmation. */
40
+ confirmDeleteOk: string;
41
+ /** Title of the bulk-delete confirmation. */
42
+ confirmBulkDeleteTitle: (count: number) => string;
43
+ /** Confirm button of the bulk-delete confirmation. */
44
+ confirmBulkDeleteOk: string;
45
+ /** Toolbar button opening the bulk-delete confirmation. */
46
+ deleteSelected: (count: number) => string;
47
+ /** Warning shown when bulk delete is invoked with nothing selected. */
48
+ selectItemsToDelete: string;
49
+ /** Result message when every delete in a bulk run succeeded. */
50
+ bulkDeleteSuccess: (count: number) => string;
51
+ /** Result message when only some deletes in a bulk run succeeded. */
52
+ bulkDeletePartial: (succeeded: number, total: number, failed: number) => string;
53
+ /** Menu entry writing every matching record. */
54
+ exportAll: (format: string) => string;
55
+ /** Menu entry writing only the rows on screen. */
56
+ exportPage: (format: string) => string;
57
+ /** Warning shown when there is nothing to write. */
58
+ nothingToExport: string;
59
+ /** Error shown when gathering or writing the export failed. */
60
+ exportFailed: (message: string) => string;
61
+ /** Confirmation that a record was created. */
62
+ createSuccess: string;
63
+ /** Confirmation that a record was updated. */
64
+ updateSuccess: string;
65
+ /** Confirmation that a record was deleted. */
66
+ deleteSuccess: string;
67
+ /** Placeholder while the code-split table loads. */
68
+ loading: string;
69
+ /** Cell text for a true boolean. */
70
+ yes: string;
71
+ /** Cell text for a false boolean. */
72
+ no: string;
73
+ /** Cell text for a missing value. */
74
+ empty: string;
75
+ /** Placeholder of an enum column's select control. */
76
+ selectPlaceholder: (title: string) => string;
77
+ /** Placeholder of a tags column's input. */
78
+ tagsPlaceholder: string;
79
+ /** Validation message for an `email` column. */
80
+ invalidEmail: string;
81
+ /** Validation message for a `url` column. */
82
+ invalidUrl: string;
83
+ /** Validation message for an `image` column. */
84
+ invalidImageUrl: string;
85
+ /** Validation message for a `json` column. */
86
+ invalidJson: string;
87
+ }
88
+ /** A locale override: supply only the strings that differ from the default. */
89
+ export type PartialCrudTableLocale = Partial<CrudTableLocale>;
@@ -0,0 +1,35 @@
1
+ import { Locale as AntdLocale } from 'antd/es/locale';
2
+ import { enUSIntl } from '@ant-design/pro-components';
3
+ import { CrudTableLocale, PartialCrudTableLocale } from './types';
4
+ /** Everything `CrudTable` needs to render in the right language. */
5
+ export interface ResolvedLocale {
6
+ /** The library's own strings, defaults merged with any override. */
7
+ strings: CrudTableLocale;
8
+ /** ProTable's message bundle, derived from the surrounding antd locale. */
9
+ intl: typeof enUSIntl;
10
+ /**
11
+ * The antd locale to apply, or `undefined` to inherit.
12
+ *
13
+ * `undefined` means the consumer already has a `ConfigProvider`, so the
14
+ * table must not override it. A value means there is none, and antd's
15
+ * components would otherwise fall back to their built-in defaults - which
16
+ * are Chinese, not English.
17
+ */
18
+ antdLocale: AntdLocale | undefined;
19
+ /** Whether an antd `ConfigProvider` locale was found in the tree. */
20
+ inherited: boolean;
21
+ }
22
+ /**
23
+ * Resolve the language for a table from three sources, in order.
24
+ *
25
+ * 1. An explicit `locale` prop, for overriding individual strings.
26
+ * 2. The surrounding antd `ConfigProvider`, so a table follows the app.
27
+ * 3. English, when there is no provider at all.
28
+ *
29
+ * Step 3 is the one that matters most in practice. antd's components read
30
+ * their own `ConfigProvider`, which `ProConfigProvider`'s `intl` does not
31
+ * feed, so a table rendered outside any provider showed English chrome from
32
+ * ProTable next to Chinese pagination and modal buttons from antd. Supplying
33
+ * an explicit antd locale in that case is what makes the default coherent.
34
+ */
35
+ export declare const useResolvedLocale: (override?: PartialCrudTableLocale) => ResolvedLocale;
@@ -0,0 +1 @@
1
+ const e=require("./en_US-D3Kl6g3n.cjs");let t=require("antd"),n=require("react");var r=()=>{let e=globalThis.crypto===void 0?void 0:globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`},i=/^\d+$/,a=e=>t=>{let n=t.map(t=>t[e]).filter(e=>e!=null);if(n.length===0)return 1;if(n.every(e=>typeof e==`number`)){let e=Math.max(...n.filter(Number.isFinite));return(Number.isFinite(e)?e:0)+1}if(n.every(e=>typeof e==`string`)){let e=n;if(e.every(e=>i.test(e))){let t=Math.max(...e.map(Number));return String(t+1)}return r()}throw Error(`Cannot derive the next id for "${String(e)}": existing keys are neither all numbers nor all strings. Supply an explicit \`generateId\` to the data source.`)},o=(e,t)=>typeof e==`number`&&typeof t==`number`?e-t:typeof e==`boolean`&&typeof t==`boolean`?Number(e)-Number(t):e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():String(e).localeCompare(String(t),void 0,{numeric:!0}),s=(e,t)=>e!=null&&String(e).toLowerCase().includes(String(t).toLowerCase()),c=(e,t)=>{if(!t)return e;let n=Object.entries(t).filter(([,e])=>e!=null&&e!==``);return n.length===0?e:e.filter(e=>n.every(([t,n])=>s(e[t],n)))},l=(e,t)=>!t||t.length===0?e:[...e].sort((e,n)=>{for(let{field:r,direction:i}of t){let t=e[r],a=n[r],s=t==null,c=a==null;if(s&&c)continue;if(s)return 1;if(c)return-1;let l=o(t,a);if(l!==0)return i===`ascend`?l:-l}return 0}),u=(e,t,n)=>{let r=Math.max(0,(t-1)*n);return e.slice(r,r+n)},d=(e,t)=>{let n=l(c(e,t.filters),t.sort);return{items:u(n,t.page,t.pageSize),total:n.length}},f=class{key;generateId;constructor(e,t){this.key=e,this.generateId=t??a(e)}decorate(e,t){return{}}indexOf(e){return this.read().findIndex(t=>t[this.key]===e)}async list(e){return d(this.read(),e)}async listAll(e){return l(c(this.read(),e.filters),e.sort)}async create(e){let t=this.read(),n={[this.key]:this.generateId(t),...e,...this.decorate(e,`create`)};return this.write([...t,n]),n}async update(e,t){let n=this.read(),r=this.indexOf(e);if(r===-1)throw Error(`No record with ${String(this.key)} "${String(e)}"`);let i={...n[r],...t,...this.decorate(t,`update`),[this.key]:e},a=[...n];return a[r]=i,this.write(a),i}async remove(e){let t=this.read();if(this.indexOf(e)===-1)throw Error(`No record with ${String(this.key)} "${String(e)}"`);this.write(t.filter(t=>t[this.key]!==e))}},p=class extends f{records;constructor(e,t,n){super(t,n),this.records=[...e]}read(){return this.records}write(e){this.records=e}},m=class extends f{storageKey;seed;constructor(e,t,n=[],r){super(t,r),this.storageKey=e,this.seed=n}read(){let e;try{e=localStorage.getItem(this.storageKey)}catch{return this.seed}if(e===null)return this.seed;try{let t=JSON.parse(e);return Array.isArray(t)?t:this.seed}catch{return this.seed}}write(e){try{localStorage.setItem(this.storageKey,JSON.stringify(e))}catch(e){throw Error(`Failed to persist to localStorage key "${this.storageKey}": ${e instanceof Error?e.message:String(e)}`)}}decorate(e,t){let n=new Date().toISOString();return t===`create`?{createdAt:n,updatedAt:n}:{updatedAt:n}}},h={list:`/list`,create:`/create`,update:`/update`,remove:`/delete`},g={page:`current`,pageSize:`pageSize`,sortBy:`sortBy`,sortOrder:`sortOrder`},_={create:`POST`,update:`PUT`,remove:`DELETE`},v=class extends Error{status;body;constructor(e,t,n){super(`Request to ${n} failed with status ${e}`),this.name=`RestError`,this.status=e,this.body=t}},y=class{baseUrl;endpoints;paramNames;methods;headers;serializeRequest;parseResponse;fetchImpl;constructor(e={}){this.baseUrl=e.baseUrl??``,this.endpoints={...h,...e.endpoints},this.paramNames={...g,...e.paramNames},this.methods={..._,...e.methods},this.headers=e.headers??{},this.serializeRequest=e.serializeRequest??(e=>e),this.parseResponse=e.parseResponse,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis)}serializeSort(e,t){let n=e?.[0];n&&(t.set(this.paramNames.sortBy,String(n.field)),t.set(this.paramNames.sortOrder,n.direction))}buildListUrl(e){let t=new URLSearchParams;t.set(this.paramNames.page,String(e.page)),t.set(this.paramNames.pageSize,String(e.pageSize)),this.serializeSort(e.sort,t);for(let[n,r]of Object.entries(e.filters??{}))r!=null&&r!==``&&t.set(n,String(r));return`${this.endpoints.list}?${t.toString()}`}buildRecordPath(e,t){return`${e}/${encodeURIComponent(String(t))}`}toPage(e){if(this.parseResponse)return this.parseResponse(e);if(Array.isArray(e))return{items:e,total:e.length};if(typeof e==`object`&&e){let t=e;if(Array.isArray(t.data)){let e=t.data;return{items:e,total:typeof t.total==`number`?t.total:e.length}}}throw Error("Unrecognised list response. Provide `parseResponse` to map it to { items, total }.")}async request(e,t={}){let n=`${this.baseUrl}${e}`,r=await this.fetchImpl(n,{...t,headers:{"Content-Type":`application/json`,...this.headers,...t.headers}});if(!r.ok)throw new v(r.status,await r.text().catch(()=>``),n);if(r.status===204)return;let i=await r.text();return i===``?void 0:JSON.parse(i)}async list(e){return this.toPage(await this.request(this.buildListUrl(e)))}async create(e){return await this.request(this.endpoints.create,{method:this.methods.create,body:JSON.stringify(this.serializeRequest(e))})}async update(e,t){return await this.request(this.buildRecordPath(this.endpoints.update,e),{method:this.methods.update,body:JSON.stringify(this.serializeRequest(t))})}async remove(e){await this.request(this.buildRecordPath(this.endpoints.remove,e),{method:this.methods.remove})}},b=class extends Error{operation;constructor(e){super(`This table's data source does not support "${e}". Provide an \`${e}\` operation to enable it.`),this.name=`UnsupportedOperationError`,this.operation=e}},x=class{operations;constructor(e){this.operations=e}supports(e){return typeof this.operations[e]==`function`}async list(e){if(!this.operations.list)throw new b(`list`);return this.operations.list(e)}async listAll(e){if(this.operations.listAll)return this.operations.listAll(e);throw new b(`listAll`)}async create(e){if(!this.operations.create)throw new b(`create`);return this.operations.create(e)}async update(e,t){if(!this.operations.update)throw new b(`update`);return this.operations.update(e,t)}async remove(e){if(!this.operations.remove)throw new b(`remove`);return this.operations.remove(e)}},S=e=>e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e}),C=(e,t)=>{if(`dataSource`in t)return t.dataSource;if(`operations`in t)return new x(t.operations);if(`storageKey`in t)return new m(t.storageKey,e,t.initialData??[],t.generateId);if(`staticData`in t)return new p(t.staticData,e,t.generateId);if(`api`in t)return new y(t.api);throw Error("useCrudTable: supply exactly one of `staticData`, `api`, `storageKey`, `operations` or `dataSource`.")},w=(r,i)=>{let a=(0,n.useRef)(void 0),{defaultPageSize:o=10,optimisticUpdates:s=!1,refreshAfterMutation:c=!0,notifications:l=!0}=i,u=(0,n.useMemo)(()=>i.locale?{...e.t,...i.locale}:e.t,[i.locale]),d=(0,n.useRef)(i);d.current=i;let f=(0,n.useRef)(null);f.current===null&&(f.current=C(r,i));let p=f.current,[m,h]=(0,n.useState)({loading:!1,error:null,data:[],total:0,page:1,pageSize:o}),{page:g,pageSize:_}=m,v=(0,n.useCallback)((e,n)=>{d.current.onError?.(e,n),l&&t.message.error(n.message)},[l]),y=(0,n.useCallback)((e,n,r)=>{d.current.onSuccess?.(e,n),l&&t.message.success(r)},[l]),b=(0,n.useCallback)(async()=>{h(e=>({...e,loading:!0,error:null}));try{let e={page:g,pageSize:_},t=await p.list(e);h(e=>({...e,data:t.items,total:t.total,loading:!1}))}catch(e){let t=S(e);h(e=>({...e,loading:!1,error:t})),v(`list`,t)}},[p,g,_,v]),x=(0,n.useCallback)(async e=>{if(s){h(e);return}if(c){await b();return}h(e=>({...e,loading:!1}))},[s,c,b]),w=(0,n.useCallback)(async e=>{h(e=>({...e,loading:!0}));try{let t=await p.create(e);return await x(e=>({...e,data:[...e.data,t],total:e.total+1,loading:!1})),y(`create`,t,u.createSuccess),t}catch(e){return h(e=>({...e,loading:!1})),v(`create`,S(e)),null}},[p,x,v,y,u]),T=(0,n.useCallback)(async(e,t)=>{h(e=>({...e,loading:!0}));try{let n=await p.update(e,t);return await x(t=>({...t,data:t.data.map(t=>t[r]===e?n:t),loading:!1})),y(`update`,n,u.updateSuccess),n}catch(e){return h(e=>({...e,loading:!1})),v(`update`,S(e)),null}},[p,x,v,r,y,u]),E=(0,n.useCallback)(async e=>{h(e=>({...e,loading:!0}));try{return await p.remove(e),await x(t=>({...t,data:t.data.filter(t=>t[r]!==e),total:Math.max(0,t.total-1),loading:!1})),y(`delete`,e,u.deleteSuccess),!0}catch(e){return h(e=>({...e,loading:!1})),v(`delete`,S(e)),!1}},[p,x,v,r,y,u]),D=(0,n.useCallback)(e=>{h(t=>({...t,page:e}))},[]),O=(0,n.useCallback)(e=>{h(t=>({...t,pageSize:e,page:1}))},[]);return(0,n.useMemo)(()=>({refresh:b,create:w,update:T,remove:E,dataSource:p,setPage:D,setPageSize:O,state:m,actionRef:a}),[b,w,T,E,p,D,O,m])};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return c}});