@jsenv/navi 0.10.2 → 0.11.1

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 (207) hide show
  1. package/dist/jsenv_navi.js +13838 -23291
  2. package/dist/jsenv_navi.js.map +1281 -0
  3. package/package.json +6 -8
  4. package/index.js +0 -122
  5. package/src/action_private_properties.js +0 -11
  6. package/src/action_proxy_test.html +0 -353
  7. package/src/action_run_states.js +0 -5
  8. package/src/actions.js +0 -1401
  9. package/src/browser_integration/browser_integration.js +0 -216
  10. package/src/browser_integration/document_back_and_forward.js +0 -17
  11. package/src/browser_integration/document_loading_signal.js +0 -100
  12. package/src/browser_integration/document_state_signal.js +0 -9
  13. package/src/browser_integration/document_url_signal.js +0 -9
  14. package/src/browser_integration/use_is_visited.js +0 -19
  15. package/src/browser_integration/via_history.js +0 -232
  16. package/src/browser_integration/via_navigation.js +0 -168
  17. package/src/components/action_execution/form_context.js +0 -5
  18. package/src/components/action_execution/render_actionable_component.jsx +0 -29
  19. package/src/components/action_execution/use_action.js +0 -99
  20. package/src/components/action_execution/use_execute_action.js +0 -193
  21. package/src/components/action_execution/use_run_on_mount.js +0 -9
  22. package/src/components/action_renderer.jsx +0 -125
  23. package/src/components/callout/callout.js +0 -990
  24. package/src/components/callout/callout_demo.html +0 -201
  25. package/src/components/callout/test_dynamic_positioning.html +0 -161
  26. package/src/components/callout/test_html_document_iframe.html +0 -182
  27. package/src/components/demos/0_button_demo.html +0 -707
  28. package/src/components/demos/10_column_reordering_debug.html +0 -277
  29. package/src/components/demos/11_table_selection_debug.html +0 -432
  30. package/src/components/demos/1_checkbox_demo.html +0 -754
  31. package/src/components/demos/2_input_textual_demo.html +0 -286
  32. package/src/components/demos/3_radio_demo.html +0 -874
  33. package/src/components/demos/4_select_demo.html +0 -100
  34. package/src/components/demos/5_list_scrollable_demo.html +0 -153
  35. package/src/components/demos/6_tablist_demo.html +0 -77
  36. package/src/components/demos/7_table_selection_demo.html +0 -176
  37. package/src/components/demos/8_table_fixed_headers_demo.html +0 -584
  38. package/src/components/demos/9_table_column_drag_demo.html +0 -325
  39. package/src/components/demos/action/0_button_demo.html +0 -204
  40. package/src/components/demos/action/10_shortcuts_demo.html +0 -189
  41. package/src/components/demos/action/11_nested_shortcuts_demo.xhtml +0 -401
  42. package/src/components/demos/action/1_input_text_demo.html +0 -876
  43. package/src/components/demos/action/2_form_multiple.html +0 -303
  44. package/src/components/demos/action/3_details_demo.html +0 -203
  45. package/src/components/demos/action/4_input_checkbox_demo.html +0 -731
  46. package/src/components/demos/action/5_input_checkbox_state_demo.html +0 -270
  47. package/src/components/demos/action/6_checkbox_list_demo.html +0 -341
  48. package/src/components/demos/action/7_radio_list_demo.html +0 -357
  49. package/src/components/demos/action/8_editable_demo.html +0 -431
  50. package/src/components/demos/action/9_link_demo.html +0 -194
  51. package/src/components/demos/demo.md +0 -0
  52. package/src/components/demos/route/basic/basic.html +0 -14
  53. package/src/components/demos/route/basic/basic_route_demo.jsx +0 -224
  54. package/src/components/demos/route/multi/multi.html +0 -14
  55. package/src/components/demos/route/multi/multi_route_demo.jsx +0 -277
  56. package/src/components/demos/ui_transition/0_action_renderer_ui_transition_demo.html +0 -695
  57. package/src/components/demos/ui_transition/1_nested_ui_transition_demo.html +0 -429
  58. package/src/components/demos/ui_transition/2_height_transition_test.html +0 -295
  59. package/src/components/details/details.jsx +0 -245
  60. package/src/components/details/summary_marker.jsx +0 -141
  61. package/src/components/edition/editable.jsx +0 -186
  62. package/src/components/error_boundary_context.js +0 -9
  63. package/src/components/field/README.md +0 -247
  64. package/src/components/field/button.jsx +0 -429
  65. package/src/components/field/checkbox_list.jsx +0 -185
  66. package/src/components/field/collect_form_element_values.js +0 -82
  67. package/src/components/field/custom_field.js +0 -106
  68. package/src/components/field/form.jsx +0 -209
  69. package/src/components/field/input.jsx +0 -16
  70. package/src/components/field/input_checkbox.jsx +0 -434
  71. package/src/components/field/input_radio.jsx +0 -432
  72. package/src/components/field/input_textual.jsx +0 -389
  73. package/src/components/field/label.jsx +0 -46
  74. package/src/components/field/radio_list.jsx +0 -183
  75. package/src/components/field/select.jsx +0 -256
  76. package/src/components/field/use_action_events.js +0 -132
  77. package/src/components/field/use_form_events.js +0 -59
  78. package/src/components/field/use_ui_state_controller.js +0 -506
  79. package/src/components/item_tracker/README.md +0 -461
  80. package/src/components/item_tracker/use_isolated_item_tracker.jsx +0 -209
  81. package/src/components/item_tracker/use_isolated_item_tracker_demo.html +0 -148
  82. package/src/components/item_tracker/use_isolated_item_tracker_demo.jsx +0 -460
  83. package/src/components/item_tracker/use_item_tracker.jsx +0 -143
  84. package/src/components/item_tracker/use_item_tracker_demo.html +0 -207
  85. package/src/components/item_tracker/use_item_tracker_demo.jsx +0 -216
  86. package/src/components/keyboard_shortcuts/active_keyboard_shortcuts.jsx +0 -87
  87. package/src/components/keyboard_shortcuts/aria_key_shortcuts.js +0 -61
  88. package/src/components/keyboard_shortcuts/keyboard_key_meta.js +0 -17
  89. package/src/components/keyboard_shortcuts/keyboard_shortcuts.js +0 -371
  90. package/src/components/keyboard_shortcuts/os.js +0 -9
  91. package/src/components/layout/demos/demo_flex.html +0 -638
  92. package/src/components/layout/demos/demo_layout_style_buttons.html +0 -351
  93. package/src/components/layout/demos/demo_layout_style_input.html +0 -226
  94. package/src/components/layout/demos/demo_layout_style_text.html +0 -514
  95. package/src/components/layout/flex.jsx +0 -109
  96. package/src/components/layout/layout_context.jsx +0 -3
  97. package/src/components/layout/spacing.jsx +0 -20
  98. package/src/components/layout/use_layout_style.js +0 -249
  99. package/src/components/link/link.jsx +0 -267
  100. package/src/components/link/link_with_icon.jsx +0 -52
  101. package/src/components/loader/loader_background.jsx +0 -372
  102. package/src/components/loader/loading_spinner.jsx +0 -68
  103. package/src/components/loader/network_speed.js +0 -83
  104. package/src/components/loader/rectangle_loading.jsx +0 -244
  105. package/src/components/props_composition/demos/demo_with_props_style.html +0 -81
  106. package/src/components/props_composition/with_props_class_name.js +0 -37
  107. package/src/components/props_composition/with_props_style.js +0 -26
  108. package/src/components/route.jsx +0 -19
  109. package/src/components/selection/selection.jsx +0 -1583
  110. package/src/components/svg/font_sized_svg.jsx +0 -59
  111. package/src/components/svg/icon_and_text.jsx +0 -21
  112. package/src/components/svg/svg_mask_overlay.jsx +0 -105
  113. package/src/components/table/drag/table_drag.jsx +0 -506
  114. package/src/components/table/resize/table_resize.jsx +0 -650
  115. package/src/components/table/resize/table_size.js +0 -43
  116. package/src/components/table/selection/table_selection.js +0 -106
  117. package/src/components/table/selection/table_selection.jsx +0 -203
  118. package/src/components/table/sticky/sticky_group.js +0 -354
  119. package/src/components/table/sticky/table_sticky.js +0 -25
  120. package/src/components/table/sticky/table_sticky.jsx +0 -501
  121. package/src/components/table/table.jsx +0 -721
  122. package/src/components/table/table_css.js +0 -211
  123. package/src/components/table/table_ui.jsx +0 -49
  124. package/src/components/table/use_cells_and_columns.js +0 -90
  125. package/src/components/table/use_object_array_to_cells.js +0 -46
  126. package/src/components/table/z_indexes.js +0 -23
  127. package/src/components/tablist/tablist.jsx +0 -99
  128. package/src/components/text/demos/demo_text_and_icon.html +0 -421
  129. package/src/components/text/overflow.jsx +0 -15
  130. package/src/components/text/text.jsx +0 -83
  131. package/src/components/text/text_and_count.jsx +0 -28
  132. package/src/components/ui_transition.jsx +0 -128
  133. package/src/components/use_auto_focus.js +0 -94
  134. package/src/components/use_batch_during_render.js +0 -33
  135. package/src/components/use_debounce_true.js +0 -31
  136. package/src/components/use_dependencies_diff.js +0 -35
  137. package/src/components/use_focus_group.js +0 -20
  138. package/src/components/use_initial_value.js +0 -78
  139. package/src/components/use_is_visited.js +0 -19
  140. package/src/components/use_ref_array.js +0 -38
  141. package/src/components/use_signal_sync.js +0 -50
  142. package/src/components/use_stable_callback.js +0 -68
  143. package/src/components/use_state_array.js +0 -47
  144. package/src/docs/actions.md +0 -250
  145. package/src/docs/demos/resource/action_status.jsx +0 -42
  146. package/src/docs/demos/resource/demo.md +0 -1
  147. package/src/docs/demos/resource/resource_demo_0.html +0 -84
  148. package/src/docs/demos/resource/resource_demo_10_post_gc.html +0 -364
  149. package/src/docs/demos/resource/resource_demo_11_describe_many.html +0 -362
  150. package/src/docs/demos/resource/resource_demo_2.html +0 -173
  151. package/src/docs/demos/resource/resource_demo_3_filtered_users.html +0 -415
  152. package/src/docs/demos/resource/resource_demo_4_details.html +0 -284
  153. package/src/docs/demos/resource/resource_demo_5_renderer_lazy.html +0 -115
  154. package/src/docs/demos/resource/resource_demo_6_gc.html +0 -217
  155. package/src/docs/demos/resource/resource_demo_7_child_gc.html +0 -240
  156. package/src/docs/demos/resource/resource_demo_8_proxy_gc.html +0 -319
  157. package/src/docs/demos/resource/resource_demo_9_describe_one.html +0 -472
  158. package/src/docs/demos/resource/tata.jsx +0 -3
  159. package/src/docs/demos/resource/toto.jsx +0 -3
  160. package/src/docs/demos/user_nav/user_nav.html +0 -12
  161. package/src/docs/demos/user_nav/user_nav.jsx +0 -330
  162. package/src/docs/resource_dependencies.md +0 -103
  163. package/src/docs/resource_with_params.md +0 -80
  164. package/src/navi_css_vars.js +0 -14
  165. package/src/notes.md +0 -34
  166. package/src/route/route.js +0 -596
  167. package/src/route/route.xtest.html +0 -228
  168. package/src/store/array_signal_store.js +0 -537
  169. package/src/store/local_storage_signal.js +0 -17
  170. package/src/store/resource_graph.js +0 -1304
  171. package/src/store/tests/resource_graph_autoreload_demo.html +0 -12
  172. package/src/store/tests/resource_graph_autoreload_demo.jsx +0 -964
  173. package/src/store/tests/resource_graph_dependencies.test_manual.js +0 -95
  174. package/src/store/value_in_local_storage.js +0 -187
  175. package/src/symbol_object_signal.js +0 -1
  176. package/src/use_action_data.js +0 -10
  177. package/src/use_action_status.js +0 -47
  178. package/src/utils/add_many_event_listeners.js +0 -15
  179. package/src/utils/array_add_remove.js +0 -61
  180. package/src/utils/array_signal.js +0 -15
  181. package/src/utils/compare_two_js_values.js +0 -172
  182. package/src/utils/execute_with_cleanup.js +0 -21
  183. package/src/utils/get_caller_info.js +0 -85
  184. package/src/utils/is_signal.js +0 -20
  185. package/src/utils/js_value_weak_map.js +0 -162
  186. package/src/utils/js_value_weak_map_demo.html +0 -690
  187. package/src/utils/merge_two_js_values.js +0 -53
  188. package/src/utils/stringify_for_display.js +0 -131
  189. package/src/utils/weak_effect.js +0 -48
  190. package/src/validation/constraints/confirm_constraint.js +0 -14
  191. package/src/validation/constraints/create_unique_value_constraint.js +0 -27
  192. package/src/validation/constraints/native_constraints.js +0 -338
  193. package/src/validation/constraints/readonly_constraint.js +0 -41
  194. package/src/validation/constraints/same_as_constraint.js +0 -42
  195. package/src/validation/constraints/single_space_constraint.js +0 -13
  196. package/src/validation/custom_constraint_validation.js +0 -793
  197. package/src/validation/custom_message.js +0 -18
  198. package/src/validation/demos/browser_style.png +0 -0
  199. package/src/validation/demos/demo_same_as_constraint.html +0 -259
  200. package/src/validation/demos/form_validation_demo.html +0 -142
  201. package/src/validation/demos/form_validation_demo_preact.html +0 -87
  202. package/src/validation/demos/form_validation_native_popover_demo.html +0 -168
  203. package/src/validation/demos/form_validation_vs_native_demo.html +0 -172
  204. package/src/validation/hooks/use_constraints.js +0 -23
  205. package/src/validation/hooks/use_custom_validation_ref.js +0 -73
  206. package/src/validation/hooks/use_validation_message.js +0 -19
  207. package/src/validation/input_change_effect.js +0 -106
