@wordpress/views 2.0.0 → 3.1.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.
@@ -1,123 +1,192 @@
1
- // packages/views/src/resolve-view.ts
2
1
  import { dequal } from "dequal";
3
- var QUERY_PARAMS = ["page", "search"];
2
+ // packages/views/src/resolve-view.ts
3
+ /**
4
+ * `page` and `search` are URL-managed: the URL is their only source. They are
5
+ * never persisted, and no other layer may configure them — an absent URL param
6
+ * is indistinguishable from the user having cleared the value, so any fallback
7
+ * would resurrect a cleared search on the next read.
8
+ */
9
+ const QUERY_PARAMS = ["page", "search"];
4
10
  function isPlainObject(value) {
5
- return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
12
  }
13
+ /**
14
+ * Copies a layer without the URL-managed properties.
15
+ *
16
+ * @param layer The layer to copy.
17
+ * @return A copy of the layer with `page` and `search` removed.
18
+ */
7
19
  function withoutQueryParams(layer) {
8
- const result = isPlainObject(layer) ? { ...layer } : {};
9
- for (const key of QUERY_PARAMS) {
10
- delete result[key];
11
- }
12
- return result;
20
+ const result = isPlainObject(layer) ? { ...layer } : {};
21
+ for (const key of QUERY_PARAMS) delete result[key];
22
+ return result;
13
23
  }
24
+ /**
25
+ * Merges a layer on top of another, recursing into plain objects so the upper
26
+ * layer only takes over the leaves it declares. Arrays and scalars are leaves:
27
+ * they are replaced wholesale.
28
+ *
29
+ * Nested properties (`layout.styles.<field>.width`, `groupBy.direction`,
30
+ * `sort.direction`) are merged leaf by leaf: a shallow merge would let a layer
31
+ * that only declares one leaf wipe every sibling the layers below provide.
32
+ *
33
+ * @param lower The layer to merge into.
34
+ * @param upper The layer to merge on top.
35
+ * @return The merged layer.
36
+ */
14
37
  function mergeLayer(lower, upper) {
15
- const result = { ...lower };
16
- for (const key of Object.keys(upper)) {
17
- const value = upper[key];
18
- const current = result[key];
19
- result[key] = isPlainObject(current) && isPlainObject(value) ? mergeLayer(current, value) : value;
20
- }
21
- return result;
38
+ const result = { ...lower };
39
+ for (const key of Object.keys(upper)) {
40
+ const value = upper[key];
41
+ const current = result[key];
42
+ result[key] = isPlainObject(current) && isPlainObject(value) ? mergeLayer(current, value) : value;
43
+ }
44
+ return result;
22
45
  }
46
+ /**
47
+ * The leaves of `value` that differ from `base`. Mirrors `mergeLayer`:
48
+ * `mergeLayer( base, diffLayer( value, base ) )` resolves back to `value`.
49
+ *
50
+ * A persisted leaf that equals both `value` and `base` is kept even though it
51
+ * is not a difference: the preference is shared by every view of the same
52
+ * entity, and such a leaf may only differ from the base of *another* view. In
53
+ * this one, where it coincides with the base, a revert is unobservable — so
54
+ * equality cannot mean the user reverted it. Dropping a persisted leaf
55
+ * requires `value` to actually move away from it, back to `base`.
56
+ *
57
+ * @param value The layer to compare.
58
+ * @param base The layer to compare it against.
59
+ * @param persisted The previously persisted leaves.
60
+ * @return The leaves that differ, as a layer of its own.
61
+ */
23
62
  function diffLayer(value, base, persisted = {}) {
24
- const result = {};
25
- for (const key of Object.keys(value)) {
26
- const next = value[key];
27
- const current = base[key];
28
- const prev = persisted[key];
29
- if (next === void 0) {
30
- continue;
31
- }
32
- if (isPlainObject(next) && isPlainObject(current)) {
33
- const nested = diffLayer(
34
- next,
35
- current,
36
- isPlainObject(prev) ? prev : {}
37
- );
38
- if (Object.keys(nested).length > 0) {
39
- result[key] = nested;
40
- }
41
- } else if (!dequal(next, current)) {
42
- result[key] = next;
43
- } else if (prev !== void 0 && dequal(next, prev)) {
44
- result[key] = prev;
45
- }
46
- }
47
- return result;
63
+ const result = {};
64
+ for (const key of Object.keys(value)) {
65
+ const next = value[key];
66
+ const current = base[key];
67
+ const prev = persisted[key];
68
+ if (next === void 0) continue;
69
+ if (isPlainObject(next) && isPlainObject(current)) {
70
+ const nested = diffLayer(next, current, isPlainObject(prev) ? prev : {});
71
+ if (Object.keys(nested).length > 0) result[key] = nested;
72
+ } else if (!dequal(next, current)) result[key] = next;
73
+ else if (prev !== void 0 && dequal(next, prev)) result[key] = prev;
74
+ }
75
+ return result;
48
76
  }
49
77
  function getLockedFilters(overrides) {
50
- return (overrides?.filters ?? []).filter((filter) => filter.isLocked);
78
+ return (overrides?.filters ?? []).filter((filter) => filter.isLocked);
51
79
  }
80
+ /**
81
+ * Hoists the locked filters an override provides to the front of the view's
82
+ * filters, replacing any same-field filter. Locked filters are not the user's
83
+ * to change, so they are pinned in place instead of taking part in the layer
84
+ * resolution.
85
+ *
86
+ * @param view The view to apply the locked filters to.
87
+ * @param overrides The active view overrides.
88
+ * @return The view with the locked filters applied.
89
+ */
52
90
  function applyLockedFilters(view, overrides) {
53
- const locked = getLockedFilters(overrides);
54
- if (locked.length === 0) {
55
- return view;
56
- }
57
- const rest = (view.filters ?? []).filter(
58
- (filter) => !locked.some((f) => f.field === filter.field)
59
- );
60
- return { ...view, filters: [...locked, ...rest] };
91
+ const locked = getLockedFilters(overrides);
92
+ if (locked.length === 0) return view;
93
+ const rest = (view.filters ?? []).filter((filter) => !locked.some((f) => f.field === filter.field));
94
+ return {
95
+ ...view,
96
+ filters: [...locked, ...rest]
97
+ };
61
98
  }
