hyper-admin 1.0.0__py3-none-any.whl

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 (442) hide show
  1. hyper_admin-1.0.0.dist-info/METADATA +366 -0
  2. hyper_admin-1.0.0.dist-info/RECORD +442 -0
  3. hyper_admin-1.0.0.dist-info/WHEEL +4 -0
  4. hyper_admin-1.0.0.dist-info/entry_points.txt +2 -0
  5. hyper_admin-1.0.0.dist-info/licenses/LICENSE +21 -0
  6. hyperadmin/__init__.py +52 -0
  7. hyperadmin/__main__.py +21 -0
  8. hyperadmin/adapters/__init__.py +28 -0
  9. hyperadmin/adapters/_estimate.py +33 -0
  10. hyperadmin/adapters/_filter_clause.py +9 -0
  11. hyperadmin/adapters/_occ.py +44 -0
  12. hyperadmin/adapters/_relation_loading.py +23 -0
  13. hyperadmin/adapters/_search.py +84 -0
  14. hyperadmin/adapters/filtering.py +86 -0
  15. hyperadmin/adapters/introspection.py +239 -0
  16. hyperadmin/adapters/registry.py +37 -0
  17. hyperadmin/adapters/schema.py +239 -0
  18. hyperadmin/adapters/sqlalchemy.py +423 -0
  19. hyperadmin/adapters/sqlmodel.py +650 -0
  20. hyperadmin/auth/__init__.py +156 -0
  21. hyperadmin/auth/_types.py +52 -0
  22. hyperadmin/auth/backend.py +37 -0
  23. hyperadmin/auth/bridge.py +351 -0
  24. hyperadmin/auth/exceptions.py +124 -0
  25. hyperadmin/auth/middleware.py +287 -0
  26. hyperadmin/auth/models.py +245 -0
  27. hyperadmin/auth/oauth/__init__.py +81 -0
  28. hyperadmin/auth/oauth/backend.py +611 -0
  29. hyperadmin/auth/oauth/providers.py +214 -0
  30. hyperadmin/auth/oauth/refresh.py +126 -0
  31. hyperadmin/auth/oauth/session.py +96 -0
  32. hyperadmin/auth/oauth/tokens.py +114 -0
  33. hyperadmin/auth/oauth/views.py +306 -0
  34. hyperadmin/auth/oauth/wiring.py +131 -0
  35. hyperadmin/auth/otp.py +189 -0
  36. hyperadmin/auth/permissions.py +232 -0
  37. hyperadmin/auth/session.py +81 -0
  38. hyperadmin/auth/session_middleware.py +164 -0
  39. hyperadmin/auth/token_handoff.py +452 -0
  40. hyperadmin/auth/user_cache.py +222 -0
  41. hyperadmin/auth/views.py +581 -0
  42. hyperadmin/core/__init__.py +76 -0
  43. hyperadmin/core/actions.py +151 -0
  44. hyperadmin/core/adapters.py +883 -0
  45. hyperadmin/core/app.py +1437 -0
  46. hyperadmin/core/auth.py +97 -0
  47. hyperadmin/core/bulk_results.py +28 -0
  48. hyperadmin/core/cache.py +68 -0
  49. hyperadmin/core/choices.py +38 -0
  50. hyperadmin/core/concurrency.py +107 -0
  51. hyperadmin/core/csrf.py +108 -0
  52. hyperadmin/core/discovery.py +161 -0
  53. hyperadmin/core/display.py +172 -0
  54. hyperadmin/core/fields.py +158 -0
  55. hyperadmin/core/fieldsets.py +22 -0
  56. hyperadmin/core/filtering.py +403 -0
  57. hyperadmin/core/filters_compat.py +78 -0
  58. hyperadmin/core/inlines.py +64 -0
  59. hyperadmin/core/introspection.py +280 -0
  60. hyperadmin/core/layouts.py +17 -0
  61. hyperadmin/core/lifecycle.py +278 -0
  62. hyperadmin/core/model.py +189 -0
  63. hyperadmin/core/navigation.py +354 -0
  64. hyperadmin/core/options.py +391 -0
  65. hyperadmin/core/palette.py +94 -0
  66. hyperadmin/core/panels.py +227 -0
  67. hyperadmin/core/plugin_wiring.py +205 -0
  68. hyperadmin/core/plugins.py +588 -0
  69. hyperadmin/core/primary_key.py +118 -0
  70. hyperadmin/core/rate_limit.py +90 -0
  71. hyperadmin/core/registry.py +129 -0
  72. hyperadmin/core/relation_loading.py +25 -0
  73. hyperadmin/core/schema.py +83 -0
  74. hyperadmin/core/sensitive.py +134 -0
  75. hyperadmin/core/settings.py +377 -0
  76. hyperadmin/core/storage_paths.py +54 -0
  77. hyperadmin/core/timezones.py +137 -0
  78. hyperadmin/core/uploads.py +16 -0
  79. hyperadmin/db.py +160 -0
  80. hyperadmin/discover.py +54 -0
  81. hyperadmin/filters/__init__.py +39 -0
  82. hyperadmin/filters/base.py +246 -0
  83. hyperadmin/filters/boolean.py +105 -0
  84. hyperadmin/filters/choice.py +74 -0
  85. hyperadmin/filters/date.py +265 -0
  86. hyperadmin/filters/relation.py +69 -0
  87. hyperadmin/filters/saved_views.py +203 -0
  88. hyperadmin/i18n/__init__.py +50 -0
  89. hyperadmin/i18n/loader.py +150 -0
  90. hyperadmin/i18n/middleware.py +159 -0
  91. hyperadmin/i18n/validation_messages.py +264 -0
  92. hyperadmin/loadtest/__init__.py +28 -0
  93. hyperadmin/loadtest/batch.py +263 -0
  94. hyperadmin/loadtest/checkpoint.py +168 -0
  95. hyperadmin/loadtest/generators/__init__.py +29 -0
  96. hyperadmin/loadtest/generators/auth.py +86 -0
  97. hyperadmin/loadtest/generators/erp.py +177 -0
  98. hyperadmin/loadtest/plan.py +189 -0
  99. hyperadmin/loadtest/pool.py +113 -0
  100. hyperadmin/loadtest/progress.py +150 -0
  101. hyperadmin/locale/ar/LC_MESSAGES/messages.mo +0 -0
  102. hyperadmin/locale/ar/LC_MESSAGES/messages.po +2139 -0
  103. hyperadmin/locale/de/LC_MESSAGES/messages.mo +0 -0
  104. hyperadmin/locale/de/LC_MESSAGES/messages.po +2114 -0
  105. hyperadmin/locale/en/LC_MESSAGES/messages.mo +0 -0
  106. hyperadmin/locale/en/LC_MESSAGES/messages.po +1780 -0
  107. hyperadmin/locale/es/LC_MESSAGES/messages.mo +0 -0
  108. hyperadmin/locale/es/LC_MESSAGES/messages.po +2094 -0
  109. hyperadmin/locale/fr/LC_MESSAGES/messages.mo +0 -0
  110. hyperadmin/locale/fr/LC_MESSAGES/messages.po +2100 -0
  111. hyperadmin/locale/he/LC_MESSAGES/messages.mo +0 -0
  112. hyperadmin/locale/he/LC_MESSAGES/messages.po +2076 -0
  113. hyperadmin/locale/hi/LC_MESSAGES/messages.mo +0 -0
  114. hyperadmin/locale/hi/LC_MESSAGES/messages.po +2084 -0
  115. hyperadmin/locale/id/LC_MESSAGES/messages.mo +0 -0
  116. hyperadmin/locale/id/LC_MESSAGES/messages.po +2071 -0
  117. hyperadmin/locale/it/LC_MESSAGES/messages.mo +0 -0
  118. hyperadmin/locale/it/LC_MESSAGES/messages.po +2098 -0
  119. hyperadmin/locale/ja/LC_MESSAGES/messages.mo +0 -0
  120. hyperadmin/locale/ja/LC_MESSAGES/messages.po +2049 -0
  121. hyperadmin/locale/ko/LC_MESSAGES/messages.mo +0 -0
  122. hyperadmin/locale/ko/LC_MESSAGES/messages.po +2049 -0
  123. hyperadmin/locale/nl/LC_MESSAGES/messages.mo +0 -0
  124. hyperadmin/locale/nl/LC_MESSAGES/messages.po +2100 -0
  125. hyperadmin/locale/pl/LC_MESSAGES/messages.mo +0 -0
  126. hyperadmin/locale/pl/LC_MESSAGES/messages.po +2112 -0
  127. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.mo +0 -0
  128. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.po +2098 -0
  129. hyperadmin/locale/ru/LC_MESSAGES/messages.mo +0 -0
  130. hyperadmin/locale/ru/LC_MESSAGES/messages.po +2112 -0
  131. hyperadmin/locale/th/LC_MESSAGES/messages.mo +0 -0
  132. hyperadmin/locale/th/LC_MESSAGES/messages.po +2065 -0
  133. hyperadmin/locale/tr/LC_MESSAGES/messages.mo +0 -0
  134. hyperadmin/locale/tr/LC_MESSAGES/messages.po +2084 -0
  135. hyperadmin/locale/uk/LC_MESSAGES/messages.mo +0 -0
  136. hyperadmin/locale/uk/LC_MESSAGES/messages.po +1889 -0
  137. hyperadmin/locale/vi/LC_MESSAGES/messages.mo +0 -0
  138. hyperadmin/locale/vi/LC_MESSAGES/messages.po +2063 -0
  139. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.mo +0 -0
  140. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.po +2049 -0
  141. hyperadmin/main.py +3 -0
  142. hyperadmin/management/__init__.py +0 -0
  143. hyperadmin/management/commands/__init__.py +0 -0
  144. hyperadmin/management/commands/createsuperuser.py +114 -0
  145. hyperadmin/management/commands/initdb.py +76 -0
  146. hyperadmin/management/commands/plugins.py +31 -0
  147. hyperadmin/management/commands/seed.py +125 -0
  148. hyperadmin/navigation/__init__.py +9 -0
  149. hyperadmin/navigation/pins.py +153 -0
  150. hyperadmin/panels/__init__.py +10 -0
  151. hyperadmin/panels/pdf.py +151 -0
  152. hyperadmin/permissions/__init__.py +59 -0
  153. hyperadmin/permissions/audit.py +109 -0
  154. hyperadmin/permissions/matrix.py +343 -0
  155. hyperadmin/permissions/object_rules.py +143 -0
  156. hyperadmin/realtime/__init__.py +51 -0
  157. hyperadmin/realtime/_debug.py +77 -0
  158. hyperadmin/realtime/config.py +124 -0
  159. hyperadmin/realtime/emitting.py +143 -0
  160. hyperadmin/realtime/events.py +107 -0
  161. hyperadmin/realtime/presence.py +193 -0
  162. hyperadmin/realtime/presence_redis.py +142 -0
  163. hyperadmin/realtime/pubsub.py +129 -0
  164. hyperadmin/realtime/pubsub_redis.py +159 -0
  165. hyperadmin/realtime/registry.py +102 -0
  166. hyperadmin/realtime/sse.py +82 -0
  167. hyperadmin/realtime/ws.py +477 -0
  168. hyperadmin/routing.py +680 -0
  169. hyperadmin/static/css/_accessibility.css +149 -0
  170. hyperadmin/static/css/_alerts.css +147 -0
  171. hyperadmin/static/css/_autocomplete.css +39 -0
  172. hyperadmin/static/css/_banner.css +118 -0
  173. hyperadmin/static/css/_buttons.css +241 -0
  174. hyperadmin/static/css/_card.css +86 -0
  175. hyperadmin/static/css/_dark-mode.css +232 -0
  176. hyperadmin/static/css/_fieldsets.css +71 -0
  177. hyperadmin/static/css/_filter.css +203 -0
  178. hyperadmin/static/css/_fonts.css +25 -0
  179. hyperadmin/static/css/_forms.css +862 -0
  180. hyperadmin/static/css/_inline-cell.css +222 -0
  181. hyperadmin/static/css/_inlines.css +160 -0
  182. hyperadmin/static/css/_layout.css +62 -0
  183. hyperadmin/static/css/_login.css +112 -0
  184. hyperadmin/static/css/_menu.css +156 -0
  185. hyperadmin/static/css/_navbar.css +299 -0
  186. hyperadmin/static/css/_page-header.css +139 -0
  187. hyperadmin/static/css/_pagination.css +125 -0
  188. hyperadmin/static/css/_palette.css +304 -0
  189. hyperadmin/static/css/_panels.css +174 -0
  190. hyperadmin/static/css/_permissions.css +547 -0
  191. hyperadmin/static/css/_pill.css +123 -0
  192. hyperadmin/static/css/_popover.css +170 -0
  193. hyperadmin/static/css/_popup.css +65 -0
  194. hyperadmin/static/css/_progress.css +161 -0
  195. hyperadmin/static/css/_realtime.css +78 -0
  196. hyperadmin/static/css/_reset.css +48 -0
  197. hyperadmin/static/css/_responsive.css +51 -0
  198. hyperadmin/static/css/_rtl.css +23 -0
  199. hyperadmin/static/css/_search.css +67 -0
  200. hyperadmin/static/css/_seg.css +95 -0
  201. hyperadmin/static/css/_sidebar.css +446 -0
  202. hyperadmin/static/css/_sticky.css +54 -0
  203. hyperadmin/static/css/_table.css +776 -0
  204. hyperadmin/static/css/_theme-terminal-type.css +92 -0
  205. hyperadmin/static/css/_theme-terminal.css +330 -0
  206. hyperadmin/static/css/_theme-toggle.css +46 -0
  207. hyperadmin/static/css/_tokens.css +232 -0
  208. hyperadmin/static/css/_utilities.css +133 -0
  209. hyperadmin/static/css/hyperadmin.css +58 -0
  210. hyperadmin/static/fonts/Inter-OFL.txt +93 -0
  211. hyperadmin/static/fonts/InterVariable.woff2 +0 -0
  212. hyperadmin/static/fonts/JetBrainsMono-OFL.txt +93 -0
  213. hyperadmin/static/fonts/JetBrainsMonoVariable.woff2 +0 -0
  214. hyperadmin/static/icons/arrow-down.svg +1 -0
  215. hyperadmin/static/icons/arrow-up.svg +1 -0
  216. hyperadmin/static/icons/bar-chart-3.svg +1 -0
  217. hyperadmin/static/icons/bell.svg +1 -0
  218. hyperadmin/static/icons/bookmark.svg +1 -0
  219. hyperadmin/static/icons/briefcase.svg +1 -0
  220. hyperadmin/static/icons/building-2.svg +1 -0
  221. hyperadmin/static/icons/calendar.svg +1 -0
  222. hyperadmin/static/icons/check.svg +1 -0
  223. hyperadmin/static/icons/chevron-down.svg +1 -0
  224. hyperadmin/static/icons/chevron-left.svg +1 -0
  225. hyperadmin/static/icons/chevron-right.svg +1 -0
  226. hyperadmin/static/icons/circle-check.svg +1 -0
  227. hyperadmin/static/icons/circle-help.svg +1 -0
  228. hyperadmin/static/icons/circle-x.svg +1 -0
  229. hyperadmin/static/icons/clock.svg +1 -0
  230. hyperadmin/static/icons/columns-3.svg +1 -0
  231. hyperadmin/static/icons/command.svg +1 -0
  232. hyperadmin/static/icons/copy.svg +1 -0
  233. hyperadmin/static/icons/credit-card.svg +1 -0
  234. hyperadmin/static/icons/database.svg +1 -0
  235. hyperadmin/static/icons/download.svg +1 -0
  236. hyperadmin/static/icons/ellipsis.svg +1 -0
  237. hyperadmin/static/icons/external-link.svg +1 -0
  238. hyperadmin/static/icons/eye.svg +1 -0
  239. hyperadmin/static/icons/file-text.svg +1 -0
  240. hyperadmin/static/icons/filter.svg +1 -0
  241. hyperadmin/static/icons/folder.svg +1 -0
  242. hyperadmin/static/icons/globe.svg +1 -0
  243. hyperadmin/static/icons/history.svg +1 -0
  244. hyperadmin/static/icons/home.svg +1 -0
  245. hyperadmin/static/icons/image.svg +1 -0
  246. hyperadmin/static/icons/info.svg +1 -0
  247. hyperadmin/static/icons/key-round.svg +1 -0
  248. hyperadmin/static/icons/layers.svg +1 -0
  249. hyperadmin/static/icons/layout-grid.svg +1 -0
  250. hyperadmin/static/icons/list-checks.svg +1 -0
  251. hyperadmin/static/icons/lock.svg +1 -0
  252. hyperadmin/static/icons/log-out.svg +1 -0
  253. hyperadmin/static/icons/mail.svg +1 -0
  254. hyperadmin/static/icons/map-pin.svg +1 -0
  255. hyperadmin/static/icons/menu.svg +1 -0
  256. hyperadmin/static/icons/moon.svg +1 -0
  257. hyperadmin/static/icons/package.svg +1 -0
  258. hyperadmin/static/icons/panel-left-close.svg +1 -0
  259. hyperadmin/static/icons/panel-left-open.svg +1 -0
  260. hyperadmin/static/icons/pencil.svg +1 -0
  261. hyperadmin/static/icons/pin-off.svg +1 -0
  262. hyperadmin/static/icons/pin.svg +1 -0
  263. hyperadmin/static/icons/plus.svg +1 -0
  264. hyperadmin/static/icons/receipt.svg +1 -0
  265. hyperadmin/static/icons/refresh-cw.svg +1 -0
  266. hyperadmin/static/icons/rotate-ccw.svg +1 -0
  267. hyperadmin/static/icons/search.svg +1 -0
  268. hyperadmin/static/icons/settings.svg +1 -0
  269. hyperadmin/static/icons/shield-check.svg +1 -0
  270. hyperadmin/static/icons/shopping-cart.svg +1 -0
  271. hyperadmin/static/icons/sliders-horizontal.svg +1 -0
  272. hyperadmin/static/icons/sparkles.svg +1 -0
  273. hyperadmin/static/icons/store.svg +1 -0
  274. hyperadmin/static/icons/sun.svg +1 -0
  275. hyperadmin/static/icons/tag.svg +1 -0
  276. hyperadmin/static/icons/trash-2.svg +1 -0
  277. hyperadmin/static/icons/triangle-alert.svg +1 -0
  278. hyperadmin/static/icons/truck.svg +1 -0
  279. hyperadmin/static/icons/upload.svg +1 -0
  280. hyperadmin/static/icons/user.svg +1 -0
  281. hyperadmin/static/icons/users.svg +1 -0
  282. hyperadmin/static/icons/wallet.svg +1 -0
  283. hyperadmin/static/icons/x.svg +1 -0
  284. hyperadmin/static/img/hyperadmin-favicon.svg +1 -0
  285. hyperadmin/static/img/hyperadmin-mark-mono.svg +1 -0
  286. hyperadmin/static/img/hyperadmin-mark.svg +1 -0
  287. hyperadmin/static/img/hyperadmin-wordmark-dark.svg +1 -0
  288. hyperadmin/static/img/hyperadmin-wordmark.svg +1 -0
  289. hyperadmin/static/img/terminal/hyperadmin-favicon-16.svg +1 -0
  290. hyperadmin/static/img/terminal/hyperadmin-favicon.svg +1 -0
  291. hyperadmin/static/img/terminal/hyperadmin-mark.svg +1 -0
  292. hyperadmin/static/img/terminal/hyperadmin-wordmark-dark.svg +1 -0
  293. hyperadmin/static/img/terminal/hyperadmin-wordmark.svg +1 -0
  294. hyperadmin/static/js/autocomplete.js +475 -0
  295. hyperadmin/static/js/confirm_delete.js +113 -0
  296. hyperadmin/static/js/error_summary.js +37 -0
  297. hyperadmin/static/js/form_guard.js +77 -0
  298. hyperadmin/static/js/inline_edit.js +97 -0
  299. hyperadmin/static/js/palette.js +292 -0
  300. hyperadmin/static/js/primitives.js +205 -0
  301. hyperadmin/static/js/realtime-status.js +515 -0
  302. hyperadmin/static/js/request_errors.js +85 -0
  303. hyperadmin/static/js/shortcuts.js +175 -0
  304. hyperadmin/static/js/sidebar.js +83 -0
  305. hyperadmin/static/js/vendor/LICENSE-alpinejs.txt +21 -0
  306. hyperadmin/static/js/vendor/LICENSE-htmx.txt +25 -0
  307. hyperadmin/static/js/vendor/alpinejs-3.17.4.min.js +21 -0
  308. hyperadmin/static/js/vendor/alpinejs-focus-3.17.4.min.js +18 -0
  309. hyperadmin/static/js/vendor/htmx-1.9.10.min.js +1 -0
  310. hyperadmin/templates/_base.html +161 -0
  311. hyperadmin/templates/_messages.html +11 -0
  312. hyperadmin/templates/_navbar.html +126 -0
  313. hyperadmin/templates/_sidebar.html +80 -0
  314. hyperadmin/templates/auth/mfa_challenge.html +75 -0
  315. hyperadmin/templates/auth/mfa_settings.html +110 -0
  316. hyperadmin/templates/auth/oauth_link_required.html +24 -0
  317. hyperadmin/templates/auth/oauth_settings.html +55 -0
  318. hyperadmin/templates/base.html +16 -0
  319. hyperadmin/templates/bulk_form.html +18 -0
  320. hyperadmin/templates/bulk_result.html +20 -0
  321. hyperadmin/templates/components/_icons.html +86 -0
  322. hyperadmin/templates/components/_macros.html +27 -0
  323. hyperadmin/templates/components/_nav.html +55 -0
  324. hyperadmin/templates/components/_row_access.html +26 -0
  325. hyperadmin/templates/components/banner.html +77 -0
  326. hyperadmin/templates/components/bulk_form.html +81 -0
  327. hyperadmin/templates/components/bulk_result.html +133 -0
  328. hyperadmin/templates/components/bulk_toolbar.html +63 -0
  329. hyperadmin/templates/components/command_palette.html +59 -0
  330. hyperadmin/templates/components/confirm_delete_dialog.html +26 -0
  331. hyperadmin/templates/components/conflict_dialog.html +42 -0
  332. hyperadmin/templates/components/csrf_reload_banner.html +20 -0
  333. hyperadmin/templates/components/error_summary.html +39 -0
  334. hyperadmin/templates/components/error_toast.html +18 -0
  335. hyperadmin/templates/components/fieldset.html +38 -0
  336. hyperadmin/templates/components/filter_bar.html +50 -0
  337. hyperadmin/templates/components/filter_sidebar.html +31 -0
  338. hyperadmin/templates/components/filters/boolean.html +10 -0
  339. hyperadmin/templates/components/filters/current_period.html +8 -0
  340. hyperadmin/templates/components/filters/date_range.html +26 -0
  341. hyperadmin/templates/components/filters/is_owner.html +8 -0
  342. hyperadmin/templates/components/filters/multi_choice.html +10 -0
  343. hyperadmin/templates/components/filters/multi_relation.html +20 -0
  344. hyperadmin/templates/components/filters/select.html +11 -0
  345. hyperadmin/templates/components/inline_cell.html +23 -0
  346. hyperadmin/templates/components/inline_cell_error.html +51 -0
  347. hyperadmin/templates/components/inline_cell_stale.html +20 -0
  348. hyperadmin/templates/components/inline_editor.html +85 -0
  349. hyperadmin/templates/components/inline_formset.html +34 -0
  350. hyperadmin/templates/components/inline_row.html +49 -0
  351. hyperadmin/templates/components/list_error.html +12 -0
  352. hyperadmin/templates/components/menu.html +74 -0
  353. hyperadmin/templates/components/nav_pinned.html +24 -0
  354. hyperadmin/templates/components/pagination.html +87 -0
  355. hyperadmin/templates/components/panel_document.html +19 -0
  356. hyperadmin/templates/components/panel_states.html +35 -0
  357. hyperadmin/templates/components/panel_tab_strip.html +31 -0
  358. hyperadmin/templates/components/pill.html +15 -0
  359. hyperadmin/templates/components/popover.html +59 -0
  360. hyperadmin/templates/components/presence_banner.html +28 -0
  361. hyperadmin/templates/components/progress.html +72 -0
  362. hyperadmin/templates/components/saved_views.html +61 -0
  363. hyperadmin/templates/components/search_input.html +19 -0
  364. hyperadmin/templates/components/seg.html +38 -0
  365. hyperadmin/templates/components/shortcuts_overlay.html +45 -0
  366. hyperadmin/templates/components/sortable_header.html +23 -0
  367. hyperadmin/templates/components/table.html +45 -0
  368. hyperadmin/templates/components/table_body.html +86 -0
  369. hyperadmin/templates/components/thumbnail.html +8 -0
  370. hyperadmin/templates/components/toast.html +36 -0
  371. hyperadmin/templates/components/tooltip.html +20 -0
  372. hyperadmin/templates/create.html +43 -0
  373. hyperadmin/templates/dashboard.html +8 -0
  374. hyperadmin/templates/detail.html +120 -0
  375. hyperadmin/templates/detail_layout.html +15 -0
  376. hyperadmin/templates/error.html +24 -0
  377. hyperadmin/templates/form_layout.html +26 -0
  378. hyperadmin/templates/list.html +5 -0
  379. hyperadmin/templates/list_layout.html +105 -0
  380. hyperadmin/templates/login.html +79 -0
  381. hyperadmin/templates/permissions/_banner.html +55 -0
  382. hyperadmin/templates/permissions/_diff_row.html +6 -0
  383. hyperadmin/templates/permissions/_group_gone.html +16 -0
  384. hyperadmin/templates/permissions/_macros.html +22 -0
  385. hyperadmin/templates/permissions/matrix.html +408 -0
  386. hyperadmin/templates/permissions/object_popover.html +95 -0
  387. hyperadmin/templates/update.html +69 -0
  388. hyperadmin/templates/widgets/autocomplete.html +100 -0
  389. hyperadmin/templates/widgets/checkbox_input.html +20 -0
  390. hyperadmin/templates/widgets/choices_options.html +3 -0
  391. hyperadmin/templates/widgets/date_input.html +13 -0
  392. hyperadmin/templates/widgets/datetime_input.html +18 -0
  393. hyperadmin/templates/widgets/encoded_textarea.html +4 -0
  394. hyperadmin/templates/widgets/file_input.html +15 -0
  395. hyperadmin/templates/widgets/float_input.html +12 -0
  396. hyperadmin/templates/widgets/image_input.html +108 -0
  397. hyperadmin/templates/widgets/multiselect_input.html +13 -0
  398. hyperadmin/templates/widgets/number_input.html +11 -0
  399. hyperadmin/templates/widgets/popup_form.html +64 -0
  400. hyperadmin/templates/widgets/relation_multiselect_input.html +36 -0
  401. hyperadmin/templates/widgets/relation_select_input.html +38 -0
  402. hyperadmin/templates/widgets/select_input.html +17 -0
  403. hyperadmin/templates/widgets/text_input.html +13 -0
  404. hyperadmin/templates/widgets/textarea.html +4 -0
  405. hyperadmin/uploads/__init__.py +44 -0
  406. hyperadmin/uploads/images.py +272 -0
  407. hyperadmin/uploads/storage.py +265 -0
  408. hyperadmin/uploads/validation.py +37 -0
  409. hyperadmin/views/__init__.py +3 -0
  410. hyperadmin/views/csrf.py +316 -0
  411. hyperadmin/views/dynamic/__init__.py +35 -0
  412. hyperadmin/views/dynamic/actions.py +264 -0
  413. hyperadmin/views/dynamic/base.py +576 -0
  414. hyperadmin/views/dynamic/concurrency.py +138 -0
  415. hyperadmin/views/dynamic/core.py +33 -0
  416. hyperadmin/views/dynamic/create.py +189 -0
  417. hyperadmin/views/dynamic/detail.py +231 -0
  418. hyperadmin/views/dynamic/files.py +233 -0
  419. hyperadmin/views/dynamic/form_data.py +162 -0
  420. hyperadmin/views/dynamic/helpers.py +151 -0
  421. hyperadmin/views/dynamic/inline.py +348 -0
  422. hyperadmin/views/dynamic/list_view.py +612 -0
  423. hyperadmin/views/dynamic/model_view.py +17 -0
  424. hyperadmin/views/dynamic/palette_search.py +78 -0
  425. hyperadmin/views/dynamic/relations.py +544 -0
  426. hyperadmin/views/dynamic/saved_views.py +159 -0
  427. hyperadmin/views/dynamic/update.py +313 -0
  428. hyperadmin/views/error_pages.py +46 -0
  429. hyperadmin/views/forms.py +1294 -0
  430. hyperadmin/views/htmx.py +53 -0
  431. hyperadmin/views/locale.py +113 -0
  432. hyperadmin/views/nav_pins.py +149 -0
  433. hyperadmin/views/navigation.py +143 -0
  434. hyperadmin/views/palette_context.py +91 -0
  435. hyperadmin/views/palette_search.py +103 -0
  436. hyperadmin/views/permissions_matrix.py +490 -0
  437. hyperadmin/views/rate_limit.py +87 -0
  438. hyperadmin/views/route.py +316 -0
  439. hyperadmin/views/static.py +138 -0
  440. hyperadmin/views/template_filters.py +305 -0
  441. hyperadmin/views/uploads.py +92 -0
  442. hyperadmin/views/urls.py +180 -0
