reactiveadmin 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +88 -0
  3. data/LICENSE +21 -0
  4. data/README.md +81 -0
  5. data/app/assets/reactive_admin/bridge.js +89 -0
  6. data/app/controllers/reactive_admin/api_controller.rb +30 -0
  7. data/app/controllers/reactive_admin/client_errors_controller.rb +38 -0
  8. data/app/controllers/reactive_admin/manifest_controller.rb +10 -0
  9. data/app/controllers/reactive_admin/mcp_controller.rb +48 -0
  10. data/app/controllers/reactive_admin/openapi_controller.rb +13 -0
  11. data/app/controllers/reactive_admin/session_controller.rb +11 -0
  12. data/app/views/layouts/reactive_admin/embed.html.erb +30 -0
  13. data/lib/generators/reactiveadmin/install/install_generator.rb +341 -0
  14. data/lib/generators/reactiveadmin/install/templates/menu.rb.tt +25 -0
  15. data/lib/generators/reactiveadmin/install/templates/reactive_admin.rb.tt +53 -0
  16. data/lib/generators/reactiveadmin/install/templates/reactive_admin_annotated.rb.tt +110 -0
  17. data/lib/reactive_admin/aa/v3/controller.rb +76 -0
  18. data/lib/reactive_admin/aa/v3/forms.rb +29 -0
  19. data/lib/reactive_admin/aa/v3/inputs/filters/typeahead_input.rb +51 -0
  20. data/lib/reactive_admin/aa/v3/inputs/typeahead_input.rb +8 -0
  21. data/lib/reactive_admin/aa/v3/install.rb +36 -0
  22. data/lib/reactive_admin/aa/v3/menu.rb +67 -0
  23. data/lib/reactive_admin/aa/v3/presenters.rb +102 -0
  24. data/lib/reactive_admin/aa/v3/registry.rb +78 -0
  25. data/lib/reactive_admin/aa/v3/views.rb +63 -0
  26. data/lib/reactive_admin/aa/v3.rb +23 -0
  27. data/lib/reactive_admin/aa/v4.rb +59 -0
  28. data/lib/reactive_admin/aa.rb +46 -0
  29. data/lib/reactive_admin/action_items.rb +39 -0
  30. data/lib/reactive_admin/action_links.rb +197 -0
  31. data/lib/reactive_admin/action_safety.rb +19 -0
  32. data/lib/reactive_admin/actions.rb +95 -0
  33. data/lib/reactive_admin/api_errors.rb +116 -0
  34. data/lib/reactive_admin/api_fallback.rb +15 -0
  35. data/lib/reactive_admin/api_guards.rb +445 -0
  36. data/lib/reactive_admin/audit.rb +72 -0
  37. data/lib/reactive_admin/auth/guard.rb +68 -0
  38. data/lib/reactive_admin/auth/token_requests.rb +15 -0
  39. data/lib/reactive_admin/auth.rb +135 -0
  40. data/lib/reactive_admin/authorizer.rb +47 -0
  41. data/lib/reactive_admin/background_requests.rb +33 -0
  42. data/lib/reactive_admin/batch_actions.rb +57 -0
  43. data/lib/reactive_admin/choices.rb +289 -0
  44. data/lib/reactive_admin/client_error.rb +70 -0
  45. data/lib/reactive_admin/composite_keys.rb +12 -0
  46. data/lib/reactive_admin/configuration.rb +221 -0
  47. data/lib/reactive_admin/controller_extension.rb +229 -0
  48. data/lib/reactive_admin/csv_injection.rb +26 -0
  49. data/lib/reactive_admin/date_bound.rb +31 -0
  50. data/lib/reactive_admin/degradation.rb +72 -0
  51. data/lib/reactive_admin/diagnostics.rb +16 -0
  52. data/lib/reactive_admin/doctor.rb +466 -0
  53. data/lib/reactive_admin/dry_run.rb +147 -0
  54. data/lib/reactive_admin/dry_run_flag.rb +18 -0
  55. data/lib/reactive_admin/embed.rb +73 -0
  56. data/lib/reactive_admin/engine.rb +47 -0
  57. data/lib/reactive_admin/error_keys.rb +23 -0
  58. data/lib/reactive_admin/exposure.rb +86 -0
  59. data/lib/reactive_admin/filters.rb +165 -0
  60. data/lib/reactive_admin/fixtures/scrubber.rb +1075 -0
  61. data/lib/reactive_admin/fixtures.rb +161 -0
  62. data/lib/reactive_admin/form_content.rb +78 -0
  63. data/lib/reactive_admin/form_field.rb +279 -0
  64. data/lib/reactive_admin/form_has_many.rb +116 -0
  65. data/lib/reactive_admin/form_lock.rb +71 -0
  66. data/lib/reactive_admin/form_payload.rb +57 -0
  67. data/lib/reactive_admin/form_recorder.rb +192 -0
  68. data/lib/reactive_admin/form_schema.rb +160 -0
  69. data/lib/reactive_admin/frame.rb +97 -0
  70. data/lib/reactive_admin/html_nodes.rb +390 -0
  71. data/lib/reactive_admin/html_policy.rb +338 -0
  72. data/lib/reactive_admin/html_rich.rb +186 -0
  73. data/lib/reactive_admin/implicit_defaults.rb +102 -0
  74. data/lib/reactive_admin/index_options.rb +41 -0
  75. data/lib/reactive_admin/index_payload.rb +259 -0
  76. data/lib/reactive_admin/index_recorder.rb +115 -0
  77. data/lib/reactive_admin/index_views.rb +85 -0
  78. data/lib/reactive_admin/inline_style.rb +125 -0
  79. data/lib/reactive_admin/labels_payload.rb +34 -0
  80. data/lib/reactive_admin/ladder.rb +268 -0
  81. data/lib/reactive_admin/layout_classes.rb +167 -0
  82. data/lib/reactive_admin/legacy_inventory.rb +547 -0
  83. data/lib/reactive_admin/location.rb +22 -0
  84. data/lib/reactive_admin/lookup_audit.rb +30 -0
  85. data/lib/reactive_admin/lookup_payload.rb +41 -0
  86. data/lib/reactive_admin/manifest.rb +36 -0
  87. data/lib/reactive_admin/masked_json.rb +62 -0
  88. data/lib/reactive_admin/masking.rb +100 -0
  89. data/lib/reactive_admin/mcp/access.rb +111 -0
  90. data/lib/reactive_admin/mcp/api.rb +123 -0
  91. data/lib/reactive_admin/mcp/count_tool.rb +22 -0
  92. data/lib/reactive_admin/mcp/layout.rb +175 -0
  93. data/lib/reactive_admin/mcp/output.rb +46 -0
  94. data/lib/reactive_admin/mcp/prompts.rb +111 -0
  95. data/lib/reactive_admin/mcp/server.rb +134 -0
  96. data/lib/reactive_admin/mcp/shapes.rb +164 -0
  97. data/lib/reactive_admin/mcp/tools.rb +386 -0
  98. data/lib/reactive_admin/mcp.rb +53 -0
  99. data/lib/reactive_admin/media_nodes.rb +34 -0
  100. data/lib/reactive_admin/menu.rb +90 -0
  101. data/lib/reactive_admin/menu_overlay.rb +291 -0
  102. data/lib/reactive_admin/node_registry.rb +47 -0
  103. data/lib/reactive_admin/open_api/builder.rb +156 -0
  104. data/lib/reactive_admin/open_api/context.rb +46 -0
  105. data/lib/reactive_admin/open_api/core.rb +51 -0
  106. data/lib/reactive_admin/open_api/operation_ids.rb +18 -0
  107. data/lib/reactive_admin/open_api/page_doc.rb +75 -0
  108. data/lib/reactive_admin/open_api/parts.rb +86 -0
  109. data/lib/reactive_admin/open_api/resource_doc.rb +423 -0
  110. data/lib/reactive_admin/open_api/security.rb +55 -0
  111. data/lib/reactive_admin/open_api/write_schema.rb +104 -0
  112. data/lib/reactive_admin/open_api.rb +41 -0
  113. data/lib/reactive_admin/option_source.rb +36 -0
  114. data/lib/reactive_admin/option_sources.rb +14 -0
  115. data/lib/reactive_admin/options_payload.rb +61 -0
  116. data/lib/reactive_admin/page_controller_extension.rb +112 -0
  117. data/lib/reactive_admin/page_forms.rb +181 -0
  118. data/lib/reactive_admin/page_payload.rb +120 -0
  119. data/lib/reactive_admin/param_normalizer.rb +89 -0
  120. data/lib/reactive_admin/paths.rb +63 -0
  121. data/lib/reactive_admin/permissions.rb +31 -0
  122. data/lib/reactive_admin/provenance.rb +57 -0
  123. data/lib/reactive_admin/query_guard.rb +108 -0
  124. data/lib/reactive_admin/ransack_guard.rb +107 -0
  125. data/lib/reactive_admin/rate_limit.rb +59 -0
  126. data/lib/reactive_admin/reactive_dsl.rb +99 -0
  127. data/lib/reactive_admin/readiness.rb +189 -0
  128. data/lib/reactive_admin/registry.rb +69 -0
  129. data/lib/reactive_admin/resource_meta.rb +120 -0
  130. data/lib/reactive_admin/resource_summary.rb +41 -0
  131. data/lib/reactive_admin/routes.rb +60 -0
  132. data/lib/reactive_admin/row_errors.rb +29 -0
  133. data/lib/reactive_admin/rspec.rb +116 -0
  134. data/lib/reactive_admin/scrubbed_error.rb +22 -0
  135. data/lib/reactive_admin/search.rb +79 -0
  136. data/lib/reactive_admin/server_timing.rb +31 -0
  137. data/lib/reactive_admin/show_payload.rb +88 -0
  138. data/lib/reactive_admin/sidebars.rb +34 -0
  139. data/lib/reactive_admin/site.rb +55 -0
  140. data/lib/reactive_admin/style_report.rb +129 -0
  141. data/lib/reactive_admin/style_sources.rb +83 -0
  142. data/lib/reactive_admin/template_actions.rb +126 -0
  143. data/lib/reactive_admin/template_content.rb +49 -0
  144. data/lib/reactive_admin/template_form.rb +442 -0
  145. data/lib/reactive_admin/test_support.rb +31 -0
  146. data/lib/reactive_admin/typeahead.rb +33 -0
  147. data/lib/reactive_admin/ui/assets.rb +91 -0
  148. data/lib/reactive_admin/ui/client_build.rb +47 -0
  149. data/lib/reactive_admin/ui/helper.rb +24 -0
  150. data/lib/reactive_admin/ui/packaged_client.rb +67 -0
  151. data/lib/reactive_admin/ui/shell.rb +81 -0
  152. data/lib/reactive_admin/ui/switch.rb +38 -0
  153. data/lib/reactive_admin/ui.rb +43 -0
  154. data/lib/reactive_admin/value_payload.rb +147 -0
  155. data/lib/reactive_admin/value_token.rb +36 -0
  156. data/lib/reactive_admin/values.rb +43 -0
  157. data/lib/reactive_admin/version.rb +3 -0
  158. data/lib/reactive_admin/write_audit.rb +60 -0
  159. data/lib/reactive_admin/write_guards.rb +142 -0
  160. data/lib/reactive_admin.rb +153 -0
  161. data/lib/reactiveadmin.rb +1 -0
  162. data/lib/tasks/reactiveadmin.rake +36 -0
  163. data/lib/tasks/reactiveadmin_client.rake +11 -0
  164. data/lib/tasks/reactiveadmin_legacy.rake +7 -0
  165. data/lib/tasks/reactiveadmin_styles.rake +6 -0
  166. data/openapi/core.yaml +1643 -0
  167. data/vendor/client/assets/ActionPage-XUYorI8E.js +1 -0
  168. data/vendor/client/assets/ActionView-BsZFcsgp.js +1 -0
  169. data/vendor/client/assets/CommandPalette-C59HT1ip.js +1 -0
  170. data/vendor/client/assets/DatePicker-DuaK0iMg.js +1 -0
  171. data/vendor/client/assets/DateRangeCalendar-B2BDsG-X.js +1 -0
  172. data/vendor/client/assets/DegradedNotice-DiH5n2DO.js +1 -0
  173. data/vendor/client/assets/FormDialog-pmYl8Eov.js +1 -0
  174. data/vendor/client/assets/FormSkeleton-DuSBZO3C.js +1 -0
  175. data/vendor/client/assets/FrameView-2X8cFvUt.css +1 -0
  176. data/vendor/client/assets/FrameView-zmUeDO8d.js +1 -0
  177. data/vendor/client/assets/GroupOverview-DI5T3k5K.js +1 -0
  178. data/vendor/client/assets/InlineForm-CMEIMgeh.js +1 -0
  179. data/vendor/client/assets/JsonDiff-o7JWr7CH.js +3 -0
  180. data/vendor/client/assets/JsonEditor-D4VXdlEx.js +1 -0
  181. data/vendor/client/assets/JsonView-BrJLDmSN.js +1 -0
  182. data/vendor/client/assets/MobileMenu-GAeFOeEb.js +1 -0
  183. data/vendor/client/assets/Node-SQl61V4K.js +2 -0
  184. data/vendor/client/assets/PageView-C-laNEPZ.js +1 -0
  185. data/vendor/client/assets/ResourceForm-BPjsoCY6.js +1 -0
  186. data/vendor/client/assets/ResourceIndex-COezAw5t.js +3 -0
  187. data/vendor/client/assets/ResourceOrPage-CRZGCY84.js +1 -0
  188. data/vendor/client/assets/ResourceShow-DweRXn18.js +1 -0
  189. data/vendor/client/assets/Segmented-BE9TCbph.js +1 -0
  190. data/vendor/client/assets/Sidebars-CsB9rFqX.js +1 -0
  191. data/vendor/client/assets/breadcrumb-DSA3Tlyd.js +1 -0
  192. data/vendor/client/assets/button-CvZ4_DFC.js +1 -0
  193. data/vendor/client/assets/calendar-BoyMpJIf.js +1 -0
  194. data/vendor/client/assets/check-C5A3J16N.js +1 -0
  195. data/vendor/client/assets/command-CMuk0oAt.js +1 -0
  196. data/vendor/client/assets/dist-CqEI82S_.js +1 -0
  197. data/vendor/client/assets/dist-IW4yX942.js +1 -0
  198. data/vendor/client/assets/editor-yqRLzgsJ.js +2 -0
  199. data/vendor/client/assets/external-link-C2aR4slL.js +1 -0
  200. data/vendor/client/assets/frames-C9gPCc3N.js +1 -0
  201. data/vendor/client/assets/humanize-DtU_Kpr4.js +1 -0
  202. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  203. data/vendor/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  204. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  205. data/vendor/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  206. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  207. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  208. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  209. data/vendor/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  210. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  211. data/vendor/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  212. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  213. data/vendor/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  214. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  215. data/vendor/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  216. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  217. data/vendor/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  218. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  219. data/vendor/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  220. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  221. data/vendor/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  222. data/vendor/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  223. data/vendor/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  224. data/vendor/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  225. data/vendor/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  226. data/vendor/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  227. data/vendor/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  228. data/vendor/client/assets/index-B51aUaAY.js +43 -0
  229. data/vendor/client/assets/index-Cs9rCoWM.css +2 -0
  230. data/vendor/client/assets/input-DByFmQPa.js +1 -0
  231. data/vendor/client/assets/json-De3PN-R6.css +1 -0
  232. data/vendor/client/assets/json-oTp7Q-d-.js +5 -0
  233. data/vendor/client/assets/media-D4a_En8R.js +1 -0
  234. data/vendor/client/assets/plus-CfJ9vo8X.js +1 -0
  235. data/vendor/client/assets/popover-CDtI9R8Q.js +1 -0
  236. data/vendor/client/assets/purify-G7QKJyJq.js +1 -0
  237. data/vendor/client/assets/query-CCsZN2fa.js +1 -0
  238. data/vendor/client/assets/recent-BrzLwL0D.js +1 -0
  239. data/vendor/client/assets/rich-BQc_q5T7.js +1 -0
  240. data/vendor/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  241. data/vendor/client/assets/select-C43qDA3k.js +1 -0
  242. data/vendor/client/assets/sheet-BPl2n-4n.js +1 -0
  243. data/vendor/client/assets/textarea-BnOphXry.js +1 -0
  244. data/vendor/client/assets/uiMode-z0ZbRV49.js +1 -0
  245. data/vendor/client/assets/uiToggle-DwnRQTH1.js +1 -0
  246. data/vendor/client/assets/useRecordForm-X_DExEP2.js +1 -0
  247. data/vendor/client/assets/useRecordVisit-BRtfMi-q.js +1 -0
  248. data/vendor/client/assets/utils-DwBGbDkG.js +1 -0
  249. data/vendor/client/assets/vendor-calendar-nTZiq9oY.js +1 -0
  250. data/vendor/client/assets/vendor-datefns-BoC6MCnl.js +1 -0
  251. data/vendor/client/assets/vendor-forms-D0h8hG_S.js +55 -0
  252. data/vendor/client/assets/vendor-purify-BXoPR7WT.js +3 -0
  253. data/vendor/client/assets/vendor-query-DZ6APRNI.js +1 -0
  254. data/vendor/client/assets/vendor-react-C1iE8mnY.js +9 -0
  255. data/vendor/client/assets/vendor-router-CI6Vh4k_.js +1 -0
  256. data/vendor/client/assets/vendor-table-DuQ835by.js +4 -0
  257. data/vendor/client/index.html +24 -0
  258. data/vendor/client/manifest.json +867 -0
  259. data/vendor/client/reactiveadmin-client.json +4 -0
  260. metadata +350 -0