99
+ /**
100
+ * The user's persisted modifications that still apply.
101
+ *
102
+ * A persisted `type` that `defaultLayouts` does not offer is dropped: DataViews
103
+ * renders nothing for a layout it is not given, and the preference may predate
104
+ * the current set of layouts (a screen that used to offer the list layout, say,
105
+ * and no longer does). The type then resolves out of the layers below, and the
106
+ * other modifications are kept. Without `defaultLayouts` every type is offered.
107
+ *
108
+ * `true` is a valid entry, so the check mirrors DataViews': an entry counts as
109
+ * long as it is truthy.
110
+ *
111
+ * @param persistedView The user's persisted modifications.
112
+ * @param defaultLayouts The layouts on offer, keyed by layout type.
113
+ * @return The modifications that apply, or `undefined` when there are none.
114
+ */
62
115
  function getApplicablePersistedView(persistedView, defaultLayouts) {
63
- if (!persistedView || persistedView.type === void 0 || !defaultLayouts || defaultLayouts[persistedView.type]) {
64
- return persistedView;
65
- }
66
- const { type, ...rest } = persistedView;
67
- return Object.keys(rest).length > 0 ? rest : void 0;
116
+ if (!persistedView || persistedView.type === void 0 || !defaultLayouts || defaultLayouts[persistedView.type]) return persistedView;
117
+ const { type, ...rest } = persistedView;
118
+ return Object.keys(rest).length > 0 ? rest : void 0;
68
119
  }
120
+ /**
121
+ * Resolves the layers below the user's modifications — what a modification has
122
+ * to differ from to count as one. The layout type selects which entry of
123
+ * `defaultLayouts` applies, so the base only makes sense relative to a type.
124
+ *
125
+ * @param layers The layers to resolve.
126
+ * @param effectiveType The layout type to resolve the base at.
127
+ * @return The resolved base view.
128
+ */
69
129
  function resolveBaseView(layers, effectiveType) {
70
- const { defaultView, defaultLayouts, activeViewOverrides } = layers;
71
- const layoutDefaults = defaultLayouts?.[effectiveType];
72
- return applyLockedFilters(
73
- [layoutDefaults, activeViewOverrides].reduce(
74
- (lower, upper) => mergeLayer(lower, withoutQueryParams(upper)),
75
- withoutQueryParams(defaultView)
76
- ),
77
- activeViewOverrides
78
- );
130
+ const { defaultView, defaultLayouts, activeViewOverrides } = layers;
131
+ const layoutDefaults = defaultLayouts?.[effectiveType];
132
+ return applyLockedFilters([layoutDefaults, activeViewOverrides].reduce((lower, upper) => mergeLayer(lower, withoutQueryParams(upper)), withoutQueryParams(defaultView)), activeViewOverrides);
79
133
  }
134
+ /**
135
+ * Resolves a view out of its layers. Later layers override earlier ones:
136
+ *
137
+ * 1. `defaultView`
138
+ * 2. `defaultLayouts` (for the effective type)
139
+ * 3. `activeViewOverrides`
140
+ * 4. the user's persisted modifications (see `getApplicablePersistedView`)
141
+ * 5. the URL query params (`page` and `search` only)
142
+ *
143
+ * @param args See `ResolveViewArgs`.
144
+ * @return The resolved `view`.
145
+ */
80
146
  function resolveView(args) {
81
- const { defaultView, defaultLayouts, activeViewOverrides, page, search } = args;
82
- const persistedView = getApplicablePersistedView(
83
- args.persistedView,
84
- defaultLayouts
85
- );
86
- const effectiveType = persistedView?.type ?? activeViewOverrides?.type ?? defaultView?.type;
87
- const baseView = resolveBaseView(args, effectiveType);
88
- const view = {
89
- ...applyLockedFilters(
90
- mergeLayer(baseView, withoutQueryParams(persistedView)),
91
- activeViewOverrides
92
- ),
93
- page: Number(page ?? 1),
94
- search: search ?? ""
95
- };
96
- return view;
147
+ const { defaultView, defaultLayouts, activeViewOverrides, page, search } = args;
148
+ const persistedView = getApplicablePersistedView(args.persistedView, defaultLayouts);
149
+ return {
150
+ ...applyLockedFilters(mergeLayer(resolveBaseView(args, persistedView?.type ?? activeViewOverrides?.type ?? defaultView?.type), withoutQueryParams(persistedView)), activeViewOverrides),
151
+ page: Number(page ?? 1),
152
+ search: search ?? ""
153
+ };
97
154
  }
155
+ /**
156
+ * The user's modifications: the leaves of the view they interacted with that
157
+ * the layers below do not already resolve to. This is what gets persisted, so
158
+ * that a change to any of those layers keeps showing through the properties the
159
+ * user never touched.
160
+ *
161
+ * Previously persisted leaves that coincide with the base of the current view
162
+ * are carried over rather than dropped: they may still make a difference in
163
+ * another view sharing the preference. See `diffLayer`.
164
+ *
165
+ * The diff basis is resolved at `newView.type`, not at the type the previous
166
+ * resolution used: the type selects the `defaultLayouts` entry, and a layout
167
+ * switch reports the new type together with that entry's values. Diffing them
168
+ * against the previous type's base would persist the difference between the
169
+ * two entries as if the user had picked those values — leaves the layouts
170
+ * already provide, which then linger as phantom modifications after switching
171
+ * back.
172
+ *
173
+ * A persisted `type` the current layouts do not offer never applied (see
174
+ * `getApplicablePersistedView`), so it is not carried over either: the
175
+ * modifications returned replace it with whatever the user picked.
176
+ *
177
+ * @param newView The view the user produced.
178
+ * @param layers The layers the view resolves from. See `ViewLayers`.
179
+ * @return The modified properties, or `undefined` when the user modified none.
180
+ */
98
181
  function getUserModifications(newView, layers) {
99
- const { defaultLayouts, activeViewOverrides } = layers;
100
- const persistedView = getApplicablePersistedView(
101
- layers.persistedView,
102
- defaultLayouts
103
- );
104
- const baseView = resolveBaseView(layers, newView.type);
105
- const modifications = diffLayer(
106
- withoutQueryParams(newView),
107
- withoutQueryParams(baseView),
108
- withoutQueryParams(persistedView)
109
- );
110
- const locked = getLockedFilters(activeViewOverrides);
111
- if (locked.length > 0 && Array.isArray(modifications.filters)) {
112
- modifications.filters = modifications.filters.filter(
113
- (filter) => !locked.some((f) => f.field === filter.field)
114
- );
115
- }
116
- return Object.keys(modifications).length > 0 ? modifications : void 0;
182
+ const { defaultLayouts, activeViewOverrides } = layers;
183
+ const persistedView = getApplicablePersistedView(layers.persistedView, defaultLayouts);
184
+ const baseView = resolveBaseView(layers, newView.type);
185
+ const modifications = diffLayer(withoutQueryParams(newView), withoutQueryParams(baseView), withoutQueryParams(persistedView));
186
+ const locked = getLockedFilters(activeViewOverrides);
187
+ if (locked.length > 0 && Array.isArray(modifications.filters)) modifications.filters = modifications.filters.filter((filter) => !locked.some((f) => f.field === filter.field));
188
+ return Object.keys(modifications).length > 0 ? modifications : void 0;
117
189
  }