@@ -1,1304 +0,0 @@
1
- import { createIterableWeakSet } from "@jsenv/dom";
2
- import { computed, signal } from "@preact/signals";
3
-
4
- import { getActionPrivateProperties } from "../action_private_properties.js";
5
- import { createAction, getActionDispatcher } from "../actions.js";
6
- import { SYMBOL_OBJECT_SIGNAL } from "../symbol_object_signal.js";
7
- import {
8
- SYMBOL_IDENTITY,
9
- compareTwoJsValues,
10
- } from "../utils/compare_two_js_values.js";
11
- import { getCallerInfo } from "../utils/get_caller_info.js";
12
- import { arraySignalStore, primitiveCanBeId } from "./array_signal_store.js";
13
-
14
- let DEBUG = false;
15
-
16
- // Resource Lifecycle Manager
17
- // This handles ALL resource lifecycle logic (rerun/reset) across all resources
18
- const createResourceLifecycleManager = () => {
19
- const registeredResources = new Map(); // Map<resourceInstance, lifecycleConfig>
20
- const resourceDependencies = new Map(); // Map<resourceInstance, Set<dependentResources>>
21
-
22
- const registerResource = (resourceInstance, config) => {
23
- const {
24
- rerunOn,
25
- paramScope = null,
26
- dependencies = [],
27
- mutableIdKeys = [],
28
- } = config;
29
-
30
- registeredResources.set(resourceInstance, {
31
- rerunOn,
32
- paramScope,
33
- mutableIdKeys,
34
- httpActions: new Set(),
35
- });
36
-
37
- // Register dependencies
38
- if (dependencies.length > 0) {
39
- for (const dependency of dependencies) {
40
- if (!resourceDependencies.has(dependency)) {
41
- resourceDependencies.set(dependency, new Set());
42
- }
43
- resourceDependencies.get(dependency).add(resourceInstance);
44
- }
45
- }
46
- };
47
-
48
- const registerAction = (resourceInstance, httpAction) => {
49
- const config = registeredResources.get(resourceInstance);
50
- if (config) {
51
- config.httpActions.add(httpAction);
52
- }
53
- };
54
-
55
- const shouldRerunAfter = (rerunConfig, httpVerb) => {
56
- if (rerunConfig === false) return false;
57
- if (rerunConfig === "*") return true;
58
- if (Array.isArray(rerunConfig)) {
59
- const verbSet = new Set(rerunConfig.map((v) => v.toUpperCase()));
60
- if (verbSet.has("*")) return true;
61
- return verbSet.has(httpVerb.toUpperCase());
62
- }
63
- return false;
64
- };
65
-
66
- const isParamSubset = (parentParams, childParams) => {
67
- if (!parentParams || !childParams) return false;
68
- for (const [key, value] of Object.entries(parentParams)) {
69
- if (
70
- !(key in childParams) ||
71
- !compareTwoJsValues(childParams[key], value)
72
- ) {
73
- return false;
74
- }
75
- }
76
- return true;
77
- };
78
-
79
- const findEffectOnActions = (triggeringAction) => {
80
- // Determines which actions to rerun/reset when an action completes.
81
-
82
- const actionsToRerun = new Set();
83
- const actionsToReset = new Set();
84
- const reasonSet = new Set();
85
-
86
- for (const [resourceInstance, config] of registeredResources) {
87
- const shouldRerunGetMany = shouldRerunAfter(
88
- config.rerunOn.GET_MANY,
89
- triggeringAction.meta.httpVerb,
90
- );
91
- const shouldRerunGet = shouldRerunAfter(
92
- config.rerunOn.GET,
93
- triggeringAction.meta.httpVerb,
94
- );
95
-
96
- // Skip if no rerun or reset rules apply
97
- const hasMutableIdAutorerun =
98
- (triggeringAction.meta.httpVerb === "POST" ||
99
- triggeringAction.meta.httpVerb === "PUT" ||
100
- triggeringAction.meta.httpVerb === "PATCH") &&
101
- config.mutableIdKeys.length > 0;
102
-
103
- if (
104
- !shouldRerunGetMany &&
105
- !shouldRerunGet &&
106
- triggeringAction.meta.httpVerb !== "DELETE" &&
107
- !hasMutableIdAutorerun
108
- ) {
109
- continue;
110
- }
111
-
112
- // Parameter scope predicate for config-driven rules
113
- // Same scope ID or no scope = compatible, subset check for different scopes
114
- const paramScopePredicate = config.paramScope
115
- ? (candidateAction) => {
116
- if (candidateAction.meta.paramScope?.id === config.paramScope.id)
117
- return true;
118
- if (!candidateAction.meta.paramScope) return true;
119
- const candidateParams = candidateAction.meta.paramScope.params;
120
- const currentParams = config.paramScope.params;
121
- return isParamSubset(candidateParams, currentParams);
122
- }
123
- : (candidateAction) => !candidateAction.meta.paramScope;
124
-
125
- for (const httpAction of config.httpActions) {
126
- // Find all instances of this action
127
- const actionCandidateArray = httpAction.matchAllSelfOrDescendant(
128
- (action) =>
129
- !action.isPrerun && action.completed && action !== triggeringAction,
130
- );
131
-
132
- for (const actionCandidate of actionCandidateArray) {
133
- const triggerVerb = triggeringAction.meta.httpVerb;
134
- const candidateVerb = actionCandidate.meta.httpVerb;
135
- const candidateIsPlural = actionCandidate.meta.httpMany;
136
- if (triggerVerb === candidateVerb) {
137
- continue;
138
- }
139
-
140
- const triggeringResource = getResourceForAction(triggeringAction);
141
- const isSameResource = triggeringResource === resourceInstance;
142
-
143
- // Config-driven same-resource effects (respects param scope)
144
- config_effect: {
145
- if (
146
- !isSameResource ||
147
- triggerVerb === "GET" ||
148
- candidateVerb !== "GET"
149
- ) {
150
- break config_effect;
151
- }
152
- const shouldRerun = candidateIsPlural
153
- ? shouldRerunGetMany
154
- : shouldRerunGet;
155
- if (!shouldRerun) {
156
- break config_effect;
157
- }
158
- if (!paramScopePredicate(actionCandidate)) {
159
- break config_effect;
160
- }
161
- actionsToRerun.add(actionCandidate);
162
- reasonSet.add("same-resource autorerun");
163
- continue;
164
- }
165
-
166
- // DELETE effects on same resource (ignores param scope)
167
- delete_effect: {
168
- if (!isSameResource || triggerVerb !== "DELETE") {
169
- break delete_effect;
170
- }
171
- if (candidateIsPlural) {
172
- if (!shouldRerunGetMany) {
173
- break delete_effect;
174
- }
175
- actionsToRerun.add(actionCandidate);
176
- reasonSet.add("same-resource DELETE rerun GET_MANY");
177
- continue;
178
- }
179
- // Get the ID(s) that were deleted
180
- const { dataSignal } = getActionPrivateProperties(triggeringAction);
181
- const deleteIdSet = triggeringAction.meta.httpMany
182
- ? new Set(dataSignal.peek())
183
- : new Set([dataSignal.peek()]);
184
-
185
- const candidateId = actionCandidate.data;
186
- const isAffected = deleteIdSet.has(candidateId);
187
- if (!isAffected) {
188
- break delete_effect;
189
- }
190
- if (candidateVerb === "GET" && shouldRerunGet) {
191
- actionsToRerun.add(actionCandidate);
192
- reasonSet.add("same-resource DELETE rerun GET");
193
- continue;
194
- }
195
- actionsToReset.add(actionCandidate);
196
- reasonSet.add("same-resource DELETE reset");
197
- continue;
198
- }
199
-
200
- // MutableId effects: rerun GET when matching resource created/updated
201
- mutable_id_effect: {
202
- if (
203
- hasMutableIdAutorerun &&
204
- candidateVerb === "GET" &&
205
- !candidateIsPlural &&
206
- isSameResource
207
- ) {
208
- const { computedDataSignal } =
209
- getActionPrivateProperties(triggeringAction);
210
- const modifiedData = computedDataSignal.peek();
211
-
212
- if (modifiedData && typeof modifiedData === "object") {
213
- for (const mutableIdKey of config.mutableIdKeys) {
214
- const modifiedMutableId = modifiedData[mutableIdKey];
215
- const candidateParams = actionCandidate.params;
216
-
217
- if (
218
- modifiedMutableId !== undefined &&
219
- candidateParams &&
220
- typeof candidateParams === "object" &&
221
- candidateParams[mutableIdKey] === modifiedMutableId
222
- ) {
223
- actionsToRerun.add(actionCandidate);
224
- reasonSet.add(
225
- `${triggeringAction.meta.httpVerb}-mutableId autorerun`,
226
- );
227
- break;
228
- }
229
- }
230
- }
231
- }
232
- }
233
-
234
- // Cross-resource dependency effects: rerun dependent GET_MANY
235
- dependency_effect: {
236
- if (
237
- triggeringResource &&
238
- resourceDependencies
239
- .get(triggeringResource)
240
- ?.has(resourceInstance) &&
241
- triggerVerb !== "GET" &&
242
- candidateVerb === "GET" &&
243
- candidateIsPlural
244
- ) {
245
- actionsToRerun.add(actionCandidate);
246
- reasonSet.add("dependency autorerun");
247
- continue;
248
- }
249
- }
250
- }
251
- }
252
- }
253
-
254
- return {
255
- actionsToRerun,
256
- actionsToReset,
257
- reasons: Array.from(reasonSet),
258
- };
259
- };
260
-
261
- const onActionComplete = (httpAction) => {
262
- const { actionsToRerun, actionsToReset, reasons } =
263
- findEffectOnActions(httpAction);
264
-
265
- if (actionsToRerun.size > 0 || actionsToReset.size > 0) {
266
- const reason = `${httpAction} triggered ${reasons.join(" and ")}`;
267
- const dispatchActions = getActionDispatcher();
268
- dispatchActions({
269
- rerunSet: actionsToRerun,
270
- resetSet: actionsToReset,
271
- reason,
272
- });
273
- }
274
- };
275
-
276
- // Helper to find which resource an action belongs to
277
- const getResourceForAction = (action) => {
278
- return action.meta.resourceInstance;
279
- };
280
-
281
- return {
282
- registerResource,
283
- registerAction,
284
- onActionComplete,
285
- };
286
- };
287
-
288
- // Global resource lifecycle manager instance
289
- const resourceLifecycleManager = createResourceLifecycleManager();
290
-
291
- // Cache for parameter scope identifiers
292
- const paramScopeWeakSet = createIterableWeakSet();
293
- let paramScopeIdCounter = 0;
294
- const getParamScope = (params) => {
295
- for (const existingParamScope of paramScopeWeakSet) {
296
- if (compareTwoJsValues(existingParamScope.params, params)) {
297
- return existingParamScope;
298
- }
299
- }
300
- const id = Symbol(`paramScope-${++paramScopeIdCounter}`);
301
- const newParamScope = {
302
- params,
303
- id,
304
- };
305
- paramScopeWeakSet.add(newParamScope);
306
- return newParamScope;
307
- };
308
-
309
- const createHttpHandlerForRootResource = (
310
- name,
311
- {
312
- idKey,
313
- store,
314
- /*
315
- Default autorerun behavior explanation:
316
-
317
- GET: false (RECOMMENDED)
318
- What happens:
319
- - GET actions are reset by DELETE operations (not rerun)
320
- - DELETE operation on the displayed item would display nothing in the UI (action is in IDLE state)
321
- - PUT/PATCH operations update UI via signals, no rerun needed
322
- - This approach minimizes unnecessary API calls
323
-
324
- How to handle:
325
- - Applications can provide custom UI for deleted items (e.g., "Item not found")
326
- - Or redirect users to appropriate pages (e.g., back to list view)
327
-
328
- Alternative (NOT RECOMMENDED):
329
- - Use GET: ["DELETE"] to rerun and display 404 error received from backend
330
- - Poor UX: users expect immediate feedback, not loading + error state
331
-
332
- GET_MANY: ["POST"]
333
- - POST: New items may or may not appear in lists (depends on filters, pagination, etc.)
334
- Backend determines visibility better than client-side logic
335
- - DELETE: Excluded by default because:
336
- • UI handles deletions via store signals (selectAll filters out deleted items)
337
- • DELETE operations rarely change list content beyond item removal
338
- • Avoids unnecessary API calls (can be overridden if needed)
339
- */
340
- rerunOn = {
341
- GET: false,
342
- GET_MANY: [
343
- "POST",
344
- // "DELETE"
345
- ],
346
- },
347
- paramScope,
348
- dependencies = [],
349
- resourceInstance,
350
- mutableIdKeys = [],
351
- },
352
- ) => {
353
- // Register this resource with the resource lifecycle manager
354
- resourceLifecycleManager.registerResource(resourceInstance, {
355
- rerunOn,
356
- paramScope,
357
- dependencies,
358
- idKey,
359
- mutableIdKeys,
360
- });
361
-
362
- const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
363
- const applyDataEffect =
364
- httpVerb === "DELETE"
365
- ? (itemIdOrItemProps) => {
366
- const itemId = store.drop(itemIdOrItemProps);
367
- return itemId;
368
- }
369
- : (data) => {
370
- let item;
371
- if (Array.isArray(data)) {
372
- // the callback is returning something like [property, value, props]
373
- // this is to support a case like:
374
- // store.upsert("name", "currentName", { name: "newName" })
375
- // where we want to update the name property of an existing item
376
- item = store.upsert(...data);
377
- } else {
378
- item = store.upsert(data);
379
- }
380
- const itemId = item[idKey];
381
- return itemId;
382
- };
383
-
384
- const callerInfo = getCallerInfo(null, 2);
385
- // Provide more fallback options for better debugging
386
- const locationInfo =
387
- callerInfo.file && callerInfo.line && callerInfo.column
388
- ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
389
- : callerInfo.raw || "unknown location";
390
- const originalActionName = `${name}.${httpVerb}`;
391
- const httpActionAffectingOneItem = createAction(callback, {
392
- meta: { httpVerb, httpMany: false, paramScope, resourceInstance, store },
393
- name: `${name}.${httpVerb}`,
394
- dataEffect: (data, action) => {
395
- const actionLabel = action.name;
396
-
397
- if (httpVerb === "DELETE") {
398
- if (!isProps(data) && !primitiveCanBeId(data)) {
399
- throw new TypeError(
400
- `${actionLabel} must return an object (that will be used to drop "${name}" resource), received ${data}.
401
- ${originalActionName} source location: ${locationInfo}`,
402
- );
403
- }
404
- return applyDataEffect(data);
405
- }
406
- if (!isProps(data)) {
407
- throw new TypeError(
408
- `${actionLabel} must return an object (that will be used to upsert "${name}" resource), received ${data}.
409
- ${originalActionName} source location: ${locationInfo}`,
410
- );
411
- }
412
- return applyDataEffect(data);
413
- },
414
- compute: (itemId) => store.select(itemId),
415
- completeSideEffect: (actionCompleted) =>
416
- resourceLifecycleManager.onActionComplete(actionCompleted),
417
- ...options,
418
- });
419
- resourceLifecycleManager.registerAction(
420
- resourceInstance,
421
- httpActionAffectingOneItem,
422
- );
423
- return httpActionAffectingOneItem;
424
- };
425
- const GET = (callback, options) =>
426
- createActionAffectingOneItem("GET", {
427
- callback,
428
- applyDataEffect: (data) => {
429
- const item = store.upsert(data);
430
- const itemId = item[idKey];
431
- return itemId;
432
- },
433
- compute: (itemId) => store.select(itemId),
434
- ...options,
435
- });
436
- const POST = (callback, options) =>
437
- createActionAffectingOneItem("POST", {
438
- callback,
439
- applyDataEffect: (data) => {
440
- const item = store.upsert(data);
441
- const itemId = item[idKey];
442
- return itemId;
443
- },
444
- compute: (itemId) => store.select(itemId),
445
- ...options,
446
- });
447
- const PUT = (callback, options) =>
448
- createActionAffectingOneItem("PUT", {
449
- callback,
450
- ...options,
451
- });
452
- const PATCH = (callback, options) =>
453
- createActionAffectingOneItem("PATCH", {
454
- callback,
455
- ...options,
456
- });
457
- const DELETE = (callback, options) =>
458
- createActionAffectingOneItem("DELETE", {
459
- callback,
460
- ...options,
461
- });
462
-
463
- const createActionAffectingManyItems = (
464
- httpVerb,
465
- { callback, ...options },
466
- ) => {
467
- const applyDataEffect =
468
- httpVerb === "DELETE"
469
- ? (idOrMutableIdArray) => {
470
- const idArray = store.drop(idOrMutableIdArray);
471
- return idArray;
472
- }
473
- : (dataArray) => {
474
- const itemArray = store.upsert(dataArray);
475
- const idArray = itemArray.map((item) => item[idKey]);
476
- return idArray;
477
- };
478
-
479
- const httpActionAffectingManyItems = createAction(callback, {
480
- meta: { httpVerb, httpMany: true, paramScope, resourceInstance, store },
481
- name: `${name}.${httpVerb}_MANY`,
482
- data: [],
483
- dataEffect: applyDataEffect,
484
- compute: (idArray) => store.selectAll(idArray),
485
- completeSideEffect: (actionCompleted) =>
486
- resourceLifecycleManager.onActionComplete(actionCompleted),
487
- ...options,
488
- });
489
- resourceLifecycleManager.registerAction(
490
- resourceInstance,
491
- httpActionAffectingManyItems,
492
- );
493
- return httpActionAffectingManyItems;
494
- };
495
- const GET_MANY = (callback, options) =>
496
- createActionAffectingManyItems("GET", { callback, ...options });
497
- const POST_MANY = (callback, options) =>
498
- createActionAffectingManyItems("POST", { callback, ...options });
499
- const PUT_MANY = (callback, options) =>
500
- createActionAffectingManyItems("PUT", { callback, ...options });
501
- const PATCH_MANY = (callback, options) =>
502
- createActionAffectingManyItems("PATCH", { callback, ...options });
503
- const DELETE_MANY = (callback, options) =>
504
- createActionAffectingManyItems("DELETE", { callback, ...options });
505
-
506
- return {
507
- GET,
508
- POST,
509
- PUT,
510
- PATCH,
511
- DELETE,
512
- GET_MANY,
513
- POST_MANY,
514
- PUT_MANY,
515
- PATCH_MANY,
516
- DELETE_MANY,
517
- };
518
- };
519
- const createHttpHandlerForRelationshipToOneResource = (
520
- name,
521
- {
522
- idKey,
523
- store,
524
- propertyName,
525
- childIdKey,
526
- childStore,
527
- resourceInstance,
528
- resourceLifecycleManager,
529
- },
530
- ) => {
531
- const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
532
- const applyDataEffect =
533
- httpVerb === "DELETE"
534
- ? (itemId) => {
535
- const item = store.select(itemId);
536
- const childItemId = item[propertyName][childIdKey];
537
- store.upsert({
538
- [idKey]: itemId,
539
- [propertyName]: null,
540
- });
541
- return childItemId;
542
- }
543
- : // callback must return object with the following format:
544
- // {
545
- // [idKey]: 123,
546
- // [propertyName]: {
547
- // [childIdKey]: 456, ...childProps
548
- // }
549
- // }
550
- // the following could happen too if there is no relationship
551
- // {
552
- // [idKey]: 123,
553
- // [propertyName]: null
554
- // }
555
- (data) => {
556
- const item = store.upsert(data);
557
- const childItem = item[propertyName];
558
- const childItemId = childItem ? childItem[childIdKey] : undefined;
559
- return childItemId;
560
- };
561
-
562
- const callerInfo = getCallerInfo(null, 2);
563
- // Provide more fallback options for better debugging
564
- const locationInfo =
565
- callerInfo.file && callerInfo.line && callerInfo.column
566
- ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
567
- : callerInfo.raw || "unknown location";
568
- const originalActionName = `${name}.${httpVerb}`;
569
-
570
- const httpActionAffectingOneItem = createAction(callback, {
571
- meta: { httpVerb, httpMany: false, resourceInstance, store },
572
- name: `${name}.${httpVerb}`,
573
- dataEffect: (data, action) => {
574
- const actionLabel = action.name;
575
-
576
- if (httpVerb === "DELETE") {
577
- if (!isProps(data) && !primitiveCanBeId(data)) {
578
- throw new TypeError(
579
- `${actionLabel} must return an object (that will be used to drop "${name}" resource), received ${data}.
580
- ${originalActionName} source location: ${locationInfo}`,
581
- );
582
- }
583
- return applyDataEffect(data);
584
- }
585
- if (!isProps(data)) {
586
- throw new TypeError(
587
- `${actionLabel} must return an object (that will be used to upsert "${name}" resource), received ${data}.
588
- ${originalActionName} source location: ${locationInfo}`,
589
- );
590
- }
591
- return applyDataEffect(data);
592
- },
593
- compute: (childItemId) => childStore.select(childItemId),
594
- completeSideEffect: (actionCompleted) =>
595
- resourceLifecycleManager.onActionComplete(actionCompleted),
596
- ...options,
597
- });
598
- resourceLifecycleManager.registerAction(
599
- resourceInstance,
600
- httpActionAffectingOneItem,
601
- );
602
- return httpActionAffectingOneItem;
603
- };
604
-
605
- const GET = (callback, options) =>
606
- createActionAffectingOneItem("GET", {
607
- callback,
608
- ...options,
609
- });
610
- const PUT = (callback, options) =>
611
- createActionAffectingOneItem("PUT", {
612
- callback,
613
- ...options,
614
- });
615
- const DELETE = (callback, options) =>
616
- createActionAffectingOneItem("DELETE", {
617
- callback,
618
- ...options,
619
- });
620
-
621
- // il n'y a pas de many puisque on cible une seule resource
622
- // genre table.owner -> c'est un seul owner qu'on peut
623
- // GET -> recup les infos de l'objet
624
- // PUT -> mettre a jour l'owner de la table
625
- // DELETE -> supprimer l'owner de la table
626
-
627
- return { GET, PUT, DELETE };
628
- };
629
- const createHttpHandlerRelationshipToManyResource = (
630
- name,
631
- {
632
- idKey,
633
- store,
634
- propertyName,
635
- childIdKey,
636
- childStore,
637
- resourceInstance,
638
- resourceLifecycleManager,
639
- } = {},
640
- ) => {
641
- // idéalement s'il y a un GET sur le store originel on voudrait ptet le reload
642
- // parce que le store originel peut retourner cette liste ou etre impacté
643
- // pour l'instant on ignore
644
-
645
- // one item AND many child items
646
- const createActionAffectingOneItem = (httpVerb, { callback, ...options }) => {
647
- const applyDataEffect =
648
- httpVerb === "DELETE"
649
- ? ([itemId, childItemId]) => {
650
- const item = store.select(itemId);
651
- const childItemArray = item[propertyName];
652
- const childItemArrayWithoutThisOne = [];
653
- let found = false;
654
- for (const childItemCandidate of childItemArray) {
655
- const childItemCandidateId = childItemCandidate[childIdKey];
656
- if (childItemCandidateId === childItemId) {
657
- found = true;
658
- } else {
659
- childItemArrayWithoutThisOne.push(childItemCandidate);
660
- }
661
- }
662
- if (found) {
663
- store.upsert({
664
- [idKey]: itemId,
665
- [propertyName]: childItemArrayWithoutThisOne,
666
- });
667
- }
668
- return childItemId;
669
- }
670
- : (childData) => {
671
- const childItem = childStore.upsert(childData); // if the child item was used it will reload thanks to signals
672
- const childItemId = childItem[childIdKey];
673
- return childItemId;
674
- };
675
-
676
- const callerInfo = getCallerInfo(null, 2);
677
- // Provide more fallback options for better debugging
678
- const locationInfo =
679
- callerInfo.file && callerInfo.line && callerInfo.column
680
- ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
681
- : callerInfo.raw || "unknown location";
682
- const originalActionName = `${name}.${httpVerb}`;
683
-
684
- const httpActionAffectingOneItem = createAction(callback, {
685
- meta: { httpVerb, httpMany: false, resourceInstance, store: childStore },
686
- name: `${name}.${httpVerb}`,
687
- dataEffect: (data, action) => {
688
- const actionLabel = action.name;
689
-
690
- if (httpVerb === "DELETE") {
691
- // For DELETE in many relationship, we expect [itemId, childItemId] array
692
- if (!Array.isArray(data) || data.length !== 2) {
693
- throw new TypeError(
694
- `${actionLabel} must return an array [itemId, childItemId] (that will be used to remove relationship), received ${data}.
695
- ${originalActionName} source location: ${locationInfo}`,
696
- );
697
- }
698
- return applyDataEffect(data);
699
- }
700
- if (!isProps(data)) {
701
- throw new TypeError(
702
- `${actionLabel} must return an object (that will be used to upsert child item), received ${data}.
703
- ${originalActionName} source location: ${locationInfo}`,
704
- );
705
- }
706
- return applyDataEffect(data);
707
- },
708
- compute: (childItemId) => childStore.select(childItemId),
709
- completeSideEffect: (actionCompleted) =>
710
- resourceLifecycleManager.onActionComplete(actionCompleted),
711
- ...options,
712
- });
713
- resourceLifecycleManager.registerAction(
714
- resourceInstance,
715
- httpActionAffectingOneItem,
716
- );
717
- return httpActionAffectingOneItem;
718
- };
719
- const GET = (callback, options) =>
720
- createActionAffectingOneItem("GET", {
721
- callback,
722
- ...options,
723
- });
724
- // le souci que je vois ici c'est que je n'ai pas la moindre idée d'ou
725
- // inserer le childItem (ni meme s'il doit etre visible)
726
- // je pense que la bonne chose a faire est de reload
727
- // l'objet user.tables s'il en existe un
728
- // TODO: find any GET action on "user" and reload it
729
- const POST = (callback, options) =>
730
- createActionAffectingOneItem("POST", {
731
- callback,
732
- ...options,
733
- });
734
- const PUT = (callback, options) =>
735
- createActionAffectingOneItem("PUT", {
736
- callback,
737
- ...options,
738
- });
739
- const PATCH = (callback, options) =>
740
- createActionAffectingOneItem("PATCH", {
741
- callback,
742
- ...options,
743
- });
744
- const DELETE = (callback, options) =>
745
- createActionAffectingOneItem("DELETE", {
746
- callback,
747
- ...options,
748
- });
749
-
750
- const createActionAffectingManyItems = (
751
- httpVerb,
752
- { callback, ...options },
753
- ) => {
754
- const applyDataEffect =
755
- httpVerb === "GET"
756
- ? (data) => {
757
- // callback must return object with the following format:
758
- // {
759
- // [idKey]: 123,
760
- // [propertyName]: [
761
- // { [childIdKey]: 456, ...childProps },
762
- // { [childIdKey]: 789, ...childProps },
763
- // ...
764
- // ]
765
- // }
766
- // the array can be empty
767
- const item = store.upsert(data);
768
- const childItemArray = item[propertyName];
769
- const childItemIdArray = childItemArray.map(
770
- (childItem) => childItem[childIdKey],
771
- );
772
- return childItemIdArray;
773
- }
774
- : httpVerb === "DELETE"
775
- ? ([itemIdOrMutableId, childItemIdOrMutableIdArray]) => {
776
- const item = store.select(itemIdOrMutableId);
777
- const childItemArray = item[propertyName];
778
- const deletedChildItemIdArray = [];
779
- const childItemArrayWithoutThoose = [];
780
- let someFound = false;
781
- const deletedChildItemArray = childStore.select(
782
- childItemIdOrMutableIdArray,
783
- );
784
- for (const childItemCandidate of childItemArray) {
785
- if (deletedChildItemArray.includes(childItemCandidate)) {
786
- someFound = true;
787
- deletedChildItemIdArray.push(childItemCandidate[childIdKey]);
788
- } else {
789
- childItemArrayWithoutThoose.push(childItemCandidate);
790
- }
791
- }
792
- if (someFound) {
793
- store.upsert({
794
- [idKey]: item[idKey],
795
- [propertyName]: childItemArrayWithoutThoose,
796
- });
797
- }
798
- return deletedChildItemIdArray;
799
- }
800
- : (childDataArray) => {
801
- // hum ici aussi on voudra reload "user" pour POST
802
- // les autres les signals se charge de reload si visible
803
- const childItemArray = childStore.upsert(childDataArray);
804
- const childItemIdArray = childItemArray.map(
805
- (childItem) => childItem[childIdKey],
806
- );
807
- return childItemIdArray;
808
- };
809
-
810
- const callerInfo = getCallerInfo(null, 2);
811
- // Provide more fallback options for better debugging
812
- const locationInfo =
813
- callerInfo.file && callerInfo.line && callerInfo.column
814
- ? `${callerInfo.file}:${callerInfo.line}:${callerInfo.column}`
815
- : callerInfo.raw || "unknown location";
816
- const originalActionName = `${name}.${httpVerb}[many]`;
817
-
818
- const httpActionAffectingManyItem = createAction(callback, {
819
- meta: { httpVerb, httpMany: true, resourceInstance, store: childStore },
820
- name: `${name}.${httpVerb}[many]`,
821
- data: [],
822
- dataEffect: (data, action) => {
823
- const actionLabel = action.name;
824
-
825
- if (httpVerb === "GET") {
826
- if (!isProps(data)) {
827
- throw new TypeError(
828
- `${actionLabel} must return an object (that will be used to upsert "${name}" resource with many relationships), received ${data}.
829
- ${originalActionName} source location: ${locationInfo}`,
830
- );
831
- }
832
- return applyDataEffect(data);
833
- }
834
- if (httpVerb === "DELETE") {
835
- // For DELETE_MANY in many relationship, we expect [itemId, childItemIdArray] array
836
- if (
837
- !Array.isArray(data) ||
838
- data.length !== 2 ||
839
- !Array.isArray(data[1])
840
- ) {
841
- throw new TypeError(
842
- `${actionLabel} must return an array [itemId, childItemIdArray] (that will be used to remove relationships), received ${data}.
843
- ${originalActionName} source location: ${locationInfo}`,
844
- );
845
- }
846
- return applyDataEffect(data);
847
- }
848
- // For POST, PUT, PATCH - expect array of objects
849
- if (!Array.isArray(data)) {
850
- throw new TypeError(
851
- `${actionLabel} must return an array of objects (that will be used to upsert child items), received ${data}.
852
- ${originalActionName} source location: ${locationInfo}`,
853
- );
854
- }
855
- return applyDataEffect(data);
856
- },
857
- compute: (childItemIdArray) => childStore.selectAll(childItemIdArray),
858
- completeSideEffect: (actionCompleted) =>
859
- resourceLifecycleManager.onActionComplete(actionCompleted),
860
- ...options,
861
- });
862
- resourceLifecycleManager.registerAction(
863
- resourceInstance,
864
- httpActionAffectingManyItem,
865
- );
866
- return httpActionAffectingManyItem;
867
- };
868
-
869
- const GET_MANY = (callback, options) =>
870
- createActionAffectingManyItems("GET", { callback, ...options });
871
- const POST_MANY = (callback, options) =>
872
- createActionAffectingManyItems("POST", { callback, ...options });
873
- const PUT_MANY = (callback, options) =>
874
- createActionAffectingManyItems("PUT", { callback, ...options });
875
- const PATCH_MANY = (callback, options) =>
876
- createActionAffectingManyItems("PATCH", { callback, ...options });
877
- const DELETE_MANY = (callback, options) =>
878
- createActionAffectingManyItems("DELETE", { callback, ...options });
879
-
880
- return {
881
- GET,
882
- POST,
883
- PUT,
884
- PATCH,
885
- DELETE,
886
- GET_MANY,
887
- POST_MANY,
888
- PUT_MANY,
889
- PATCH_MANY,
890
- DELETE_MANY,
891
- };
892
- };
893
-
894
- export const resource = (
895
- name,
896
- { idKey, mutableIdKeys = [], rerunOn, httpHandler, ...rest } = {},
897
- ) => {
898
- if (idKey === undefined) {
899
- idKey = mutableIdKeys.length === 0 ? "id" : mutableIdKeys[0];
900
- }
901
- const resourceInstance = {
902
- isResource: true,
903
- name,
904
- idKey,
905
- httpActions: {},
906
- addItemSetup: undefined,
907
- httpHandler,
908
- };
909
- if (!httpHandler) {
910
- const setupCallbackSet = new Set();
911
- const addItemSetup = (callback) => {
912
- setupCallbackSet.add(callback);
913
- };
914
- resourceInstance.addItemSetup = addItemSetup;
915
-
916
- const itemPrototype = {
917
- [Symbol.toStringTag]: name,
918
- toString() {
919
- let string = `${name}`;
920
- if (mutableIdKeys.length) {
921
- for (const mutableIdKey of mutableIdKeys) {
922
- const mutableId = this[mutableIdKey];
923
- if (mutableId !== undefined) {
924
- string += `[${mutableIdKey}=${mutableId}]`;
925
- return string;
926
- }
927
- }
928
- }
929
- const id = this[idKey];
930
- if (id) {
931
- string += `[${idKey}=${id}]`;
932
- }
933
- return string;
934
- },
935
- };
936
-
937
- const store = arraySignalStore([], idKey, {
938
- mutableIdKeys,
939
- name: `${name} store`,
940
- createItem: (props) => {
941
- const item = Object.create(itemPrototype);
942
- Object.assign(item, props);
943
- Object.defineProperty(item, SYMBOL_IDENTITY, {
944
- value: item[idKey],
945
- writable: false,
946
- enumerable: false,
947
- configurable: false,
948
- });
949
- for (const setupCallback of setupCallbackSet) {
950
- setupCallback(item);
951
- }
952
- return item;
953
- },
954
- });
955
- const useArray = () => {
956
- return store.arraySignal.value;
957
- };
958
- const useById = (id) => {
959
- return store.select(idKey, id);
960
- };
961
-
962
- Object.assign(resourceInstance, {
963
- useArray,
964
- useById,
965
- store,
966
- });
967
-
968
- httpHandler = createHttpHandlerForRootResource(name, {
969
- idKey,
970
- store,
971
- rerunOn,
972
- resourceInstance,
973
- mutableIdKeys,
974
- });
975
- }
976
- resourceInstance.httpHandler = httpHandler;
977
-
978
- // Store the action callback definitions for withParams to use later
979
- resourceInstance.httpActions = rest;
980
-
981
- // Create HTTP actions
982
- for (const key of Object.keys(rest)) {
983
- const method = httpHandler[key];
984
- if (!method) {
985
- continue;
986
- }
987
- const action = method(rest[key]);
988
- resourceInstance[key] = action;
989
- }
990
-
991
- resourceInstance.one = (propertyName, childResource, options) => {
992
- const childIdKey = childResource.idKey;
993
- const childName = `${name}.${propertyName}`;
994
- resourceInstance.addItemSetup((item) => {
995
- const childItemIdSignal = signal();
996
- const updateChildItemId = (value) => {
997
- const currentChildItemId = childItemIdSignal.peek();
998
- if (isProps(value)) {
999
- const childItem = childResource.store.upsert(value);
1000
- const childItemId = childItem[childIdKey];
1001
- if (currentChildItemId === childItemId) {
1002
- return false;
1003
- }
1004
- childItemIdSignal.value = childItemId;
1005
- return true;
1006
- }
1007
- if (primitiveCanBeId(value)) {
1008
- const childItemProps = { [childIdKey]: value };
1009
- const childItem = childResource.store.upsert(childItemProps);
1010
- const childItemId = childItem[childIdKey];
1011
- if (currentChildItemId === childItemId) {
1012
- return false;
1013
- }
1014
- childItemIdSignal.value = childItemId;
1015
- return true;
1016
- }
1017
- if (currentChildItemId === undefined) {
1018
- return false;
1019
- }
1020
- childItemIdSignal.value = undefined;
1021
- return true;
1022
- };
1023
- updateChildItemId(item[propertyName]);
1024
-
1025
- const childItemSignal = computed(() => {
1026
- const childItemId = childItemIdSignal.value;
1027
- const childItem = childResource.store.select(childItemId);
1028
- return childItem;
1029
- });
1030
- const childItemFacadeSignal = computed(() => {
1031
- const childItem = childItemSignal.value;
1032
- if (childItem) {
1033
- const childItemCopy = Object.create(
1034
- Object.getPrototypeOf(childItem),
1035
- Object.getOwnPropertyDescriptors(childItem),
1036
- );
1037
- Object.defineProperty(childItemCopy, SYMBOL_OBJECT_SIGNAL, {
1038
- value: childItemSignal,
1039
- writable: false,
1040
- enumerable: false,
1041
- configurable: false,
1042
- });
1043
- return childItemCopy;
1044
- }
1045
- const nullItem = {
1046
- [SYMBOL_OBJECT_SIGNAL]: childItemSignal,
1047
- valueOf: () => null,
1048
- };
1049
- return nullItem;
1050
- });
1051
-
1052
- if (DEBUG) {
1053
- console.debug(
1054
- `setup ${item}.${propertyName} is one "${childResource.name}" (current value: ${childItemSignal.peek()})`,
1055
- );
1056
- }
1057
-
1058
- Object.defineProperty(item, propertyName, {
1059
- get: () => {
1060
- const childItemFacade = childItemFacadeSignal.value;
1061
- return childItemFacade;
1062
- },
1063
- set: (value) => {
1064
- if (!updateChildItemId(value)) {
1065
- return;
1066
- }
1067
- if (DEBUG) {
1068
- console.debug(
1069
- `${item}.${propertyName} updated to ${childItemSignal.peek()}`,
1070
- );
1071
- }
1072
- },
1073
- });
1074
- });
1075
- const httpHandlerForRelationshipToOneChild =
1076
- createHttpHandlerForRelationshipToOneResource(childName, {
1077
- idKey,
1078
- store: resourceInstance.store,
1079
- propertyName,
1080
- childIdKey,
1081
- childStore: childResource.store,
1082
- resourceInstance,
1083
- resourceLifecycleManager,
1084
- });
1085
- return resource(childName, {
1086
- idKey: childIdKey,
1087
- httpHandler: httpHandlerForRelationshipToOneChild,
1088
- ...options,
1089
- });
1090
- };
1091
- resourceInstance.many = (propertyName, childResource, options) => {
1092
- const childIdKey = childResource.idKey;
1093
- const childName = `${name}.${propertyName}`;
1094
- resourceInstance.addItemSetup((item) => {
1095
- const childItemIdArraySignal = signal([]);
1096
- const updateChildItemIdArray = (valueArray) => {
1097
- const currentIdArray = childItemIdArraySignal.peek();
1098
-
1099
- if (!Array.isArray(valueArray)) {
1100
- if (currentIdArray.length === 0) {
1101
- return;
1102
- }
1103
- childItemIdArraySignal.value = [];
1104
- return;
1105
- }
1106
-
1107
- let i = 0;
1108
- const idArray = [];
1109
- let modified = false;
1110
- while (i < valueArray.length) {
1111
- const value = valueArray[i];
1112
- const currentIdAtIndex = currentIdArray[idArray.length];
1113
- i++;
1114
- if (isProps(value)) {
1115
- const childItem = childResource.store.upsert(value);
1116
- const childItemId = childItem[childIdKey];
1117
- if (currentIdAtIndex !== childItemId) {
1118
- modified = true;
1119
- }
1120
- idArray.push(childItemId);
1121
- continue;
1122
- }
1123
- if (primitiveCanBeId(value)) {
1124
- const childItemProps = { [childIdKey]: value };
1125
- const childItem = childResource.store.upsert(childItemProps);
1126
- const childItemId = childItem[childIdKey];
1127
- if (currentIdAtIndex !== childItemId) {
1128
- modified = true;
1129
- }
1130
- idArray.push(childItemId);
1131
- continue;
1132
- }
1133
- }
1134
- if (modified || currentIdArray.length !== idArray.length) {
1135
- childItemIdArraySignal.value = idArray;
1136
- }
1137
- };
1138
- updateChildItemIdArray(item[propertyName]);
1139
-
1140
- const childItemArraySignal = computed(() => {
1141
- const childItemIdArray = childItemIdArraySignal.value;
1142
- const childItemArray = childResource.store.selectAll(childItemIdArray);
1143
- Object.defineProperty(childItemArray, SYMBOL_OBJECT_SIGNAL, {
1144
- value: childItemArraySignal,
1145
- writable: false,
1146
- enumerable: false,
1147
- configurable: false,
1148
- });
1149
- return childItemArray;
1150
- });
1151
-
1152
- if (DEBUG) {
1153
- const childItemArray = childItemArraySignal.peek();
1154
- console.debug(
1155
- `setup ${item}.${propertyName} is many "${childResource.name}" (current value: ${childItemArray.length ? childItemArray.join(",") : "[]"})`,
1156
- );
1157
- }
1158
-
1159
- Object.defineProperty(item, propertyName, {
1160
- get: () => {
1161
- const childItemArray = childItemArraySignal.value;
1162
- if (DEBUG) {
1163
- console.debug(
1164
- `return ${childItemArray.length ? childItemArray.join(",") : "[]"} for ${item}.${propertyName}`,
1165
- );
1166
- }
1167
- return childItemArray;
1168
- },
1169
- set: (value) => {
1170
- updateChildItemIdArray(value);
1171
- if (DEBUG) {
1172
- console.debug(
1173
- `${item}.${propertyName} updated to ${childItemIdArraySignal.peek()}`,
1174
- );
1175
- }
1176
- },
1177
- });
1178
- });
1179
- const httpHandleForChildManyResource =
1180
- createHttpHandlerRelationshipToManyResource(childName, {
1181
- idKey,
1182
- store: resourceInstance.store,
1183
- propertyName,
1184
- childIdKey,
1185
- childStore: childResource.store,
1186
- resourceInstance,
1187
- resourceLifecycleManager,
1188
- });
1189
- return resource(childName, {
1190
- idKey: childIdKey,
1191
- httpHandler: httpHandleForChildManyResource,
1192
- ...options,
1193
- });
1194
- };
1195
-
1196
- /**
1197
- * Creates a parameterized version of the resource with isolated resource lifecycle behavior.
1198
- *
1199
- * Actions from parameterized resources only trigger rerun/reset for other actions with
1200
- * identical parameters, preventing cross-contamination between different parameter sets.
1201
- *
1202
- * @param {Object} params - Parameters to bind to all actions of this resource (required)
1203
- * @param {Object} options - Additional options for the parameterized resource
1204
- * @param {Array} options.dependencies - Array of resources that should trigger autorerun when modified
1205
- * @param {Object} options.rerunOn - Configuration for when to rerun GET/GET_MANY actions
1206
- * @param {false|Array|string} options.rerunOn.GET - HTTP verbs that trigger GET rerun (false = reset on DELETE)
1207
- * @param {false|Array|string} options.rerunOn.GET_MANY - HTTP verbs that trigger GET_MANY rerun (false = reset on DELETE)
1208
- * @returns {Object} A new resource instance with parameter-bound actions and isolated lifecycle
1209
- * @see {@link ./docs/resource_with_params.md} for detailed documentation and examples
1210
- *
1211
- * @example
1212
- * const ROLE = resource("role", { GET: (params) => fetchRole(params) });
1213
- * const adminRoles = ROLE.withParams({ canlogin: true });
1214
- * const guestRoles = ROLE.withParams({ canlogin: false });
1215
- * // adminRoles and guestRoles have isolated autorerun behavior
1216
- *
1217
- * @example
1218
- * // Cross-resource dependencies
1219
- * const role = resource("role");
1220
- * const database = resource("database");
1221
- * const tables = resource("tables");
1222
- * const ROLE_WITH_OWNERSHIP = role.withParams({ owners: true }, {
1223
- * dependencies: [role, database, tables],
1224
- * });
1225
- * // ROLE_WITH_OWNERSHIP.GET_MANY will autorerun when any table/database/role is POST/DELETE
1226
- */
1227
- const withParams = (params, options = {}) => {
1228
- // Require parameters
1229
- if (!params || Object.keys(params).length === 0) {
1230
- throw new Error(`resource(${name}).withParams() requires parameters`);
1231
- }
1232
-
1233
- const { dependencies = [], rerunOn: customRerunOn } = options;
1234
-
1235
- // Generate unique param scope for these parameters
1236
- const paramScopeObject = getParamScope(params);
1237
-
1238
- // Use custom rerunOn settings if provided, otherwise use resource defaults
1239
- const finalRerunOn = customRerunOn || rerunOn;
1240
-
1241
- // Create a new httpHandler with the param scope for isolated autorerun
1242
- const parameterizedHttpHandler = createHttpHandlerForRootResource(name, {
1243
- idKey,
1244
- store: resourceInstance.store,
1245
- rerunOn: finalRerunOn,
1246
- paramScope: paramScopeObject,
1247
- dependencies,
1248
- resourceInstance,
1249
- mutableIdKeys,
1250
- });
1251
-
1252
- // Create parameterized resource
1253
- const parameterizedResource = {
1254
- isResource: true,
1255
- name,
1256
- idKey,
1257
- useArray: resourceInstance.useArray,
1258
- useById: resourceInstance.useById,
1259
- store: resourceInstance.store,
1260
- addItemSetup: resourceInstance.addItemSetup,
1261
- httpHandler: parameterizedHttpHandler,
1262
- one: resourceInstance.one,
1263
- many: resourceInstance.many,
1264
- dependencies, // Store dependencies for debugging/inspection
1265
- httpActions: resourceInstance.httpActions,
1266
- };
1267
-
1268
- // Create HTTP actions from the parameterized handler and bind parameters
1269
- for (const key of Object.keys(resourceInstance.httpActions)) {
1270
- const method = parameterizedHttpHandler[key];
1271
- if (method) {
1272
- const action = method(resourceInstance.httpActions[key]);
1273
- // Bind the parameters to get a parameterized action instance
1274
- parameterizedResource[key] = action.bindParams(params);
1275
- }
1276
- }
1277
-
1278
- // Add withParams method to the parameterized resource for chaining
1279
- parameterizedResource.withParams = (newParams, newOptions = {}) => {
1280
- if (!newParams || Object.keys(newParams).length === 0) {
1281
- throw new Error(`resource(${name}).withParams() requires parameters`);
1282
- }
1283
- // Merge current params with new ones for chaining
1284
- const mergedParams = { ...params, ...newParams };
1285
- // Merge options, with new options taking precedence
1286
- const mergedOptions = {
1287
- dependencies,
1288
- rerunOn: finalRerunOn,
1289
- ...newOptions,
1290
- };
1291
- return withParams(mergedParams, mergedOptions);
1292
- };
1293
-
1294
- return parameterizedResource;
1295
- };
1296
-
1297
- resourceInstance.withParams = withParams;
1298
-
1299
- return resourceInstance;
1300
- };
1301
-
1302
- const isProps = (value) => {
1303
- return value !== null && typeof value === "object";
1304
- };