@@ -0,0 +1,1294 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import types
5
+ import uuid
6
+ from dataclasses import dataclass
7
+ from dataclasses import field as dc_field
8
+ from datetime import date, datetime, tzinfo
9
+ from datetime import timezone as dt_timezone
10
+ from enum import Enum
11
+ from typing import TYPE_CHECKING, Any, ClassVar, Literal, Union, get_args, get_origin
12
+
13
+ from markupsafe import Markup
14
+ from pydantic import BaseModel, TypeAdapter, ValidationError
15
+ from pydantic.fields import FieldInfo
16
+
17
+ from hyperadmin.core.choices import ChoiceItem
18
+ from hyperadmin.core.display import get_enum_label
19
+ from hyperadmin.core.primary_key import DEFAULT_PK, InvalidPrimaryKey, PrimaryKeyInfo
20
+ from hyperadmin.core.schema import dump_instance, schema_for
21
+ from hyperadmin.core.sensitive import effective_sensitive_field_names
22
+ from hyperadmin.core.timezones import (
23
+ annotation_datetime_kind,
24
+ format_datetime_input,
25
+ is_auto_now_factory,
26
+ parse_datetime_input,
27
+ )
28
+ from hyperadmin.i18n import gettext_lazy, translate_error_lazy
29
+
30
+ try:
31
+ from hyperadmin.core.fields import classify_field as _classify_field
32
+
33
+ _HAS_CLASSIFY = True
34
+ except ImportError:
35
+ _classify_field = None # type: ignore[assignment]
36
+ _HAS_CLASSIFY = False
37
+
38
+ if TYPE_CHECKING:
39
+ from collections.abc import Callable, Mapping
40
+
41
+ from starlette.requests import Request
42
+ from starlette.templating import Jinja2Templates
43
+
44
+ from hyperadmin.core.fieldsets import FieldsetSpec
45
+ from hyperadmin.core.inlines import InlineModelSpec
46
+ from hyperadmin.core.layouts import FormLayout
47
+ from hyperadmin.core.timezones import DateTimeKind
48
+
49
+ # Type alias: errors can be lazy-translated proxies or plain strings.
50
+ # ``babel.support.LazyProxy`` satisfies the string protocol via ``__str__``.
51
+ ErrorList = list[Any]
52
+
53
+ # Row error for an inline ``<prefix>-<i>-pk`` the inline model's codec rejects.
54
+ _INVALID_PK_MESSAGE = gettext_lazy("Invalid primary key.")
55
+
56
+ # Field error for a datetime input that is not a valid ISO-8601 date/time.
57
+ _INVALID_DATETIME_MESSAGE = gettext_lazy("Enter a valid date/time")
58
+
59
+ # Field error for a JSON textarea whose text is not valid JSON.
60
+ _INVALID_JSON_MESSAGE = gettext_lazy("Enter valid JSON")
61
+
62
+ # Field error for a binary field whose text is not hexadecimal.
63
+ _INVALID_HEX_MESSAGE = gettext_lazy("Enter hexadecimal digits")
64
+
65
+ # Plain-language replacements for pydantic's wording on the errors users hit most.
66
+ # Keyed by the pydantic error ``type``; anything else keeps ``translate_error_lazy``.
67
+ _FRIENDLY_MESSAGES: dict[str, Any] = {
68
+ "missing": gettext_lazy("This field is required"),
69
+ "int_parsing": gettext_lazy("Enter a whole number"),
70
+ "int_type": gettext_lazy("Enter a whole number"),
71
+ "int_from_float": gettext_lazy("Enter a whole number"),
72
+ "float_parsing": gettext_lazy("Enter a number"),
73
+ "float_type": gettext_lazy("Enter a number"),
74
+ "decimal_parsing": gettext_lazy("Enter a number"),
75
+ "bool_parsing": gettext_lazy("Choose yes or no"),
76
+ "datetime_parsing": gettext_lazy("Enter a valid date and time"),
77
+ "datetime_from_date_parsing": gettext_lazy("Enter a valid date and time"),
78
+ "datetime_type": gettext_lazy("Enter a valid date and time"),
79
+ "uuid_parsing": gettext_lazy("Enter a valid identifier"),
80
+ "url_parsing": gettext_lazy("Enter a valid URL"),
81
+ }
82
+ _FRIENDLY_DATE_TYPES = frozenset({"date_parsing", "date_from_datetime_parsing", "date_type"})
83
+ _ENTER_A_DATE = gettext_lazy("Enter a date")
84
+ _ENTER_A_VALID_DATE = gettext_lazy("Enter a valid date")
85
+
86
+
87
+ def friendly_error(error: Mapping[str, Any]) -> Any:
88
+ """Return a user-facing message for one pydantic error.
89
+
90
+ Common types (missing, number and date parsing) get plain wording; an empty
91
+ date or text input reads "Enter a date" / "This field is required". Other
92
+ types fall back to :func:`translate_error_lazy`.
93
+ """
94
+ err_type = error.get("type")
95
+ entered = error.get("input")
96
+ blank = isinstance(entered, str) and not entered.strip()
97
+ if err_type in _FRIENDLY_DATE_TYPES:
98
+ return _ENTER_A_DATE if blank else _ENTER_A_VALID_DATE
99
+ if err_type == "string_too_short" and blank:
100
+ return _FRIENDLY_MESSAGES["missing"]
101
+ if err_type in _FRIENDLY_MESSAGES:
102
+ return _FRIENDLY_MESSAGES[err_type]
103
+ return translate_error_lazy(error)
104
+
105
+
106
+ def _unwrap_optional(annotation: Any) -> Any:
107
+ """Return the first non-``None`` member of an optional union, else ``annotation``.
108
+
109
+ Handles both ``typing.Optional[X]`` / ``Union[X, None]`` and PEP 604 ``X | None``
110
+ (``types.UnionType``), so ``datetime | None`` picks the same widget as ``datetime``.
111
+ """
112
+ origin = get_origin(annotation)
113
+ args = get_args(annotation)
114
+ if (origin is Union or origin is types.UnionType) and type(None) in args:
115
+ return next(arg for arg in args if arg is not type(None))
116
+ return annotation
117
+
118
+
119
+ def _is_json_annotation(annotation: Any) -> bool:
120
+ """Whether ``annotation`` holds JSON: ``dict``, ``list`` (parametrised or not) or a union
121
+ with one of them, such as the ``dict | list | Any`` built for a ``JSON`` column."""
122
+ origin = get_origin(annotation)
123
+ if origin is Union or origin is types.UnionType:
124
+ return any(_is_json_annotation(arg) for arg in get_args(annotation))
125
+ return (origin or annotation) in (dict, list)
126
+
127
+
128
+ def _is_datetime_annotation(annotation: Any) -> bool:
129
+ """Whether ``annotation`` is a datetime: ``datetime`` (or a subclass),
130
+ ``AwareDatetime``, ``NaiveDatetime`` or ``Annotated[datetime, ...]``."""
131
+ return annotation_datetime_kind(annotation) is not None
132
+
133
+
134
+ class _FormData(dict):
135
+ """Submitted values handed to schema validation.
136
+
137
+ SQLModel table models read their relationships back with ``getattr(data, name)``;
138
+ on a plain dict a relationship named ``items``, ``keys`` or ``values`` resolves
139
+ to the dict method and is assigned to the relationship. Lookups of the model's
140
+ relationship names raise ``AttributeError`` here so SQLModel skips them.
141
+ """
142
+
143
+ def __init__(self, data: dict[str, Any], model: type) -> None:
144
+ super().__init__(data)
145
+ self._hidden = frozenset(getattr(model, "__sqlmodel_relationships__", ()))
146
+
147
+ def __getattribute__(self, name: str) -> Any:
148
+ if name in object.__getattribute__(self, "_hidden"):
149
+ raise AttributeError(name)
150
+ return super().__getattribute__(name)
151
+
152
+
153
+ def _placeholder_key(annotation: Any) -> Any:
154
+ """A value ``annotation`` accepts, standing in for a parent key not yet assigned.
155
+
156
+ A new parent has no key while its inline rows are validated; the real key
157
+ replaces this one when the rows are saved. Returns ``None`` when no
158
+ candidate validates, which leaves the field to report its own error.
159
+ """
160
+ adapter = TypeAdapter(annotation)
161
+ for candidate in (0, uuid.UUID(int=0), ""):
162
+ try:
163
+ adapter.validate_python(candidate)
164
+ except ValidationError:
165
+ continue
166
+ return candidate
167
+ return None
168
+
169
+
170
+ @dataclass(slots=True)
171
+ class HtmxWidget:
172
+ """A minimal widget abstraction capable of rendering via a Jinja template.
173
+
174
+ template_path: path to template included under the project templates directory.
175
+ static_list: optional JS/CSS assets to include once per page.
176
+ htmx_attrs: optional HTMX attributes to include on the input element.
177
+ input_type: HTML input type string returned to templates (e.g. ``"text"``, ``"number"``).
178
+ """
179
+
180
+ template_path: str
181
+ static_list: tuple[str, ...] = ()
182
+ htmx_attrs: Mapping[str, str] | None = None
183
+ input_type: ClassVar[str] = "text"
184
+
185
+ def render(self, templates: Jinja2Templates, form_field: FormField, request: Request) -> Markup:
186
+ """Render ``template_path`` with ``request``, the bound ``field`` and this ``widget``."""
187
+ context = {
188
+ "request": request,
189
+ "field": form_field,
190
+ "widget": self,
191
+ }
192
+ return Markup(templates.get_template(self.template_path).render(context)) # noqa: S704
193
+
194
+
195
+ class TextInput(HtmxWidget):
196
+ input_type: ClassVar[str] = "text"
197
+
198
+ def __init__(self):
199
+ super().__init__(template_path="widgets/text_input.html")
200
+
201
+
202
+ class NumberInput(HtmxWidget):
203
+ input_type: ClassVar[str] = "number"
204
+
205
+ def __init__(self):
206
+ super().__init__(template_path="widgets/number_input.html")
207
+
208
+
209
+ class FloatInput(HtmxWidget):
210
+ input_type: ClassVar[str] = "number"
211
+
212
+ def __init__(self):
213
+ super().__init__(template_path="widgets/float_input.html")
214
+
215
+
216
+ class Textarea(HtmxWidget):
217
+ def __init__(self):
218
+ super().__init__(template_path="widgets/textarea.html")
219
+
220
+
221
+ class EncodedTextarea(Textarea):
222
+ """A textarea for a value whose text form is not ``str(value)``.
223
+
224
+ ``dump`` turns the stored value into the text shown, ``parse`` turns the submitted text
225
+ back into the value (raising ``ValueError`` when it cannot). Without them a ``dict`` or
226
+ ``bytes`` column is shown as a Python repr, and the repr is what an edit writes back.
227
+ """
228
+
229
+ error_message: ClassVar[Any] = _INVALID_JSON_MESSAGE
230
+ error_type: ClassVar[str] = "json_invalid"
231
+
232
+ def __init__(self) -> None:
233
+ HtmxWidget.__init__(self, template_path="widgets/encoded_textarea.html")
234
+
235
+ @staticmethod
236
+ def encode(value: Any) -> str:
237
+ """The text form of a stored (non-``None``, non-``str``) value."""
238
+ raise NotImplementedError
239
+
240
+ @staticmethod
241
+ def parse(raw: str) -> Any:
242
+ """The value for submitted text; ``ValueError`` when the text is not valid."""
243
+ raise NotImplementedError
244
+
245
+ @classmethod
246
+ def dump(cls, value: Any) -> str:
247
+ """The text shown in the textarea: re-submitted text as typed, else the encoded value."""
248
+ if value is None:
249
+ return ""
250
+ if isinstance(value, str):
251
+ return value
252
+ return cls.encode(value)
253
+
254
+
255
+ class JsonTextarea(EncodedTextarea):
256
+ """A textarea for ``dict`` / ``list`` fields: indented JSON in, ``json.loads`` out."""
257
+
258
+ @staticmethod
259
+ def encode(value: Any) -> str:
260
+ return json.dumps(value, indent=2, ensure_ascii=False, default=str)
261
+
262
+ @staticmethod
263
+ def parse(raw: str) -> Any:
264
+ return json.loads(raw)
265
+
266
+
267
+ class HexTextarea(EncodedTextarea):
268
+ """A textarea for ``bytes`` fields: the bytes as hex digits, parsed back with ``fromhex``."""
269
+
270
+ error_message: ClassVar[Any] = _INVALID_HEX_MESSAGE
271
+ error_type: ClassVar[str] = "bytes_invalid"
272
+
273
+ @staticmethod
274
+ def encode(value: Any) -> str:
275
+ return bytes(value).hex()
276
+
277
+ @staticmethod
278
+ def parse(raw: str) -> Any:
279
+ return bytes.fromhex(raw)
280
+
281
+
282
+ class CheckboxInput(HtmxWidget):
283
+ input_type: ClassVar[str] = "checkbox"
284
+
285
+ def __init__(self):
286
+ super().__init__(template_path="widgets/checkbox_input.html")
287
+
288
+
289
+ class SelectInput(HtmxWidget):
290
+ def __init__(self):
291
+ super().__init__(template_path="widgets/select_input.html")
292
+
293
+
294
+ class SelectWidget(HtmxWidget):
295
+ """Widget for a single-select with a pre-built choices list."""
296
+
297
+ choices: list[ChoiceItem]
298
+
299
+ def __init__(self, choices: list[ChoiceItem] | None = None) -> None:
300
+ # HtmxWidget is slots=True; bypass super().__init__ to avoid the
301
+ # zero-arg super() cell-variable issue introduced by @dataclass(slots=True).
302
+ object.__setattr__(self, "template_path", "widgets/select_input.html")
303
+ object.__setattr__(self, "static_list", ())
304
+ object.__setattr__(self, "htmx_attrs", None)
305
+ self.choices = choices or []
306
+
307
+
308
+ class MultiSelectWidget(HtmxWidget):
309
+ """Widget for a multi-select with a pre-built choices list."""
310
+
311
+ choices: list[ChoiceItem]
312
+
313
+ def __init__(self, choices: list[ChoiceItem] | None = None) -> None:
314
+ object.__setattr__(self, "template_path", "widgets/multiselect_input.html")
315
+ object.__setattr__(self, "static_list", ())
316
+ object.__setattr__(self, "htmx_attrs", None)
317
+ self.choices = choices or []
318
+
319
+
320
+ class DateTimeInput(HtmxWidget):
321
+ input_type: ClassVar[str] = "datetime-local"
322
+
323
+ def __init__(self):
324
+ super().__init__(template_path="widgets/datetime_input.html")
325
+
326
+
327
+ class DateInput(HtmxWidget):
328
+ """A native ``<input type="date">`` for ``date`` fields; submits ISO ``YYYY-MM-DD``."""
329
+
330
+ input_type: ClassVar[str] = "date"
331
+
332
+ def __init__(self):
333
+ super().__init__(template_path="widgets/date_input.html")
334
+
335
+
336
+ class FileInputWidget(HtmxWidget):
337
+ """Widget for file upload fields (``FileType`` / ``ImageType`` columns)."""
338
+
339
+ input_type: ClassVar[str] = "file"
340
+ is_image: bool
341
+ current_file: str | None
342
+
343
+ def __init__(
344
+ self,
345
+ is_image: bool = False,
346
+ current_file: str | None = None,
347
+ ) -> None:
348
+ object.__setattr__(self, "template_path", "widgets/file_input.html")
349
+ object.__setattr__(self, "static_list", ())
350
+ object.__setattr__(self, "htmx_attrs", None)
351
+ self.is_image = is_image
352
+ self.current_file = current_file
353
+
354
+
355
+ class ImagePreviewWidget(FileInputWidget):
356
+ """``ImageType`` widget: drag-and-drop zone with an instant client-side preview."""
357
+
358
+ thumbnail_url: str | None
359
+
360
+ def __init__(self, current_file: str | None = None, thumbnail_url: str | None = None) -> None:
361
+ super().__init__(is_image=True, current_file=current_file)
362
+ self.thumbnail_url = thumbnail_url
363
+ object.__setattr__(self, "template_path", "widgets/image_input.html")
364
+
365
+
366
+ class RelationSelectWidget(HtmxWidget):
367
+ """Widget for a single FK relation field — supports preload and lazy (HTMX) strategies."""
368
+
369
+ choices: list[ChoiceItem]
370
+ choices_url: str
371
+ preload: bool
372
+ dependent_on: str | None
373
+
374
+ def __init__(
375
+ self,
376
+ choices_url: str,
377
+ choices: list[ChoiceItem] | None = None,
378
+ preload: bool = True,
379
+ dependent_on: str | None = None,
380
+ ) -> None:
381
+ object.__setattr__(self, "template_path", "widgets/relation_select_input.html")
382
+ object.__setattr__(self, "static_list", ())
383
+ object.__setattr__(self, "htmx_attrs", None)
384
+ self.choices = choices or []
385
+ self.choices_url = choices_url
386
+ self.preload = preload
387
+ self.dependent_on = dependent_on
388
+
389
+
390
+ class RelationMultiSelectWidget(HtmxWidget):
391
+ """Widget for a M2M relation field — supports preload and lazy (HTMX) strategies."""
392
+
393
+ choices: list[ChoiceItem]
394
+ choices_url: str
395
+ preload: bool
396
+ dependent_on: str | None
397
+
398
+ def __init__(
399
+ self,
400
+ choices_url: str,
401
+ choices: list[ChoiceItem] | None = None,
402
+ preload: bool = True,
403
+ dependent_on: str | None = None,
404
+ ) -> None:
405
+ object.__setattr__(self, "template_path", "widgets/relation_multiselect_input.html")
406
+ object.__setattr__(self, "static_list", ())
407
+ object.__setattr__(self, "htmx_attrs", None)
408
+ self.choices = choices or []
409
+ self.choices_url = choices_url
410
+ self.preload = preload
411
+ self.dependent_on = dependent_on
412
+
413
+
414
+ class _AutocompleteMixin:
415
+ """Search input + populated ``<select>`` (+ optional "+" popup) for a relation (H6).
416
+
417
+ The search input GETs ``choices_url?q=`` debounced and swaps the returned
418
+ ``<option>`` fragment into the select. ``dependent_on`` adds an
419
+ ``hx-include`` of the parent field and re-fetches when the parent changes.
420
+ ``popup_url`` renders the "+" button that loads the create popup into
421
+ ``#ha-popup-root``; it is ``None`` when the related model is not registered.
422
+ """
423
+
424
+ multiple: ClassVar[bool] = False
425
+ placeholder: str | None
426
+ popup_url: str | None
427
+
428
+ def _init_autocomplete(self, placeholder: str | None, popup_url: str | None) -> None:
429
+ object.__setattr__(self, "template_path", "widgets/autocomplete.html")
430
+ self.placeholder = placeholder
431
+ self.popup_url = popup_url
432
+
433
+
434
+ class AutocompleteWidget(_AutocompleteMixin, RelationSelectWidget):
435
+ """Autocomplete widget for a single FK relation field."""
436
+
437
+ def __init__(
438
+ self,
439
+ choices_url: str,
440
+ choices: list[ChoiceItem] | None = None,
441
+ preload: bool = True,
442
+ dependent_on: str | None = None,
443
+ placeholder: str | None = None,
444
+ popup_url: str | None = None,
445
+ ) -> None:
446
+ super().__init__(choices_url, choices, preload, dependent_on)
447
+ self._init_autocomplete(placeholder, popup_url)
448
+
449
+
450
+ class AutocompleteMultiWidget(_AutocompleteMixin, RelationMultiSelectWidget):
451
+ """Autocomplete widget for a M2M relation field (multi-select list)."""
452
+
453
+ multiple: ClassVar[bool] = True
454
+
455
+ def __init__(
456
+ self,
457
+ choices_url: str,
458
+ choices: list[ChoiceItem] | None = None,
459
+ preload: bool = True,
460
+ dependent_on: str | None = None,
461
+ placeholder: str | None = None,
462
+ popup_url: str | None = None,
463
+ ) -> None:
464
+ super().__init__(choices_url, choices, preload, dependent_on)
465
+ self._init_autocomplete(placeholder, popup_url)
466
+
467
+
468
+ def relation_widget(
469
+ *,
470
+ choices_url: str,
471
+ choices: list[ChoiceItem],
472
+ preload: bool,
473
+ multiple: bool,
474
+ dependent_on: str | None = None,
475
+ autocomplete: bool = False,
476
+ placeholder: str | None = None,
477
+ popup_url: str | None = None,
478
+ ) -> HtmxWidget:
479
+ """Return the widget for a relation field: autocomplete when enabled, else the plain select."""
480
+ if autocomplete:
481
+ cls: type[AutocompleteWidget] | type[AutocompleteMultiWidget] = (
482
+ AutocompleteMultiWidget if multiple else AutocompleteWidget
483
+ )
484
+ return cls(
485
+ choices_url=choices_url,
486
+ choices=choices,
487
+ preload=preload,
488
+ dependent_on=dependent_on,
489
+ placeholder=placeholder,
490
+ popup_url=popup_url,
491
+ )
492
+ plain = RelationMultiSelectWidget if multiple else RelationSelectWidget
493
+ return plain(
494
+ choices_url=choices_url, choices=choices, preload=preload, dependent_on=dependent_on
495
+ )
496
+
497
+
498
+ def field_is_required(field: Any) -> bool:
499
+ """Whether a pydantic ``FieldInfo`` is required.
500
+
501
+ ``FieldInfo.is_required`` is a method; ``bool()`` of the bound method is
502
+ always ``True``, which marked every optional field as required. Plain
503
+ ``is_required`` booleans (lightweight field stand-ins) are honoured too.
504
+ """
505
+ is_required = getattr(field, "is_required", False)
506
+ return bool(is_required() if callable(is_required) else is_required)
507
+
508
+
509
+ def _is_untouched_datetime(raw: str, original: datetime, tz: tzinfo) -> bool:
510
+ """Whether ``raw`` is the rendered input value of ``original``.
511
+
512
+ The input shows ``original`` at second precision in ``tz``; a browser
513
+ submits a zero-seconds value in its short form (``2026-07-01T10:00``), so
514
+ the comparison is between parsed wall-clock times, not strings. Input with
515
+ an explicit offset was not produced by the widget and never matches.
516
+ """
517
+ try:
518
+ entered = datetime.fromisoformat(raw.strip())
519
+ except ValueError:
520
+ return False
521
+ shown = datetime.fromisoformat(format_datetime_input(original, tz))
522
+ return entered.tzinfo is None and entered == shown
523
+
524
+
525
+ def _accepts_none(field: Any) -> bool:
526
+ """Whether a field's annotation is optional (``X | None``), so ``""`` may become ``None``.
527
+
528
+ An optional field with a non-``None`` default (``notes: str = ""``) keeps
529
+ the empty string: ``None`` would fail validation.
530
+ """
531
+ return type(None) in get_args(getattr(field, "annotation", None))
532
+
533
+
534
+ @dataclass(slots=True)
535
+ class FormField:
536
+ name: str
537
+ model_field: FieldInfo
538
+ widget: HtmxWidget
539
+ value: Any | None = None
540
+ errors: ErrorList | None = None
541
+ #: A checkbox whose stored value is ``NULL``: it cannot show "unset", so the form
542
+ #: posts a marker and an unchecked box keeps the ``NULL`` instead of writing ``False``.
543
+ keeps_null: bool = False
544
+
545
+ @property
546
+ def label(self) -> str:
547
+ t = getattr(self.model_field, "title", None)
548
+ if t:
549
+ return t
550
+ name = self.name
551
+ # A foreign-key picker is labelled by what it points at, not by its column.
552
+ if isinstance(self.widget, RelationSelectWidget) and name.endswith("_id") and len(name) > 3:
553
+ name = name[: -len("_id")]
554
+ return name.replace("_", " ").capitalize()
555
+
556
+ @property
557
+ def required(self) -> bool:
558
+ return field_is_required(self.model_field)
559
+
560
+ def is_selected(self, choice_value: Any) -> bool:
561
+ """Whether ``choice_value`` is (one of) this field's current value(s).
562
+
563
+ Compares as text, so a stored enum member, a raw enum value and a
564
+ re-submitted form string all match their ``<option value>``.
565
+ """
566
+ if self.value is None:
567
+ return False
568
+ values = (
569
+ self.value if isinstance(self.value, list | tuple | set | frozenset) else [self.value]
570
+ )
571
+ current = {str(v.value if isinstance(v, Enum) else v) for v in values}
572
+ return str(choice_value) in current
573
+
574
+ @property
575
+ def help_text(self) -> str | None:
576
+ return getattr(self.model_field, "description", None)
577
+
578
+ @property
579
+ def input_type(self) -> str:
580
+ ann = getattr(self.model_field, "annotation", None)
581
+ try:
582
+ return ann.__name__ if ann else "text"
583
+ except AttributeError:
584
+ return "text"
585
+
586
+
587
+ @dataclass(slots=True)
588
+ class FieldsetGroup:
589
+ """A resolved group of ``FormField`` instances for template rendering.
590
+
591
+ Attributes:
592
+ name: Display heading for the fieldset.
593
+ fields: The ``FormField`` instances belonging to this group.
594
+ collapsed: Whether the fieldset starts collapsed.
595
+ description: Optional help text shown under the heading.
596
+ slug: URL-safe identifier derived from *name*, used in ``data-testid``.
597
+ """
598
+
599
+ name: str
600
+ fields: list[FormField]
601
+ collapsed: bool = False
602
+ description: str | None = None
603
+ slug: str = ""
604
+
605
+ def __post_init__(self) -> None:
606
+ if not self.slug:
607
+ self.slug = self.name.lower().replace(" ", "-")
608
+
609
+
610
+ class PydanticForm:
611
+ """A form over a Pydantic or SQLModel class: picks a widget per field, binds and validates.
612
+
613
+ The admin builds one per create and update page. ``bind`` fills the fields with values,
614
+ ``validate`` turns submitted strings into a model instance or per-field error lists.
615
+ """
616
+
617
+ def __init__(
618
+ self,
619
+ model: type[BaseModel],
620
+ *,
621
+ widgets: dict[str, HtmxWidget] | None = None,
622
+ include: list[str] | None = None,
623
+ exclude: list[str] | None = None,
624
+ initial: dict[str, Any] | None = None,
625
+ choices_base_url: str = "",
626
+ fieldsets: list[FieldsetSpec] | None = None,
627
+ form_layout: FormLayout | None = None,
628
+ form_fields: list[str] | None = None,
629
+ pk_attr: str = "id",
630
+ pk_editable: bool = False,
631
+ timezone: tzinfo = dt_timezone.utc,
632
+ datetime_kind: Callable[[str], DateTimeKind | None] | None = None,
633
+ ) -> None:
634
+ """Build a form over ``model``'s fields.
635
+
636
+ Args:
637
+ pk_attr: The model's primary-key attribute; skipped unless ``pk_editable``.
638
+ pk_editable: Render the primary key as an input. Set only on create
639
+ forms of models whose key is not generated (a natural key).
640
+ timezone: The display timezone for datetime input.
641
+ datetime_kind: Resolves a field to ``"aware"`` or ``"naive"``
642
+ (typically ``adapter.datetime_kind``). Fields it returns ``None``
643
+ for fall back to their annotation.
644
+ """
645
+ self.model = model
646
+ self.pk_attr = pk_attr
647
+ self.pk_editable = pk_editable
648
+ self.timezone = timezone
649
+ self.datetime_kind = datetime_kind
650
+ self.widgets = widgets or {}
651
+ self.include = set(include or [])
652
+ self.exclude = set(exclude or [])
653
+ self.initial = initial or {}
654
+ self.choices_base_url = choices_base_url
655
+ self.errors: dict[str, ErrorList] = {}
656
+ #: Field -> pydantic error types of the last ``validate`` (never input values).
657
+ self.error_types: dict[str, list[str]] = {}
658
+ self._fields: list[FormField] = []
659
+ self._fieldset_specs: list[FieldsetSpec] = fieldsets or []
660
+ self._form_layout: FormLayout | None = form_layout
661
+ self._form_fields: list[str] = form_fields or []
662
+
663
+ @staticmethod
664
+ def _enum_choices(enum_cls: type[Enum]) -> list[ChoiceItem]:
665
+ return [
666
+ ChoiceItem(
667
+ value=member.value,
668
+ label=get_enum_label(member),
669
+ selected=False,
670
+ )
671
+ for member in enum_cls
672
+ ]
673
+
674
+ @staticmethod
675
+ def _literal_choices(annotation: Any, field: FieldInfo) -> list[ChoiceItem]:
676
+ """Options for a ``Literal[...]`` of strings; a blank first when ``None`` is accepted."""
677
+ choices = [ChoiceItem(value=m, label=m, selected=False) for m in get_args(annotation)]
678
+ if _accepts_none(field):
679
+ choices.insert(0, ChoiceItem(value="", label="", selected=False))
680
+ return choices
681
+
682
+ def _pick_widget(self, name: str, field: FieldInfo) -> HtmxWidget: # noqa: PLR0911, PLR0912
683
+ if name in self.widgets:
684
+ return self.widgets[name]
685
+
686
+ # --- classify_field auto-detection (requires SQLAlchemy) ---
687
+ if _HAS_CLASSIFY and _classify_field is not None:
688
+ from hyperadmin.core.choices import SelectFieldMeta # noqa: PLC0415
689
+ from hyperadmin.core.uploads import FileFieldMeta # noqa: PLC0415
690
+
691
+ raw_meta = _classify_field(field, self.model)
692
+ if isinstance(raw_meta, FileFieldMeta):
693
+ if raw_meta.is_image:
694
+ return ImagePreviewWidget()
695
+ return FileInputWidget()
696
+ if isinstance(raw_meta, SelectFieldMeta):
697
+ meta = raw_meta
698
+ choices_url = f"{self.choices_base_url}/{name}" if self.choices_base_url else ""
699
+ if meta.choices_source == "enum":
700
+ # Extract enum type for choices
701
+ ann = _unwrap_optional(getattr(field, "annotation", None))
702
+ # Unwrap list[Enum]
703
+ if get_origin(ann) is list and get_args(ann):
704
+ ann = get_args(ann)[0]
705
+ enum_choices = (
706
+ self._enum_choices(ann)
707
+ if isinstance(ann, type) and issubclass(ann, Enum)
708
+ else []
709
+ )
710
+ if meta.multiple:
711
+ return MultiSelectWidget(choices=enum_choices)
712
+ return SelectWidget(choices=enum_choices)
713
+ if meta.choices_source == "static" and meta.multiple:
714
+ return MultiSelectWidget()
715
+ if meta.choices_source == "relation":
716
+ if meta.multiple:
717
+ return RelationMultiSelectWidget(
718
+ choices_url=choices_url,
719
+ preload=meta.preload,
720
+ dependent_on=meta.dependent_on,
721
+ )
722
+ return RelationSelectWidget(
723
+ choices_url=choices_url,
724
+ preload=meta.preload,
725
+ dependent_on=meta.dependent_on,
726
+ )
727
+
728
+ # --- Legacy heuristics ---
729
+ lower = name.lower()
730
+ if lower in {"description", "text", "body", "content"}:
731
+ return Textarea()
732
+
733
+ ann = _unwrap_optional(getattr(field, "annotation", None))
734
+
735
+ if ann is bool:
736
+ return CheckboxInput()
737
+ if ann is int:
738
+ return NumberInput()
739
+ if ann is float:
740
+ return FloatInput()
741
+ if _is_datetime_annotation(ann):
742
+ return DateTimeInput()
743
+ if ann is date:
744
+ return DateInput()
745
+ if isinstance(ann, type) and issubclass(ann, Enum):
746
+ return SelectInput()
747
+ if get_origin(ann) is Literal and all(isinstance(a, str) for a in get_args(ann)):
748
+ return SelectWidget(choices=self._literal_choices(ann, field))
749
+ if _is_json_annotation(ann):
750
+ return JsonTextarea()
751
+ if ann is bytes:
752
+ return HexTextarea()
753
+ return TextInput()
754
+
755
+ @staticmethod
756
+ def _is_auto_now_field(field: FieldInfo) -> bool:
757
+ if isinstance(field, FieldInfo):
758
+ # SQLModel keeps the column kwargs on the FieldInfo; schemas generated for plain
759
+ # SQLAlchemy models carry the same hint in json_schema_extra.
760
+ extra = field.json_schema_extra if isinstance(field.json_schema_extra, dict) else {}
761
+ sa_column_kwargs = getattr(field, "sa_column_kwargs", None) or extra.get(
762
+ "sa_column_kwargs"
763
+ )
764
+ if (
765
+ sa_column_kwargs
766
+ and isinstance(sa_column_kwargs, dict)
767
+ and ("server_default" in sa_column_kwargs or "onupdate" in sa_column_kwargs)
768
+ ):
769
+ return True
770
+ if is_auto_now_factory(field.default_factory):
771
+ return True
772
+ return False
773
+
774
+ @property
775
+ def auto_now_field_names(self) -> frozenset[str]:
776
+ """Names of model fields hidden from the form because they stamp "now".
777
+
778
+ An update must not write these: validation would fill them from their
779
+ default factory and overwrite the stored timestamp.
780
+ """
781
+ return frozenset(
782
+ name
783
+ for name, field in schema_for(self.model).model_fields.items()
784
+ if self._is_auto_now_field(field)
785
+ )
786
+
787
+ def _build_all_fields(self) -> dict[str, FormField]:
788
+ """Build all eligible form fields as a name->FormField mapping."""
789
+ field_map: dict[str, FormField] = {}
790
+ for name, field in schema_for(self.model).model_fields.items():
791
+ if self.include and name not in self.include:
792
+ continue
793
+ if name in self.exclude:
794
+ continue
795
+ if name == self.pk_attr and not self.pk_editable:
796
+ continue
797
+ if self._is_auto_now_field(field):
798
+ continue
799
+ widget = self._pick_widget(name, field)
800
+ default_val = getattr(field, "default", None)
801
+ if str(default_val) == "PydanticUndefined":
802
+ default_val = None
803
+ value = self.initial.get(name, default_val if default_val is not None else None)
804
+ if isinstance(value, (set, frozenset)):
805
+ # A MySQL SET column loads as a Python set; its text form is comma separated.
806
+ value = ",".join(sorted(value))
807
+ keeps_null = (
808
+ isinstance(widget, CheckboxInput) and name in self.initial and value is None
809
+ )
810
+ field_map[name] = FormField(
811
+ name=name, model_field=field, widget=widget, value=value, keeps_null=keeps_null
812
+ )
813
+ return field_map
814
+
815
+ @property
816
+ def fields(self) -> list[FormField]:
817
+ if self._fields:
818
+ return self._fields
819
+
820
+ field_map = self._build_all_fields()
821
+
822
+ # If form_fields is specified, use that ordering (and only those fields)
823
+ if self._form_fields:
824
+ for name in self._form_fields:
825
+ if name in field_map:
826
+ self._fields.append(field_map[name])
827
+ else:
828
+ # Default: model-definition order
829
+ self._fields = list(field_map.values())
830
+
831
+ return self._fields
832
+
833
+ @property
834
+ def fieldset_groups(self) -> list[FieldsetGroup]:
835
+ """Return form fields grouped according to the configured fieldsets.
836
+
837
+ If no fieldsets are configured, returns a single group containing all fields.
838
+ Fields referenced in a fieldset spec but not present in the form are silently
839
+ skipped. Fields not covered by any fieldset are collected into a trailing
840
+ "Other fields" group.
841
+ """
842
+ all_fields = self.fields
843
+ if not self._fieldset_specs:
844
+ return [FieldsetGroup(name="", fields=all_fields, slug="")]
845
+
846
+ field_map = {f.name: f for f in all_fields}
847
+ claimed: set[str] = set()
848
+ groups: list[FieldsetGroup] = []
849
+
850
+ for spec in self._fieldset_specs:
851
+ group_fields: list[FormField] = []
852
+ for fname in spec.fields:
853
+ if fname in field_map:
854
+ group_fields.append(field_map[fname])
855
+ claimed.add(fname)
856
+ if group_fields:
857
+ groups.append(
858
+ FieldsetGroup(
859
+ name=spec.name,
860
+ fields=group_fields,
861
+ collapsed=spec.collapsed,
862
+ description=spec.description,
863
+ )
864
+ )
865
+
866
+ # Collect unclaimed fields into a default group
867
+ remaining = [f for f in all_fields if f.name not in claimed]
868
+ if remaining:
869
+ groups.append(FieldsetGroup(name="Other fields", fields=remaining))
870
+
871
+ return groups
872
+
873
+ def bind(self, data: dict[str, Any]) -> None:
874
+ """Set each field's value from ``data`` (missing keys become ``None``)."""
875
+ for f in self.fields:
876
+ f.value = data.get(f.name)
877
+
878
+ def _field_datetime_kind(self, form_field: FormField) -> DateTimeKind | None:
879
+ """The datetime kind of a datetime-annotated field, else ``None``.
880
+
881
+ The resolver (the adapter's column introspection) decides; its ``None``
882
+ falls back to the annotation. A non-datetime field is never parsed here.
883
+ """
884
+ declared = annotation_datetime_kind(getattr(form_field.model_field, "annotation", None))
885
+ if declared is None:
886
+ return None
887
+ kind = self.datetime_kind(form_field.name) if self.datetime_kind else None
888
+ return kind or declared
889
+
890
+ def _clean_datetimes(self, cleaned_data: dict[str, Any]) -> dict[str, ErrorList]:
891
+ """Parse submitted datetime strings in place; return the fields that failed.
892
+
893
+ Aware columns localise naive input in ``self.timezone`` and store UTC;
894
+ naive columns keep the wall-clock value. A string naming the same second
895
+ as the formatted initial value (browsers submit ``10:00`` for
896
+ ``10:00:00``) keeps the original datetime, so an untouched field does
897
+ not lose its sub-second precision on edit.
898
+ """
899
+ errors: dict[str, ErrorList] = {}
900
+ for f in self.fields:
901
+ raw = cleaned_data.get(f.name)
902
+ if not isinstance(raw, str) or not raw.strip():
903
+ continue
904
+ kind = self._field_datetime_kind(f)
905
+ if kind is None:
906
+ continue
907
+ original = self.initial.get(f.name)
908
+ if isinstance(original, datetime) and _is_untouched_datetime(
909
+ raw, original, self.timezone
910
+ ):
911
+ cleaned_data[f.name] = original
912
+ continue
913
+ try:
914
+ cleaned_data[f.name] = parse_datetime_input(raw, kind=kind, tz=self.timezone)
915
+ except ValueError:
916
+ errors[f.name] = [_INVALID_DATETIME_MESSAGE]
917
+ return errors
918
+
919
+ def _clean_encoded(self, cleaned_data: dict[str, Any]) -> dict[str, tuple[ErrorList, str]]:
920
+ """Parse the text of each encoded textarea in place; return the fields that failed.
921
+
922
+ Each failure maps to its error list and its error type.
923
+ """
924
+ errors: dict[str, tuple[ErrorList, str]] = {}
925
+ for f in self.fields:
926
+ raw = cleaned_data.get(f.name)
927
+ if not isinstance(f.widget, EncodedTextarea) or not isinstance(raw, str):
928
+ continue
929
+ if not raw.strip():
930
+ continue
931
+ try:
932
+ cleaned_data[f.name] = f.widget.parse(raw)
933
+ except ValueError:
934
+ errors[f.name] = ([f.widget.error_message], f.widget.error_type)
935
+ return errors
936
+
937
+ def validate(self, data: dict[str, Any]) -> tuple[BaseModel | None, dict[str, ErrorList]]:
938
+ """Validate submitted ``data`` against the model.
939
+
940
+ Blank optional inputs become ``None`` and datetimes are parsed in the form's
941
+ timezone first. Returns ``(instance, {})`` on success, or ``(None, errors)`` with
942
+ the error list of each failing field (also stored on the fields for re-rendering).
943
+ """
944
+ cleaned_data = data.copy()
945
+ for f in self.fields:
946
+ if not f.required and cleaned_data.get(f.name) == "" and _accepts_none(f.model_field):
947
+ cleaned_data[f.name] = None
948
+ datetime_errors = self._clean_datetimes(cleaned_data)
949
+ encoded_errors = self._clean_encoded(cleaned_data)
950
+
951
+ instance: BaseModel | None = None
952
+ errs: dict[str, ErrorList] = {}
953
+ error_types: dict[str, list[str]] = {}
954
+ try:
955
+ instance = schema_for(self.model).model_validate(_FormData(cleaned_data, self.model))
956
+ except ValidationError as e:
957
+ for error in e.errors():
958
+ loc = error["loc"][0]
959
+ key = str(loc)
960
+ errs.setdefault(key, []).append(friendly_error(error))
961
+ error_types.setdefault(key, []).append(error["type"])
962
+ # A datetime, JSON or hex text the form could not parse replaces pydantic's message.
963
+ errs.update(datetime_errors)
964
+ for name in datetime_errors:
965
+ error_types[name] = ["datetime_parsing"]
966
+ for name, (messages, error_type) in encoded_errors.items():
967
+ errs[name] = messages
968
+ error_types[name] = [error_type]
969
+ self.error_types = error_types
970
+ self.errors = errs
971
+ if not errs:
972
+ return instance, {}
973
+ for f in self.fields:
974
+ f.errors = errs.get(f.name)
975
+ return None, errs
976
+
977
+ @property
978
+ def media(self) -> tuple[str, ...]:
979
+ seen: set[str] = set()
980
+ assets: list[str] = []
981
+ for f in self.fields:
982
+ for path in f.widget.static_list:
983
+ if path not in seen:
984
+ seen.add(path)
985
+ assets.append(path)
986
+ return tuple(assets)
987
+
988
+ @property
989
+ def layout_css_class(self) -> str:
990
+ """Return the CSS class for the form layout.
991
+
992
+ Returns ``ha-form-grid-2`` for two-column layout, empty string for single.
993
+ """
994
+ from hyperadmin.core.layouts import FormLayout # noqa: PLC0415
995
+
996
+ if self._form_layout == FormLayout.TWO_COLUMN:
997
+ return "ha-form-grid-2"
998
+ return ""
999
+
1000
+
1001
+ @dataclass(slots=True)
1002
+ class InlineFormRow:
1003
+ """A single row within an inline formset.
1004
+
1005
+ Attributes:
1006
+ index: The row index (0-based) within the formset.
1007
+ fields: The form fields for this row.
1008
+ pk: The primary key of an existing inline record, or ``None`` for new rows.
1009
+ A submitted key the inline model's codec rejects is kept raw.
1010
+ delete: Whether this row is marked for deletion.
1011
+ pk_errors: Errors for a submitted key the codec rejected.
1012
+ """
1013
+
1014
+ index: int
1015
+ fields: list[FormField]
1016
+ pk: Any = None
1017
+ delete: bool = False
1018
+ pk_errors: ErrorList | None = None
1019
+
1020
+ @property
1021
+ def has_errors(self) -> bool:
1022
+ """Whether the row's key or any of its fields carries a validation error."""
1023
+ return bool(self.pk_errors) or any(field.errors for field in self.fields)
1024
+
1025
+
1026
+ @dataclass
1027
+ class InlineFormset:
1028
+ """Manages a set of inline model rows for a parent form.
1029
+
1030
+ Provides methods to build empty rows, populate from existing data,
1031
+ validate submitted data, and extract structured results.
1032
+
1033
+ ``pk`` is the *inline* model's primary-key codec (from its adapter). Every
1034
+ submitted ``<prefix>-<i>-pk`` is parsed through it; a value it rejects is a
1035
+ row error. A parsed key is still only a claim: the adapter's ownership
1036
+ check rejects any key that is not an existing child of the parent.
1037
+ """
1038
+
1039
+ spec: InlineModelSpec
1040
+ rows: list[InlineFormRow] = dc_field(default_factory=list)
1041
+ errors: dict[int, dict[str, ErrorList]] = dc_field(default_factory=dict)
1042
+ add_row_url: str = ""
1043
+ pk: PrimaryKeyInfo = DEFAULT_PK
1044
+
1045
+ @property
1046
+ def prefix(self) -> str:
1047
+ """Return the form field name prefix for this inline."""
1048
+ return self.spec.model_name
1049
+
1050
+ @property
1051
+ def display_fields(self) -> list[str]:
1052
+ """Return field names shown in each row."""
1053
+ return self.spec.get_display_fields(pk_attr=self.pk.attr)
1054
+
1055
+ @property
1056
+ def sensitive_fields(self) -> set[str]:
1057
+ """Sensitive fields of the inline model (write-only: never rendered with a value)."""
1058
+ return effective_sensitive_field_names(self.spec.model)
1059
+
1060
+ @property
1061
+ def field_labels(self) -> list[str]:
1062
+ """Return human-readable labels for each display field."""
1063
+ model_fields = schema_for(self.spec.model).model_fields
1064
+ labels = []
1065
+ for name in self.display_fields:
1066
+ fi = model_fields.get(name)
1067
+ title = getattr(fi, "title", None) if fi else None
1068
+ labels.append(title or name.replace("_", " ").capitalize())
1069
+ return labels
1070
+
1071
+ @property
1072
+ def title(self) -> str:
1073
+ return self.spec.title
1074
+
1075
+ @property
1076
+ def max_num(self) -> int:
1077
+ return self.spec.max_num
1078
+
1079
+ def _build_row(
1080
+ self, index: int, values: dict[str, Any] | None = None, pk: Any = None
1081
+ ) -> InlineFormRow:
1082
+ """Build a single ``InlineFormRow`` for the given index."""
1083
+ model_fields = schema_for(self.spec.model).model_fields
1084
+ vals = values or {}
1085
+ sensitive = self.sensitive_fields
1086
+ fields: list[FormField] = []
1087
+ for name in self.display_fields:
1088
+ fi = model_fields.get(name)
1089
+ if fi is None:
1090
+ continue
1091
+ widget = _pick_inline_widget(name, fi)
1092
+ # Sensitive values are write-only: an empty input keeps the stored value.
1093
+ value = None if name in sensitive else vals.get(name)
1094
+ fields.append(FormField(name=name, model_field=fi, widget=widget, value=value))
1095
+ return InlineFormRow(index=index, fields=fields, pk=pk)
1096
+
1097
+ def build_empty_rows(self, count: int | None = None) -> None:
1098
+ """Populate ``self.rows`` with empty rows.
1099
+
1100
+ Args:
1101
+ count: Number of empty rows. Defaults to ``spec.extra``.
1102
+ """
1103
+ n = count if count is not None else self.spec.extra
1104
+ start = len(self.rows)
1105
+ for i in range(n):
1106
+ self.rows.append(self._build_row(start + i))
1107
+
1108
+ def populate_from_instances(self, instances: list[Any]) -> None:
1109
+ """Populate rows from existing related model instances."""
1110
+ self.rows = []
1111
+ for i, inst in enumerate(instances):
1112
+ vals = dump_instance(inst)
1113
+ pk = self.pk.value_of(inst)
1114
+ self.rows.append(self._build_row(i, values=vals, pk=pk))
1115
+ # Add extra empty rows
1116
+ self.build_empty_rows()
1117
+
1118
+ def extract_submitted_data(self, form_data: Any) -> list[dict[str, Any]]:
1119
+ """Parse submitted form data into a list of row dicts.
1120
+
1121
+ Form fields are named ``{prefix}-{index}-{field_name}``.
1122
+ Returns only rows that have at least one non-empty value and are not
1123
+ marked for deletion.
1124
+ """
1125
+ prefix = self.prefix
1126
+ results: list[dict[str, Any]] = []
1127
+ # Discover max index present in form data
1128
+ max_index = -1
1129
+ for key in form_data:
1130
+ if key.startswith(f"{prefix}-") and key.count("-") >= 2:
1131
+ parts = key.split("-", 2)
1132
+ try:
1133
+ idx = int(parts[1])
1134
+ max_index = max(max_index, idx)
1135
+ except (ValueError, IndexError):
1136
+ pass
1137
+
1138
+ for i in range(max_index + 1):
1139
+ # Check deletion flag
1140
+ delete_key = f"{prefix}-{i}-DELETE"
1141
+ if form_data.get(delete_key):
1142
+ # Collect pk for deletion
1143
+ pk_key = f"{prefix}-{i}-pk"
1144
+ pk_val = form_data.get(pk_key)
1145
+ if pk_val is not None:
1146
+ results.append({"_delete": True, **self._submitted_pk(pk_val)})
1147
+ continue
1148
+
1149
+ row_data: dict[str, Any] = {}
1150
+ pk_key = f"{prefix}-{i}-pk"
1151
+ pk_val = form_data.get(pk_key)
1152
+ if pk_val is not None:
1153
+ row_data.update(self._submitted_pk(pk_val))
1154
+
1155
+ has_data = False
1156
+ for field_name in self.display_fields:
1157
+ key = f"{prefix}-{i}-{field_name}"
1158
+ val = form_data.get(key, "")
1159
+ row_data[field_name] = val
1160
+ if val not in ("", None):
1161
+ has_data = True
1162
+
1163
+ if has_data:
1164
+ results.append(row_data)
1165
+
1166
+ return results
1167
+
1168
+ def validate_rows(
1169
+ self,
1170
+ rows_data: list[dict[str, Any]],
1171
+ parent_pk: Any = None,
1172
+ ) -> tuple[list[dict[str, Any]], dict[int, dict[str, ErrorList]]]:
1173
+ """Validate each row's data against the inline model.
1174
+
1175
+ Returns:
1176
+ A tuple of (valid_rows, errors_by_index).
1177
+ Each valid row is a dict ready for adapter.create/update.
1178
+ """
1179
+ valid: list[dict[str, Any]] = []
1180
+ errors: dict[int, dict[str, ErrorList]] = {}
1181
+
1182
+ for i, row in enumerate(rows_data):
1183
+ if "_pk_invalid" in row:
1184
+ errors[i] = {"pk": [_INVALID_PK_MESSAGE]}
1185
+ continue
1186
+ if row.get("_delete"):
1187
+ valid.append(row)
1188
+ continue
1189
+
1190
+ # Build full data dict including FK
1191
+ data = {k: v for k, v in row.items() if not k.startswith("_")}
1192
+ if parent_pk is not None:
1193
+ data[self.spec.fk_field] = parent_pk
1194
+ else:
1195
+ fk_info = schema_for(self.spec.model).model_fields.get(self.spec.fk_field)
1196
+ if fk_info is not None and fk_info.is_required():
1197
+ data.setdefault(self.spec.fk_field, _placeholder_key(fk_info.annotation))
1198
+
1199
+ # Clean empty strings to None for optional fields
1200
+ model_fields = schema_for(self.spec.model).model_fields
1201
+ for field_name, val in list(data.items()):
1202
+ fi = model_fields.get(field_name)
1203
+ if fi and not fi.is_required() and val == "":
1204
+ data[field_name] = None
1205
+
1206
+ try:
1207
+ instance = schema_for(self.spec.model).model_validate(
1208
+ _FormData(data, self.spec.model)
1209
+ )
1210
+ result = instance.model_dump()
1211
+ if "_pk" in row:
1212
+ result["_pk"] = row["_pk"]
1213
+ valid.append(result)
1214
+ except ValidationError as e:
1215
+ row_errors: dict[str, ErrorList] = {}
1216
+ for error in e.errors():
1217
+ loc = str(error["loc"][0])
1218
+ row_errors.setdefault(loc, []).append(friendly_error(error))
1219
+ errors[i] = row_errors
1220
+
1221
+ self.errors = errors
1222
+ return valid, errors
1223
+
1224
+ def rebuild_from_submitted(self, form_data: Any) -> None:
1225
+ """Rebuild rows from submitted form data for re-rendering on validation errors."""
1226
+ prefix = self.prefix
1227
+ max_index = -1
1228
+ for key in form_data:
1229
+ if key.startswith(f"{prefix}-") and key.count("-") >= 2:
1230
+ parts = key.split("-", 2)
1231
+ try:
1232
+ idx = int(parts[1])
1233
+ max_index = max(max_index, idx)
1234
+ except (ValueError, IndexError):
1235
+ pass
1236
+
1237
+ self.rows = []
1238
+ for i in range(max_index + 1):
1239
+ vals: dict[str, Any] = {}
1240
+ for field_name in self.display_fields:
1241
+ key = f"{prefix}-{i}-{field_name}"
1242
+ vals[field_name] = form_data.get(key, "")
1243
+
1244
+ pk_key = f"{prefix}-{i}-pk"
1245
+ pk_val = form_data.get(pk_key)
1246
+ pk_info = self._submitted_pk(pk_val) if pk_val is not None else {}
1247
+ pk = pk_info.get("_pk", pk_info.get("_pk_invalid"))
1248
+
1249
+ row = self._build_row(i, values=vals, pk=pk)
1250
+ if "_pk_invalid" in pk_info:
1251
+ row.pk_errors = [_INVALID_PK_MESSAGE]
1252
+
1253
+ # Apply field-level errors
1254
+ if i in self.errors:
1255
+ for field in row.fields:
1256
+ field.errors = self.errors.get(i, {}).get(field.name)
1257
+
1258
+ delete_key = f"{prefix}-{i}-DELETE"
1259
+ row.delete = bool(form_data.get(delete_key))
1260
+
1261
+ self.rows.append(row)
1262
+
1263
+ def _submitted_pk(self, raw: Any) -> dict[str, Any]:
1264
+ """Parse a submitted ``<prefix>-<i>-pk`` with the inline model's codec.
1265
+
1266
+ Returns ``{"_pk": <typed key>}``, or ``{"_pk_invalid": <raw str>}`` when
1267
+ the codec rejects it (e.g. ``"zzz"`` for a UUID key). A ``str`` key keeps
1268
+ its exact text, so ``"007"`` is never turned into ``7``.
1269
+ """
1270
+ try:
1271
+ return {"_pk": self.pk.parse(raw)}
1272
+ except InvalidPrimaryKey:
1273
+ return {"_pk_invalid": str(raw)}
1274
+
1275
+
1276
+ def _pick_inline_widget(name: str, field_info: FieldInfo) -> HtmxWidget:
1277
+ """Pick a simple widget for an inline field (no relation support yet)."""
1278
+ ann = _unwrap_optional(getattr(field_info, "annotation", None))
1279
+
1280
+ if ann is bool:
1281
+ return CheckboxInput()
1282
+ if ann is int:
1283
+ return NumberInput()
1284
+ if ann is float:
1285
+ return FloatInput()
1286
+ if _is_datetime_annotation(ann):
1287
+ return DateTimeInput()
1288
+ if isinstance(ann, type) and issubclass(ann, Enum):
1289
+ return SelectInput()
1290
+
1291
+ lower = name.lower()
1292
+ if lower in {"description", "text", "body", "content"}:
1293
+ return Textarea()
1294
+ return TextInput()