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,79 @@
1
+ module ReactiveAdmin
2
+ # Typeahead matching over a relation (ILIKE on Postgres, LOWER() LIKE elsewhere): every token of the term must start a word in
3
+ # at least one search column. Exact matches rank first, then prefix matches.
4
+ class Search
5
+ UUID = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
6
+ TEXT_TYPES = %i[string text citext].freeze
7
+ COMMON_COLUMNS = %i[name given_name family_name first_name last_name].freeze
8
+
9
+ # Resolution order: source, the model's `reactive do search ... end`, the model itself, conventions.
10
+ def self.columns_for(klass, source = nil, label_column: nil)
11
+ names = source&.search || registered(klass) || (klass.reactive_admin_search_columns if klass.respond_to?(:reactive_admin_search_columns))
12
+ names ||= [label_column, *AA.display_name_methods, *COMMON_COLUMNS]
13
+ names.compact.map(&:to_s).uniq.select { text_column?(klass, it) }
14
+ end
15
+
16
+ def self.text_column?(klass, name) = klass.columns_hash[name.to_s]&.type&.in?(TEXT_TYPES) || false
17
+
18
+ def self.registered(klass)
19
+ AA.resource_for(Registry.namespace, klass)&.reactive_options&.[](:search)
20
+ end
21
+
22
+ def initialize(scope, columns:, value_column: nil, by_primary_key: true)
23
+ @scope = scope
24
+ @columns = columns
25
+ @value_column = value_column
26
+ @by_primary_key = by_primary_key
27
+ @klass = scope.klass
28
+ end
29
+
30
+ # Returns [records, truncated].
31
+ def call(term, limit:, offset: 0)
32
+ term = term.to_s.strip
33
+ records = ranked(filtered(term), term).offset(offset).limit(limit + 1).to_a
34
+ [records.first(limit), records.size > limit]
35
+ end
36
+
37
+ private
38
+
39
+ def filtered(term)
40
+ tokens = term.split
41
+ return @scope if tokens.empty?
42
+
43
+ match = tokens.map { token_match(it) }.reduce(:and)
44
+ id = id_match(term)
45
+ @scope.where(id ? match.or(id) : match)
46
+ end
47
+
48
+ def token_match(token)
49
+ like = @klass.sanitize_sql_like(token)
50
+ @columns.map { column(it) }.flat_map { [it.matches("#{like}%", nil, false), it.matches("% #{like}%", nil, false)] }.reduce(:or)
51
+ end
52
+
53
+ # Pasting an id finds its record, whichever column the label comes from.
54
+ def id_match(term)
55
+ [@value_column, (@klass.primary_key if @by_primary_key && @klass.primary_key.is_a?(String))].compact.uniq.filter_map do |key|
56
+ type = @klass.type_for_attribute(key)
57
+ column(key).eq(type.cast(term)) if (type.type == :uuid && term.match?(UUID)) || (type.type == :integer && term.match?(/\A\d+\z/))
58
+ end.reduce(:or)
59
+ end
60
+
61
+ # DISTINCT scopes can only order by what they select.
62
+ def ranked(scope, term)
63
+ return scope if term.empty? || scope.distinct_value || @columns.empty?
64
+
65
+ like = "#{@klass.sanitize_sql_like(term)}%"
66
+ exact = @columns.map { "lower(#{quoted(it)}) = lower(:term)" }
67
+ exact << "CAST(#{quoted(@value_column)} AS TEXT) = :term" if @value_column
68
+ prefix = @columns.map { postgres? ? "#{quoted(it)} ILIKE :like" : "lower(#{quoted(it)}) LIKE lower(:like)" }
69
+ rank = @klass.sanitize_sql_array(["CASE WHEN #{exact.join(" OR ")} THEN 0 WHEN #{prefix.join(" OR ")} THEN 1 ELSE 2 END", {term:, like:}])
70
+ scope.reorder(Arel.sql(rank), *scope.order_values)
71
+ end
72
+
73
+ def postgres? = @klass.connection.adapter_name.match?(/postg/i)
74
+
75
+ def column(name) = @klass.arel_table[name]
76
+
77
+ def quoted(name) = "#{@klass.quoted_table_name}.#{@klass.connection.quote_column_name(name)}"
78
+ end
79
+ end
@@ -0,0 +1,31 @@
1
+ module ReactiveAdmin
2
+ # Adds a Server-Timing header (total app time and time spent in SQL) to API responses.
3
+ class ServerTiming
4
+ KEY = :reactiveadmin_db_ms
5
+ STATE = ActiveSupport::IsolatedExecutionState
6
+
7
+ # One global subscriber that only counts while a request has opened a counter on its own
8
+ # thread/fiber, so concurrent requests don't see each other's queries.
9
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |event|
10
+ STATE[KEY] += event.duration if STATE[KEY] && event.payload[:name] != "SCHEMA"
11
+ end
12
+
13
+ def initialize(app)
14
+ @app = app
15
+ end
16
+
17
+ def call(env)
18
+ return @app.call(env) unless env["PATH_INFO"].start_with?("#{ReactiveAdmin.config.mount_path}/")
19
+
20
+ outer = STATE[KEY]
21
+ STATE[KEY] = 0.0
22
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
23
+ status, headers, body = @app.call(env)
24
+ app_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000
25
+ headers["Server-Timing"] = format("db;dur=%.1f, app;dur=%.1f", STATE[KEY], app_ms)
26
+ [status, headers, body]
27
+ ensure
28
+ STATE[KEY] = outer
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,88 @@
1
+ module ReactiveAdmin
2
+ class ShowPayload
3
+ # Arbre context mirroring ActiveAdmin::Views::Pages::Show#attributes_table.
4
+ class Page < AA.arbre_element
5
+ include PageForms::ArbreForms
6
+
7
+ def attributes_table(*args, &block)
8
+ options = args.extract_options!
9
+ title = if options.key?(:title)
10
+ AA.render_or_call(helpers, resource, options[:title])
11
+ else
12
+ AA.resource_text(active_admin_config, :details)
13
+ end
14
+ panel(title) { attributes_table_for(resource, *args, &block) }
15
+ end
16
+
17
+ # Never `attributes_table` with no columns: AA reads that as "all of them".
18
+ def default_main_content(&)
19
+ return ImplicitDefaults.blocked("show") if ImplicitDefaults.strict?
20
+
21
+ columns = ImplicitDefaults.columns(active_admin_config, where: "show")
22
+ helpers.reactiveadmin_implicit_text = ImplicitDefaults.text_columns(active_admin_config)
23
+ attributes_table(*columns, &) if columns.any?
24
+ end
25
+ end
26
+
27
+ def initialize(controller)
28
+ @controller = controller
29
+ @config = AA.config_of(controller)
30
+ @view = ValuePayload.install(Masking.install(controller.view_context, @config), @config).extend(ImplicitDefaults::Display)
31
+ @authorizer = Authorizer.for(controller)
32
+ end
33
+
34
+ def as_json(*)
35
+ record = AA.resource(@controller)
36
+ presenter = AA.page_presenter(@config, :show)
37
+ links = ActionLinks.new(host: @controller.request.host, base_url: @controller.request.base_url, authorizer: @authorizer, subject: record)
38
+ derived = Actions.new(@config, @authorizer, record, view: @view)
39
+ generated = derived.as_json
40
+ items = ActionItems.new(@controller, "show", subject: record).call(generated)
41
+ Degradation.attach({
42
+ resource: Registry.route_key(@config),
43
+ id: record.to_param.to_s,
44
+ paths: Paths.record(@config, record),
45
+ title: title(record, presenter),
46
+ display_name: Values.display_name(record, @view),
47
+ permissions: Permissions.new(@config, @authorizer).record(record),
48
+ actions: generated + items + derived.exposed(items),
49
+ layout: NodeRegistry.with_scope { HtmlNodes.layout(render_layout(record, presenter, forms: true), src: Paths.record(@config, record)[:show], host: @controller.request.host, links:, resource: @config.resource_name) }
50
+ }.merge(sidebars(record)))
51
+ end
52
+
53
+ # Attributes the page shows as symbol rows: the allowlist for `_value`.
54
+ def rendered_attributes(record)
55
+ render_layout(record, AA.page_presenter(@config, :show))
56
+ @view.reactiveadmin_attributes
57
+ end
58
+
59
+ private
60
+
61
+ def sidebars(record)
62
+ list = Sidebars.new(@controller, "show", src: Paths.record(@config, record)[:show], subject: record).as_json
63
+ list.any? ? {sidebars: list} : {}
64
+ end
65
+
66
+ def title(record, presenter)
67
+ custom = presenter && presenter[:title]
68
+ text = custom ? AA.render_or_call(@view, record, custom) : AA.display_name(@view, record)
69
+ CGI.unescapeHTML(text.to_s)
70
+ end
71
+
72
+ # `forms` records the Formtastic forms of the block into form nodes; `_value` only needs the attributes.
73
+ def render_layout(record, presenter, forms: false)
74
+ page = new_page
75
+ run = -> { presenter&.block ? page.instance_exec(record, &presenter.block) : page.default_main_content }
76
+ forms ? PageForms.recording(@view, @controller, &run) : run.call
77
+ page.arbre_context.to_s
78
+ rescue => e
79
+ Rails.logger.warn("[reactiveadmin] #{@config.resource_name} show block fell back to defaults: #{e.class} at #{e.backtrace&.first}")
80
+ Degradation.record(kind: :show_block_failed, where: "show", reason: "Show block raised #{e.class}; showing default attributes")
81
+ page = new_page
82
+ page.default_main_content
83
+ page.arbre_context.to_s
84
+ end
85
+
86
+ def new_page = AA.arbre_context(@controller.view_assigns, @view).insert_tag(Page)
87
+ end
88
+ end
@@ -0,0 +1,34 @@
1
+ module ReactiveAdmin
2
+ # A resource's AA sidebar sections for one page, rendered in the page's view context and walked
3
+ # into nodes. AA's own filters and search-status sections are left out: the client has its own.
4
+ class Sidebars
5
+ BUILT_IN = %w[filters search_status].freeze
6
+
7
+ def initialize(controller, action, src:, subject: nil)
8
+ @controller = controller
9
+ @action = action
10
+ @src = src
11
+ @config = AA.config_of(controller)
12
+ @view = controller.view_context
13
+ @links = ActionLinks.new(host: controller.request.host, base_url: controller.request.base_url, authorizer: Authorizer.for(controller), subject: subject || @config.resource_class)
14
+ end
15
+
16
+ def as_json(*)
17
+ sections = AA.sidebar_sections(@config).reject { BUILT_IN.include?(it.name) }.sort_by(&:priority)
18
+ sections.filter_map { render(it) }
19
+ end
20
+
21
+ private
22
+
23
+ def render(section)
24
+ rendered = AA.render_sidebar(section, @action, @controller.view_assigns, @view) or return
25
+
26
+ {title: rendered[:title], layout: HtmlNodes.layout(rendered[:html], src: @src, host: @controller.request.host, links: @links, title: rendered[:title], resource: @config.resource_name)}
27
+ rescue => e
28
+ Rails.logger.warn("[reactiveadmin] #{@config.resource_name} sidebar #{section.name} skipped: #{e.class} at #{e.backtrace&.first}")
29
+ ReactiveAdmin.diagnostics.record(:sidebar_failed, resource: @config.resource_name, section: section.name)
30
+ Degradation.record(kind: :sidebar_dropped, where: "#{@action}/sidebar[#{section.name}]", reason: "Sidebar raised #{e.class}; left out")
31
+ nil
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,55 @@
1
+ module ReactiveAdmin
2
+ # The AA namespace's settings (title, logout, formats, ...) evaluated for the current user.
3
+ class Site
4
+ def initialize(controller, menu)
5
+ @view = controller.view_context
6
+ @user = ReactiveAdmin.current_user(controller)
7
+ @menu = menu
8
+ @settings = AA.site_settings(Registry.namespace, @view)
9
+ @host = controller.request.host
10
+ end
11
+
12
+ def as_json(*)
13
+ {
14
+ title: @settings[:title].to_s,
15
+ title_link: @settings[:title_link].presence,
16
+ title_image: asset(@settings[:title_image]),
17
+ favicon: asset(@settings[:favicon]),
18
+ home:,
19
+ logout:,
20
+ utility_menu: @menu.menu(AA.utility_menu),
21
+ current_user: current_user,
22
+ locale: I18n.locale.to_s,
23
+ time_zone: @user.try(:time_zone).presence || Time.zone.name,
24
+ date_format: I18n.t("date.formats.#{localize_format}", default: nil),
25
+ datetime_format: I18n.t("time.formats.#{localize_format}", default: nil),
26
+ footer: @settings[:footer].presence,
27
+ comments: @settings[:comments],
28
+ default_per_page: @settings[:default_per_page],
29
+ max_per_page: @settings[:max_per_page],
30
+ trusted_media_hosts: HtmlPolicy.trusted_hosts
31
+ }
32
+ end
33
+
34
+ private
35
+
36
+ def current_user = @user && {id: @user.id.to_s, display_name: Values.display_label(@user, @view)}
37
+
38
+ def localize_format = AA.localize_format
39
+
40
+ def asset(path) = (@view.asset_path(path) if path.present?)
41
+
42
+ def home
43
+ url = @view.public_send(:"#{@settings[:name]}_root_path")
44
+ Location.for(url, host: @host).slice(:resource, :url)
45
+ rescue NoMethodError
46
+ nil
47
+ end
48
+
49
+ def logout
50
+ return unless (path = @settings[:logout_path])
51
+
52
+ {url: AA.render_or_call(@view, @view, path), method: (@settings[:logout_method] || :get).to_s.downcase}
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,129 @@
1
+ require "json"
2
+
3
+ module ReactiveAdmin
4
+ # Where the host's markup uses classes and inline styles the walker has no typed layout for, with
5
+ # the exact strings, the source lines and what to use instead. Two views of the same problem:
6
+ # `sampled` is what the API degrades on for the sampled records (grouped by resource), and
7
+ # `scanned` is every style and utility class in the host's admin source, whether or not a sample
8
+ # reached it. Output names resources, files and CSS strings only, never record data.
9
+ class StyleReport
10
+ KINDS = %w[unknown_layout_class inline_style_ignored].freeze
11
+ SCAN = %w[app/admin/**/* app/views/admin/**/*].freeze
12
+ STYLE_ATTRIBUTE = /\bstyle(?:=|:\s*|\s*=>\s*)(?:"([^"]*)"|'([^']*)')/
13
+ CLASS_ATTRIBUTE = /\bclass(?:=|:\s*|\s*=>\s*)(?:"([^"]*)"|'([^']*)')/
14
+
15
+ Finding = Data.define(:resource, :kind, :value, :untranslated, :count, :paths, :sources, :advice)
16
+ Occurrence = Data.define(:file, :line, :kind, :value, :untranslated, :advice)
17
+
18
+ def self.run(**) = new(**).run
19
+
20
+ def initialize(user: nil, sample: true)
21
+ @user = user
22
+ @sample = sample
23
+ end
24
+
25
+ def run
26
+ Rails.application.reload_routes_unless_loaded
27
+ entries = StyleSources.trace { Doctor.run(user: @user, sample: @sample)[:diagnostics] }
28
+ {sampled: sampled(entries), scanned: scanned}
29
+ end
30
+
31
+ private
32
+
33
+ def sampled(entries)
34
+ entries.select { KINDS.include?(it[:kind]) }.group_by { [it[:resource].presence || "(unlabelled)", it[:kind], it[:class] || it[:style]] }.map do |(resource, kind, value), group|
35
+ untranslated = (kind == "inline_style_ignored") ? group.first[:ignored] : value
36
+ Finding.new(resource:, kind:, value:, untranslated:, count: group.size, paths: group.pluck(:path).first(3),
37
+ sources: group.filter_map { it[:source] }.flat_map { it.split(", ") }.uniq, advice: advice(kind, untranslated))
38
+ end.sort_by { [it.resource, it.kind, it.value] }
39
+ end
40
+
41
+ def scanned
42
+ Rails.root.glob(SCAN).sort.select(&:file?).flat_map { |path| occurrences(path) }
43
+ end
44
+
45
+ def occurrences(path)
46
+ file = path.relative_path_from(Rails.root).to_s
47
+ path.each_line.with_index(1).flat_map do |text, line|
48
+ text = text.scrub
49
+ [*strings(text, STYLE_ATTRIBUTE).filter_map { occurrence(file, line, "inline_style_ignored", it) },
50
+ *strings(text, CLASS_ATTRIBUTE).filter_map { occurrence(file, line, "unknown_layout_class", it) }]
51
+ end
52
+ end
53
+
54
+ def strings(text, pattern) = text.scan(pattern).map { it.compact.first }.reject { it.include?("\#{") }
55
+
56
+ # Only what the walker can't translate fully is a finding; `value` keeps the exact string.
57
+ def occurrence(file, line, kind, value)
58
+ untranslated = (kind == "inline_style_ignored") ? InlineStyle.parse(value).unknown.join("; ") : LayoutClasses.parse(value).unknown.join(" ")
59
+ Occurrence.new(file:, line:, kind:, value:, untranslated:, advice: advice(kind, untranslated)) if untranslated.present?
60
+ end
61
+
62
+ def advice(kind, untranslated)
63
+ if kind == "inline_style_ignored"
64
+ untranslated.split("; ").map { "#{it.split(":").first}: #{InlineStyle.advice(it)}" }.uniq.join("; ")
65
+ else
66
+ untranslated.split.map { "#{it}: #{LayoutClasses.advice(it)}" }.join("; ")
67
+ end
68
+ end
69
+
70
+ # Markdown and JSON renderings.
71
+ class Renderer
72
+ def initialize(report) = @report = report
73
+
74
+ def to_json(*) = JSON.pretty_generate(summary: summary, sampled: @report[:sampled].map(&:to_h), scanned: @report[:scanned].map(&:to_h))
75
+
76
+ def summary
77
+ sampled = @report[:sampled]
78
+ scanned = @report[:scanned]
79
+ {sampled_findings: sampled.size, sampled_occurrences: sampled.sum(&:count), sampled_resources: sampled.map(&:resource).uniq.size,
80
+ scanned_untranslated: scanned.size, scanned_files: scanned.map(&:file).uniq.size}
81
+ end
82
+
83
+ def to_markdown
84
+ s = summary
85
+ lines = ["# Styles report", "",
86
+ "Classes and inline styles with no typed layout, from `rake reactiveadmin:styles`. Values are CSS, not data.", "",
87
+ "**#{s[:sampled_findings]}** distinct findings (#{s[:sampled_occurrences]} occurrences) in #{s[:sampled_resources]} sampled resources; " \
88
+ "**#{s[:scanned_untranslated]}** untranslatable strings in #{s[:scanned_files]} source files.", "",
89
+ "## Sampled: what the API degrades on", ""]
90
+ lines.concat(@report[:sampled].empty? ? ["None."] : sampled_lines)
91
+ lines.concat(["", "## Source scan: every untranslatable string in `app/admin` and `app/views/admin`", ""])
92
+ lines.concat(@report[:scanned].empty? ? ["None."] : scanned_lines)
93
+ lines.join("\n") + "\n"
94
+ end
95
+
96
+ private
97
+
98
+ def sampled_lines
99
+ @report[:sampled].group_by(&:resource).flat_map do |resource, findings|
100
+ ["### #{resource}", "", "| Kind | Value | Untranslated | Count | Source | Instead |", "| --- | --- | --- | ---: | --- | --- |",
101
+ *findings.map { "| #{it.kind} | #{cell(it.value)} | #{cell(it.untranslated)} | #{it.count} | #{cell(it.sources.first(3).join(", "))} | #{cell(it.advice)} |" }, ""]
102
+ end
103
+ end
104
+
105
+ def scanned_lines
106
+ @report[:scanned].group_by(&:file).flat_map do |file, items|
107
+ ["### #{file}", "", "| Line | Kind | Value | Untranslated | Instead |", "| ---: | --- | --- | --- | --- |",
108
+ *items.map { "| #{it.line} | #{it.kind} | #{cell(it.value)} | #{cell(it.untranslated)} | #{cell(it.advice)} |" }, ""]
109
+ end
110
+ end
111
+
112
+ def cell(text) = text.to_s.empty? ? "" : "`#{text.to_s.tr("|`", "/'")}`"
113
+ end
114
+
115
+ module CLI
116
+ module_function
117
+
118
+ def run(env = ENV, out: $stdout)
119
+ report = StyleReport.run(sample: env["SAMPLE"] != "0")
120
+ renderer = Renderer.new(report)
121
+ text = (env["FORMAT"] == "json") ? renderer.to_json : renderer.to_markdown
122
+ return out.puts(text) unless env["OUT"].present?
123
+
124
+ File.write(env["OUT"], text)
125
+ out.puts("styles report written to #{env["OUT"]}: #{renderer.summary}")
126
+ end
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,83 @@
1
+ module ReactiveAdmin
2
+ # Finds the host source lines behind a class or inline style, for `doctor`. While tracing, Arbre
3
+ # tags note the DSL line that built them; markup from ERB and helpers is found by scanning the
4
+ # app's templates. Only runs under doctor, so requests never pay for it.
5
+ module StyleSources
6
+ KEY = :reactiveadmin_style_sources
7
+ STATE = ActiveSupport::IsolatedExecutionState
8
+ SCAN = "app/**/*.{rb,erb,arb,haml,slim}".freeze
9
+ LIMIT = 3
10
+ OWN = File.expand_path("..", __dir__)
11
+
12
+ # Arbre calls `build` for every tag, with the attributes the DSL line passed.
13
+ module Tracer
14
+ def build(*args, &block)
15
+ super.tap { StyleSources.note(self) if StyleSources.tracing? }
16
+ end
17
+ ruby2_keywords :build
18
+ end
19
+
20
+ Line = Data.define(:file, :number, :text)
21
+
22
+ module_function
23
+
24
+ def tracing? = !STATE[KEY].nil?
25
+
26
+ def trace
27
+ return yield if tracing?
28
+
29
+ install
30
+ STATE[KEY] = {}
31
+ begin
32
+ yield
33
+ ensure
34
+ STATE[KEY] = nil
35
+ @lines = nil
36
+ end
37
+ end
38
+
39
+ # "app/admin/x.rb:12, app/views/admin/y.erb:3" for a class token or a whole style attribute of
40
+ # a resource's page (by `resource_name`, as the walker labels it).
41
+ def locate(string, resource: nil)
42
+ string = string.to_s.squish
43
+ return if string.empty? || !tracing?
44
+
45
+ (STATE[KEY][[resource.to_s, string]]&.to_a.presence || scan(string)).first(LIMIT).join(", ").presence
46
+ end
47
+
48
+ def note(tag)
49
+ style = tag.get_attribute(:style).to_s.squish
50
+ strings = [style, *tag.class_names.split].reject(&:empty?)
51
+ where = origin if strings.any?
52
+ return unless where
53
+
54
+ resource = tag.arbre_context.helpers.try(:active_admin_config)&.resource_name.to_s
55
+ strings.each { (STATE[KEY][[resource, it]] ||= Set.new) << where }
56
+ end
57
+
58
+ def origin
59
+ root = "#{Rails.root}/"
60
+ frame = caller_locations.find do |location|
61
+ path = location.absolute_path.to_s
62
+ path.start_with?(root) && !path.start_with?(OWN) && %w[/gems/ /vendor/].none? { |part| path.include?(part) }
63
+ end
64
+ "#{frame.absolute_path.delete_prefix(root)}:#{frame.lineno}" if frame
65
+ end
66
+
67
+ def install
68
+ AA.trace_arbre_tags(Tracer)
69
+ end
70
+
71
+ def scan(string)
72
+ pattern = /(?<![\w:\/\[-])#{Regexp.escape(string)}(?![\w-])/
73
+ lines.select { it.text.match?(pattern) }.map { "#{it.file}:#{it.number}" }
74
+ end
75
+
76
+ def lines
77
+ @lines ||= Rails.root.glob(SCAN).sort.flat_map do |path|
78
+ file = path.relative_path_from(Rails.root).to_s
79
+ path.each_line.with_index(1).map { |text, number| Line.new(file:, number:, text: text.scrub) }
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,126 @@
1
+ module ReactiveAdmin
2
+ # Shared by resource and page controllers: GET actions that render a template answer natively
3
+ # (a FormResponse) when the ladder says so, and so does the re-render after a failed write.
4
+ module TemplateActions
5
+ EXPLICIT_OUTPUT = %i[json plain body text html xml js inline file nothing].freeze
6
+
7
+ private
8
+
9
+ # A read-only template is only answered natively for a GET: a write that renders it again stays classic.
10
+ def native_template?(template)
11
+ decision = Ladder.for_template(active_admin_config, template_path(template))
12
+ decision.native? && (!decision.read_only || request.get?)
13
+ end
14
+
15
+ def template_path(template) = template.to_s.include?("/") ? template.to_s : "#{controller_path}/#{template}"
16
+
17
+ def template_render?(args) = args.none? { it.is_a?(Hash) && it.keys.intersect?(EXPLICIT_OUTPUT) }
18
+
19
+ def rendered_template(args) = rendered_target(args).split("/").last.to_s
20
+
21
+ def rendered_template_path(args) = template_path(rendered_target(args))
22
+
23
+ def rendered_target(args)
24
+ target = args.first
25
+ target = target[:action] || target[:template] if target.is_a?(Hash)
26
+ target.to_s
27
+ end
28
+
29
+ # `context=template&field=` asks the same action for one field's options, as `_options` does for forms.
30
+ def render_native_template(template)
31
+ return render_read_only_template(template_path(template)) if Ladder.for_template(active_admin_config, template_path(template)).read_only
32
+
33
+ searching = params[:context] == "template" && params[:field].present?
34
+ form = TemplateForm.new(self, template_path(template), only: (params[:field] if searching))
35
+ if searching
36
+ render json: TemplateOptions.new(self, form.choices(params[:field])).as_json, content_type: "application/json"
37
+ else
38
+ render_collected("form") { recorded(form, template_path(template)) }
39
+ end
40
+ rescue TemplateForm::Unsupported
41
+ render_api_error(:unsupported, "This action renders an HTML page; use the classic admin", 501)
42
+ end
43
+
44
+ # What the static ladder took for read-only markup may render controls: it is a frame from now on.
45
+ def render_read_only_template(path)
46
+ render_collected("template") { recorded(TemplateContent.new(self, path), path) }
47
+ rescue TemplateForm::Unsupported
48
+ Ladder.downgrade!(path)
49
+ render_api_error(:unsupported, "This action renders an HTML page; use the classic admin", 501)
50
+ end
51
+
52
+ # A template that can't be recorded is shown as a frame from now on: this answer is the same
53
+ # "use the classic admin" as for an unsupported one, never a 500.
54
+ def recorded(form, path)
55
+ form.as_json
56
+ rescue ActionView::Template::Error => e
57
+ raise if [AA::AccessDenied, ActiveRecord::RecordNotFound].any? { e.cause.is_a?(it) }
58
+
59
+ Rails.logger.warn("[reactiveadmin] #{controller_path} #{path} not recordable: #{e.cause.class} at #{e.backtrace&.first}")
60
+ Degradation.record(kind: :template_form_failed, where: "form", reason: "Template raised #{e.cause.class} while recording; shown as a frame")
61
+ Ladder.downgrade!(path)
62
+ raise TemplateForm::Unsupported, "#{path} could not be recorded"
63
+ end
64
+
65
+ # Renders a payload built in the block, with whatever it fell back to listed as `degraded`.
66
+ def render_collected(action, &)
67
+ render_body(collected(action, &))
68
+ end
69
+
70
+ def collected(action, &)
71
+ Provenance.with_scope { Degradation.with_collection(resource: active_admin_config.resource_name, action:, controller: self, &) }
72
+ end
73
+
74
+ def render_body(body)
75
+ response.set_header(Degradation::HEADER, Array(body[:degraded]).size.to_s)
76
+ render json: body, content_type: "application/json"
77
+ end
78
+
79
+ # A template rendered by name: the form itself on a GET. After a write it is the same page again,
80
+ # as classic shows it (a search's results), unless the write was rejected.
81
+ def render_native_page_or_rejection(path)
82
+ return render_native_template(path) if request.get?
83
+
84
+ form = TemplateForm.new(self, path)
85
+ body = collected("form") { template_form_json(form) }
86
+ return render_body(body) if body && !rejected?(form)
87
+
88
+ render_invalid(form: body, base: form_messages(form))
89
+ end
90
+
91
+ # What the form's own objects say (a search object that failed validation); the record's errors are
92
+ # reported by render_invalid itself.
93
+ def form_messages(form)
94
+ record = AA.resource_ivar(self)
95
+ form.objects.reject { it.equal?(record) }.flat_map { it.try(:errors)&.full_messages.to_a }
96
+ end
97
+
98
+ # An alert flash or an object with errors says the write didn't take; a page with neither is an answer.
99
+ def rejected?(form)
100
+ return true if flash.to_hash.values_at("alert", "error").any?(&:present?)
101
+
102
+ [*form.objects, (rejected_record if respond_to?(:rejected_record, true))].any? { it.respond_to?(:errors) && it.errors.any? }
103
+ end
104
+
105
+ # The options endpoint's paging and lookup over choices a template form produced.
106
+ class TemplateOptions < OptionsPayload
107
+ def initialize(controller, source)
108
+ super(controller)
109
+ @source = source
110
+ end
111
+
112
+ private
113
+
114
+ def choices = @source
115
+ end
116
+
117
+ # The form a write rendered its template with; the response is still valid without it.
118
+ def template_form_json(form)
119
+ form.as_json
120
+ rescue => e
121
+ Rails.logger.warn("[reactiveadmin] #{controller_path} #{action_name} form unavailable: #{e.class} at #{e.backtrace&.first}")
122
+ Degradation.record(kind: :template_form_failed, where: "form", reason: "Form for the write unavailable (#{e.class})")
123
+ nil
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,49 @@
1
+ module ReactiveAdmin
2
+ # A read-only template of a custom GET action, answered natively as a PageResponse: its html walked
3
+ # into the same typed nodes as a show page. A template that turns out to hold anything to intercept
4
+ # (a form, a button, a link that acts) is Unsupported and stays a frame.
5
+ class TemplateContent
6
+ INTERACTIVE = "form, input, select, textarea, button, fieldset, a[data-method], a[data-remote], a[data-confirm]".freeze
7
+
8
+ def initialize(controller, template)
9
+ @controller = controller
10
+ @template = template
11
+ @config = AA.config_of(controller)
12
+ end
13
+
14
+ def as_json(*)
15
+ NodeRegistry.with_scope do
16
+ fragment = HtmlPolicy.parse(render) or raise TemplateForm::Unsupported, "#{@template} is too complex to display"
17
+ raise TemplateForm::Unsupported, "#{@template} has controls to intercept" if fragment.at_css(INTERACTIVE) || Ladder.script?(fragment.to_html)
18
+
19
+ title = leading_heading(fragment)
20
+ Degradation.attach({key:, title: title || default_title, layout: nodes(fragment), actions: []})
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ def render
27
+ @controller.lookup_context.formats = [:html]
28
+ @controller.view_context.render(template: @template, layout: false)
29
+ end
30
+
31
+ def nodes(fragment)
32
+ request = @controller.request
33
+ links = ActionLinks.new(host: request.host, base_url: request.base_url, authorizer: Authorizer.for(@controller), subject: AA.resource_ivar(@controller) || @config)
34
+ HtmlNodes.nodes(fragment.to_html, host: request.host, links:, frame_src: request.path.delete_prefix(ReactiveAdmin.config.mount_path), resource: key)
35
+ end
36
+
37
+ # The page's title, as a form's first heading is: taken out of the content.
38
+ def leading_heading(fragment)
39
+ heading = fragment.element_children.first
40
+ return unless heading&.name&.match?(/\Ah[1-4]\z/)
41
+
42
+ heading.text.strip.presence&.tap { heading.remove }
43
+ end
44
+
45
+ def key = AA.page?(@config) ? @config.underscored_resource_name : Registry.route_key(@config)
46
+
47
+ def default_title = AA.t(@controller.action_name, default: @controller.action_name.to_s.titleize)
48
+ end
49
+ end