118
- export {
119
- getApplicablePersistedView,
120
- getUserModifications,
121
- resolveView
122
- };
123
- //# sourceMappingURL=resolve-view.mjs.map
190
+ export { getApplicablePersistedView, getUserModifications, resolveView };
191
+
192
+ //# sourceMappingURL=resolve-view.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/resolve-view.ts"],
4
- "sourcesContent": ["import { dequal } from 'dequal';\nimport type { View, Filter, SupportedLayouts } from '@wordpress/dataviews';\nimport type { ViewOverrides } from './types';\n\ntype PlainObject = Record< string, unknown >;\n\n/**\n * `page` and `search` are URL-managed: the URL is their only source. They are\n * never persisted, and no other layer may configure them — an absent URL param\n * is indistinguishable from the user having cleared the value, so any fallback\n * would resurrect a cleared search on the next read.\n */\nconst QUERY_PARAMS = [ 'page', 'search' ] as const;\n\nfunction isPlainObject( value: unknown ): value is PlainObject {\n\treturn (\n\t\ttypeof value === 'object' && value !== null && ! Array.isArray( value )\n\t);\n}\n\n/**\n * Copies a layer without the URL-managed properties.\n *\n * @param layer The layer to copy.\n * @return A copy of the layer with `page` and `search` removed.\n */\nfunction withoutQueryParams( layer: unknown ): PlainObject {\n\tconst result: PlainObject = isPlainObject( layer ) ? { ...layer } : {};\n\tfor ( const key of QUERY_PARAMS ) {\n\t\tdelete result[ key ];\n\t}\n\treturn result;\n}\n\n/**\n * Merges a layer on top of another, recursing into plain objects so the upper\n * layer only takes over the leaves it declares. Arrays and scalars are leaves:\n * they are replaced wholesale.\n *\n * Nested properties (`layout.styles.<field>.width`, `groupBy.direction`,\n * `sort.direction`) are merged leaf by leaf: a shallow merge would let a layer\n * that only declares one leaf wipe every sibling the layers below provide.\n *\n * @param lower The layer to merge into.\n * @param upper The layer to merge on top.\n * @return The merged layer.\n */\nfunction mergeLayer( lower: PlainObject, upper: PlainObject ): PlainObject {\n\tconst result: PlainObject = { ...lower };\n\tfor ( const key of Object.keys( upper ) ) {\n\t\tconst value = upper[ key ];\n\t\tconst current = result[ key ];\n\t\tresult[ key ] =\n\t\t\tisPlainObject( current ) && isPlainObject( value )\n\t\t\t\t? mergeLayer( current, value )\n\t\t\t\t: value;\n\t}\n\treturn result;\n}\n\n/**\n * The leaves of `value` that differ from `base`. Mirrors `mergeLayer`:\n * `mergeLayer( base, diffLayer( value, base ) )` resolves back to `value`.\n *\n * A persisted leaf that equals both `value` and `base` is kept even though it\n * is not a difference: the preference is shared by every view of the same\n * entity, and such a leaf may only differ from the base of *another* view. In\n * this one, where it coincides with the base, a revert is unobservable — so\n * equality cannot mean the user reverted it. Dropping a persisted leaf\n * requires `value` to actually move away from it, back to `base`.\n *\n * @param value The layer to compare.\n * @param base The layer to compare it against.\n * @param persisted The previously persisted leaves.\n * @return The leaves that differ, as a layer of its own.\n */\nfunction diffLayer(\n\tvalue: PlainObject,\n\tbase: PlainObject,\n\tpersisted: PlainObject = {}\n): PlainObject {\n\tconst result: PlainObject = {};\n\tfor ( const key of Object.keys( value ) ) {\n\t\tconst next = value[ key ];\n\t\tconst current = base[ key ];\n\t\tconst prev = persisted[ key ];\n\t\tif ( next === undefined ) {\n\t\t\tcontinue;\n\t\t}\n\t\tif ( isPlainObject( next ) && isPlainObject( current ) ) {\n\t\t\tconst nested = diffLayer(\n\t\t\t\tnext,\n\t\t\t\tcurrent,\n\t\t\t\tisPlainObject( prev ) ? prev : {}\n\t\t\t);\n\t\t\tif ( Object.keys( nested ).length > 0 ) {\n\t\t\t\tresult[ key ] = nested;\n\t\t\t}\n\t\t} else if ( ! dequal( next, current ) ) {\n\t\t\tresult[ key ] = next;\n\t\t} else if ( prev !== undefined && dequal( next, prev ) ) {\n\t\t\tresult[ key ] = prev;\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getLockedFilters( overrides?: ViewOverrides ): Filter[] {\n\treturn ( overrides?.filters ?? [] ).filter( ( filter ) => filter.isLocked );\n}\n\n/**\n * Hoists the locked filters an override provides to the front of the view's\n * filters, replacing any same-field filter. Locked filters are not the user's\n * to change, so they are pinned in place instead of taking part in the layer\n * resolution.\n *\n * @param view The view to apply the locked filters to.\n * @param overrides The active view overrides.\n * @return The view with the locked filters applied.\n */\nfunction applyLockedFilters(\n\tview: PlainObject,\n\toverrides?: ViewOverrides\n): PlainObject {\n\tconst locked = getLockedFilters( overrides );\n\tif ( locked.length === 0 ) {\n\t\treturn view;\n\t}\n\tconst rest = ( ( view.filters ?? [] ) as Filter[] ).filter(\n\t\t( filter ) => ! locked.some( ( f ) => f.field === filter.field )\n\t);\n\treturn { ...view, filters: [ ...locked, ...rest ] };\n}\n\ninterface ViewLayers {\n\tdefaultView?: View;\n\tdefaultLayouts?: SupportedLayouts;\n\tactiveViewOverrides?: ViewOverrides;\n\t/**\n\t * The user's persisted modifications: a partial view holding only the\n\t * properties they actually changed.\n\t */\n\tpersistedView?: ViewOverrides;\n}\n\ninterface ResolveViewArgs extends ViewLayers {\n\tpage?: number;\n\tsearch?: string;\n}\n\n/**\n * The user's persisted modifications that still apply.\n *\n * A persisted `type` that `defaultLayouts` does not offer is dropped: DataViews\n * renders nothing for a layout it is not given, and the preference may predate\n * the current set of layouts (a screen that used to offer the list layout, say,\n * and no longer does). The type then resolves out of the layers below, and the\n * other modifications are kept. Without `defaultLayouts` every type is offered.\n *\n * `true` is a valid entry, so the check mirrors DataViews': an entry counts as\n * long as it is truthy.\n *\n * @param persistedView The user's persisted modifications.\n * @param defaultLayouts The layouts on offer, keyed by layout type.\n * @return The modifications that apply, or `undefined` when there are none.\n */\nexport function getApplicablePersistedView(\n\tpersistedView: ViewOverrides | undefined,\n\tdefaultLayouts: SupportedLayouts | undefined\n): ViewOverrides | undefined {\n\tif (\n\t\t! persistedView ||\n\t\tpersistedView.type === undefined ||\n\t\t! defaultLayouts ||\n\t\tdefaultLayouts[ persistedView.type as keyof SupportedLayouts ]\n\t) {\n\t\treturn persistedView;\n\t}\n\tconst { type, ...rest } = persistedView;\n\treturn Object.keys( rest ).length > 0 ? rest : undefined;\n}\n\n/**\n * Resolves the layers below the user's modifications — what a modification has\n * to differ from to count as one. The layout type selects which entry of\n * `defaultLayouts` applies, so the base only makes sense relative to a type.\n *\n * @param layers The layers to resolve.\n * @param effectiveType The layout type to resolve the base at.\n * @return The resolved base view.\n */\nfunction resolveBaseView(\n\tlayers: ViewLayers,\n\teffectiveType: View[ 'type' ] | undefined\n): PlainObject {\n\tconst { defaultView, defaultLayouts, activeViewOverrides } = layers;\n\tconst layoutDefaults =\n\t\tdefaultLayouts?.[ effectiveType as keyof SupportedLayouts ];\n\treturn applyLockedFilters(\n\t\t[ layoutDefaults, activeViewOverrides ].reduce< PlainObject >(\n\t\t\t( lower, upper ) =>\n\t\t\t\tmergeLayer( lower, withoutQueryParams( upper ) ),\n\t\t\twithoutQueryParams( defaultView )\n\t\t),\n\t\tactiveViewOverrides\n\t);\n}\n\n/**\n * Resolves a view out of its layers. Later layers override earlier ones:\n *\n * 1. `defaultView`\n * 2. `defaultLayouts` (for the effective type)\n * 3. `activeViewOverrides`\n * 4. the user's persisted modifications (see `getApplicablePersistedView`)\n * 5. the URL query params (`page` and `search` only)\n *\n * @param args See `ResolveViewArgs`.\n * @return The resolved `view`.\n */\nexport function resolveView( args: ResolveViewArgs ): View {\n\tconst { defaultView, defaultLayouts, activeViewOverrides, page, search } =\n\t\targs;\n\tconst persistedView = getApplicablePersistedView(\n\t\targs.persistedView,\n\t\tdefaultLayouts\n\t);\n\n\t// Resolve the effective layout type first: it selects which entry of\n\t// `defaultLayouts` applies, and the layers above the layouts may change it.\n\tconst effectiveType =\n\t\tpersistedView?.type ?? activeViewOverrides?.type ?? defaultView?.type;\n\tconst baseView = resolveBaseView( args, effectiveType );\n\n\tconst view = {\n\t\t...applyLockedFilters(\n\t\t\tmergeLayer( baseView, withoutQueryParams( persistedView ) ),\n\t\t\tactiveViewOverrides\n\t\t),\n\t\tpage: Number( page ?? 1 ),\n\t\tsearch: search ?? '',\n\t};\n\n\t// The layers are resolved as plain objects: `View` requires a `type`, which\n\t// only the layers taken together are guaranteed to provide.\n\treturn view as unknown as View;\n}\n\n/**\n * The user's modifications: the leaves of the view they interacted with that\n * the layers below do not already resolve to. This is what gets persisted, so\n * that a change to any of those layers keeps showing through the properties the\n * user never touched.\n *\n * Previously persisted leaves that coincide with the base of the current view\n * are carried over rather than dropped: they may still make a difference in\n * another view sharing the preference. See `diffLayer`.\n *\n * The diff basis is resolved at `newView.type`, not at the type the previous\n * resolution used: the type selects the `defaultLayouts` entry, and a layout\n * switch reports the new type together with that entry's values. Diffing them\n * against the previous type's base would persist the difference between the\n * two entries as if the user had picked those values — leaves the layouts\n * already provide, which then linger as phantom modifications after switching\n * back.\n *\n * A persisted `type` the current layouts do not offer never applied (see\n * `getApplicablePersistedView`), so it is not carried over either: the\n * modifications returned replace it with whatever the user picked.\n *\n * @param newView The view the user produced.\n * @param layers The layers the view resolves from. See `ViewLayers`.\n * @return The modified properties, or `undefined` when the user modified none.\n */\nexport function getUserModifications(\n\tnewView: View,\n\tlayers: ViewLayers\n): ViewOverrides | undefined {\n\tconst { defaultLayouts, activeViewOverrides } = layers;\n\tconst persistedView = getApplicablePersistedView(\n\t\tlayers.persistedView,\n\t\tdefaultLayouts\n\t);\n\tconst baseView = resolveBaseView( layers, newView.type );\n\n\tconst modifications = diffLayer(\n\t\twithoutQueryParams( newView ),\n\t\twithoutQueryParams( baseView ),\n\t\twithoutQueryParams( persistedView )\n\t);\n\n\t// Locked filters are pinned on every read, so persisting them would only\n\t// leak them into the views that do not lock them.\n\tconst locked = getLockedFilters( activeViewOverrides );\n\tif ( locked.length > 0 && Array.isArray( modifications.filters ) ) {\n\t\tmodifications.filters = ( modifications.filters as Filter[] ).filter(\n\t\t\t( filter ) => ! locked.some( ( f ) => f.field === filter.field )\n\t\t);\n\t}\n\n\treturn Object.keys( modifications ).length > 0\n\t\t? ( modifications as ViewOverrides )\n\t\t: undefined;\n}\n"],
5
- "mappings": ";AAAA,SAAS,cAAc;AAYvB,IAAM,eAAe,CAAE,QAAQ,QAAS;AAExC,SAAS,cAAe,OAAuC;AAC9D,SACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAE,MAAM,QAAS,KAAM;AAExE;AAQA,SAAS,mBAAoB,OAA8B;AAC1D,QAAM,SAAsB,cAAe,KAAM,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC;AACrE,aAAY,OAAO,cAAe;AACjC,WAAO,OAAQ,GAAI;AAAA,EACpB;AACA,SAAO;AACR;AAeA,SAAS,WAAY,OAAoB,OAAkC;AAC1E,QAAM,SAAsB,EAAE,GAAG,MAAM;AACvC,aAAY,OAAO,OAAO,KAAM,KAAM,GAAI;AACzC,UAAM,QAAQ,MAAO,GAAI;AACzB,UAAM,UAAU,OAAQ,GAAI;AAC5B,WAAQ,GAAI,IACX,cAAe,OAAQ,KAAK,cAAe,KAAM,IAC9C,WAAY,SAAS,KAAM,IAC3B;AAAA,EACL;AACA,SAAO;AACR;AAkBA,SAAS,UACR,OACA,MACA,YAAyB,CAAC,GACZ;AACd,QAAM,SAAsB,CAAC;AAC7B,aAAY,OAAO,OAAO,KAAM,KAAM,GAAI;AACzC,UAAM,OAAO,MAAO,GAAI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,EAAE,SAAS,IACxC,gBACF;AACJ;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"resolve-view.mjs","names":[],"sources":["../src/resolve-view.ts"],"sourcesContent":["import { dequal } from 'dequal';\nimport type { View, Filter, SupportedLayouts } from '@wordpress/dataviews';\nimport type { ViewOverrides } from './types';\n\ntype PlainObject = Record< string, unknown >;\n\n/**\n * `page` and `search` are URL-managed: the URL is their only source. They are\n * never persisted, and no other layer may configure them — an absent URL param\n * is indistinguishable from the user having cleared the value, so any fallback\n * would resurrect a cleared search on the next read.\n */\nconst QUERY_PARAMS = [ 'page', 'search' ] as const;\n\nfunction isPlainObject( value: unknown ): value is PlainObject {\n\treturn (\n\t\ttypeof value === 'object' && value !== null && ! Array.isArray( value )\n\t);\n}\n\n/**\n * Copies a layer without the URL-managed properties.\n *\n * @param layer The layer to copy.\n * @return A copy of the layer with `page` and `search` removed.\n */\nfunction withoutQueryParams( layer: unknown ): PlainObject {\n\tconst result: PlainObject = isPlainObject( layer ) ? { ...layer } : {};\n\tfor ( const key of QUERY_PARAMS ) {\n\t\tdelete result[ key ];\n\t}\n\treturn result;\n}\n\n/**\n * Merges a layer on top of another, recursing into plain objects so the upper\n * layer only takes over the leaves it declares. Arrays and scalars are leaves:\n * they are replaced wholesale.\n *\n * Nested properties (`layout.styles.<field>.width`, `groupBy.direction`,\n * `sort.direction`) are merged leaf by leaf: a shallow merge would let a layer\n * that only declares one leaf wipe every sibling the layers below provide.\n *\n * @param lower The layer to merge into.\n * @param upper The layer to merge on top.\n * @return The merged layer.\n */\nfunction mergeLayer( lower: PlainObject, upper: PlainObject ): PlainObject {\n\tconst result: PlainObject = { ...lower };\n\tfor ( const key of Object.keys( upper ) ) {\n\t\tconst value = upper[ key ];\n\t\tconst current = result[ key ];\n\t\tresult[ key ] =\n\t\t\tisPlainObject( current ) && isPlainObject( value )\n\t\t\t\t? mergeLayer( current, value )\n\t\t\t\t: value;\n\t}\n\treturn result;\n}\n\n/**\n * The leaves of `value` that differ from `base`. Mirrors `mergeLayer`:\n * `mergeLayer( base, diffLayer( value, base ) )` resolves back to `value`.\n *\n * A persisted leaf that equals both `value` and `base` is kept even though it\n * is not a difference: the preference is shared by every view of the same\n * entity, and such a leaf may only differ from the base of *another* view. In\n * this one, where it coincides with the base, a revert is unobservable — so\n * equality cannot mean the user reverted it. Dropping a persisted leaf\n * requires `value` to actually move away from it, back to `base`.\n *\n * @param value The layer to compare.\n * @param base The layer to compare it against.\n * @param persisted The previously persisted leaves.\n * @return The leaves that differ, as a layer of its own.\n */\nfunction diffLayer(\n\tvalue: PlainObject,\n\tbase: PlainObject,\n\tpersisted: PlainObject = {}\n): PlainObject {\n\tconst result: PlainObject = {};\n\tfor ( const key of Object.keys( value ) ) {\n\t\tconst next = value[ key ];\n\t\tconst current = base[ key ];\n\t\tconst prev = persisted[ key ];\n\t\tif ( next === undefined ) {\n\t\t\tcontinue;\n\t\t}\n\t\tif ( isPlainObject( next ) && isPlainObject( current ) ) {\n\t\t\tconst nested = diffLayer(\n\t\t\t\tnext,\n\t\t\t\tcurrent,\n\t\t\t\tisPlainObject( prev ) ? prev : {}\n\t\t\t);\n\t\t\tif ( Object.keys( nested ).length > 0 ) {\n\t\t\t\tresult[ key ] = nested;\n\t\t\t}\n\t\t} else if ( ! dequal( next, current ) ) {\n\t\t\tresult[ key ] = next;\n\t\t} else if ( prev !== undefined && dequal( next, prev ) ) {\n\t\t\tresult[ key ] = prev;\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction getLockedFilters( overrides?: ViewOverrides ): Filter[] {\n\treturn ( overrides?.filters ?? [] ).filter( ( filter ) => filter.isLocked );\n}\n\n/**\n * Hoists the locked filters an override provides to the front of the view's\n * filters, replacing any same-field filter. Locked filters are not the user's\n * to change, so they are pinned in place instead of taking part in the layer\n * resolution.\n *\n * @param view The view to apply the locked filters to.\n * @param overrides The active view overrides.\n * @return The view with the locked filters applied.\n */\nfunction applyLockedFilters(\n\tview: PlainObject,\n\toverrides?: ViewOverrides\n): PlainObject {\n\tconst locked = getLockedFilters( overrides );\n\tif ( locked.length === 0 ) {\n\t\treturn view;\n\t}\n\tconst rest = ( ( view.filters ?? [] ) as Filter[] ).filter(\n\t\t( filter ) => ! locked.some( ( f ) => f.field === filter.field )\n\t);\n\treturn { ...view, filters: [ ...locked, ...rest ] };\n}\n\ninterface ViewLayers {\n\tdefaultView?: View;\n\tdefaultLayouts?: SupportedLayouts;\n\tactiveViewOverrides?: ViewOverrides;\n\t/**\n\t * The user's persisted modifications: a partial view holding only the\n\t * properties they actually changed.\n\t */\n\tpersistedView?: ViewOverrides;\n}\n\ninterface ResolveViewArgs extends ViewLayers {\n\tpage?: number;\n\tsearch?: string;\n}\n\n/**\n * The user's persisted modifications that still apply.\n *\n * A persisted `type` that `defaultLayouts` does not offer is dropped: DataViews\n * renders nothing for a layout it is not given, and the preference may predate\n * the current set of layouts (a screen that used to offer the list layout, say,\n * and no longer does). The type then resolves out of the layers below, and the\n * other modifications are kept. Without `defaultLayouts` every type is offered.\n *\n * `true` is a valid entry, so the check mirrors DataViews': an entry counts as\n * long as it is truthy.\n *\n * @param persistedView The user's persisted modifications.\n * @param defaultLayouts The layouts on offer, keyed by layout type.\n * @return The modifications that apply, or `undefined` when there are none.\n */\nexport function getApplicablePersistedView(\n\tpersistedView: ViewOverrides | undefined,\n\tdefaultLayouts: SupportedLayouts | undefined\n): ViewOverrides | undefined {\n\tif (\n\t\t! persistedView ||\n\t\tpersistedView.type === undefined ||\n\t\t! defaultLayouts ||\n\t\tdefaultLayouts[ persistedView.type as keyof SupportedLayouts ]\n\t) {\n\t\treturn persistedView;\n\t}\n\tconst { type, ...rest } = persistedView;\n\treturn Object.keys( rest ).length > 0 ? rest : undefined;\n}\n\n/**\n * Resolves the layers below the user's modifications — what a modification has\n * to differ from to count as one. The layout type selects which entry of\n * `defaultLayouts` applies, so the base only makes sense relative to a type.\n *\n * @param layers The layers to resolve.\n * @param effectiveType The layout type to resolve the base at.\n * @return The resolved base view.\n */\nfunction resolveBaseView(\n\tlayers: ViewLayers,\n\teffectiveType: View[ 'type' ] | undefined\n): PlainObject {\n\tconst { defaultView, defaultLayouts, activeViewOverrides } = layers;\n\tconst layoutDefaults =\n\t\tdefaultLayouts?.[ effectiveType as keyof SupportedLayouts ];\n\treturn applyLockedFilters(\n\t\t[ layoutDefaults, activeViewOverrides ].reduce< PlainObject >(\n\t\t\t( lower, upper ) =>\n\t\t\t\tmergeLayer( lower, withoutQueryParams( upper ) ),\n\t\t\twithoutQueryParams( defaultView )\n\t\t),\n\t\tactiveViewOverrides\n\t);\n}\n\n/**\n * Resolves a view out of its layers. Later layers override earlier ones:\n *\n * 1. `defaultView`\n * 2. `defaultLayouts` (for the effective type)\n * 3. `activeViewOverrides`\n * 4. the user's persisted modifications (see `getApplicablePersistedView`)\n * 5. the URL query params (`page` and `search` only)\n *\n * @param args See `ResolveViewArgs`.\n * @return The resolved `view`.\n */\nexport function resolveView( args: ResolveViewArgs ): View {\n\tconst { defaultView, defaultLayouts, activeViewOverrides, page, search } =\n\t\targs;\n\tconst persistedView = getApplicablePersistedView(\n\t\targs.persistedView,\n\t\tdefaultLayouts\n\t);\n\n\t// Resolve the effective layout type first: it selects which entry of\n\t// `defaultLayouts` applies, and the layers above the layouts may change it.\n\tconst effectiveType =\n\t\tpersistedView?.type ?? activeViewOverrides?.type ?? defaultView?.type;\n\tconst baseView = resolveBaseView( args, effectiveType );\n\n\tconst view = {\n\t\t...applyLockedFilters(\n\t\t\tmergeLayer( baseView, withoutQueryParams( persistedView ) ),\n\t\t\tactiveViewOverrides\n\t\t),\n\t\tpage: Number( page ?? 1 ),\n\t\tsearch: search ?? '',\n\t};\n\n\t// The layers are resolved as plain objects: `View` requires a `type`, which\n\t// only the layers taken together are guaranteed to provide.\n\treturn view as unknown as View;\n}\n\n/**\n * The user's modifications: the leaves of the view they interacted with that\n * the layers below do not already resolve to. This is what gets persisted, so\n * that a change to any of those layers keeps showing through the properties the\n * user never touched.\n *\n * Previously persisted leaves that coincide with the base of the current view\n * are carried over rather than dropped: they may still make a difference in\n * another view sharing the preference. See `diffLayer`.\n *\n * The diff basis is resolved at `newView.type`, not at the type the previous\n * resolution used: the type selects the `defaultLayouts` entry, and a layout\n * switch reports the new type together with that entry's values. Diffing them\n * against the previous type's base would persist the difference between the\n * two entries as if the user had picked those values — leaves the layouts\n * already provide, which then linger as phantom modifications after switching\n * back.\n *\n * A persisted `type` the current layouts do not offer never applied (see\n * `getApplicablePersistedView`), so it is not carried over either: the\n * modifications returned replace it with whatever the user picked.\n *\n * @param newView The view the user produced.\n * @param layers The layers the view resolves from. See `ViewLayers`.\n * @return The modified properties, or `undefined` when the user modified none.\n */\nexport function getUserModifications(\n\tnewView: View,\n\tlayers: ViewLayers\n): ViewOverrides | undefined {\n\tconst { defaultLayouts, activeViewOverrides } = layers;\n\tconst persistedView = getApplicablePersistedView(\n\t\tlayers.persistedView,\n\t\tdefaultLayouts\n\t);\n\tconst baseView = resolveBaseView( layers, newView.type );\n\n\tconst modifications = diffLayer(\n\t\twithoutQueryParams( newView ),\n\t\twithoutQueryParams( baseView ),\n\t\twithoutQueryParams( persistedView )\n\t);\n\n\t// Locked filters are pinned on every read, so persisting them would only\n\t// leak them into the views that do not lock them.\n\tconst locked = getLockedFilters( activeViewOverrides );\n\tif ( locked.length > 0 && Array.isArray( modifications.filters ) ) {\n\t\tmodifications.filters = ( modifications.filters as Filter[] ).filter(\n\t\t\t( filter ) => ! locked.some( ( f ) => f.field === filter.field )\n\t\t);\n\t}\n\n\treturn Object.keys( modifications ).length > 0\n\t\t? ( modifications as ViewOverrides )\n\t\t: undefined;\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,eAAe,CAAE,QAAQ,QAAS;AAExC,SAAS,cAAe,OAAuC;CAC9D,OACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAE,MAAM,QAAS,KAAM;AAExE;;;;;;;AAQA,SAAS,mBAAoB,OAA8B;CAC1D,MAAM,SAAsB,cAAe,KAAM,IAA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,aAAc,CACnC;CAIA,MAAM,SAAS,iBAAkB,mBAAoB;CACrD,IAAK,OAAO,SAAS,KAAK,MAAM,QAAS,cAAc,OAAQ,GAC9D,cAAc,UAAY,cAAc,QAAsB,QAC3D,WAAY,CAAE,OAAO,MAAQ,MAAO,EAAE,UAAU,OAAO,KAAM,CAChE;CAGD,OAAO,OAAO,KAAM,aAAc,CAAC,CAAC,SAAS,IACxC,gBACF,KAAA;AACJ"}
@@ -1 +0,0 @@
1
- //# sourceMappingURL=types.mjs.map
@@ -1,28 +1,33 @@
1
- // packages/views/src/use-view-config.ts
2
1
  import { useSelect } from "@wordpress/data";
3
- import { store as coreStore } from "@wordpress/core-data";
2
+ import { store } from "@wordpress/core-data";
4
3
  import { unlock } from "./lock-unlock.mjs";
5
- function useViewConfig({
6
- kind,
7
- name,
8
- fields
9
- }) {
10
- const fieldList = Array.isArray(fields) ? fields : fields?.split(",");
11
- const fieldsKey = fieldList ? [...fieldList].sort().join(",") : void 0;
12
- return useSelect(
13
- (select) => {
14
- return unlock(select(coreStore)).getViewConfig(
15
- kind,
16
- name,
17
- fieldsKey ? {
18
- fields: fieldsKey
19
- } : void 0
20
- );
21
- },
22
- [kind, name, fieldsKey]
23
- );
4
+ // packages/views/src/use-view-config.ts
5
+ /**
6
+ * A hook that retrieves the view configuration for a given entity
7
+ * from the core data store.
8
+ *
9
+ * @param {Object} params
10
+ * @param {string} params.kind The kind of the entity.
11
+ * @param {string} params.name The name of the entity.
12
+ * @param {?(string|string[])} [params.fields] Subset of top-level config
13
+ * properties to request, as an array
14
+ * or a comma-separated string
15
+ * (mapped to the REST API `_fields`
16
+ * parameter). When omitted, the full
17
+ * config is requested.
18
+ * @return {Object} An object containing the `default_view`, `default_layouts`, `view_list`, and `form` configuration for the entity.
19
+ */
20
+ function useViewConfig({ kind, name, fields }) {
21
+ const fieldList = Array.isArray(fields) ? fields : fields?.split(",");
22
+ const fieldsKey = fieldList ? fieldList.toSorted().join(",") : void 0;
23
+ return useSelect((select) => {
24
+ return unlock(select(store)).getViewConfig(kind, name, fieldsKey ? { fields: fieldsKey } : void 0);
25
+ }, [
26
+ kind,
27
+ name,
28
+ fieldsKey
29
+ ]);
24
30
  }
25
- export {
26
- useViewConfig
27
- };
28
- //# sourceMappingURL=use-view-config.mjs.map
31
+ export { useViewConfig };
32
+
33
+ //# sourceMappingURL=use-view-config.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/use-view-config.ts"],
4
- "sourcesContent": ["import { useSelect } from '@wordpress/data';\nimport { store as coreStore } from '@wordpress/core-data';\nimport type { View, SupportedLayouts, Form } from '@wordpress/dataviews';\nimport { unlock } from './lock-unlock';\n\n/**\n * A hook that retrieves the view configuration for a given entity\n * from the core data store.\n *\n * @param {Object} params\n * @param {string} params.kind The kind of the entity.\n * @param {string} params.name The name of the entity.\n * @param {?(string|string[])} [params.fields] Subset of top-level config\n * properties to request, as an array\n * or a comma-separated string\n * (mapped to the REST API `_fields`\n * parameter). When omitted, the full\n * config is requested.\n * @return {Object} An object containing the `default_view`, `default_layouts`, `view_list`, and `form` configuration for the entity.\n */\nexport function useViewConfig( {\n\tkind,\n\tname,\n\tfields,\n}: {\n\tkind: string;\n\tname: string;\n\tfields?: string | string[];\n} ): {\n\tdefault_view: View | undefined;\n\tdefault_layouts: SupportedLayouts | undefined;\n\tview_list: Array< any > | undefined;\n\tform: Form | undefined;\n} {\n\t// Sort fields so the cache key is independent of the order callers list\n\t// them; `['title','author']` and `['author','title']` request the same data.\n\tconst fieldList = Array.isArray( fields ) ? fields : fields?.split( ',' );\n\tconst fieldsKey = fieldList\n\t\t? [ ...fieldList ].sort().join( ',' )\n\t\t: undefined;\n\treturn useSelect(\n\t\t( select ) => {\n\t\t\treturn unlock( select( coreStore ) ).getViewConfig(\n\t\t\t\tkind,\n\t\t\t\tname,\n\t\t\t\tfieldsKey\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tfields: fieldsKey,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\t\t);\n\t\t},\n\t\t[ kind, name, fieldsKey ]\n\t);\n}\n"],
5
- "mappings": ";AAAA,SAAS,iBAAiB;AAC1B,SAAS,SAAS,iBAAiB;AAEnC,SAAS,cAAc;AAiBhB,SAAS,cAAe;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACD,GASE;AAGD,QAAM,YAAY,MAAM,QAAS,MAAO,IAAI,SAAS,QAAQ,MAAO,GAAI;AACxE,QAAM,YAAY,YACf,CAAE,GAAG,SAAU,EAAE,KAAK,EAAE,KAAM,GAAI,IAClC;AACH,SAAO;AAAA,IACN,CAAE,WAAY;AACb,aAAO,OAAQ,OAAQ,SAAU,CAAE,EAAE;AAAA,QACpC;AAAA,QACA;AAAA,QACA,YACG;AAAA,UACA,QAAQ;AAAA,QACT,IACC;AAAA,MACJ;AAAA,IACD;AAAA,IACA,CAAE,MAAM,MAAM,SAAU;AAAA,EACzB;AACD;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"use-view-config.mjs","names":["coreStore"],"sources":["../src/use-view-config.ts"],"sourcesContent":["import { useSelect } from '@wordpress/data';\nimport { store as coreStore } from '@wordpress/core-data';\nimport type { View, SupportedLayouts, Form } from '@wordpress/dataviews';\nimport { unlock } from './lock-unlock';\n\n/**\n * A hook that retrieves the view configuration for a given entity\n * from the core data store.\n *\n * @param {Object} params\n * @param {string} params.kind The kind of the entity.\n * @param {string} params.name The name of the entity.\n * @param {?(string|string[])} [params.fields] Subset of top-level config\n * properties to request, as an array\n * or a comma-separated string\n * (mapped to the REST API `_fields`\n * parameter). When omitted, the full\n * config is requested.\n * @return {Object} An object containing the `default_view`, `default_layouts`, `view_list`, and `form` configuration for the entity.\n */\nexport function useViewConfig( {\n\tkind,\n\tname,\n\tfields,\n}: {\n\tkind: string;\n\tname: string;\n\tfields?: string | string[];\n} ): {\n\tdefault_view: View | undefined;\n\tdefault_layouts: SupportedLayouts | undefined;\n\tview_list: Array< any > | undefined;\n\tform: Form | undefined;\n} {\n\t// Sort fields so the cache key is independent of the order callers list\n\t// them; `['title','author']` and `['author','title']` request the same data.\n\tconst fieldList = Array.isArray( fields ) ? fields : fields?.split( ',' );\n\tconst fieldsKey = fieldList ? fieldList.toSorted().join( ',' ) : undefined;\n\treturn useSelect(\n\t\t( select ) => {\n\t\t\treturn unlock( select( coreStore ) ).getViewConfig(\n\t\t\t\tkind,\n\t\t\t\tname,\n\t\t\t\tfieldsKey\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tfields: fieldsKey,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\t\t);\n\t\t},\n\t\t[ kind, name, fieldsKey ]\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,cAAe,EAC9B,MACA,MACA,UAUC;CAGD,MAAM,YAAY,MAAM,QAAS,MAAO,IAAI,SAAS,QAAQ,MAAO,GAAI;CACxE,MAAM,YAAY,YAAY,UAAU,SAAS,CAAC,CAAC,KAAM,GAAI,IAAI,KAAA;CACjE,OAAO,WACJ,WAAY;EACb,OAAO,OAAQ,OAAQA,KAAU,CAAE,CAAC,CAAC,cACpC,MACA,MACA,YACG,EACA,QAAQ,UACT,IACC,KAAA,CACJ;CACD,GACA;EAAE;EAAM;EAAM;CAAU,CACzB;AACD"}
@@ -1,103 +1,82 @@
1
- // packages/views/src/use-view.ts
2
1
  import { dequal } from "dequal";
3
2
  import { useCallback, useMemo } from "@wordpress/element";
4
3
  import { useDispatch, useSelect } from "@wordpress/data";
5
- import { store as preferencesStore } from "@wordpress/preferences";
4
+ import { store } from "@wordpress/preferences";
6
5
  import { generatePreferenceKey } from "./preference-keys.mjs";
7
- import {
8
- getApplicablePersistedView,
9
- getUserModifications,
10
- resolveView
11
- } from "./resolve-view.mjs";
6
+ import { getApplicablePersistedView, getUserModifications, resolveView } from "./resolve-view.mjs";
7
+ // packages/views/src/use-view.ts
8
+ /**
9
+ * Hook for managing DataViews view state with local persistence.
10
+ *
11
+ * Only the properties the user actually modified are persisted: every other
12
+ * property keeps resolving out of the layers below, so a change to the default
13
+ * view, to the layout defaults or to the active view overrides keeps showing
14
+ * through.
15
+ *
16
+ * @param config Configuration object for loading the view.
17
+ *
18
+ * @return Object with current view, modification state, and update functions.
19
+ */
12
20
  function useView(config) {
13
- const {
14
- kind,
15
- name,
16
- slug,
17
- defaultView,
18
- defaultLayouts,
19
- activeViewOverrides,
20
- queryParams,
21
- onChangeQueryParams
22
- } = config;
23
- const preferenceKey = generatePreferenceKey(kind, name, slug);
24
- const persistedView = useSelect(
25
- (select) => {
26
- return select(preferencesStore).get(
27
- "core/views",
28
- preferenceKey
29
- );
30
- },
31
- [preferenceKey]
32
- );
33
- const { set } = useDispatch(preferencesStore);
34
- const page = Number(queryParams?.page ?? 1);
35
- const search = queryParams?.search ?? "";
36
- const view = useMemo(
37
- () => resolveView({
38
- defaultView,
39
- defaultLayouts,
40
- activeViewOverrides,
41
- persistedView,
42
- page,
43
- search
44
- }),
45
- [
46
- defaultView,
47
- defaultLayouts,
48
- activeViewOverrides,
49
- persistedView,
50
- page,
51
- search
52
- ]
53
- );
54
- const applicablePersistedView = getApplicablePersistedView(
55
- persistedView,
56
- defaultLayouts
57
- );
58
- const isModified = !!applicablePersistedView && Object.keys(applicablePersistedView).length > 0;
59
- const updateView = useCallback(
60
- (newView) => {
61
- const newQueryParams = {
62
- page: Number(newView?.page ?? 1),
63
- search: newView?.search ?? ""
64
- };
65
- if (onChangeQueryParams && !dequal(newQueryParams, { page, search })) {
66
- onChangeQueryParams(newQueryParams);
67
- }
68
- const modifications = getUserModifications(newView, {
69
- defaultView,
70
- defaultLayouts,
71
- activeViewOverrides,
72
- persistedView
73
- });
74
- if (!dequal(modifications, persistedView)) {
75
- set("core/views", preferenceKey, modifications);
76
- }
77
- },
78
- [
79
- onChangeQueryParams,
80
- page,
81
- search,
82
- defaultView,
83
- defaultLayouts,
84
- activeViewOverrides,
85
- persistedView,
86
- set,
87
- preferenceKey
88
- ]
89
- );
90
- const resetToDefault = useCallback(() => {
91
- set("core/views", preferenceKey, void 0);
92
- }, [preferenceKey, set]);
93
- return {
94
- view,
95
- isModified,
96
- updateView,
97
- resetToDefault
98
- };
21
+ const { kind, name, slug, defaultView, defaultLayouts, activeViewOverrides, queryParams, onChangeQueryParams } = config;
22
+ const preferenceKey = generatePreferenceKey(kind, name, slug);
23
+ const persistedView = useSelect((select) => {
24
+ return select(store).get("core/views", preferenceKey);
25
+ }, [preferenceKey]);
26
+ const { set } = useDispatch(store);
27
+ const page = Number(queryParams?.page ?? 1);
28
+ const search = queryParams?.search ?? "";
29
+ const view = useMemo(() => resolveView({
30
+ defaultView,
31
+ defaultLayouts,
32
+ activeViewOverrides,
33
+ persistedView,
34
+ page,
35
+ search
36
+ }), [
37
+ defaultView,
38
+ defaultLayouts,
39
+ activeViewOverrides,
40
+ persistedView,
41
+ page,
42
+ search
43
+ ]);
44
+ const applicablePersistedView = getApplicablePersistedView(persistedView, defaultLayouts);
45
+ return {
46
+ view,
47
+ isModified: !!applicablePersistedView && Object.keys(applicablePersistedView).length > 0,
48
+ updateView: useCallback((newView) => {
49
+ const newQueryParams = {
50
+ page: Number(newView?.page ?? 1),
51
+ search: newView?.search ?? ""
52
+ };
53
+ if (onChangeQueryParams && !dequal(newQueryParams, {
54
+ page,
55
+ search
56
+ })) onChangeQueryParams(newQueryParams);
57
+ const modifications = getUserModifications(newView, {
58
+ defaultView,
59
+ defaultLayouts,
60
+ activeViewOverrides,
61
+ persistedView
62
+ });
63
+ if (!dequal(modifications, persistedView)) set("core/views", preferenceKey, modifications);
64
+ }, [
65
+ onChangeQueryParams,
66
+ page,
67
+ search,
68
+ defaultView,
69
+ defaultLayouts,
70
+ activeViewOverrides,
71
+ persistedView,
72
+ set,
73
+ preferenceKey
74
+ ]),
75
+ resetToDefault: useCallback(() => {
76
+ set("core/views", preferenceKey, void 0);
77
+ }, [preferenceKey, set])
78
+ };
99
79
  }
100
- export {
101
- useView
102
- };
103
- //# sourceMappingURL=use-view.mjs.map
80
+ export { useView };
81
+
82
+ //# sourceMappingURL=use-view.mjs.map