@@ -0,0 +1,161 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "stringio"
4
+
5
+ module ReactiveAdmin
6
+ # Real response shapes as JSON files for Storybook and MSW: the manifest, and per resource its
7
+ # meta, first index page, a show page, and the new and edit forms, rendered as `config.doctor_user`
8
+ # and scrubbed of record data (see Scrubber). Output names resources and counts, never values.
9
+ module Fixtures
10
+ autoload :Scrubber, "reactive_admin/fixtures/scrubber"
11
+
12
+ Error = Class.new(StandardError)
13
+ SampleFailed = Class.new(Error)
14
+ Result = Struct.new(:files, :skipped, :kept)
15
+
16
+ SEED_ENV = "REACTIVEADMIN_FIXTURES_SEED".freeze
17
+ SEED_FILE = "tmp/reactiveadmin_fixtures_seed".freeze
18
+ SECTIONS = {meta: :reactiveadmin_meta, index: :index, show: :show, new: :new, edit: :edit}.freeze
19
+ KINDS = {meta: :meta, index: :index, show: :show, new: :form, edit: :form}.freeze
20
+
21
+ module_function
22
+
23
+ # resources: route keys, or nil for every resource the user's manifest lists. Returns the
24
+ # scrubbed files as {relative path => payload}, the sections left out with the reason, and the
25
+ # host-written strings kept verbatim.
26
+ def record(user: ReactiveAdmin.config.doctor_user&.call, resources: nil, scrubber: nil)
27
+ raise Error, "set config.doctor_user (-> { a user }) to render the payloads as" unless user
28
+
29
+ Rails.application.reload_routes_unless_loaded
30
+ ApiGuards.with_channel(:session) do
31
+ ActiveRecord::Base.while_preventing_writes { Recorder.new(user, scrubber || Scrubber.new(seed:, vocabulary:, routes: route_segments)).call(resources) }
32
+ end
33
+ end
34
+
35
+ # The app's private seed: REACTIVEADMIN_FIXTURES_SEED, else a random one kept in tmp/ (created on first run), so the
36
+ # same machine records the same fakes and nobody without the seed can undo them. Never commit it.
37
+ def seed
38
+ ENV[SEED_ENV].presence || begin
39
+ path = Rails.root.join(SEED_FILE)
40
+ restrict(path) if path.exist?
41
+ (path.read.strip.presence if path.exist?) || SecureRandom.hex(32).tap do |seed|
42
+ FileUtils.mkdir_p(path.dirname)
43
+ File.open(path, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { it.write(seed) }
44
+ end
45
+ end
46
+ end
47
+
48
+ # Anyone who can read the seed can undo the fakes.
49
+ def restrict(path)
50
+ return unless path.stat.mode.anybits?(0o077)
51
+
52
+ warn "reactiveadmin: #{SEED_FILE} was readable by others; restricted it to its owner"
53
+ path.chmod(0o600)
54
+ end
55
+
56
+ def write(result, dir)
57
+ stale(result).each { FileUtils.rm_f(File.join(dir, it)) }
58
+ result.files.each do |path, payload|
59
+ file = File.join(dir, path)
60
+ FileUtils.mkdir_p(File.dirname(file))
61
+ File.write(file, "#{JSON.pretty_generate(payload)}\n")
62
+ end
63
+ end
64
+
65
+ # Files an earlier recording of these resources left that this one no longer produces.
66
+ def stale(result)
67
+ keys = result.files.keys.filter_map { File.dirname(it) unless it == "_manifest.json" } | result.skipped.map(&:first)
68
+ keys.flat_map { |key| SECTIONS.keys.map { "#{key}/#{it}.json" } } - result.files.keys
69
+ end
70
+
71
+ # The literal segments of the admin's own routes: structure, never record data.
72
+ def route_segments
73
+ prefixes = ["/#{ReactiveAdmin.config.namespace}", Paths.api("/#{ReactiveAdmin.config.namespace}")].map { Regexp.escape(it) }
74
+ Rails.application.routes.routes.map { it.path.spec.to_s }.grep(/\A(?:#{prefixes.join("|")})(?:[\/(]|\z)/).flat_map { it.split(/[\/()]/) }.grep(/\A[\w-]+\z/).uniq
75
+ end
76
+
77
+ # Enum names are schema, so they stay readable in the fixtures, but only as choices of their own attribute.
78
+ def vocabulary = Registry.resources.to_h { [Registry.route_key(it), it.resource_class.try(:defined_enums).to_h.transform_values(&:keys)] }
79
+
80
+ class Recorder
81
+ def initialize(user, scrubber)
82
+ @user = user
83
+ @scrubber = scrubber
84
+ end
85
+
86
+ def call(keys)
87
+ manifest = fetch(Struct.new(:controller).new(ManifestController), :show)
88
+ known = manifest["resources"].pluck("key")
89
+ keys = Array(keys).presence || known
90
+ unknown = keys - known
91
+ raise Error, "unknown resources: #{unknown.join(", ")} (known: #{known.join(", ")})" if unknown.any?
92
+
93
+ entries = [["_manifest.json", :manifest, manifest]]
94
+ skipped = []
95
+ keys.each { |key| resource(Registry.resources.find { Registry.route_key(it) == key }, key, entries, skipped) }
96
+ Result.new(entries.map(&:first).zip(@scrubber.scrub_all(entries.map { it.drop(1) })).to_h, skipped, @scrubber.kept)
97
+ end
98
+
99
+ private
100
+
101
+ def resource(config, key, entries, skipped)
102
+ rows = nil
103
+ SECTIONS.each do |section, action|
104
+ if (reason = unavailable(config, section, rows))
105
+ skipped << [key, section, reason]
106
+ next
107
+ end
108
+ payload = fetch(config, action, **arguments(config, section, rows))
109
+ rows = payload["rows"] if section == :index
110
+ entries << ["#{key}/#{section}.json", KINDS.fetch(section), payload, key]
111
+ rescue SampleFailed => e
112
+ skipped << [key, section, e.message]
113
+ end
114
+ end
115
+
116
+ def unavailable(config, section, rows)
117
+ return if section == :meta
118
+
119
+ action = (section == :new) ? :new : section
120
+ return "not routed" unless Registry.actions(config).include?(action)
121
+ return "nested under a parent" if Paths.nested?(config) || !Registry.top_level_actions(config).include?(action)
122
+ return "api guard" if ApiGuards.with_channel(:session) { ApiGuards.denies?(config, action) }
123
+
124
+ "no records" if %i[show edit].include?(section) && rows.blank?
125
+ end
126
+
127
+ def arguments(config, section, rows)
128
+ case section
129
+ when :show, :edit then {path_params: {id: rows.first["id"]}}
130
+ when :new then {path_params: Paths.parent_params(config, config.resource_class.first)}
131
+ else {}
132
+ end
133
+ end
134
+
135
+ def fetch(config, action, path_params: {}, query: {})
136
+ status, payload = Doctor::Sample.new(config, @user).call(action, path_params:, query:)
137
+ raise SampleFailed, "#{status} #{payload["code"]}" unless status == 200
138
+
139
+ payload
140
+ end
141
+ end
142
+
143
+ # The rake task's driver.
144
+ module CLI
145
+ module_function
146
+
147
+ def run(resources: nil, out_dir: nil, out: $stdout)
148
+ keys = resources.to_s.split(/[\s+]+/).reject { it.empty? || it == "all" }
149
+ dir = Rails.root.join(out_dir.presence || "tmp/reactiveadmin/fixtures")
150
+ result = Fixtures.record(resources: keys)
151
+ Fixtures.write(result, dir)
152
+ out.puts "wrote #{result.files.size} files to #{dir.relative_path_from(Rails.root)}"
153
+ result.skipped.each { |key, section, reason| out.puts "skipped #{key} #{section}: #{reason}" }
154
+ return if result.kept.empty?
155
+
156
+ out.puts "warning: kept #{result.kept.size} host-written strings verbatim; check none quotes a record:"
157
+ result.kept.each { out.puts " #{it.inspect}" }
158
+ end
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,78 @@
1
+ module ReactiveAdmin
2
+ # Arbre content of a `form do |f|` block (headings, panels, tables of the current record) as typed nodes,
3
+ # walked by the same HtmlNodes as a show page. The recorder leaves a marker wherever it records an input;
4
+ # the content before each marker becomes one `content` field in that spot, with the elements still open
5
+ # around an input (a panel holding `f.inputs`) copied into each part they span.
6
+ class FormContent
7
+ CUT = "ra-cut".freeze
8
+ # Containers that carry nothing once the content around an input is split off.
9
+ SHELLS = %w[box panel group].freeze
10
+
11
+ def self.marker(id) = %(<#{CUT} data-id="#{id}"></#{CUT}>).html_safe
12
+
13
+ def initialize(controller, record)
14
+ @controller = controller
15
+ @record = record
16
+ end
17
+
18
+ # The html split at its markers: [[id, html], ...] in order, then what follows the last one under a nil id.
19
+ # Nil when the markup is too deep to split.
20
+ def split(raw)
21
+ fragment = HtmlPolicy.parse(raw) or return
22
+ parts = fragment.css(CUT).map do |marker|
23
+ html = take_before(fragment, marker, marker.ancestors.to_a).map(&:to_html).join
24
+ marker.unlink
25
+ [marker["data-id"], html]
26
+ end
27
+ [*parts, [nil, fragment.to_html]]
28
+ end
29
+
30
+ # Nodes for the html, outside any frame: forms and stored markup stay inert, as on a show page.
31
+ def nodes(html)
32
+ return [] if html.blank?
33
+
34
+ request = @controller.request
35
+ links = ActionLinks.new(host: request.host, base_url: request.base_url, authorizer: Authorizer.for(@controller), subject: @record)
36
+ tidy(HtmlNodes.nodes(html, host: request.host, links:, resource: Registry.route_key(AA.config_of(@controller))))
37
+ end
38
+
39
+ private
40
+
41
+ # Moves the nodes before the marker out of the fragment. An ancestor of the marker stays, and its
42
+ # copy takes the part of it that precedes the marker.
43
+ def take_before(parent, marker, chain)
44
+ taken = []
45
+ parent.children.to_a.each do |child|
46
+ break if child == marker
47
+
48
+ if chain.include?(child)
49
+ taken << shell(child).tap { |copy| take_before(child, marker, chain).each { copy.add_child(it) } }
50
+ break
51
+ end
52
+ taken << child.unlink
53
+ end
54
+ taken
55
+ end
56
+
57
+ # The element and its attributes (a provenance stamp among them) without its children.
58
+ def shell(element)
59
+ Nokogiri::XML::Node.new(element.name, element.document).tap do |copy|
60
+ element.attribute_nodes.each { copy[it.name] = it.value }
61
+ end
62
+ end
63
+
64
+ # Drops what an emptied wrapper leaves behind. A panel left with only its title is a heading.
65
+ def tidy(nodes)
66
+ nodes.filter_map do |node|
67
+ next node unless SHELLS.include?(node[:type])
68
+
69
+ node = node.merge(children: tidy(node[:children]))
70
+ next node if node[:children].any? || node[:header_actions].present?
71
+
72
+ title(node[:title]) if node[:title].present?
73
+ end
74
+ end
75
+
76
+ def title(text) = {type: "heading", level: 3, children: [{type: "text", text:}]}
77
+ end
78
+ end
@@ -0,0 +1,279 @@
1
+ module ReactiveAdmin
2
+ # One recorded `f.input`, described the way Formtastic would have rendered it: its input
3
+ # class supplies the label, requiredness, hint, collection and param name.
4
+ class FormField
5
+ CONTROLS = {
6
+ "string" => "text", "search" => "text", "color" => "text", "country" => "text",
7
+ "text" => "textarea", "number" => "number", "range" => "number", "email" => "email",
8
+ "url" => "url", "phone" => "phone", "password" => "password", "select" => "select",
9
+ "time_zone" => "select", "radio" => "radio", "check_boxes" => "checkboxes",
10
+ "boolean" => "boolean", "datepicker" => "date", "date_picker" => "date", "date_select" => "date",
11
+ "datetime_picker" => "datetime", "datetime_select" => "datetime", "time_picker" => "time",
12
+ "time_select" => "time", "file" => "file", "hidden" => "hidden", "datalist" => "typeahead",
13
+ "typeahead" => "typeahead"
14
+ }.freeze
15
+ CHOICE_CONTROLS = %w[select radio checkboxes typeahead].freeze
16
+ DAY_CONTROLS = %w[date datetime].freeze
17
+ JSON_TYPES = %i[json jsonb hstore].freeze
18
+ DERIVED_HTML = {
19
+ "number" => %i[min max step], "date" => %i[min max], "datetime" => %i[min max],
20
+ "text" => %i[maxlength], "textarea" => %i[maxlength],
21
+ "email" => %i[maxlength], "url" => %i[maxlength], "phone" => %i[maxlength]
22
+ }.freeze
23
+
24
+ # Anything the API can't express is carried as sanitized html instead of being dropped.
25
+ def self.html(html, name, label: "") = {name:, param: nil, label:, control: "html", value: html, required: false}
26
+
27
+ # What the form block rendered around its inputs, read-only; the recorder fills `layout` once it can walk it.
28
+ def self.content(name) = {name:, param: nil, label: "", control: "content", required: false}
29
+
30
+ def self.hidden_id(nested, record)
31
+ {name: "id", param: nested.field_name(:id), label: "Id", control: "hidden", value: record.to_param.to_s, required: false}
32
+ end
33
+
34
+ def initialize(builder, schema, prefix = nil)
35
+ @builder = builder
36
+ @schema = schema
37
+ @view = schema.view
38
+ @prefix = prefix
39
+ end
40
+
41
+ # Nil when the schema is built for one other field only.
42
+ def call(method, options)
43
+ return unless @schema.wants?([@prefix, method].compact.join("."))
44
+
45
+ options = options.dup
46
+ input = AA.build_input(@builder, @view, method, options)
47
+ control = control_for(input)
48
+ control ? build(input, control) : degraded(input)
49
+ rescue => e
50
+ Rails.logger.warn("[reactiveadmin] #{@schema.config.resource_name} field #{method} degraded: #{e.class} at #{e.backtrace&.first}")
51
+ Degradation.record(kind: :form_field_failed, where: "form/field[#{[@prefix, method].compact.join(".")}]", reason: "Input raised #{e.class}; field left empty")
52
+ @schema.unsupported!(:input_degraded)
53
+ self.class.html("", @schema.next_html_name, label: method.to_s.humanize)
54
+ end
55
+
56
+ private
57
+
58
+ def control_for(input)
59
+ control = CONTROLS[input.as] or return
60
+ return "date" if input.as == "string" && datepicker?(input)
61
+
62
+ (json?(input) && %w[text textarea].include?(control)) ? "json" : control
63
+ end
64
+
65
+ # AA's JS datepicker is attached by class; the client has a native date control instead.
66
+ def datepicker?(input) = input.options.dig(:input_html, :class).to_s.split.include?("datepicker")
67
+
68
+ def build(input, control)
69
+ multiple = control == "checkboxes" || (control == "select" && input.multiple?)
70
+ control = "multiselect" if multiple && control == "select"
71
+ return signals(input, control, multiple) if @schema.controls_only?
72
+
73
+ value = value_for(input, control)
74
+ field = {name: input.method.to_s, param: param(input, multiple), label: label(input), control:,
75
+ value:, required: !!input.required?}
76
+ field = summarized(field, input) if control == "json"
77
+ field.merge!(choices(input, field, multiple)) if choice?(control)
78
+ field = field.merge(extras(input, control).compact)
79
+ field = api_marks(field, input)
80
+ masked?(input, control) ? field.except(:value).merge(masked: true) : field
81
+ end
82
+
83
+ # What a write is judged by. A single select and a typeahead are normalized alike, so their options
84
+ # are skipped. The other choice controls turn into a typeahead when truncated, which changes how a
85
+ # blank is normalized, so for those the options are only counted.
86
+ def signals(input, control, multiple)
87
+ field = {name: input.method.to_s, param: param(input, multiple), control:}
88
+ field[:value] = value_for(input, control) if control == "json"
89
+ field = summarized(field, input) if control == "json"
90
+ field.merge!(truncation(input, field)) if resolves_options?(control)
91
+ field = field.merge(disabled: (true if input.options.dig(:input_html, :disabled) || input.readonly? || api_denied?(input))).compact.except(:value)
92
+ masked?(input, control) ? field.merge(masked: true) : field
93
+ end
94
+
95
+ def api_denied?(input) = reserved_keys.intersect?(keys_of(input))
96
+
97
+ def api_marks(field, input)
98
+ return field.merge(disabled: true, api_denied: true, classic_url: ApiGuards.classic_url(@view.controller)) if api_denied?(input)
99
+
100
+ ApiGuards.annotate(field, ApiGuards.attribute_guard(@schema.config, action_names, keys_of(input)))
101
+ end
102
+
103
+ def keys_of(input) = [input.method.to_s, input.input_name.to_s]
104
+
105
+ def action_names = @action_names ||= ApiGuards.names_for(@view.controller)
106
+
107
+ def reserved_keys = @reserved_keys ||= ApiGuards.reserved_keys(@schema.config, action_names)
108
+
109
+ def resolves_options?(control) = choice?(control) && !%w[select typeahead].include?(control)
110
+
111
+ # Same rule as a show row: a large value, or one with a masked key at any depth, is not sent. The
112
+ # editor loads it through the audited `_value`, so a value never reaches the page unrecorded.
113
+ def summarized(field, input)
114
+ value = field[:value]
115
+ return field unless ValuePayload.json?(value) && value.present?
116
+ return field.merge(value: ValuePayload.mask(value, @schema.config)) unless @builder.object.persisted? && !ValuePayload.inline?(value, @schema.config)
117
+
118
+ source = ValuePayload::Source.new(config: @schema.config, record: @builder.object, field: field[:name], controller: @view.controller, via: "form") unless @prefix || @schema.controls_only?
119
+ field.merge(value: nil, summary: ValuePayload.summary(value), **{expand_path: ValuePayload.expand_path(source)}.compact)
120
+ end
121
+
122
+ # A new record has no stored value to protect, so its masked fields are ordinary inputs.
123
+ def masked?(input, control) = control != "hidden" && @builder.object.try(:persisted?) && Masking.attribute?(input.method, @schema.config)
124
+
125
+ def degraded(input)
126
+ Degradation.record(kind: :form_field_html, where: "form/field[#{[@prefix, input.method].compact.join(".")}]", reason: "Input type #{input.as} has no typed control; shown as html")
127
+ if @schema.controls_only?
128
+ @schema.unsupported!(:input_degraded)
129
+ return
130
+ end
131
+
132
+ collection = input.options[:collection]
133
+ input.options[:collection] = @view.instance_exec(&collection) if collection.is_a?(Proc)
134
+ html = HtmlNodes.sanitize(input.to_html)
135
+ @schema.unsupported!(:input_degraded)
136
+ self.class.html(html, input.method.to_s, label: label(input))
137
+ rescue
138
+ @schema.unsupported!(:input_degraded)
139
+ self.class.html("", input.method.to_s, label: label(input))
140
+ end
141
+
142
+ # The builder names it as Rails does, `index:` of a repeated `fields_for` included. Formtastic's
143
+ # check_boxes input_name is already the whole param, brackets included, and its hidden input posts
144
+ # under the method name even for an association (`category`, not `category_id`).
145
+ def param(input, multiple)
146
+ kind = AA.input_kind(input)
147
+ return plain(input.input_name) if kind == :check_boxes
148
+
149
+ name = (kind == :hidden) ? input.method : input.input_name
150
+ @builder.field_name(name, multiple:)
151
+ end
152
+
153
+ # An object-less form (`semantic_form_for ""`) posts top-level params, but Formtastic still wraps the name in brackets.
154
+ def plain(param) = @builder.object_name.blank? ? param.to_s.sub(/\A\[([^\]]+)\]/, '\1') : param
155
+
156
+ def label(input)
157
+ return "" if input.options[:label] == false
158
+
159
+ (input.localized_label || input.humanized_method_name).to_s
160
+ end
161
+
162
+ def extras(input, control)
163
+ {
164
+ hint: (CGI.unescapeHTML(@view.strip_tags(input.hint_text.to_s)) if input.hint?),
165
+ placeholder: input.options[:placeholder] || input.options.dig(:input_html, :placeholder),
166
+ errors: input.errors.presence,
167
+ disabled: (true if input.options.dig(:input_html, :disabled) || input.readonly?),
168
+ free_text: (true if %w[datalist typeahead].include?(input.as)),
169
+ input_html: input_html(input, control)
170
+ }
171
+ end
172
+
173
+ # Limits Formtastic derives from validations/columns, plus whatever the form block set explicitly.
174
+ def input_html(input, control)
175
+ derived = input.input_html_options.slice(*DERIVED_HTML.fetch(control, []))
176
+ html = derived.merge(input.options[:input_html].to_h.slice(*DERIVED_HTML.values.flatten, :rows))
177
+ html = html.merge(day_limits(input, html, control)) if DAY_CONTROLS.include?(control)
178
+ html.compact_blank.presence
179
+ end
180
+
181
+ # `input_html:` wins over the classic datepicker's `datepicker_options: {min_date:, max_date:}`.
182
+ def day_limits(input, html, control)
183
+ picker = input.options[:datepicker_options].to_h.transform_keys { it.to_s.underscore.to_sym }
184
+ %i[min max].to_h { |limit| [limit, DateBound.call(html[limit] || picker[:"#{limit}_date"], control)] }
185
+ end
186
+
187
+ def choices(input, field, multiple)
188
+ key = [@prefix, field[:name]].compact.join(".")
189
+ source = collection_choices(input, key)
190
+ @schema.choices[key] ||= source
191
+ return {} if @schema.only
192
+
193
+ listing = source.list(Array(field[:value]).map(&:to_s), ReactiveAdmin.config.inline_options_limit)
194
+ attrs = {options: listing[:options], multiple: (true if multiple)}.compact
195
+ return attrs unless listing[:truncated]
196
+
197
+ attrs.merge(control: "typeahead", options_path: Choices.path(@schema.config, key, "form", id: @schema.record_id, parent_id: @schema.parent_id))
198
+ end
199
+
200
+ def truncation(input, field)
201
+ source = collection_choices(input, [@prefix, field[:name]].compact.join("."))
202
+ source.truncated?(ReactiveAdmin.config.inline_options_limit) ? {control: "typeahead"} : {}
203
+ end
204
+
205
+ def collection_choices(input, key)
206
+ return Choices.for(ActiveSupport::TimeZone.all.map { [it.to_s, it.name] }, @view) if input.as == "time_zone"
207
+
208
+ cache = Choices.cache_key(@schema.config, "form", key, @view, id: @schema.record_id, parent_id: @schema.parent_id)
209
+ return Choices.source(input.options[:source], @view, scope: input.options[:scope], object: scope_object, policy: true, cache:) if input.options[:source]
210
+
211
+ collection = input.options[:collection]
212
+ return Choices.for(collection, @view, cache:, policy: true) if collection.is_a?(Proc)
213
+
214
+ raw = input.raw_collection
215
+ if raw.is_a?(ActiveRecord::Relation)
216
+ Choices.for(raw, @view, label: input.label_method, value: input.value_method, policy: true)
217
+ else
218
+ Choices.for(input.collection, @view, cache:)
219
+ end
220
+ end
221
+
222
+ # Inside has_many the parent's form object, matching what the classic input hands to `scope:`.
223
+ def scope_object = (@builder.options[:parent_builder] || @builder).object
224
+
225
+ def json?(input)
226
+ type = @builder.object.class.type_for_attribute(input.method.to_s).type
227
+ JSON_TYPES.include?(type) || current(input).is_a?(Hash) || current(input).is_a?(Array)
228
+ rescue
229
+ false
230
+ end
231
+
232
+ def current(input)
233
+ object = @builder.object
234
+ names = [(input.association_primary_key if input.respond_to?(:association_primary_key)), input.input_name, input.method]
235
+ name = names.find { (it.is_a?(Symbol) || it.is_a?(String)) && object.respond_to?(it) }
236
+ object.public_send(name) if name
237
+ end
238
+
239
+ def value_for(input, control)
240
+ return if control == "password"
241
+
242
+ value = current(input)
243
+ html = input.options[:input_html].to_h
244
+ return serialize(html[:value], control) if value.nil? && html.key?(:value)
245
+
246
+ (control == "boolean" && value.nil? && html.key?(:checked)) ? !!html[:checked] : serialize(value, control)
247
+ end
248
+
249
+ def serialize(value, control)
250
+ case value
251
+ when Time, DateTime, ActiveSupport::TimeWithZone then temporal(value, control)
252
+ when Date then value.iso8601
253
+ when BigDecimal then value.to_s("F")
254
+ when Symbol then value.to_s
255
+ when Hash then value
256
+ when Array then (control == "json") ? value : value.map { serialize(it, control) }
257
+ else attachment_or_choice(value, control)
258
+ end
259
+ end
260
+
261
+ def attachment_or_choice(value, control)
262
+ if value.respond_to?(:attached?)
263
+ {filename: value.filename.to_s} if value.attached?
264
+ else
265
+ (choice?(control) && !value.nil?) ? value.to_s : value
266
+ end
267
+ end
268
+
269
+ def temporal(value, control)
270
+ case control
271
+ when "time" then value.strftime("%H:%M:%S")
272
+ when "date" then value.to_date.iso8601
273
+ else value.iso8601
274
+ end
275
+ end
276
+
277
+ def choice?(control) = CHOICE_CONTROLS.include?(control) || control == "multiselect"
278
+ end
279
+ end
@@ -0,0 +1,116 @@
1
+ module ReactiveAdmin
2
+ # Records `f.has_many`, mirroring ActiveAdmin::HasManyBuilder: one set of fields per existing
3
+ # child plus a template for new ones. Template params carry INDEX_PLACEHOLDER for the client
4
+ # to replace with the new row's index.
5
+ class FormHasMany
6
+ INDEX_PLACEHOLDER = "__INDEX__".freeze
7
+ LAYOUTS = %w[cards compact].freeze
8
+ # Rows holding just one of these read as a list item; anything bigger needs room for its label.
9
+ COMPACT_CONTROLS = %w[text email url phone number select typeahead].freeze
10
+ NO_INPUT = %w[hidden html content].freeze
11
+
12
+ def initialize(recorder, schema, assoc, options)
13
+ @recorder = recorder
14
+ @builder = recorder.builder
15
+ @schema = schema
16
+ @assoc = assoc.to_sym
17
+ @options = options
18
+ @klass = @builder.object.class.reflect_on_association(@assoc).klass
19
+ @schema.nested!(@assoc)
20
+ end
21
+
22
+ def call(&block)
23
+ sortable = @options[:sortable]
24
+ template = (fields(@klass.new, INDEX_PLACEHOLDER, &block) if new_record_label || @schema.only)
25
+ records = @schema.only ? [] : children(sortable).each_with_index.map { |child, index| record(child, index, &block) }
26
+ layout = layout(template, records)
27
+ {
28
+ title: heading(layout, template),
29
+ kind: "has_many",
30
+ name: @assoc.to_s,
31
+ param_key: "#{@assoc}_attributes",
32
+ param: "#{@builder.object_name}[#{@assoc}_attributes]",
33
+ allow_destroy: !!@options[:allow_destroy],
34
+ sortable: sortable&.to_s,
35
+ new_record_label: new_record_label,
36
+ layout:,
37
+ max_rows: @options[:max_rows],
38
+ fields: [],
39
+ template_fields: template,
40
+ records:
41
+ }.compact
42
+ end
43
+
44
+ private
45
+
46
+ # `reactive { nested_layout :assoc, :cards }` wins; otherwise a list when every row is a single control.
47
+ def layout(template, records)
48
+ declared = @schema.config.try(:reactive_options)&.dig(:nested_layout, @assoc)
49
+ return declared if declared
50
+
51
+ rows = [template, *records.map { it[:fields] }].compact
52
+ (rows.any? && !@options[:sortable] && rows.all? { compact_row?(it) }) ? "compact" : "cards"
53
+ end
54
+
55
+ def compact_row?(fields)
56
+ visible = fields.reject { NO_INPUT.include?(it[:control]) }
57
+ visible.one? && COMPACT_CONTROLS.include?(visible.first[:control]) && !visible.first[:multiple]
58
+ end
59
+
60
+ # Without a `heading:`, a list of one control is named for what it holds ("Admin policy" ->
61
+ # "Admin policies"); anything else for the association's model.
62
+ def heading(layout, template)
63
+ return (@options[:heading] if @options[:heading].is_a?(String)) if @options.key?(:heading)
64
+
65
+ label = template.reject { NO_INPUT.include?(it[:control]) }.then { it.first[:label] if it.one? } if layout == "compact" && template
66
+ label.present? ? label.pluralize : @klass.model_name.human(count: AA.plural_many_count)
67
+ end
68
+
69
+ def new_record_label
70
+ case (option = @options.fetch(:new_record, true))
71
+ when String then option
72
+ when true then AA.t("has_many_new", model: @klass.model_name.human)
73
+ end
74
+ end
75
+
76
+ def children(sortable)
77
+ records = @builder.object.public_send(@assoc).to_a
78
+ return records unless sortable
79
+
80
+ records.sort_by { [it.public_send(sortable) || Float::INFINITY, it.id || Float::INFINITY] }
81
+ end
82
+
83
+ def record(child, index, &block)
84
+ nested = nested_builder(child, index)
85
+ fields = fields_for(nested, index, &block)
86
+ fields << FormField.hidden_id(nested, child) if child.persisted?
87
+ {id: (child.to_param.to_s if child.persisted?), param: nested.object_name, fields:, destroy: destroyable?(child)}.compact
88
+ end
89
+
90
+ def fields(child, index, &block) = fields_for(nested_builder(child, index), index, &block)
91
+
92
+ def fields_for(nested, index, &block)
93
+ recorder = FormRecorder.build(nested, @schema, prefix: @assoc.to_s)
94
+ sortable = @options[:sortable]
95
+ recorder.record do
96
+ block.call(recorder, index)
97
+ recorder.input(sortable, as: :hidden) if sortable
98
+ end
99
+ recorder.fields
100
+ end
101
+
102
+ def nested_builder(child, index)
103
+ nested = nil
104
+ @builder.fields_for(@assoc, child, child_index: index) { nested = it }
105
+ nested
106
+ end
107
+
108
+ def destroyable?(child)
109
+ case (option = @options[:allow_destroy])
110
+ when Symbol, String then child.public_send(option)
111
+ when Proc then option.call(child)
112
+ else !!option
113
+ end
114
+ end
115
+ end
116
+ end