neutralino-python 0.1.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.
- neutralino/__init__.py +88 -0
- neutralino/_catalog.py +297 -0
- neutralino/_data/LICENSE.neutralino-js-client +21 -0
- neutralino/_data/LICENSE.neutralinojs +1066 -0
- neutralino/_data/docs/cli.md +315 -0
- neutralino/_data/docs/custom-components.md +107 -0
- neutralino/_data/docs/custom-frontends.md +80 -0
- neutralino/_data/docs/desktop-helpers.md +296 -0
- neutralino/_data/docs/guide.md +131 -0
- neutralino/_data/docs/llms-full.txt +3921 -0
- neutralino/_data/docs/llms.txt +43 -0
- neutralino/_data/docs/manifests/components.json +20128 -0
- neutralino/_data/docs/manifests/examples.json +52 -0
- neutralino/_data/docs/manifests/native.json +3024 -0
- neutralino/_data/docs/manifests/schema.json +43 -0
- neutralino/_data/docs/manual-checklist.md +189 -0
- neutralino/_data/docs/packaging.md +252 -0
- neutralino/_data/docs/performance.md +15 -0
- neutralino/_data/docs/platforms.md +15 -0
- neutralino/_data/docs/reference/components.md +1685 -0
- neutralino/_data/docs/reference/native.md +148 -0
- neutralino/_data/docs/security.md +60 -0
- neutralino/_data/docs/ui.md +249 -0
- neutralino/_data/docs/updates.md +366 -0
- neutralino/_data/examples/README.md +6 -0
- neutralino/_data/examples/crud/README.md +36 -0
- neutralino/_data/examples/crud/app.py +243 -0
- neutralino/_data/examples/dashboard/README.md +36 -0
- neutralino/_data/examples/dashboard/app.py +367 -0
- neutralino/_data/examples/editor/README.md +35 -0
- neutralino/_data/examples/editor/app.py +190 -0
- neutralino/_data/examples/file-manager/README.md +40 -0
- neutralino/_data/examples/file-manager/app.py +120 -0
- neutralino/_data/examples/file-manager/frontend/index.html +20 -0
- neutralino/_data/examples/file-manager/frontend/main.js +55 -0
- neutralino/_data/examples/file-manager/frontend/neutralino.js +1 -0
- neutralino/_data/examples/file-manager/frontend/python-bridge.d.ts +207 -0
- neutralino/_data/examples/file-manager/frontend/python-bridge.mjs +854 -0
- neutralino/_data/examples/file-manager/frontend/style.css +4 -0
- neutralino/_data/examples/hybrid/README.md +48 -0
- neutralino/_data/examples/hybrid/app.py +80 -0
- neutralino/_data/examples/hybrid/components/counter.mjs +37 -0
- neutralino/_data/examples/hybrid/components/widget.mjs +23 -0
- neutralino/_data/examples/hybrid/styles.css +21 -0
- neutralino/_data/examples/hybrid/widget/package.json +20 -0
- neutralino/_data/examples/hybrid/widget/src/Widget.jsx +25 -0
- neutralino/_data/examples/hybrid/widget/vite.config.mjs +19 -0
- neutralino/_data/examples/monitor/README.md +36 -0
- neutralino/_data/examples/monitor/app.py +375 -0
- neutralino/_data/examples/react/README.md +90 -0
- neutralino/_data/examples/react/app.py +68 -0
- neutralino/_data/examples/react/frontend/.gitignore +5 -0
- neutralino/_data/examples/react/frontend/index.html +17 -0
- neutralino/_data/examples/react/frontend/package-lock.json +1232 -0
- neutralino/_data/examples/react/frontend/package.json +25 -0
- neutralino/_data/examples/react/frontend/scripts/prepare-bridge.mjs +49 -0
- neutralino/_data/examples/react/frontend/src/App.tsx +157 -0
- neutralino/_data/examples/react/frontend/src/backend.ts +21 -0
- neutralino/_data/examples/react/frontend/src/calls.test.ts +206 -0
- neutralino/_data/examples/react/frontend/src/calls.ts +306 -0
- neutralino/_data/examples/react/frontend/src/globals.d.ts +14 -0
- neutralino/_data/examples/react/frontend/src/hooks.ts +45 -0
- neutralino/_data/examples/react/frontend/src/main.tsx +13 -0
- neutralino/_data/examples/react/frontend/src/styles.css +11 -0
- neutralino/_data/examples/react/frontend/tsconfig.json +18 -0
- neutralino/_data/examples/react/frontend/vite.config.ts +9 -0
- neutralino/_data/examples/settings/README.md +38 -0
- neutralino/_data/examples/settings/app.py +440 -0
- neutralino/_data/examples/updater/.gitignore +2 -0
- neutralino/_data/examples/updater/README.md +82 -0
- neutralino/_data/examples/updater/app.py +160 -0
- neutralino/_data/examples/updater/app.toml +21 -0
- neutralino/_data/examples/updater/demo.py +107 -0
- neutralino/_data/examples/updater/requirements.txt +2 -0
- neutralino/_data/examples/updater/sources/github-private.toml +21 -0
- neutralino/_data/examples/updater/sources/github-public.toml +21 -0
- neutralino/_data/examples/vanilla/README.md +35 -0
- neutralino/_data/examples/vanilla/app.py +46 -0
- neutralino/_data/examples/vanilla/frontend/index.html +17 -0
- neutralino/_data/examples/vanilla/frontend/main.js +29 -0
- neutralino/_data/examples/vanilla/frontend/neutralino.js +1 -0
- neutralino/_data/examples/vanilla/frontend/python-bridge.d.ts +207 -0
- neutralino/_data/examples/vanilla/frontend/python-bridge.mjs +854 -0
- neutralino/_data/examples/vanilla/frontend/style.css +4 -0
- neutralino/_data/explorer/app.py +1328 -0
- neutralino/_data/explorer/catalogue.json +48179 -0
- neutralino/_data/explorer/explorer_previews.py +247 -0
- neutralino/_data/explorer/sources/native/always_on_top.py +55 -0
- neutralino/_data/explorer/sources/native/binary.py +125 -0
- neutralino/_data/explorer/sources/native/borderless.py +99 -0
- neutralino/_data/explorer/sources/native/broadcast.py +90 -0
- neutralino/_data/explorer/sources/native/config.py +78 -0
- neutralino/_data/explorer/sources/native/controls.py +140 -0
- neutralino/_data/explorer/sources/native/directory.py +163 -0
- neutralino/_data/explorer/sources/native/displays.py +75 -0
- neutralino/_data/explorer/sources/native/env.py +98 -0
- neutralino/_data/explorer/sources/native/events.py +124 -0
- neutralino/_data/explorer/sources/native/exec_command.py +79 -0
- neutralino/_data/explorer/sources/native/folder.py +70 -0
- neutralino/_data/explorer/sources/native/icon_badge.py +101 -0
- neutralino/_data/explorer/sources/native/image.py +119 -0
- neutralino/_data/explorer/sources/native/lifecycle.py +99 -0
- neutralino/_data/explorer/sources/native/locale.py +70 -0
- neutralino/_data/explorer/sources/native/main_menu.py +103 -0
- neutralino/_data/explorer/sources/native/message_box.py +101 -0
- neutralino/_data/explorer/sources/native/mouse.py +70 -0
- neutralino/_data/explorer/sources/native/multi_window.py +134 -0
- neutralino/_data/explorer/sources/native/notification.py +74 -0
- neutralino/_data/explorer/sources/native/open_external.py +81 -0
- neutralino/_data/explorer/sources/native/open_file.py +102 -0
- neutralino/_data/explorer/sources/native/paths.py +77 -0
- neutralino/_data/explorer/sources/native/print_snapshot.py +84 -0
- neutralino/_data/explorer/sources/native/read_write.py +192 -0
- neutralino/_data/explorer/sources/native/resources.py +110 -0
- neutralino/_data/explorer/sources/native/save_file.py +101 -0
- neutralino/_data/explorer/sources/native/server_mount.py +106 -0
- neutralino/_data/explorer/sources/native/sound.py +84 -0
- neutralino/_data/explorer/sources/native/spawn_process.py +128 -0
- neutralino/_data/explorer/sources/native/states.py +122 -0
- neutralino/_data/explorer/sources/native/stats_permissions.py +147 -0
- neutralino/_data/explorer/sources/native/storage.py +108 -0
- neutralino/_data/explorer/sources/native/system_info.py +115 -0
- neutralino/_data/explorer/sources/native/text.py +133 -0
- neutralino/_data/explorer/sources/native/trash.py +98 -0
- neutralino/_data/explorer/sources/native/tray.py +109 -0
- neutralino/_data/explorer/sources/native/watcher.py +167 -0
- neutralino/_data/explorer/sources/patterns/content_blocks.py +119 -0
- neutralino/_data/explorer/sources/patterns/dynamic_dashboard.py +121 -0
- neutralino/_data/explorer/sources/patterns/dynamic_form.py +120 -0
- neutralino/_data/explorer/sources/patterns/dynamic_table.py +109 -0
- neutralino/_data/explorer/sources/patterns/error_reporting.mjs +24 -0
- neutralino/_data/explorer/sources/patterns/error_reporting.py +124 -0
- neutralino/_data/explorer/sources/patterns/errors_timeouts.py +108 -0
- neutralino/_data/explorer/sources/patterns/feature_flags.py +99 -0
- neutralino/_data/explorer/sources/patterns/file_drop.py +126 -0
- neutralino/_data/explorer/sources/patterns/http_from_python.py +152 -0
- neutralino/_data/explorer/sources/patterns/keyboard_shortcuts.py +153 -0
- neutralino/_data/explorer/sources/patterns/live_config_reload.py +160 -0
- neutralino/_data/explorer/sources/patterns/logging.py +184 -0
- neutralino/_data/explorer/sources/patterns/long_tasks.py +121 -0
- neutralino/_data/explorer/sources/patterns/multi_window_sync.py +68 -0
- neutralino/_data/explorer/sources/patterns/navigation_from_backend.py +109 -0
- neutralino/_data/explorer/sources/patterns/onboarding.py +123 -0
- neutralino/_data/explorer/sources/patterns/optimistic_updates.py +89 -0
- neutralino/_data/explorer/sources/patterns/persistence.py +114 -0
- neutralino/_data/explorer/sources/patterns/python_calls_page.mjs +10 -0
- neutralino/_data/explorer/sources/patterns/python_calls_page.py +64 -0
- neutralino/_data/explorer/sources/patterns/python_push.py +84 -0
- neutralino/_data/explorer/sources/patterns/recurring_events.py +114 -0
- neutralino/_data/explorer/sources/patterns/roles_permissions.py +104 -0
- neutralino/_data/explorer/sources/patterns/scheduled_jobs.py +194 -0
- neutralino/_data/explorer/sources/patterns/settings_page.py +165 -0
- neutralino/_data/explorer/sources/patterns/sqlite.py +181 -0
- neutralino/_data/explorer/sources/patterns/streaming.py +102 -0
- neutralino/_data/explorer/sources/patterns/texts_i18n.py +81 -0
- neutralino/_data/explorer/sources/patterns/theme_from_backend.py +86 -0
- neutralino/_data/explorer/sources/patterns/updater.py +232 -0
- neutralino/_data/explorer/sources/workspace/calendar/app.py +547 -0
- neutralino/_data/explorer/sources/workspace/customers/app.py +467 -0
- neutralino/_data/explorer/sources/workspace/dashboard/README.md +36 -0
- neutralino/_data/explorer/sources/workspace/dashboard/app.py +367 -0
- neutralino/_data/explorer/sources/workspace/documents/app.py +511 -0
- neutralino/_data/explorer/sources/workspace/inbox/app.py +439 -0
- neutralino/_data/explorer/sources/workspace/orders/app.py +491 -0
- neutralino/_data/explorer/sources/workspace/reports/app.py +386 -0
- neutralino/_data/explorer/sources/workspace/settings/README.md +38 -0
- neutralino/_data/explorer/sources/workspace/settings/app.py +440 -0
- neutralino/_data/explorer/sources/workspace/system/README.md +36 -0
- neutralino/_data/explorer/sources/workspace/system/app.py +375 -0
- neutralino/_data/explorer/sources/workspace/tasks/app.py +462 -0
- neutralino/_data/renderer/LICENSES/@babel__runtime@7.29.17/LICENSE +22 -0
- neutralino/_data/renderer/LICENSES/@codemirror__autocomplete@6.20.4/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__commands@6.11.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-css@6.3.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-html@6.4.12/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-javascript@6.2.5/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-json@6.0.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-markdown@6.5.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-python@6.2.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-sql@6.10.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__lang-yaml@6.1.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__language@6.13.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__search@6.7.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__state@6.7.6/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@codemirror__view@6.44.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@dnd-kit__accessibility@3.1.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@dnd-kit__core@6.3.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@dnd-kit__sortable@10.0.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@dnd-kit__utilities@3.2.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@emoji-mart__data@1.2.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@floating-ui__core@1.8.0/LICENSE +20 -0
- neutralino/_data/renderer/LICENSES/@floating-ui__dom@1.8.0/LICENSE +20 -0
- neutralino/_data/renderer/LICENSES/@floating-ui__react-dom@2.1.9/LICENSE +20 -0
- neutralino/_data/renderer/LICENSES/@floating-ui__react@0.27.20/LICENSE +20 -0
- neutralino/_data/renderer/LICENSES/@floating-ui__utils@0.2.12/LICENSE +20 -0
- neutralino/_data/renderer/LICENSES/@lezer__common@1.5.7/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__css@1.3.9/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__highlight@1.2.5/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__html@1.3.13/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__javascript@1.5.7/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__json@1.0.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__lr@1.4.13/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__markdown@1.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__python@1.1.21/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@lezer__yaml@1.0.4/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__carousel@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__charts@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__code-highlight@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__core@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__dates@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__dropzone@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__emoji@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__hooks@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__lightbox@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__notifications@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__nprogress@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__schedule@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__spotlight@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__store@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@mantine__tiptap@9.8.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@marijn__find-cluster-break@1.0.4/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@reduxjs__toolkit@2.16.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@tabler__icons-react@3.55.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@tanstack__react-virtual@3.14.32/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@tanstack__virtual-core@3.19.17/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__core@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-blockquote@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-bold@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-code-block@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-code@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-document@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-hard-break@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-heading@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-horizontal-rule@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-italic@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-link@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-list@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-paragraph@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-strike@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-text@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extension-underline@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__extensions@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__react@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/@tiptap__starter-kit@3.35.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/attr-accept@4.0.1/LICENSE +22 -0
- neutralino/_data/renderer/LICENSES/clsx@2.1.1/license +9 -0
- neutralino/_data/renderer/LICENSES/crelt@1.0.7/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/d3-array@3.2.5/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-color@3.1.1/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-format@3.1.3/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-interpolate@3.0.2/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-path@3.1.1/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-scale@4.0.3/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-shape@3.2.1/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-time-format@4.1.1/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/d3-time@3.1.1/LICENSE +13 -0
- neutralino/_data/renderer/LICENSES/dayjs@1.11.23/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/decimal.js-light@2.5.1/LICENCE.md +23 -0
- neutralino/_data/renderer/LICENSES/diff@9.0.0/LICENSE +29 -0
- neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE +202 -0
- neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE-MPL +373 -0
- neutralino/_data/renderer/LICENSES/embla-carousel-react@8.6.0/MIT-embla-carousel.txt +21 -0
- neutralino/_data/renderer/LICENSES/embla-carousel-reactive-utils@8.6.0/MIT-embla-carousel.txt +21 -0
- neutralino/_data/renderer/LICENSES/embla-carousel@8.6.0/MIT-embla-carousel.txt +21 -0
- neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/NOTICE +39 -0
- neutralino/_data/renderer/LICENSES/eventemitter3@5.0.4/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/fast-equals@5.4.7/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/file-selector@5.0.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/get-nonce@1.0.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/immer@11.2.14/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/linkifyjs@4.4.0/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/marked@18.4.0/LICENSE +44 -0
- neutralino/_data/renderer/LICENSES/neutralino.js@6.11.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/orderedmap@2.1.1/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/packages.json +1838 -0
- neutralino/_data/renderer/LICENSES/prosemirror-commands@1.7.2/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-dropcursor@1.8.4/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-gapcursor@1.4.1/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-history@1.5.2/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-keymap@1.2.3/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-model@1.25.13/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-schema-list@1.6.1/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-state@1.4.4/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-transform@1.12.7/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/prosemirror-view@1.44.0/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/react-dom@19.3.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/react-dropzone@20.1.4/LICENSE +22 -0
- neutralino/_data/renderer/LICENSES/react-is@19.3.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/react-number-format@5.4.5/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/react-redux@9.3.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/react-remove-scroll-bar@2.3.8/MIT-react-remove-scroll-bar.txt +21 -0
- neutralino/_data/renderer/LICENSES/react-remove-scroll@2.7.2/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/react-style-singleton@2.2.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/react-transition-group@4.4.5/LICENSE +30 -0
- neutralino/_data/renderer/LICENSES/react@19.3.1/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/recharts@3.11.3/LICENSE +22 -0
- neutralino/_data/renderer/LICENSES/redux-thunk@3.1.0/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/redux@5.0.1/LICENSE.md +21 -0
- neutralino/_data/renderer/LICENSES/reselect@5.2.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/rolldown@1.3.4/LICENSE +25 -0
- neutralino/_data/renderer/LICENSES/rope-sequence@1.3.4/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/rrule@2.8.1/LICENCE +65 -0
- neutralino/_data/renderer/LICENSES/scheduler@0.28.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/style-mod@4.1.5/LICENSE +19 -0
- neutralino/_data/renderer/LICENSES/tiny-invariant@1.3.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/tslib@2.9.1/LICENSE.txt +12 -0
- neutralino/_data/renderer/LICENSES/use-callback-ref@1.3.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/use-sidecar@1.1.3/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/use-sync-external-store@1.7.0/LICENSE +21 -0
- neutralino/_data/renderer/LICENSES/victory-vendor@38.1.1/LICENSE.txt +150 -0
- neutralino/_data/renderer/LICENSES/vite@8.4.1/LICENSE.md +2320 -0
- neutralino/_data/renderer/LICENSES/w3c-keyname@2.2.8/LICENSE +19 -0
- neutralino/_data/renderer/assets/IconGripVertical-BlJrWVuo.js +1 -0
- neutralino/_data/renderer/assets/carousel-D1j1SkWR.css +1 -0
- neutralino/_data/renderer/assets/carousel-DniHwTLK.js +1 -0
- neutralino/_data/renderer/assets/chunk-CCkLOSkX.css +1 -0
- neutralino/_data/renderer/assets/chunk-Du0h7lB-.js +9 -0
- neutralino/_data/renderer/assets/codehighlight-CCe_blv1.js +10 -0
- neutralino/_data/renderer/assets/codehighlight-THJMNDh8.css +1 -0
- neutralino/_data/renderer/assets/codemirror-CinrNxVJ.js +2 -0
- neutralino/_data/renderer/assets/css-CMUk25uq.js +1 -0
- neutralino/_data/renderer/assets/dist-70Le0T2N.js +1 -0
- neutralino/_data/renderer/assets/dist-BCHbQlae.js +11 -0
- neutralino/_data/renderer/assets/dist-BXts23GT.js +1 -0
- neutralino/_data/renderer/assets/dist-D2RX2UgP.js +23 -0
- neutralino/_data/renderer/assets/dist-DikJK2lp.js +1 -0
- neutralino/_data/renderer/assets/dist-acbbRM1z.js +1 -0
- neutralino/_data/renderer/assets/dnd-DaaaVala.js +5 -0
- neutralino/_data/renderer/assets/dropzone-CeqF5SZx.js +1 -0
- neutralino/_data/renderer/assets/dropzone-aPCBPjDN.css +1 -0
- neutralino/_data/renderer/assets/embla-carousel-react.esm-CbyYjwMN.js +1 -0
- neutralino/_data/renderer/assets/emoji-BfRPfoVw.js +1 -0
- neutralino/_data/renderer/assets/emoji-DV8OzU1E.css +1 -0
- neutralino/_data/renderer/assets/esm-C5ZYjSBQ.js +82 -0
- neutralino/_data/renderer/assets/highlight-CB6hGb5A.js +3 -0
- neutralino/_data/renderer/assets/highlight-Dlb5DJwL.css +1 -0
- neutralino/_data/renderer/assets/html-Dad3kwIa.js +1 -0
- neutralino/_data/renderer/assets/icon-chunk-X3Kr0nh-.js +1 -0
- neutralino/_data/renderer/assets/index-CU0HB-J7.js +69 -0
- neutralino/_data/renderer/assets/index-TWpF4Lef.css +1 -0
- neutralino/_data/renderer/assets/javascript-BQb8vpw3.js +1 -0
- neutralino/_data/renderer/assets/json-BCFmxlML.js +1 -0
- neutralino/_data/renderer/assets/lightbox-BHtgbsUV.js +1 -0
- neutralino/_data/renderer/assets/lightbox-BzKDpkAD.css +1 -0
- neutralino/_data/renderer/assets/markdown-DSuAylvy.js +5 -0
- neutralino/_data/renderer/assets/markdown-DjaNWMgH.js +77 -0
- neutralino/_data/renderer/assets/python-pdbIAveZ.js +9 -0
- neutralino/_data/renderer/assets/richtext-DIAsHMuK.css +1 -0
- neutralino/_data/renderer/assets/richtext-Z6fG9G2_.js +137 -0
- neutralino/_data/renderer/assets/spotlight-Ccstaz1-.css +1 -0
- neutralino/_data/renderer/assets/spotlight-knlyJw_A.js +1 -0
- neutralino/_data/renderer/assets/sql-DLoQFEde.js +2 -0
- neutralino/_data/renderer/assets/with-selector-BOM9_OlN.js +1 -0
- neutralino/_data/renderer/assets/yaml-BJNzokSe.js +1 -0
- neutralino/_data/renderer/index.html +22 -0
- neutralino/_data/renderer/manifest.json +202 -0
- neutralino/_data/renderer/neutralino.js +1 -0
- neutralino/_data/renderer/shared/mantine-core.mjs +5 -0
- neutralino/_data/renderer/shared/mantine-hooks.mjs +5 -0
- neutralino/_data/renderer/shared/react-dom-client.mjs +5 -0
- neutralino/_data/renderer/shared/react-dom.mjs +6 -0
- neutralino/_data/renderer/shared/react-jsx-runtime.mjs +5 -0
- neutralino/_data/renderer/shared/react.mjs +6 -0
- neutralino/_data/skills/README.md +6 -0
- neutralino/_data/skills/neutralino-app-patterns/SKILL.md +101 -0
- neutralino/_data/skills/neutralino-app-patterns/references/dashboards-and-background-work.md +55 -0
- neutralino/_data/skills/neutralino-app-patterns/references/storage-and-settings.md +57 -0
- neutralino/_data/skills/neutralino-app-patterns/references/tables-and-crud.md +81 -0
- neutralino/_data/skills/neutralino-frontend/SKILL.md +121 -0
- neutralino/_data/skills/neutralino-frontend/references/bridge.md +63 -0
- neutralino/_data/skills/neutralino-frontend/references/custom-components.md +84 -0
- neutralino/_data/skills/neutralino-frontend/references/frameworks.md +61 -0
- neutralino/_data/skills/neutralino-maintenance/SKILL.md +85 -0
- neutralino/_data/skills/neutralino-maintenance/references/platforms-and-gates.md +35 -0
- neutralino/_data/skills/neutralino-maintenance/references/records.md +38 -0
- neutralino/_data/skills/neutralino-maintenance/references/review-process.md +36 -0
- neutralino/_data/skills/neutralino-native/SKILL.md +107 -0
- neutralino/_data/skills/neutralino-native/references/api-conventions.md +72 -0
- neutralino/_data/skills/neutralino-native/references/desktop-helpers.md +53 -0
- neutralino/_data/skills/neutralino-native/references/permissions-windows.md +53 -0
- neutralino/_data/skills/neutralino-packaging/SKILL.md +99 -0
- neutralino/_data/skills/neutralino-packaging/references/build-layout.md +51 -0
- neutralino/_data/skills/neutralino-packaging/references/managed-install.md +59 -0
- neutralino/_data/skills/neutralino-packaging/references/templates-and-config.md +63 -0
- neutralino/_data/skills/neutralino-python/SKILL.md +109 -0
- neutralino/_data/skills/neutralino-python/references/architecture.md +53 -0
- neutralino/_data/skills/neutralino-python/references/cli.md +60 -0
- neutralino/_data/skills/neutralino-python/references/platforms-security.md +44 -0
- neutralino/_data/skills/neutralino-rpc/SKILL.md +114 -0
- neutralino/_data/skills/neutralino-rpc/references/errors-and-limits.md +44 -0
- neutralino/_data/skills/neutralino-rpc/references/expose-and-context.md +74 -0
- neutralino/_data/skills/neutralino-rpc/references/streams-and-cancellation.md +53 -0
- neutralino/_data/skills/neutralino-ui/SKILL.md +115 -0
- neutralino/_data/skills/neutralino-ui/references/components-and-tree.md +74 -0
- neutralino/_data/skills/neutralino-ui/references/state-forms-events.md +85 -0
- neutralino/_data/skills/neutralino-ui/references/themes-profiles-assets.md +105 -0
- neutralino/_data/skills/neutralino-updates/SKILL.md +94 -0
- neutralino/_data/skills/neutralino-updates/references/config-and-api.md +80 -0
- neutralino/_data/skills/neutralino-updates/references/releases-and-install.md +77 -0
- neutralino/_data/skills/neutralino-updates/references/security-rollback.md +48 -0
- neutralino/_data/ui/contracts.json +32927 -0
- neutralino/_data/ui/emoji.json +1 -0
- neutralino/_data/upstream-lock.json +97 -0
- neutralino/_managed.py +1099 -0
- neutralino/_paths.py +220 -0
- neutralino/_platform.py +150 -0
- neutralino/_scaffold.py +344 -0
- neutralino/api/_base.py +99 -0
- neutralino/api/_custom.py +1350 -0
- neutralino/api/_dec.py +21 -0
- neutralino/api/_enc.py +80 -0
- neutralino/api/app.py +119 -0
- neutralino/api/clipboard.py +101 -0
- neutralino/api/computer.py +261 -0
- neutralino/api/custom.py +36 -0
- neutralino/api/debug.py +41 -0
- neutralino/api/extensions.py +57 -0
- neutralino/api/filesystem.py +633 -0
- neutralino/api/net.py +22 -0
- neutralino/api/os.py +508 -0
- neutralino/api/resources.py +124 -0
- neutralino/api/server.py +66 -0
- neutralino/api/storage.py +98 -0
- neutralino/api/types.py +342 -0
- neutralino/api/updater.py +22 -0
- neutralino/api/window.py +397 -0
- neutralino/application.py +1260 -0
- neutralino/bundle.py +187 -0
- neutralino/cli.py +629 -0
- neutralino/client.py +496 -0
- neutralino/config.py +671 -0
- neutralino/devtools.py +1973 -0
- neutralino/errors.py +142 -0
- neutralino/events.py +579 -0
- neutralino/execution.py +293 -0
- neutralino/extension.py +134 -0
- neutralino/frontend/python-bridge.d.ts +207 -0
- neutralino/frontend/python-bridge.mjs +854 -0
- neutralino/protocol.py +456 -0
- neutralino/py.typed +0 -0
- neutralino/rpc.py +1625 -0
- neutralino/runtime.py +591 -0
- neutralino/supervisor.py +866 -0
- neutralino/sync_client.py +376 -0
- neutralino/templates/default/app.py +32 -0
- neutralino/templates/default/frontend/app.js +28 -0
- neutralino/templates/default/frontend/index.html +26 -0
- neutralino/templates/default/frontend/neutralino.js +1 -0
- neutralino/templates/default/frontend/styles.css +8 -0
- neutralino/templates/default/gitignore.txt +3 -0
- neutralino/templates/default/neutralino.config.json +25 -0
- neutralino/templates/hybrid/README.md +17 -0
- neutralino/templates/hybrid/app.py +49 -0
- neutralino/templates/hybrid/components/counter.mjs +37 -0
- neutralino/templates/hybrid/styles.css +21 -0
- neutralino/templates/python-ui/README.md +15 -0
- neutralino/templates/python-ui/app.py +44 -0
- neutralino/templates/python-ui/gitignore.txt +3 -0
- neutralino/templates/python-ui/requirements.txt +4 -0
- neutralino/templates/react/README.md +28 -0
- neutralino/templates/react/app.py +52 -0
- neutralino/templates/react/components/widget.mjs +23 -0
- neutralino/templates/react/widget/package.json +20 -0
- neutralino/templates/react/widget/src/Widget.jsx +25 -0
- neutralino/templates/react/widget/vite.config.mjs +19 -0
- neutralino/transport.py +661 -0
- neutralino/types.py +93 -0
- neutralino/ui/__init__.py +139 -0
- neutralino/ui/_app.py +1529 -0
- neutralino/ui/_assets.py +407 -0
- neutralino/ui/_bases.py +1210 -0
- neutralino/ui/_behaviours.py +1066 -0
- neutralino/ui/_charts.py +732 -0
- neutralino/ui/_component.py +882 -0
- neutralino/ui/_dates.py +168 -0
- neutralino/ui/_desktop.py +879 -0
- neutralino/ui/_events.py +192 -0
- neutralino/ui/_filters.py +427 -0
- neutralino/ui/_forms.py +282 -0
- neutralino/ui/_protocol.py +201 -0
- neutralino/ui/_schedule.py +543 -0
- neutralino/ui/_security.py +106 -0
- neutralino/ui/_session.py +969 -0
- neutralino/ui/_state.py +199 -0
- neutralino/ui/_tables.py +256 -0
- neutralino/ui/_theme.py +154 -0
- neutralino/ui/blocks/__init__.py +19 -0
- neutralino/ui/blocks/_data.py +2239 -0
- neutralino/ui/blocks/_interactive.py +622 -0
- neutralino/ui/blocks/_layout.py +2967 -0
- neutralino/ui/components/__init__.py +81 -0
- neutralino/ui/components/_dates.py +879 -0
- neutralino/ui/components/_editors.py +217 -0
- neutralino/ui/components/_extensions.py +790 -0
- neutralino/ui/components/_extras.py +303 -0
- neutralino/ui/components/_generated.py +30565 -0
- neutralino/ui/components/_types.py +17 -0
- neutralino/ui/schema.py +824 -0
- neutralino/ui/validators.py +362 -0
- neutralino/updates/__init__.py +96 -0
- neutralino/updates/_http.py +320 -0
- neutralino/updates/_layout.py +762 -0
- neutralino/updates/archive.py +216 -0
- neutralino/updates/config.py +256 -0
- neutralino/updates/errors.py +97 -0
- neutralino/updates/install.sh.in +201 -0
- neutralino/updates/launcher.py +18 -0
- neutralino/updates/manager.py +808 -0
- neutralino/updates/manifest.py +196 -0
- neutralino/updates/release.py +314 -0
- neutralino/updates/semver.py +84 -0
- neutralino/updates/sources.py +392 -0
- neutralino/windows.py +316 -0
- neutralino_python-0.1.0.dist-info/METADATA +121 -0
- neutralino_python-0.1.0.dist-info/RECORD +521 -0
- neutralino_python-0.1.0.dist-info/WHEEL +4 -0
- neutralino_python-0.1.0.dist-info/entry_points.txt +3 -0
- neutralino_python-0.1.0.dist-info/licenses/LICENSE +21 -0
- neutralino_python-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +16 -0
- neutralino_python-0.1.0.dist-info/licenses/src/neutralino/_data/renderer/LICENSES/packages.json +1838 -0
|
@@ -0,0 +1,2967 @@
|
|
|
1
|
+
"""Layout, navigation and input-pattern blocks (P04.07).
|
|
2
|
+
|
|
3
|
+
``Sidebar``, ``Header``, ``Footer``, ``UserMenu``, ``LanguagePicker``,
|
|
4
|
+
``SettingsPanel``, ``InputBlock``, ``LabeledSlider``, ``ChoiceCard``,
|
|
5
|
+
``ActionButton`` and ``SplitButton``: every block is a typed Python
|
|
6
|
+
composition of existing ``neutralino.ui`` components (no renderer adapter, no
|
|
7
|
+
page command, no payload of its own). A block owns its inner components, keeps
|
|
8
|
+
its state in Python on the instance (no global store) and emits typed events
|
|
9
|
+
that Python raises itself after the inner components' validated events; the
|
|
10
|
+
page can never send an event for a block. Demo *variants* are constructor
|
|
11
|
+
parameters, not copies.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import inspect
|
|
18
|
+
import math
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from decimal import Decimal, InvalidOperation
|
|
23
|
+
from functools import partial
|
|
24
|
+
from typing import Any, ClassVar, Literal, TypeVar, cast
|
|
25
|
+
|
|
26
|
+
from ...errors import ValidationError
|
|
27
|
+
from ...types import UNSET, Unset
|
|
28
|
+
from .._component import EventSpec
|
|
29
|
+
from .._events import ChangeEvent, Event, Handler
|
|
30
|
+
from ..components import (
|
|
31
|
+
ActionIcon,
|
|
32
|
+
Anchor,
|
|
33
|
+
Autocomplete,
|
|
34
|
+
Avatar,
|
|
35
|
+
Badge,
|
|
36
|
+
Box,
|
|
37
|
+
Burger,
|
|
38
|
+
Button,
|
|
39
|
+
ButtonGroup,
|
|
40
|
+
Checkbox,
|
|
41
|
+
CheckboxCard,
|
|
42
|
+
CheckboxGroup,
|
|
43
|
+
CheckboxIndicator,
|
|
44
|
+
CopyButton,
|
|
45
|
+
Divider,
|
|
46
|
+
Drawer,
|
|
47
|
+
Group,
|
|
48
|
+
HoverCard,
|
|
49
|
+
Icon,
|
|
50
|
+
Image,
|
|
51
|
+
Loader,
|
|
52
|
+
Menu,
|
|
53
|
+
MenuItem,
|
|
54
|
+
NativeSelect,
|
|
55
|
+
NavLink,
|
|
56
|
+
NumberInput,
|
|
57
|
+
Paper,
|
|
58
|
+
PasswordInput,
|
|
59
|
+
Popover,
|
|
60
|
+
Progress,
|
|
61
|
+
RangeSlider,
|
|
62
|
+
ScrollArea,
|
|
63
|
+
SegmentedControl,
|
|
64
|
+
Select,
|
|
65
|
+
SimpleGrid,
|
|
66
|
+
Slider,
|
|
67
|
+
Stack,
|
|
68
|
+
Switch,
|
|
69
|
+
Tabs,
|
|
70
|
+
TabsList,
|
|
71
|
+
TabsTab,
|
|
72
|
+
Text,
|
|
73
|
+
TextInput,
|
|
74
|
+
ThemeIcon,
|
|
75
|
+
Tooltip,
|
|
76
|
+
UnstyledButton,
|
|
77
|
+
)
|
|
78
|
+
from ..components._types import Option
|
|
79
|
+
|
|
80
|
+
__all__ = [
|
|
81
|
+
"ActionButton",
|
|
82
|
+
"ActionSpec",
|
|
83
|
+
"ChoiceCard",
|
|
84
|
+
"ChoiceEvent",
|
|
85
|
+
"ChoiceOption",
|
|
86
|
+
"Footer",
|
|
87
|
+
"FooterGroup",
|
|
88
|
+
"FooterLink",
|
|
89
|
+
"Header",
|
|
90
|
+
"HeaderLink",
|
|
91
|
+
"InputBlock",
|
|
92
|
+
"LabeledSlider",
|
|
93
|
+
"Language",
|
|
94
|
+
"LanguagePicker",
|
|
95
|
+
"LinkEvent",
|
|
96
|
+
"NavItem",
|
|
97
|
+
"NavSection",
|
|
98
|
+
"NavigateEvent",
|
|
99
|
+
"SearchEvent",
|
|
100
|
+
"SettingSpec",
|
|
101
|
+
"SettingsEvent",
|
|
102
|
+
"SettingsPanel",
|
|
103
|
+
"Sidebar",
|
|
104
|
+
"SplitButton",
|
|
105
|
+
"SubscribeEvent",
|
|
106
|
+
"UserAction",
|
|
107
|
+
"UserMenu",
|
|
108
|
+
"ValueEvent",
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
_VALUE_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.:/#@+-]{0,127}$")
|
|
112
|
+
_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
|
|
113
|
+
_EMAIL_RE = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,190}\.[^@\s.]{2,}$")
|
|
114
|
+
_MAX_TEXT = 200
|
|
115
|
+
_MAX_ITEMS = 200
|
|
116
|
+
_ICONS: frozenset[str] = frozenset(cast("tuple[str, ...]", Icon.PROPS["name"].values or ()))
|
|
117
|
+
_BREAKPOINTS = ("xs", "sm", "md", "lg", "xl")
|
|
118
|
+
Breakpoint = Literal["xs", "sm", "md", "lg", "xl"]
|
|
119
|
+
_INPUT_VARIANTS = (
|
|
120
|
+
"autocomplete-loading",
|
|
121
|
+
"contained",
|
|
122
|
+
"currency",
|
|
123
|
+
"floating-label",
|
|
124
|
+
"forgot-password",
|
|
125
|
+
"tooltip",
|
|
126
|
+
"validation",
|
|
127
|
+
"with-button",
|
|
128
|
+
"password-strength",
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------- validation
|
|
133
|
+
def _Icon(name: str, **kw: Any) -> Icon:
|
|
134
|
+
return Icon(cast("Any", name), **kw)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _text(v: Any, where: str, *, limit: int = _MAX_TEXT, empty: bool = False) -> str:
|
|
138
|
+
if not isinstance(v, str) or len(v) > limit or (not v.strip() and not empty):
|
|
139
|
+
raise ValidationError(f"{where}: expected a non-empty string up to {limit} characters")
|
|
140
|
+
return v
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _opt_text(v: Any, where: str) -> str | None:
|
|
144
|
+
return None if v is None else _text(v, where)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _value(v: Any, where: str) -> str:
|
|
148
|
+
if not isinstance(v, str) or not _VALUE_RE.fullmatch(v):
|
|
149
|
+
raise ValidationError(f"{where}: value must match {_VALUE_RE.pattern}")
|
|
150
|
+
return v
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _icon(v: Any, where: str) -> str | None:
|
|
154
|
+
if v is None:
|
|
155
|
+
return None
|
|
156
|
+
if not isinstance(v, str) or v not in _ICONS:
|
|
157
|
+
raise ValidationError(f"{where}: unknown icon {v!r}")
|
|
158
|
+
return v
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _flag(v: Any, where: str) -> bool:
|
|
162
|
+
if not isinstance(v, bool):
|
|
163
|
+
raise ValidationError(f"{where}: expected a boolean")
|
|
164
|
+
return v
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _bp(v: Any, where: str) -> Breakpoint:
|
|
168
|
+
if v not in _BREAKPOINTS:
|
|
169
|
+
raise ValidationError(f"{where}: expected one of {list(_BREAKPOINTS)}")
|
|
170
|
+
return v
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _seq(v: Any, where: str, *, limit: int = _MAX_ITEMS) -> list[Any]:
|
|
174
|
+
if isinstance(v, (str, bytes, Mapping)) or not isinstance(v, Iterable):
|
|
175
|
+
raise ValidationError(f"{where}: expected a list")
|
|
176
|
+
out = list(cast("Iterable[Any]", v))
|
|
177
|
+
if len(out) > limit:
|
|
178
|
+
raise ValidationError(f"{where}: at most {limit} entries")
|
|
179
|
+
return out
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _unique(values: Iterable[str], where: str) -> None:
|
|
183
|
+
seen: set[str] = set()
|
|
184
|
+
for v in values:
|
|
185
|
+
if v in seen:
|
|
186
|
+
raise ValidationError(f"{where}: duplicate value {v!r}")
|
|
187
|
+
seen.add(v)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
_T = TypeVar("_T")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _coerce(cls: type[_T], v: Any, where: str) -> _T:
|
|
194
|
+
if isinstance(v, cls):
|
|
195
|
+
return v
|
|
196
|
+
if isinstance(v, Mapping):
|
|
197
|
+
try:
|
|
198
|
+
return cls(**dict(cast("Mapping[str, Any]", v)))
|
|
199
|
+
except TypeError as err:
|
|
200
|
+
raise ValidationError(f"{where}: {err}") from None
|
|
201
|
+
raise ValidationError(f"{where}: expected {cls.__name__} or a mapping")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# -------------------------------------------------------------------- events
|
|
205
|
+
@dataclass
|
|
206
|
+
class ValueEvent(Event):
|
|
207
|
+
"""A block raised a named choice: ``value`` is the item/action/provider id."""
|
|
208
|
+
|
|
209
|
+
value: str | None = None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass
|
|
213
|
+
class NavigateEvent(Event):
|
|
214
|
+
"""A ``Sidebar`` link was activated (``active`` is already updated)."""
|
|
215
|
+
|
|
216
|
+
value: str = ""
|
|
217
|
+
previous: str | None = None
|
|
218
|
+
section: str | None = None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass
|
|
222
|
+
class LinkEvent(Event):
|
|
223
|
+
"""A ``Header``/``Footer`` link, tab, action or social icon was activated."""
|
|
224
|
+
|
|
225
|
+
value: str = ""
|
|
226
|
+
label: str = ""
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@dataclass
|
|
230
|
+
class SearchEvent(Event):
|
|
231
|
+
"""The header search was submitted (Enter) or a suggestion was picked."""
|
|
232
|
+
|
|
233
|
+
query: str = ""
|
|
234
|
+
selected: bool = False
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@dataclass
|
|
238
|
+
class SubscribeEvent(Event):
|
|
239
|
+
"""A footer newsletter field was submitted with a valid e-mail address."""
|
|
240
|
+
|
|
241
|
+
email: str = ""
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class SettingsEvent(Event):
|
|
246
|
+
"""A ``SettingsPanel`` snapshot changed (``values`` is the whole snapshot)."""
|
|
247
|
+
|
|
248
|
+
values: dict[str, Any] = field(default_factory=dict[str, Any])
|
|
249
|
+
previous: dict[str, Any] = field(default_factory=dict[str, Any])
|
|
250
|
+
changed: tuple[str, ...] = ()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
@dataclass
|
|
254
|
+
class ChoiceEvent(Event):
|
|
255
|
+
"""A ``ChoiceCard`` selection changed."""
|
|
256
|
+
|
|
257
|
+
selected: list[str] = field(default_factory=list[str])
|
|
258
|
+
previous: list[str] = field(default_factory=list[str])
|
|
259
|
+
changed: tuple[str, ...] = ()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _emit(comp: Any, name: str, cls: type[Event], **fields: Any) -> None:
|
|
263
|
+
"""Raise a block event from Python (only in a live window)."""
|
|
264
|
+
w = comp._window # pyright: ignore[reportPrivateUsage]
|
|
265
|
+
if w is None or not w.live:
|
|
266
|
+
return
|
|
267
|
+
w.dispatch(comp, cls(name=name, sender=comp, window=w, **fields))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _hook(comp: Any, handlers: Mapping[str, Callable[..., Any] | None]) -> None:
|
|
271
|
+
for event, fn in handlers.items():
|
|
272
|
+
if fn is not None:
|
|
273
|
+
comp.on(event, fn)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class _Local:
|
|
277
|
+
"""Mixin: block events come from Python, never from the page."""
|
|
278
|
+
|
|
279
|
+
def wire_events(self) -> list[str]:
|
|
280
|
+
return []
|
|
281
|
+
|
|
282
|
+
def _on_client_event(self, name: str, payload: Mapping[str, Any]) -> Any:
|
|
283
|
+
raise ValidationError(f"{type(self).__name__}.{name}: not a page event")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ================================================================== Sidebar
|
|
287
|
+
@dataclass(frozen=True)
|
|
288
|
+
class NavItem:
|
|
289
|
+
"""One sidebar entry. ``children`` make it a collapsible group (the group
|
|
290
|
+
row itself is not a destination); ``badge`` is a short counter text."""
|
|
291
|
+
|
|
292
|
+
value: str
|
|
293
|
+
label: str
|
|
294
|
+
icon: str | None = None
|
|
295
|
+
description: str | None = None
|
|
296
|
+
badge: str | None = None
|
|
297
|
+
children: Sequence[NavItem | Mapping[str, Any]] = ()
|
|
298
|
+
disabled: bool = False
|
|
299
|
+
|
|
300
|
+
def __post_init__(self) -> None:
|
|
301
|
+
w = f"NavItem({self.value!r})"
|
|
302
|
+
_value(self.value, w)
|
|
303
|
+
_text(self.label, f"{w}.label")
|
|
304
|
+
_icon(self.icon, f"{w}.icon")
|
|
305
|
+
_opt_text(self.description, f"{w}.description")
|
|
306
|
+
if self.badge is not None:
|
|
307
|
+
_text(self.badge, f"{w}.badge", limit=16)
|
|
308
|
+
_flag(self.disabled, f"{w}.disabled")
|
|
309
|
+
kids = tuple(_coerce(NavItem, c, f"{w}.children") for c in _seq(self.children, w))
|
|
310
|
+
if any(k.children for k in kids):
|
|
311
|
+
raise ValidationError(f"{w}: groups nest one level only")
|
|
312
|
+
object.__setattr__(self, "children", kids)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
@dataclass(frozen=True)
|
|
316
|
+
class NavSection:
|
|
317
|
+
"""A titled set of sidebar items (``segmented``/``double`` switch between
|
|
318
|
+
sections; other variants show them as titled groups)."""
|
|
319
|
+
|
|
320
|
+
value: str
|
|
321
|
+
label: str
|
|
322
|
+
items: Sequence[NavItem | Mapping[str, Any]] = ()
|
|
323
|
+
icon: str | None = None
|
|
324
|
+
|
|
325
|
+
def __post_init__(self) -> None:
|
|
326
|
+
w = f"NavSection({self.value!r})"
|
|
327
|
+
_value(self.value, w)
|
|
328
|
+
_text(self.label, f"{w}.label")
|
|
329
|
+
_icon(self.icon, f"{w}.icon")
|
|
330
|
+
object.__setattr__(
|
|
331
|
+
self, "items", tuple(_coerce(NavItem, i, f"{w}.items") for i in _seq(self.items, w))
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
_SIDEBAR_VARIANTS = (
|
|
336
|
+
"simple",
|
|
337
|
+
"simple-colored",
|
|
338
|
+
"minimal",
|
|
339
|
+
"minimal-colored",
|
|
340
|
+
"nested",
|
|
341
|
+
"links-group",
|
|
342
|
+
"search",
|
|
343
|
+
"segmented",
|
|
344
|
+
"double",
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class Sidebar(_Local, Paper):
|
|
349
|
+
"""Vertical navigation panel (``ui.AppShell`` navbar content).
|
|
350
|
+
|
|
351
|
+
``variant`` picks the demo layout: ``simple`` / ``simple-colored`` (flat
|
|
352
|
+
links with header and footer links), ``minimal`` / ``minimal-colored``
|
|
353
|
+
(icon rail with tooltips), ``nested`` and ``links-group`` (collapsible
|
|
354
|
+
groups, ``nested`` adds a scroll area and a ``user`` footer), ``search``
|
|
355
|
+
(filter box, badges, titled ``sections``), ``segmented`` (a
|
|
356
|
+
SegmentedControl switches the ``sections``), ``double`` (icon rail of
|
|
357
|
+
sections plus the section's links). ``active`` is tracked in Python; a link
|
|
358
|
+
click sets it and raises ``navigate`` (``NavigateEvent``)::
|
|
359
|
+
|
|
360
|
+
side = ui.blocks.Sidebar(
|
|
361
|
+
[ui.blocks.NavItem("home", "Home", icon="home"), ui.blocks.NavItem("db", "Data")],
|
|
362
|
+
active="home",
|
|
363
|
+
on_navigate=lambda e: show(e.value),
|
|
364
|
+
)
|
|
365
|
+
"""
|
|
366
|
+
|
|
367
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {"navigate": EventSpec("navigate", "NavigateEvent")}
|
|
368
|
+
|
|
369
|
+
def __init__(
|
|
370
|
+
self,
|
|
371
|
+
items: Iterable[NavItem | Mapping[str, Any]] = (),
|
|
372
|
+
*,
|
|
373
|
+
variant: str = "simple",
|
|
374
|
+
active: str | None = None,
|
|
375
|
+
sections: Iterable[NavSection | Mapping[str, Any]] = (),
|
|
376
|
+
section: str | None = None,
|
|
377
|
+
title: str | None = None,
|
|
378
|
+
footer_items: Iterable[NavItem | Mapping[str, Any]] = (),
|
|
379
|
+
search: bool | None = None,
|
|
380
|
+
search_placeholder: str = "Search",
|
|
381
|
+
user: Mapping[str, Any] | None = None,
|
|
382
|
+
color: str = "blue",
|
|
383
|
+
logo: str | None = None,
|
|
384
|
+
on_navigate: Handler[NavigateEvent] | None = None,
|
|
385
|
+
width: str | float | Unset = UNSET,
|
|
386
|
+
height: str | float | Unset = UNSET,
|
|
387
|
+
visible: bool | Unset = UNSET,
|
|
388
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
389
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
390
|
+
aria_label: str | Unset = "Sidebar",
|
|
391
|
+
) -> None:
|
|
392
|
+
if variant not in _SIDEBAR_VARIANTS:
|
|
393
|
+
raise ValidationError(f"Sidebar: variant must be one of {list(_SIDEBAR_VARIANTS)}")
|
|
394
|
+
flat = [_coerce(NavItem, i, "Sidebar.items") for i in _seq(items, "Sidebar.items")]
|
|
395
|
+
secs = [
|
|
396
|
+
_coerce(NavSection, s, "Sidebar.sections")
|
|
397
|
+
for s in _seq(sections, "Sidebar.sections", limit=20)
|
|
398
|
+
]
|
|
399
|
+
foot = [
|
|
400
|
+
_coerce(NavItem, i, "Sidebar.footer_items")
|
|
401
|
+
for i in _seq(footer_items, "Sidebar.footer_items", limit=20)
|
|
402
|
+
]
|
|
403
|
+
_text(color, "Sidebar.color", limit=40)
|
|
404
|
+
_icon(logo, "Sidebar.logo")
|
|
405
|
+
_opt_text(title, "Sidebar.title")
|
|
406
|
+
_text(search_placeholder, "Sidebar.search_placeholder")
|
|
407
|
+
with_search = variant == "search" if search is None else _flag(search, "Sidebar.search")
|
|
408
|
+
switching = variant in ("segmented", "double")
|
|
409
|
+
rail = variant in ("minimal", "minimal-colored")
|
|
410
|
+
if switching and not secs:
|
|
411
|
+
raise ValidationError(f"Sidebar({variant}): needs sections")
|
|
412
|
+
if not switching and not flat and not secs:
|
|
413
|
+
raise ValidationError("Sidebar: needs items or sections")
|
|
414
|
+
if switching and flat:
|
|
415
|
+
raise ValidationError(f"Sidebar({variant}): use sections, not items")
|
|
416
|
+
if rail:
|
|
417
|
+
if secs or with_search or user:
|
|
418
|
+
raise ValidationError("Sidebar(minimal): flat icon rail only (items, footer_items)")
|
|
419
|
+
if any(i.icon is None or i.children for i in [*flat, *foot]):
|
|
420
|
+
raise ValidationError("Sidebar(minimal): every entry needs an icon, no groups")
|
|
421
|
+
if user is not None and variant not in ("nested", "simple", "simple-colored", "search"):
|
|
422
|
+
raise ValidationError("Sidebar: user footer is for simple/nested/search variants")
|
|
423
|
+
every = [*flat, *foot, *(i for s in secs for i in cast("Sequence[NavItem]", s.items))]
|
|
424
|
+
kids_of = {i.value: cast("Sequence[NavItem]", i.children) for i in every}
|
|
425
|
+
names = [i.value for i in every] + [k.value for ks in kids_of.values() for k in ks]
|
|
426
|
+
_unique(names, "Sidebar")
|
|
427
|
+
if len(names) > _MAX_ITEMS:
|
|
428
|
+
raise ValidationError(f"Sidebar: at most {_MAX_ITEMS} entries")
|
|
429
|
+
group_values = {v for v, ks in kids_of.items() if ks}
|
|
430
|
+
leaves = {n for n in names if n not in group_values}
|
|
431
|
+
if switching:
|
|
432
|
+
_unique([s.value for s in secs], "Sidebar.sections")
|
|
433
|
+
cur_section = section if section is not None else (secs[0].value if switching else None)
|
|
434
|
+
if switching and cur_section not in {s.value for s in secs}:
|
|
435
|
+
raise ValidationError("Sidebar.section: not one of the sections")
|
|
436
|
+
if not switching and section is not None:
|
|
437
|
+
raise ValidationError("Sidebar.section: only for segmented/double")
|
|
438
|
+
if active is not None and active not in leaves:
|
|
439
|
+
raise ValidationError("Sidebar.active: not a link of the sidebar")
|
|
440
|
+
colored = variant in ("simple-colored", "minimal-colored")
|
|
441
|
+
super().__init__(
|
|
442
|
+
with_border=not colored,
|
|
443
|
+
p="xs" if rail else "md",
|
|
444
|
+
radius="md",
|
|
445
|
+
component="nav",
|
|
446
|
+
bg=color if colored else UNSET,
|
|
447
|
+
w=width,
|
|
448
|
+
h=height,
|
|
449
|
+
visible=visible,
|
|
450
|
+
classes=classes,
|
|
451
|
+
styles={"color": "white"} if colored and styles is UNSET else styles,
|
|
452
|
+
aria_label=aria_label,
|
|
453
|
+
)
|
|
454
|
+
self.variant = variant
|
|
455
|
+
self._color = color
|
|
456
|
+
self._colored = colored
|
|
457
|
+
self._active: str | None = active
|
|
458
|
+
self._section: str | None = cur_section
|
|
459
|
+
self._query = ""
|
|
460
|
+
self._links: dict[str, Any] = {}
|
|
461
|
+
self._groups: dict[str, Any] = {}
|
|
462
|
+
self._labels: dict[str, str] = {}
|
|
463
|
+
self._parent_of: dict[str, str] = {}
|
|
464
|
+
self._views: dict[str, list[Any]] = {}
|
|
465
|
+
self._rail_buttons: dict[str, Any] = {}
|
|
466
|
+
self.search_input: TextInput | None = None
|
|
467
|
+
self.segments: SegmentedControl | None = None
|
|
468
|
+
self.user_menu: UserMenu | None = None
|
|
469
|
+
self._build(flat, secs, foot, title, with_search, search_placeholder, user, logo)
|
|
470
|
+
if on_navigate is not None:
|
|
471
|
+
self.on("navigate", on_navigate)
|
|
472
|
+
self._apply_active()
|
|
473
|
+
if switching:
|
|
474
|
+
self._apply_section()
|
|
475
|
+
|
|
476
|
+
# ------------------------------------------------------------- building
|
|
477
|
+
def _build(
|
|
478
|
+
self,
|
|
479
|
+
flat: list[NavItem],
|
|
480
|
+
secs: list[NavSection],
|
|
481
|
+
foot: list[NavItem],
|
|
482
|
+
title: str | None,
|
|
483
|
+
with_search: bool,
|
|
484
|
+
placeholder: str,
|
|
485
|
+
user: Mapping[str, Any] | None,
|
|
486
|
+
logo: str | None,
|
|
487
|
+
) -> None:
|
|
488
|
+
variant = self.variant
|
|
489
|
+
rail = variant in ("minimal", "minimal-colored")
|
|
490
|
+
with self:
|
|
491
|
+
if variant == "double":
|
|
492
|
+
with Group(gap=0, align="flex-start", wrap="nowrap"):
|
|
493
|
+
with Stack(gap="xs", align="center", p="xs"):
|
|
494
|
+
for s in secs:
|
|
495
|
+
self._rail_button(s.value, s.label, s.icon or "list", section=True)
|
|
496
|
+
with Stack(gap=2, p="xs"):
|
|
497
|
+
if title:
|
|
498
|
+
Text(title, fw=700)
|
|
499
|
+
for s in secs:
|
|
500
|
+
self._section_stack(s)
|
|
501
|
+
self._footer(foot)
|
|
502
|
+
return
|
|
503
|
+
with Stack(gap="xs", align="center" if rail else UNSET):
|
|
504
|
+
if rail and logo:
|
|
505
|
+
with ThemeIcon(size="lg", variant="filled", color=self._color):
|
|
506
|
+
_Icon(logo)
|
|
507
|
+
if title and not rail:
|
|
508
|
+
Text(title, fw=700)
|
|
509
|
+
if with_search:
|
|
510
|
+
self.search_input = TextInput(
|
|
511
|
+
placeholder=placeholder,
|
|
512
|
+
left_section=_Icon("search", size=14),
|
|
513
|
+
debounce=150,
|
|
514
|
+
on_change=self._on_query,
|
|
515
|
+
aria_label=placeholder,
|
|
516
|
+
)
|
|
517
|
+
if variant == "segmented":
|
|
518
|
+
self.segments = SegmentedControl(
|
|
519
|
+
data=cast(
|
|
520
|
+
"list[Option]", [{"value": s.value, "label": s.label} for s in secs]
|
|
521
|
+
),
|
|
522
|
+
value=self._section,
|
|
523
|
+
full_width=True,
|
|
524
|
+
on_change=self._on_segment,
|
|
525
|
+
)
|
|
526
|
+
for s in secs:
|
|
527
|
+
self._section_stack(s)
|
|
528
|
+
else:
|
|
529
|
+
for s in secs:
|
|
530
|
+
self._titled(s)
|
|
531
|
+
scroll = ScrollArea(h="100%", type="auto") if variant == "nested" else None
|
|
532
|
+
with scroll if scroll is not None else contextlib.nullcontext():
|
|
533
|
+
for it in flat:
|
|
534
|
+
self._item(it, rail=rail)
|
|
535
|
+
self._footer(foot, rail=rail)
|
|
536
|
+
if user is not None:
|
|
537
|
+
Divider()
|
|
538
|
+
self.user_menu = UserMenu(**dict(user))
|
|
539
|
+
|
|
540
|
+
def _footer(self, foot: list[NavItem], *, rail: bool = False) -> None:
|
|
541
|
+
if not foot:
|
|
542
|
+
return
|
|
543
|
+
if not rail:
|
|
544
|
+
Divider()
|
|
545
|
+
for it in foot:
|
|
546
|
+
self._item(it, rail=rail)
|
|
547
|
+
|
|
548
|
+
def _titled(self, s: NavSection) -> None:
|
|
549
|
+
with Stack(gap=2):
|
|
550
|
+
Text(s.label, size="xs", dimmed=True, fw=600)
|
|
551
|
+
for it in cast("Sequence[NavItem]", s.items):
|
|
552
|
+
self._item(it, rail=False)
|
|
553
|
+
|
|
554
|
+
def _section_stack(self, s: NavSection) -> None:
|
|
555
|
+
with Stack(gap=2) as stack:
|
|
556
|
+
for it in cast("Sequence[NavItem]", s.items):
|
|
557
|
+
self._item(it, rail=False)
|
|
558
|
+
self._views[s.value] = [stack]
|
|
559
|
+
|
|
560
|
+
def _rail_button(self, value: str, label: str, icon: str, *, section: bool) -> None:
|
|
561
|
+
with Tooltip(label=label, position="right"):
|
|
562
|
+
btn = ActionIcon(
|
|
563
|
+
icon=cast("Any", icon),
|
|
564
|
+
variant="subtle",
|
|
565
|
+
size="lg",
|
|
566
|
+
aria_label=label,
|
|
567
|
+
on_click=(partial(self._pick_section, value))
|
|
568
|
+
if section
|
|
569
|
+
else (partial(self._go, value)),
|
|
570
|
+
)
|
|
571
|
+
(self._rail_buttons if section else self._links)[value] = btn
|
|
572
|
+
self._labels[value] = label
|
|
573
|
+
|
|
574
|
+
def _item(self, it: NavItem, *, rail: bool) -> None:
|
|
575
|
+
if rail:
|
|
576
|
+
self._rail_button(it.value, it.label, cast("str", it.icon), section=False)
|
|
577
|
+
elif it.children:
|
|
578
|
+
with self._nav_link(it, group=True) as grp:
|
|
579
|
+
for kid in cast("Sequence[NavItem]", it.children):
|
|
580
|
+
self._parent_of[kid.value] = it.value
|
|
581
|
+
self._nav_link(kid, group=False)
|
|
582
|
+
self._groups[it.value] = grp
|
|
583
|
+
self._labels[it.value] = it.label
|
|
584
|
+
else:
|
|
585
|
+
self._nav_link(it, group=False)
|
|
586
|
+
|
|
587
|
+
def _nav_link(self, it: NavItem, *, group: bool) -> NavLink:
|
|
588
|
+
link = NavLink(
|
|
589
|
+
label=it.label,
|
|
590
|
+
description=it.description if it.description else UNSET,
|
|
591
|
+
disabled=it.disabled,
|
|
592
|
+
variant="subtle" if self._colored else "light",
|
|
593
|
+
color="white" if self._colored else self._color,
|
|
594
|
+
opened=False if group else UNSET,
|
|
595
|
+
left_section=_Icon(it.icon, size=18) if it.icon else None,
|
|
596
|
+
right_section=Badge(it.badge, size="xs", circle=True, variant="filled")
|
|
597
|
+
if it.badge
|
|
598
|
+
else None,
|
|
599
|
+
on_click=None if group else (partial(self._go, it.value)),
|
|
600
|
+
)
|
|
601
|
+
if not group:
|
|
602
|
+
self._links[it.value] = link
|
|
603
|
+
self._labels[it.value] = it.label
|
|
604
|
+
return link
|
|
605
|
+
|
|
606
|
+
# ------------------------------------------------------------- behaviour
|
|
607
|
+
@property
|
|
608
|
+
def active(self) -> str | None:
|
|
609
|
+
"""Value of the active link (set from Python or by a click)."""
|
|
610
|
+
return self._active
|
|
611
|
+
|
|
612
|
+
@active.setter
|
|
613
|
+
def active(self, value: str | None) -> None:
|
|
614
|
+
if value is not None and value not in self._links:
|
|
615
|
+
raise ValidationError(f"Sidebar.active: {value!r} is not a link")
|
|
616
|
+
self._active = value
|
|
617
|
+
self._apply_active()
|
|
618
|
+
|
|
619
|
+
@property
|
|
620
|
+
def section(self) -> str | None:
|
|
621
|
+
"""Selected section of a ``segmented``/``double`` sidebar."""
|
|
622
|
+
return self._section
|
|
623
|
+
|
|
624
|
+
@section.setter
|
|
625
|
+
def section(self, value: str) -> None:
|
|
626
|
+
if value not in self._views:
|
|
627
|
+
raise ValidationError("Sidebar.section: not a section")
|
|
628
|
+
self._pick_section(value)
|
|
629
|
+
|
|
630
|
+
@property
|
|
631
|
+
def query(self) -> str:
|
|
632
|
+
"""The current filter text of a ``search`` sidebar."""
|
|
633
|
+
return self._query
|
|
634
|
+
|
|
635
|
+
@query.setter
|
|
636
|
+
def query(self, value: str) -> None:
|
|
637
|
+
if self.search_input is None:
|
|
638
|
+
raise ValidationError("Sidebar.query: this sidebar has no search box")
|
|
639
|
+
self.search_input.value = _text(value, "Sidebar.query", limit=100, empty=True)
|
|
640
|
+
self._query = value
|
|
641
|
+
self._apply_filter()
|
|
642
|
+
|
|
643
|
+
def link(self, value: str) -> Any:
|
|
644
|
+
"""The inner NavLink / rail ActionIcon of link ``value``."""
|
|
645
|
+
try:
|
|
646
|
+
return self._links[value]
|
|
647
|
+
except KeyError:
|
|
648
|
+
raise ValidationError(f"Sidebar has no link {value!r}") from None
|
|
649
|
+
|
|
650
|
+
def group(self, value: str) -> Any:
|
|
651
|
+
"""The collapsible NavLink group ``value``."""
|
|
652
|
+
try:
|
|
653
|
+
return self._groups[value]
|
|
654
|
+
except KeyError:
|
|
655
|
+
raise ValidationError(f"Sidebar has no group {value!r}") from None
|
|
656
|
+
|
|
657
|
+
def _go(self, value: str) -> None:
|
|
658
|
+
prev, self._active = self._active, value
|
|
659
|
+
self._apply_active()
|
|
660
|
+
_emit(self, "navigate", NavigateEvent, value=value, previous=prev, section=self._section)
|
|
661
|
+
|
|
662
|
+
def _pick_section(self, value: str) -> None:
|
|
663
|
+
self._section = value
|
|
664
|
+
self._apply_section()
|
|
665
|
+
if self.segments is not None and self.segments.value != value:
|
|
666
|
+
self.segments.update(value=value)
|
|
667
|
+
|
|
668
|
+
def _on_segment(self, ev: Any) -> None:
|
|
669
|
+
if isinstance(ev.value, str) and ev.value in self._views:
|
|
670
|
+
self._section = ev.value
|
|
671
|
+
self._apply_section()
|
|
672
|
+
|
|
673
|
+
def _on_query(self, ev: Any) -> None:
|
|
674
|
+
self._query = ev.value if isinstance(ev.value, str) else ""
|
|
675
|
+
self._apply_filter()
|
|
676
|
+
|
|
677
|
+
def _apply_active(self) -> None:
|
|
678
|
+
for v, comp in self._links.items():
|
|
679
|
+
on = v == self._active
|
|
680
|
+
if isinstance(comp, ActionIcon):
|
|
681
|
+
comp.update(variant=("filled" if self._colored else "light") if on else "subtle")
|
|
682
|
+
else:
|
|
683
|
+
comp.update(active=on)
|
|
684
|
+
for gv, grp in self._groups.items():
|
|
685
|
+
if self._active is not None and self._parent_of.get(self._active) == gv:
|
|
686
|
+
grp.update(opened=True)
|
|
687
|
+
|
|
688
|
+
def _apply_section(self) -> None:
|
|
689
|
+
for v, comps in self._views.items():
|
|
690
|
+
for c in comps:
|
|
691
|
+
c.update(visible=(v == self._section))
|
|
692
|
+
for v, btn in self._rail_buttons.items():
|
|
693
|
+
btn.update(variant="filled" if v == self._section else "subtle")
|
|
694
|
+
|
|
695
|
+
def _apply_filter(self) -> None:
|
|
696
|
+
q = self._query.strip().casefold()
|
|
697
|
+
shown: dict[str, bool] = {}
|
|
698
|
+
for v, comp in self._links.items():
|
|
699
|
+
ok = not q or q in self._labels[v].casefold()
|
|
700
|
+
shown[v] = ok
|
|
701
|
+
comp.update(visible=ok)
|
|
702
|
+
for gv, grp in self._groups.items():
|
|
703
|
+
kids = [k for k, p in self._parent_of.items() if p == gv]
|
|
704
|
+
own = not q or q in self._labels[gv].casefold()
|
|
705
|
+
grp.update(visible=own or any(shown.get(k) for k in kids))
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
# =================================================================== UserMenu
|
|
709
|
+
@dataclass(frozen=True)
|
|
710
|
+
class UserAction:
|
|
711
|
+
"""One entry of a ``UserMenu``: ``danger`` colours it red,
|
|
712
|
+
``section`` starts a labelled group, ``divider_before`` adds a divider."""
|
|
713
|
+
|
|
714
|
+
value: str
|
|
715
|
+
label: str
|
|
716
|
+
icon: str | None = None
|
|
717
|
+
danger: bool = False
|
|
718
|
+
divider_before: bool = False
|
|
719
|
+
section: str | None = None
|
|
720
|
+
|
|
721
|
+
def __post_init__(self) -> None:
|
|
722
|
+
w = f"UserAction({self.value!r})"
|
|
723
|
+
_value(self.value, w)
|
|
724
|
+
_text(self.label, f"{w}.label")
|
|
725
|
+
_icon(self.icon, f"{w}.icon")
|
|
726
|
+
_flag(self.danger, f"{w}.danger")
|
|
727
|
+
_flag(self.divider_before, f"{w}.divider_before")
|
|
728
|
+
_opt_text(self.section, f"{w}.section")
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
class UserMenu(_Local, Group):
|
|
732
|
+
"""Avatar and name; ``variant="button"`` is a clickable identity
|
|
733
|
+
(``click``), ``variant="menu"`` opens a dropdown of ``actions`` and raises
|
|
734
|
+
``select`` (``ValueEvent`` with the action value)::
|
|
735
|
+
|
|
736
|
+
ui.blocks.UserMenu("Ada Lovelace", email="ada@example.com",
|
|
737
|
+
actions=[ui.blocks.UserAction("out", "Sign out", danger=True)],
|
|
738
|
+
on_select=lambda e: print(e.value))
|
|
739
|
+
"""
|
|
740
|
+
|
|
741
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
742
|
+
"click": EventSpec("click", "ValueEvent"),
|
|
743
|
+
"select": EventSpec("select", "ValueEvent"),
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
def __init__(
|
|
747
|
+
self,
|
|
748
|
+
name: str,
|
|
749
|
+
*,
|
|
750
|
+
email: str | None = None,
|
|
751
|
+
image: str | None = None,
|
|
752
|
+
variant: Literal["button", "menu"] = "menu",
|
|
753
|
+
actions: Iterable[UserAction | Mapping[str, Any]] = (),
|
|
754
|
+
with_chevron: bool = True,
|
|
755
|
+
on_click: Handler[ValueEvent] | None = None,
|
|
756
|
+
on_select: Handler[ValueEvent] | None = None,
|
|
757
|
+
visible: bool | Unset = UNSET,
|
|
758
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
759
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
760
|
+
aria_label: str | Unset = UNSET,
|
|
761
|
+
) -> None:
|
|
762
|
+
if variant not in ("button", "menu"):
|
|
763
|
+
raise ValidationError("UserMenu: variant must be 'button' or 'menu'")
|
|
764
|
+
_text(name, "UserMenu.name")
|
|
765
|
+
_opt_text(email, "UserMenu.email")
|
|
766
|
+
_opt_text(image, "UserMenu.image")
|
|
767
|
+
acts = [
|
|
768
|
+
_coerce(UserAction, a, "UserMenu.actions")
|
|
769
|
+
for a in _seq(actions, "UserMenu.actions", limit=50)
|
|
770
|
+
]
|
|
771
|
+
_unique([a.value for a in acts], "UserMenu.actions")
|
|
772
|
+
if variant == "button" and acts:
|
|
773
|
+
raise ValidationError("UserMenu(button): actions need variant='menu'")
|
|
774
|
+
if variant == "menu" and not acts:
|
|
775
|
+
raise ValidationError("UserMenu(menu): needs at least one action")
|
|
776
|
+
if on_select is not None and variant != "menu":
|
|
777
|
+
raise ValidationError("UserMenu: on_select needs variant='menu'")
|
|
778
|
+
if on_click is not None and variant != "button":
|
|
779
|
+
raise ValidationError("UserMenu: on_click needs variant='button'")
|
|
780
|
+
super().__init__(
|
|
781
|
+
gap="xs",
|
|
782
|
+
visible=visible,
|
|
783
|
+
classes=classes,
|
|
784
|
+
styles=styles,
|
|
785
|
+
aria_label=aria_label,
|
|
786
|
+
)
|
|
787
|
+
self.variant = variant
|
|
788
|
+
self.user_name = name
|
|
789
|
+
self.menu: Menu | None = None
|
|
790
|
+
with self:
|
|
791
|
+
btn = self._identity(name, email, image, with_chevron)
|
|
792
|
+
self.button = btn
|
|
793
|
+
if variant == "button":
|
|
794
|
+
btn.on("click", self._clicked)
|
|
795
|
+
else:
|
|
796
|
+
with Menu(target=btn, position="bottom-end", width=220) as menu:
|
|
797
|
+
last: str | None = None
|
|
798
|
+
for a in acts:
|
|
799
|
+
if a.section is not None and a.section != last:
|
|
800
|
+
MenuItem(label=a.section, item_type="label")
|
|
801
|
+
elif a.divider_before:
|
|
802
|
+
MenuItem(item_type="divider")
|
|
803
|
+
last = a.section
|
|
804
|
+
MenuItem(
|
|
805
|
+
label=a.label,
|
|
806
|
+
color="red" if a.danger else UNSET,
|
|
807
|
+
left_section=_Icon(a.icon, size=14) if a.icon else None,
|
|
808
|
+
on_click=partial(_emit, self, "select", ValueEvent, value=a.value),
|
|
809
|
+
)
|
|
810
|
+
self.menu = cast("Menu", menu)
|
|
811
|
+
_hook(self, {"click": on_click, "select": on_select})
|
|
812
|
+
|
|
813
|
+
@staticmethod
|
|
814
|
+
def _identity(name: str, email: str | None, image: str | None, chevron: bool) -> UnstyledButton:
|
|
815
|
+
with UnstyledButton(aria_label=name) as btn, Group(gap="sm", wrap="nowrap"):
|
|
816
|
+
Avatar(src=image if image else UNSET, name=name, radius="xl")
|
|
817
|
+
with Stack(gap=0):
|
|
818
|
+
Text(name, size="sm", fw=500)
|
|
819
|
+
if email:
|
|
820
|
+
Text(email, size="xs", dimmed=True)
|
|
821
|
+
if chevron:
|
|
822
|
+
_Icon("chevron-right", size=14)
|
|
823
|
+
return cast("UnstyledButton", btn)
|
|
824
|
+
|
|
825
|
+
def _clicked(self) -> None:
|
|
826
|
+
_emit(self, "click", ValueEvent, value=None)
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
# ============================================================== LanguagePicker
|
|
830
|
+
@dataclass(frozen=True)
|
|
831
|
+
class Language:
|
|
832
|
+
"""A locale offered by ``LanguagePicker`` (``flag`` is short text/emoji)."""
|
|
833
|
+
|
|
834
|
+
code: str
|
|
835
|
+
label: str
|
|
836
|
+
flag: str | None = None
|
|
837
|
+
|
|
838
|
+
def __post_init__(self) -> None:
|
|
839
|
+
_value(self.code, f"Language({self.code!r})")
|
|
840
|
+
_text(self.label, "Language.label", limit=80)
|
|
841
|
+
if self.flag is not None:
|
|
842
|
+
_text(self.flag, "Language.flag", limit=8)
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
class LanguagePicker(_Local, Group):
|
|
846
|
+
"""Menu button of languages; emits ``change`` (``ChangeEvent[str]``) with the
|
|
847
|
+
selected locale code. ``value`` is settable from Python::
|
|
848
|
+
|
|
849
|
+
picker = ui.blocks.LanguagePicker(["en", ui.blocks.Language("de", "Deutsch", "DE")], "en")
|
|
850
|
+
"""
|
|
851
|
+
|
|
852
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {"change": EventSpec("change", "ChangeEvent")}
|
|
853
|
+
|
|
854
|
+
def __init__(
|
|
855
|
+
self,
|
|
856
|
+
languages: Iterable[Language | Mapping[str, Any] | str],
|
|
857
|
+
value: str | None = None,
|
|
858
|
+
*,
|
|
859
|
+
on_change: Handler[ChangeEvent[str]] | None = None,
|
|
860
|
+
visible: bool | Unset = UNSET,
|
|
861
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
862
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
863
|
+
aria_label: str | Unset = "Language",
|
|
864
|
+
) -> None:
|
|
865
|
+
langs = [
|
|
866
|
+
Language(x, x.upper()) if isinstance(x, str) else _coerce(Language, x, "LanguagePicker")
|
|
867
|
+
for x in _seq(languages, "LanguagePicker.languages", limit=100)
|
|
868
|
+
]
|
|
869
|
+
if not langs:
|
|
870
|
+
raise ValidationError("LanguagePicker: at least one language")
|
|
871
|
+
_unique([lang.code for lang in langs], "LanguagePicker.languages")
|
|
872
|
+
langs_by_code = {lang.code: lang for lang in langs}
|
|
873
|
+
cur = value if value is not None else langs[0].code
|
|
874
|
+
if cur not in langs_by_code:
|
|
875
|
+
raise ValidationError("LanguagePicker.value: not one of the languages")
|
|
876
|
+
super().__init__(
|
|
877
|
+
gap=0, visible=visible, classes=classes, styles=styles, aria_label=aria_label
|
|
878
|
+
)
|
|
879
|
+
self.languages = langs_by_code
|
|
880
|
+
self._value = cur
|
|
881
|
+
self.items: dict[str, MenuItem] = {}
|
|
882
|
+
with self:
|
|
883
|
+
with UnstyledButton(aria_label="Choose language") as btn, Group(gap=6, wrap="nowrap"):
|
|
884
|
+
self._flag = Text(self._flag_text(cur) or " ")
|
|
885
|
+
self._label = Text(langs_by_code[cur].label, size="sm")
|
|
886
|
+
_Icon("chevron-down", size=14)
|
|
887
|
+
self.button = btn
|
|
888
|
+
with Menu(target=btn, position="bottom-start") as menu:
|
|
889
|
+
for lang in langs:
|
|
890
|
+
self.items[lang.code] = MenuItem(
|
|
891
|
+
label=f"{self._flag_text(lang.code)} {lang.label}".strip(),
|
|
892
|
+
on_click=partial(self._pick, lang.code),
|
|
893
|
+
)
|
|
894
|
+
self.menu = menu
|
|
895
|
+
if on_change is not None:
|
|
896
|
+
self.on("change", on_change)
|
|
897
|
+
|
|
898
|
+
def _flag_text(self, code: str) -> str:
|
|
899
|
+
return self.languages[code].flag or ""
|
|
900
|
+
|
|
901
|
+
@property
|
|
902
|
+
def value(self) -> str:
|
|
903
|
+
"""Selected locale code."""
|
|
904
|
+
return self._value
|
|
905
|
+
|
|
906
|
+
@value.setter
|
|
907
|
+
def value(self, code: str) -> None:
|
|
908
|
+
if code not in self.languages:
|
|
909
|
+
raise ValidationError("LanguagePicker.value: not one of the languages")
|
|
910
|
+
self._value = code
|
|
911
|
+
self._flag.update(text=self._flag_text(code) or " ")
|
|
912
|
+
self._label.update(text=self.languages[code].label)
|
|
913
|
+
|
|
914
|
+
def _pick(self, code: str) -> None:
|
|
915
|
+
prev = self._value
|
|
916
|
+
if code == prev:
|
|
917
|
+
return
|
|
918
|
+
self.value = code
|
|
919
|
+
_emit(self, "change", ChangeEvent, value=code, previous=prev)
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
# ================================================================ SettingsPanel
|
|
923
|
+
SettingKind = Literal["switch", "checkbox", "select"]
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
def _option_of(o: Any, where: str) -> Option:
|
|
927
|
+
if isinstance(o, str):
|
|
928
|
+
return cast("Option", {"value": _text(o, where), "label": o})
|
|
929
|
+
if isinstance(o, Mapping):
|
|
930
|
+
m = cast("Mapping[str, Any]", o)
|
|
931
|
+
if set(m) - {"value", "label"}:
|
|
932
|
+
raise ValidationError(f"{where}: options take value and label only")
|
|
933
|
+
v = _text(m.get("value"), where)
|
|
934
|
+
return cast("Option", {"value": v, "label": _text(m.get("label", v), where)})
|
|
935
|
+
raise ValidationError(f"{where}: option must be a string or mapping")
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
@dataclass(frozen=True)
|
|
939
|
+
class SettingSpec:
|
|
940
|
+
"""One setting: ``switch``/``checkbox`` are booleans, ``select`` picks one
|
|
941
|
+
of ``options``. ``on_label``/``off_label`` label a switch's states."""
|
|
942
|
+
|
|
943
|
+
key: str
|
|
944
|
+
label: str
|
|
945
|
+
description: str | None = None
|
|
946
|
+
kind: SettingKind = "switch"
|
|
947
|
+
options: Sequence[str | Mapping[str, Any]] = ()
|
|
948
|
+
default: bool | str | None = None
|
|
949
|
+
on_label: str | None = None
|
|
950
|
+
off_label: str | None = None
|
|
951
|
+
|
|
952
|
+
def __post_init__(self) -> None:
|
|
953
|
+
w = f"SettingSpec({self.key!r})"
|
|
954
|
+
if not isinstance(self.key, str) or not _KEY_RE.fullmatch(self.key): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
955
|
+
raise ValidationError(f"{w}: key must match {_KEY_RE.pattern}")
|
|
956
|
+
_text(self.label, f"{w}.label")
|
|
957
|
+
_opt_text(self.description, f"{w}.description")
|
|
958
|
+
if self.kind not in ("switch", "checkbox", "select"):
|
|
959
|
+
raise ValidationError(f"{w}: kind must be switch, checkbox or select")
|
|
960
|
+
opts = [_option_of(o, w) for o in _seq(self.options, f"{w}.options", limit=100)]
|
|
961
|
+
default: Any
|
|
962
|
+
if self.kind == "select":
|
|
963
|
+
if not opts:
|
|
964
|
+
raise ValidationError(f"{w}: a select needs options")
|
|
965
|
+
_unique([o["value"] for o in opts], w)
|
|
966
|
+
default = self.default if self.default is not None else opts[0]["value"]
|
|
967
|
+
if default not in {o["value"] for o in opts}:
|
|
968
|
+
raise ValidationError(f"{w}: default is not one of the options")
|
|
969
|
+
else:
|
|
970
|
+
if opts:
|
|
971
|
+
raise ValidationError(f"{w}: only a select takes options")
|
|
972
|
+
default = False if self.default is None else self.default
|
|
973
|
+
if not isinstance(default, bool):
|
|
974
|
+
raise ValidationError(f"{w}: default must be a boolean")
|
|
975
|
+
for n in ("on_label", "off_label"):
|
|
976
|
+
if getattr(self, n) is not None:
|
|
977
|
+
if self.kind != "switch":
|
|
978
|
+
raise ValidationError(f"{w}: {n} is for switches")
|
|
979
|
+
_text(getattr(self, n), f"{w}.{n}", limit=12)
|
|
980
|
+
object.__setattr__(self, "options", tuple(opts))
|
|
981
|
+
object.__setattr__(self, "default", default)
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
class SettingsPanel(_Local, Paper):
|
|
985
|
+
"""Card of labelled switches, checkboxes and selects that commit as one
|
|
986
|
+
settings snapshot.
|
|
987
|
+
|
|
988
|
+
``variant="switches"`` is a titled card of toggle rows with descriptions;
|
|
989
|
+
``variant="custom-switch"`` shows large switches with their on/off labels.
|
|
990
|
+
Every change raises ``change`` (``SettingsEvent``: whole ``values``,
|
|
991
|
+
``previous``, ``changed`` keys); with ``apply_label`` the panel also has an
|
|
992
|
+
apply button that raises ``apply`` with the same snapshot::
|
|
993
|
+
|
|
994
|
+
panel = ui.blocks.SettingsPanel(
|
|
995
|
+
[ui.blocks.SettingSpec("emails", "Emails", "Product news"), ...],
|
|
996
|
+
title="Notifications", on_change=lambda e: save(e.values),
|
|
997
|
+
)
|
|
998
|
+
"""
|
|
999
|
+
|
|
1000
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
1001
|
+
"change": EventSpec("change", "SettingsEvent"),
|
|
1002
|
+
"apply": EventSpec("apply", "SettingsEvent"),
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
def __init__(
|
|
1006
|
+
self,
|
|
1007
|
+
settings: Iterable[SettingSpec | Mapping[str, Any]],
|
|
1008
|
+
*,
|
|
1009
|
+
variant: Literal["switches", "custom-switch"] = "switches",
|
|
1010
|
+
title: str | None = None,
|
|
1011
|
+
description: str | None = None,
|
|
1012
|
+
value: Mapping[str, Any] | None = None,
|
|
1013
|
+
apply_label: str | None = None,
|
|
1014
|
+
on_change: Handler[SettingsEvent] | None = None,
|
|
1015
|
+
on_apply: Handler[SettingsEvent] | None = None,
|
|
1016
|
+
visible: bool | Unset = UNSET,
|
|
1017
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
1018
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
1019
|
+
aria_label: str | Unset = "Settings",
|
|
1020
|
+
) -> None:
|
|
1021
|
+
if variant not in ("switches", "custom-switch"):
|
|
1022
|
+
raise ValidationError("SettingsPanel: variant must be switches or custom-switch")
|
|
1023
|
+
specs = [
|
|
1024
|
+
_coerce(SettingSpec, s, "SettingsPanel")
|
|
1025
|
+
for s in _seq(settings, "SettingsPanel", limit=64)
|
|
1026
|
+
]
|
|
1027
|
+
if not specs:
|
|
1028
|
+
raise ValidationError("SettingsPanel: at least one setting")
|
|
1029
|
+
_unique([s.key for s in specs], "SettingsPanel")
|
|
1030
|
+
_opt_text(title, "SettingsPanel.title")
|
|
1031
|
+
_opt_text(description, "SettingsPanel.description")
|
|
1032
|
+
if variant == "custom-switch" and any(s.kind != "switch" for s in specs):
|
|
1033
|
+
raise ValidationError("SettingsPanel(custom-switch): switches only")
|
|
1034
|
+
if apply_label is not None:
|
|
1035
|
+
_text(apply_label, "SettingsPanel.apply_label", limit=60)
|
|
1036
|
+
if on_apply is not None and apply_label is None:
|
|
1037
|
+
raise ValidationError("SettingsPanel: on_apply needs apply_label")
|
|
1038
|
+
super().__init__(
|
|
1039
|
+
with_border=True,
|
|
1040
|
+
p="md",
|
|
1041
|
+
radius="md",
|
|
1042
|
+
component="section",
|
|
1043
|
+
visible=visible,
|
|
1044
|
+
classes=classes,
|
|
1045
|
+
styles=styles,
|
|
1046
|
+
aria_label=aria_label,
|
|
1047
|
+
)
|
|
1048
|
+
self.variant = variant
|
|
1049
|
+
self.specs = {s.key: s for s in specs}
|
|
1050
|
+
self._inputs: dict[str, Any] = {}
|
|
1051
|
+
self._last: dict[str, Any] = {}
|
|
1052
|
+
self.apply_button: Button | None = None
|
|
1053
|
+
with self, Stack(gap="sm"):
|
|
1054
|
+
if title:
|
|
1055
|
+
Text(title, fw=600)
|
|
1056
|
+
if description:
|
|
1057
|
+
Text(description, size="sm", dimmed=True)
|
|
1058
|
+
for s in specs:
|
|
1059
|
+
self._row(s)
|
|
1060
|
+
if apply_label:
|
|
1061
|
+
self.apply_button = Button(apply_label, on_click=self._apply)
|
|
1062
|
+
_hook(self, {"change": on_change, "apply": on_apply})
|
|
1063
|
+
if value:
|
|
1064
|
+
self.set_values(value, notify=False)
|
|
1065
|
+
self._last = self.values
|
|
1066
|
+
|
|
1067
|
+
def _row(self, s: SettingSpec) -> None:
|
|
1068
|
+
custom = self.variant == "custom-switch"
|
|
1069
|
+
if s.kind == "select":
|
|
1070
|
+
self._inputs[s.key] = Select(
|
|
1071
|
+
label=s.label,
|
|
1072
|
+
description=s.description or UNSET,
|
|
1073
|
+
data=cast("list[Option]", list(s.options)),
|
|
1074
|
+
value=cast("str", s.default),
|
|
1075
|
+
allow_deselect=False,
|
|
1076
|
+
on_change=self._changed,
|
|
1077
|
+
)
|
|
1078
|
+
return
|
|
1079
|
+
with Group(justify="space-between", wrap="nowrap", align="center"):
|
|
1080
|
+
if not custom or s.description:
|
|
1081
|
+
with Stack(gap=0):
|
|
1082
|
+
Text(s.label, size="sm", fw=500)
|
|
1083
|
+
if s.description:
|
|
1084
|
+
Text(s.description, size="xs", dimmed=True)
|
|
1085
|
+
if s.kind == "switch":
|
|
1086
|
+
self._inputs[s.key] = Switch(
|
|
1087
|
+
checked=bool(s.default),
|
|
1088
|
+
aria_label=s.label,
|
|
1089
|
+
on_label=s.on_label or ("ON" if custom else UNSET),
|
|
1090
|
+
off_label=s.off_label or ("OFF" if custom else UNSET),
|
|
1091
|
+
size="lg" if custom else "md",
|
|
1092
|
+
with_thumb_indicator=custom,
|
|
1093
|
+
label=s.label if custom and not s.description else UNSET,
|
|
1094
|
+
on_change=self._changed,
|
|
1095
|
+
)
|
|
1096
|
+
else:
|
|
1097
|
+
self._inputs[s.key] = Checkbox(
|
|
1098
|
+
checked=bool(s.default), aria_label=s.label, on_change=self._changed
|
|
1099
|
+
)
|
|
1100
|
+
|
|
1101
|
+
def input(self, key: str) -> Any:
|
|
1102
|
+
"""The inner input of setting ``key``."""
|
|
1103
|
+
try:
|
|
1104
|
+
return self._inputs[key]
|
|
1105
|
+
except KeyError:
|
|
1106
|
+
raise ValidationError(f"SettingsPanel has no setting {key!r}") from None
|
|
1107
|
+
|
|
1108
|
+
@property
|
|
1109
|
+
def values(self) -> dict[str, Any]:
|
|
1110
|
+
"""The typed snapshot: ``bool`` for switches/checkboxes, ``str`` for selects."""
|
|
1111
|
+
out: dict[str, Any] = {}
|
|
1112
|
+
for k, s in self.specs.items():
|
|
1113
|
+
comp = self._inputs[k]
|
|
1114
|
+
if s.kind == "select":
|
|
1115
|
+
v = comp.value
|
|
1116
|
+
out[k] = v if isinstance(v, str) else s.default
|
|
1117
|
+
else:
|
|
1118
|
+
out[k] = bool(comp.checked)
|
|
1119
|
+
return out
|
|
1120
|
+
|
|
1121
|
+
def set_values(self, values: Mapping[str, Any], *, notify: bool = True) -> None:
|
|
1122
|
+
"""Change settings from Python (unknown keys and wrong types are rejected)."""
|
|
1123
|
+
for k, v in values.items():
|
|
1124
|
+
s = self.specs.get(k)
|
|
1125
|
+
if s is None:
|
|
1126
|
+
raise ValidationError(f"SettingsPanel has no setting {k!r}")
|
|
1127
|
+
if s.kind == "select":
|
|
1128
|
+
if v not in {cast("Mapping[str, str]", o)["value"] for o in s.options}:
|
|
1129
|
+
raise ValidationError(f"SettingsPanel.{k}: not one of the options")
|
|
1130
|
+
elif not isinstance(v, bool):
|
|
1131
|
+
raise ValidationError(f"SettingsPanel.{k}: expected a boolean")
|
|
1132
|
+
for k, v in values.items():
|
|
1133
|
+
self._inputs[k].update(
|
|
1134
|
+
**({"value": v} if self.specs[k].kind == "select" else {"checked": v})
|
|
1135
|
+
)
|
|
1136
|
+
if notify:
|
|
1137
|
+
self._changed()
|
|
1138
|
+
else:
|
|
1139
|
+
self._last = self.values
|
|
1140
|
+
|
|
1141
|
+
def _changed(self) -> None:
|
|
1142
|
+
now = self.values
|
|
1143
|
+
prev, self._last = self._last, now
|
|
1144
|
+
if now == prev:
|
|
1145
|
+
return
|
|
1146
|
+
keys = tuple(sorted(k for k in now if now[k] != prev.get(k)))
|
|
1147
|
+
_emit(self, "change", SettingsEvent, values=now, previous=prev, changed=keys)
|
|
1148
|
+
|
|
1149
|
+
def _apply(self) -> None:
|
|
1150
|
+
now = self.values
|
|
1151
|
+
_emit(self, "apply", SettingsEvent, values=now, previous=dict(now), changed=())
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
# =================================================================== InputBlock
|
|
1155
|
+
@dataclass
|
|
1156
|
+
class _Requirement:
|
|
1157
|
+
pattern: re.Pattern[str]
|
|
1158
|
+
label: str
|
|
1159
|
+
|
|
1160
|
+
|
|
1161
|
+
DEFAULT_REQUIREMENTS: tuple[tuple[str, str], ...] = (
|
|
1162
|
+
(r"[0-9]", "Includes number"),
|
|
1163
|
+
(r"[a-z]", "Includes lowercase letter"),
|
|
1164
|
+
(r"[A-Z]", "Includes uppercase letter"),
|
|
1165
|
+
(r"[^A-Za-z0-9]", "Includes special symbol"),
|
|
1166
|
+
)
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
class InputBlock(_Local, Stack):
|
|
1170
|
+
"""Single-field input patterns; ``variant`` selects the pattern.
|
|
1171
|
+
|
|
1172
|
+
``value`` is the field text (the amount for ``currency``). ``change`` is a
|
|
1173
|
+
``ChangeEvent[str]``; ``submit`` (``ValueEvent``, ``with-button`` variant:
|
|
1174
|
+
button click or Enter) and ``forgot`` (``forgot-password`` link) are the
|
|
1175
|
+
other events.
|
|
1176
|
+
|
|
1177
|
+
* ``autocomplete-loading``: ``provider(query) -> list[str]`` (sync or
|
|
1178
|
+
async) fills the suggestions; ``loading`` shows the Loader meanwhile.
|
|
1179
|
+
* ``contained``: the input inside a filled (theme hover colour) container.
|
|
1180
|
+
* ``currency``: amount plus ``currencies`` select; ``currency`` and
|
|
1181
|
+
``amount`` (``Decimal`` or None) are typed.
|
|
1182
|
+
* ``floating-label``: the label sits inside the field until it is focused
|
|
1183
|
+
or filled, then moves above it (driven from Python).
|
|
1184
|
+
* ``forgot-password``: password field with a *Forgot* link in the label row.
|
|
1185
|
+
* ``tooltip``: password field whose tooltip lists unmet ``requirements``
|
|
1186
|
+
while focused.
|
|
1187
|
+
* ``validation``: ``validator(text) -> error | None`` decides ``error``
|
|
1188
|
+
and ``valid`` (server-authoritative).
|
|
1189
|
+
* ``with-button``: text field with a submit icon button.
|
|
1190
|
+
* ``password-strength``: popover with a strength bar and a checklist of
|
|
1191
|
+
``requirements`` (``(regex, label)`` pairs plus ``min_length``);
|
|
1192
|
+
``strength`` is 0-100.
|
|
1193
|
+
"""
|
|
1194
|
+
|
|
1195
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
1196
|
+
"change": EventSpec("change", "ChangeEvent"),
|
|
1197
|
+
"submit": EventSpec("submit", "ValueEvent"),
|
|
1198
|
+
"forgot": EventSpec("forgot", "Event"),
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
def __init__(
|
|
1202
|
+
self,
|
|
1203
|
+
variant: str,
|
|
1204
|
+
*,
|
|
1205
|
+
label: str | None = None,
|
|
1206
|
+
description: str | None = None,
|
|
1207
|
+
placeholder: str | None = None,
|
|
1208
|
+
value: str = "",
|
|
1209
|
+
provider: Callable[[str], Sequence[str] | Awaitable[Sequence[str]]] | None = None,
|
|
1210
|
+
currencies: Sequence[str] = ("USD", "EUR", "GBP"),
|
|
1211
|
+
currency: str | None = None,
|
|
1212
|
+
validator: Callable[[str], str | None] | None = None,
|
|
1213
|
+
requirements: Sequence[tuple[str, str]] = DEFAULT_REQUIREMENTS,
|
|
1214
|
+
min_length: int = 6,
|
|
1215
|
+
forgot_label: str = "Forgot password?",
|
|
1216
|
+
button_icon: str = "arrow-right",
|
|
1217
|
+
on_change: Handler[ChangeEvent[str]] | None = None,
|
|
1218
|
+
on_submit: Handler[ValueEvent] | None = None,
|
|
1219
|
+
on_forgot: Handler[Event] | None = None,
|
|
1220
|
+
visible: bool | Unset = UNSET,
|
|
1221
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
1222
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
1223
|
+
aria_label: str | Unset = UNSET,
|
|
1224
|
+
) -> None:
|
|
1225
|
+
if variant not in _INPUT_VARIANTS:
|
|
1226
|
+
raise ValidationError(f"InputBlock: variant must be one of {list(_INPUT_VARIANTS)}")
|
|
1227
|
+
_opt_text(label, "InputBlock.label")
|
|
1228
|
+
_opt_text(description, "InputBlock.description")
|
|
1229
|
+
_opt_text(placeholder, "InputBlock.placeholder")
|
|
1230
|
+
_text(value, "InputBlock.value", limit=1000, empty=True)
|
|
1231
|
+
_icon(button_icon, "InputBlock.button_icon")
|
|
1232
|
+
_text(forgot_label, "InputBlock.forgot_label", limit=60)
|
|
1233
|
+
only: dict[str, tuple[Any, str]] = {
|
|
1234
|
+
"provider": (provider, "autocomplete-loading"),
|
|
1235
|
+
"validator": (validator, "validation"),
|
|
1236
|
+
"on_submit": (on_submit, "with-button"),
|
|
1237
|
+
"on_forgot": (on_forgot, "forgot-password"),
|
|
1238
|
+
}
|
|
1239
|
+
for n, (v, want) in only.items():
|
|
1240
|
+
if v is not None and variant != want:
|
|
1241
|
+
raise ValidationError(f"InputBlock: {n} is for variant {want!r}")
|
|
1242
|
+
if variant == "autocomplete-loading" and provider is None:
|
|
1243
|
+
raise ValidationError("InputBlock(autocomplete-loading): needs a provider")
|
|
1244
|
+
if variant == "validation" and validator is None:
|
|
1245
|
+
raise ValidationError("InputBlock(validation): needs a validator")
|
|
1246
|
+
cur_list = [
|
|
1247
|
+
_text(c, "InputBlock.currencies", limit=8)
|
|
1248
|
+
for c in _seq(currencies, "InputBlock.currencies", limit=50)
|
|
1249
|
+
]
|
|
1250
|
+
if variant == "currency":
|
|
1251
|
+
if not cur_list:
|
|
1252
|
+
raise ValidationError("InputBlock(currency): needs currencies")
|
|
1253
|
+
_unique(cur_list, "InputBlock.currencies")
|
|
1254
|
+
if currency is not None and currency not in cur_list:
|
|
1255
|
+
raise ValidationError("InputBlock.currency: not one of the currencies")
|
|
1256
|
+
elif currency is not None:
|
|
1257
|
+
raise ValidationError("InputBlock: currency is for variant 'currency'")
|
|
1258
|
+
if (
|
|
1259
|
+
not isinstance(min_length, int) # pyright: ignore[reportUnnecessaryIsInstance]
|
|
1260
|
+
or isinstance(min_length, bool)
|
|
1261
|
+
or not 0 <= min_length <= 128
|
|
1262
|
+
):
|
|
1263
|
+
raise ValidationError("InputBlock.min_length: 0..128")
|
|
1264
|
+
reqs: list[_Requirement] = []
|
|
1265
|
+
if variant in ("password-strength", "tooltip"):
|
|
1266
|
+
for pair in _seq(requirements, "InputBlock.requirements", limit=12):
|
|
1267
|
+
if not (isinstance(pair, (tuple, list)) and len(cast("Sequence[Any]", pair)) == 2):
|
|
1268
|
+
raise ValidationError("InputBlock.requirements: (regex, label) pairs")
|
|
1269
|
+
rx, lab = cast("Sequence[str]", pair)
|
|
1270
|
+
try:
|
|
1271
|
+
reqs.append(
|
|
1272
|
+
_Requirement(re.compile(_text(rx, "regex", limit=100)), _text(lab, "label"))
|
|
1273
|
+
)
|
|
1274
|
+
except re.error as err:
|
|
1275
|
+
raise ValidationError(f"InputBlock.requirements: bad regex ({err})") from None
|
|
1276
|
+
if min_length:
|
|
1277
|
+
reqs.append(
|
|
1278
|
+
_Requirement(
|
|
1279
|
+
re.compile(f"^.{{{min_length},}}$", re.DOTALL),
|
|
1280
|
+
f"At least {min_length} characters",
|
|
1281
|
+
)
|
|
1282
|
+
)
|
|
1283
|
+
super().__init__(
|
|
1284
|
+
gap=4, visible=visible, classes=classes, styles=styles, aria_label=aria_label
|
|
1285
|
+
)
|
|
1286
|
+
self.variant = variant
|
|
1287
|
+
self._provider = provider
|
|
1288
|
+
self._validator = validator
|
|
1289
|
+
self._reqs = reqs
|
|
1290
|
+
self._focused = False
|
|
1291
|
+
self._seq_no = 0
|
|
1292
|
+
self._loading = False
|
|
1293
|
+
self._error: str | None = None
|
|
1294
|
+
self._float_text = label or placeholder or ""
|
|
1295
|
+
self._rows: list[tuple[Icon, Text]] = []
|
|
1296
|
+
self.currencies = tuple(cur_list)
|
|
1297
|
+
self.field: Any = None
|
|
1298
|
+
self.currency_select: NativeSelect | None = None
|
|
1299
|
+
self.button: ActionIcon | None = None
|
|
1300
|
+
self.loader: Loader | None = None
|
|
1301
|
+
self.popover: Popover | None = None
|
|
1302
|
+
self.tooltip: Tooltip | None = None
|
|
1303
|
+
self.progress: Progress | None = None
|
|
1304
|
+
self.forgot_link: Anchor | None = None
|
|
1305
|
+
p = _Params(
|
|
1306
|
+
label=label,
|
|
1307
|
+
description=description,
|
|
1308
|
+
placeholder=placeholder,
|
|
1309
|
+
value=value,
|
|
1310
|
+
currency=currency,
|
|
1311
|
+
forgot_label=forgot_label,
|
|
1312
|
+
icon=button_icon,
|
|
1313
|
+
)
|
|
1314
|
+
with self:
|
|
1315
|
+
getattr(self, "_build_" + variant.replace("-", "_"))(p)
|
|
1316
|
+
_hook(self, {"change": on_change, "submit": on_submit, "forgot": on_forgot})
|
|
1317
|
+
if variant == "validation":
|
|
1318
|
+
self._validate(value)
|
|
1319
|
+
if variant in ("password-strength", "tooltip"):
|
|
1320
|
+
self._refresh_requirements(value)
|
|
1321
|
+
|
|
1322
|
+
# ---------------------------------------------------------- variants
|
|
1323
|
+
@staticmethod
|
|
1324
|
+
def _kw(p: _Params, placeholder: str | None = None) -> dict[str, Any]:
|
|
1325
|
+
ph = placeholder if placeholder is not None else p.placeholder
|
|
1326
|
+
return {
|
|
1327
|
+
"label": p.label if p.label else UNSET,
|
|
1328
|
+
"description": p.description if p.description else UNSET,
|
|
1329
|
+
"placeholder": ph if ph else UNSET,
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
def _build_autocomplete_loading(self, p: _Params) -> None:
|
|
1333
|
+
self.loader = Loader(size="xs", visible=False)
|
|
1334
|
+
self.field = Autocomplete(
|
|
1335
|
+
**self._kw(p),
|
|
1336
|
+
value=p.value,
|
|
1337
|
+
data=[],
|
|
1338
|
+
debounce=250,
|
|
1339
|
+
right_section=self.loader,
|
|
1340
|
+
on_change=self._provider_handler(),
|
|
1341
|
+
)
|
|
1342
|
+
|
|
1343
|
+
def _build_contained(self, p: _Params) -> None:
|
|
1344
|
+
with Paper(bg="var(--mantine-color-default-hover)", p="md", radius="md"):
|
|
1345
|
+
self.field = TextInput(
|
|
1346
|
+
**self._kw(p), value=p.value, debounce=150, on_change=self._on_text
|
|
1347
|
+
)
|
|
1348
|
+
|
|
1349
|
+
def _build_currency(self, p: _Params) -> None:
|
|
1350
|
+
self.currency_select = NativeSelect(
|
|
1351
|
+
data=cast("list[Option]", [{"value": c, "label": c} for c in self.currencies]),
|
|
1352
|
+
value=p.currency or self.currencies[0],
|
|
1353
|
+
aria_label="Currency",
|
|
1354
|
+
size="xs",
|
|
1355
|
+
on_change=self._on_currency,
|
|
1356
|
+
)
|
|
1357
|
+
self.field = TextInput(
|
|
1358
|
+
**self._kw(p, p.placeholder or "0.00"),
|
|
1359
|
+
value=p.value,
|
|
1360
|
+
debounce=150,
|
|
1361
|
+
right_section=self.currency_select,
|
|
1362
|
+
on_change=self._on_amount,
|
|
1363
|
+
)
|
|
1364
|
+
|
|
1365
|
+
def _build_floating_label(self, p: _Params) -> None:
|
|
1366
|
+
self.field = TextInput(
|
|
1367
|
+
description=p.description if p.description else UNSET,
|
|
1368
|
+
value=p.value,
|
|
1369
|
+
debounce=150,
|
|
1370
|
+
placeholder=self._float_text or UNSET,
|
|
1371
|
+
aria_label=self._float_text or UNSET,
|
|
1372
|
+
on_change=self._on_floating,
|
|
1373
|
+
on_focus=self._on_float_focus,
|
|
1374
|
+
on_blur=self._on_float_blur,
|
|
1375
|
+
)
|
|
1376
|
+
self._float()
|
|
1377
|
+
|
|
1378
|
+
def _build_forgot_password(self, p: _Params) -> None:
|
|
1379
|
+
with Group(justify="space-between"):
|
|
1380
|
+
if p.label:
|
|
1381
|
+
Text(p.label, size="sm", fw=500)
|
|
1382
|
+
self.forgot_link = Anchor(p.forgot_label, size="xs", on_click=self._forgot)
|
|
1383
|
+
self.field = PasswordInput(
|
|
1384
|
+
description=p.description if p.description else UNSET,
|
|
1385
|
+
placeholder=p.placeholder if p.placeholder else UNSET,
|
|
1386
|
+
value=p.value,
|
|
1387
|
+
debounce=150,
|
|
1388
|
+
aria_label=p.label if p.label else "Password",
|
|
1389
|
+
on_change=self._on_text,
|
|
1390
|
+
)
|
|
1391
|
+
|
|
1392
|
+
def _build_tooltip(self, p: _Params) -> None:
|
|
1393
|
+
with Tooltip(
|
|
1394
|
+
label=self._missing_text(p.value), opened=False, position="right", with_arrow=True
|
|
1395
|
+
) as tip:
|
|
1396
|
+
self.field = PasswordInput(
|
|
1397
|
+
**self._kw(p),
|
|
1398
|
+
value=p.value,
|
|
1399
|
+
debounce=150,
|
|
1400
|
+
on_change=self._on_tip_change,
|
|
1401
|
+
on_focus=self._on_focus,
|
|
1402
|
+
on_blur=self._on_blur,
|
|
1403
|
+
)
|
|
1404
|
+
self.tooltip = cast("Tooltip", tip)
|
|
1405
|
+
|
|
1406
|
+
def _build_validation(self, p: _Params) -> None:
|
|
1407
|
+
self.field = TextInput(
|
|
1408
|
+
**self._kw(p), value=p.value, debounce=150, on_change=self._on_validated
|
|
1409
|
+
)
|
|
1410
|
+
|
|
1411
|
+
def _build_with_button(self, p: _Params) -> None:
|
|
1412
|
+
self.button = ActionIcon(
|
|
1413
|
+
icon=cast("Any", p.icon), variant="filled", aria_label="Submit", on_click=self._submit
|
|
1414
|
+
)
|
|
1415
|
+
self.field = TextInput(
|
|
1416
|
+
**self._kw(p),
|
|
1417
|
+
value=p.value,
|
|
1418
|
+
debounce=150,
|
|
1419
|
+
right_section=self.button,
|
|
1420
|
+
on_change=self._on_text,
|
|
1421
|
+
on_enter=self._submit,
|
|
1422
|
+
)
|
|
1423
|
+
|
|
1424
|
+
def _build_password_strength(self, p: _Params) -> None:
|
|
1425
|
+
self.field = PasswordInput(
|
|
1426
|
+
**self._kw(p),
|
|
1427
|
+
value=p.value,
|
|
1428
|
+
debounce=150,
|
|
1429
|
+
on_change=self._on_strength,
|
|
1430
|
+
on_focus=self._on_focus,
|
|
1431
|
+
on_blur=self._on_blur,
|
|
1432
|
+
)
|
|
1433
|
+
with Popover(
|
|
1434
|
+
target=self.field,
|
|
1435
|
+
opened=False,
|
|
1436
|
+
position="bottom",
|
|
1437
|
+
width="target",
|
|
1438
|
+
with_arrow=True,
|
|
1439
|
+
trap_focus=False,
|
|
1440
|
+
) as pop:
|
|
1441
|
+
with Stack(gap="xs"):
|
|
1442
|
+
self.progress = Progress(value=0, size="sm", color="red")
|
|
1443
|
+
for r in self._reqs:
|
|
1444
|
+
with Group(gap=6, wrap="nowrap"):
|
|
1445
|
+
ic = _Icon("x", size=14, color="red")
|
|
1446
|
+
tx = Text(r.label, size="sm", c="red")
|
|
1447
|
+
self._rows.append((ic, tx))
|
|
1448
|
+
self.popover = cast("Popover", pop)
|
|
1449
|
+
|
|
1450
|
+
# ----------------------------------------------------------- state
|
|
1451
|
+
@property
|
|
1452
|
+
def value(self) -> str:
|
|
1453
|
+
"""The field text (the amount for ``currency``)."""
|
|
1454
|
+
v = self.field.value
|
|
1455
|
+
return v if isinstance(v, str) else ""
|
|
1456
|
+
|
|
1457
|
+
@value.setter
|
|
1458
|
+
def value(self, text: str) -> None:
|
|
1459
|
+
_text(text, "InputBlock.value", limit=1000, empty=True)
|
|
1460
|
+
self.field.value = text
|
|
1461
|
+
if self.variant == "validation":
|
|
1462
|
+
self._validate(text)
|
|
1463
|
+
elif self.variant in ("password-strength", "tooltip"):
|
|
1464
|
+
self._refresh_requirements(text)
|
|
1465
|
+
elif self.variant == "floating-label":
|
|
1466
|
+
self._float()
|
|
1467
|
+
|
|
1468
|
+
@property
|
|
1469
|
+
def error(self) -> str | None:
|
|
1470
|
+
"""The validation error of a ``validation`` input (None when fine)."""
|
|
1471
|
+
return self._error
|
|
1472
|
+
|
|
1473
|
+
@property
|
|
1474
|
+
def valid(self) -> bool:
|
|
1475
|
+
"""``validation``: non-empty and accepted by the validator."""
|
|
1476
|
+
return self.variant == "validation" and bool(self.value) and self._error is None
|
|
1477
|
+
|
|
1478
|
+
@property
|
|
1479
|
+
def currency(self) -> str | None:
|
|
1480
|
+
"""Selected currency of a ``currency`` input."""
|
|
1481
|
+
return None if self.currency_select is None else str(self.currency_select.value)
|
|
1482
|
+
|
|
1483
|
+
@currency.setter
|
|
1484
|
+
def currency(self, code: str) -> None:
|
|
1485
|
+
if self.currency_select is None or code not in self.currencies:
|
|
1486
|
+
raise ValidationError("InputBlock.currency: not one of the currencies")
|
|
1487
|
+
self.currency_select.value = code
|
|
1488
|
+
|
|
1489
|
+
@property
|
|
1490
|
+
def amount(self) -> Decimal | None:
|
|
1491
|
+
"""The parsed amount of a ``currency`` input (None when empty/invalid)."""
|
|
1492
|
+
try:
|
|
1493
|
+
d = Decimal(self.value.strip().replace(",", ""))
|
|
1494
|
+
except InvalidOperation:
|
|
1495
|
+
return None
|
|
1496
|
+
return d if d.is_finite() else None
|
|
1497
|
+
|
|
1498
|
+
@property
|
|
1499
|
+
def loading(self) -> bool:
|
|
1500
|
+
"""``autocomplete-loading``: whether suggestions are being fetched."""
|
|
1501
|
+
return self._loading
|
|
1502
|
+
|
|
1503
|
+
@property
|
|
1504
|
+
def options(self) -> list[str]:
|
|
1505
|
+
"""``autocomplete-loading``: the current suggestions."""
|
|
1506
|
+
data: Sequence[Any] = (
|
|
1507
|
+
cast("Sequence[Any]", self.field.data or [])
|
|
1508
|
+
if self.variant == "autocomplete-loading"
|
|
1509
|
+
else []
|
|
1510
|
+
)
|
|
1511
|
+
return [
|
|
1512
|
+
str(cast("Mapping[str, Any]", o)["value"]) if isinstance(o, Mapping) else str(o)
|
|
1513
|
+
for o in data
|
|
1514
|
+
]
|
|
1515
|
+
|
|
1516
|
+
@property
|
|
1517
|
+
def strength(self) -> int:
|
|
1518
|
+
"""Share of met requirements, 0-100 (password variants)."""
|
|
1519
|
+
if not self._reqs:
|
|
1520
|
+
return 0
|
|
1521
|
+
met = sum(1 for r in self._reqs if r.pattern.search(self.value))
|
|
1522
|
+
return round(100 * met / len(self._reqs))
|
|
1523
|
+
|
|
1524
|
+
# ---------------------------------------------------------- handlers
|
|
1525
|
+
def _fire_change(self, ev: Any) -> None:
|
|
1526
|
+
_emit(self, "change", ChangeEvent, value=self.value, previous=ev.previous)
|
|
1527
|
+
|
|
1528
|
+
def _on_text(self, ev: Any) -> None:
|
|
1529
|
+
self._fire_change(ev)
|
|
1530
|
+
|
|
1531
|
+
def _on_amount(self, ev: Any) -> None:
|
|
1532
|
+
text = self.value.strip()
|
|
1533
|
+
self.field.update(error="" if not text or self.amount is not None else "Enter a number")
|
|
1534
|
+
self._fire_change(ev)
|
|
1535
|
+
|
|
1536
|
+
def _on_currency(self, ev: Any) -> None:
|
|
1537
|
+
_emit(self, "change", ChangeEvent, value=self.value, previous=self.value)
|
|
1538
|
+
|
|
1539
|
+
def _on_validated(self, ev: Any) -> None:
|
|
1540
|
+
self._validate(self.value)
|
|
1541
|
+
self._fire_change(ev)
|
|
1542
|
+
|
|
1543
|
+
def _validate(self, text: str) -> None:
|
|
1544
|
+
assert self._validator is not None
|
|
1545
|
+
err = self._validator(text) if text else None
|
|
1546
|
+
if err is not None and not isinstance(err, str): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
1547
|
+
raise ValidationError("InputBlock.validator must return an error text or None")
|
|
1548
|
+
self._error = err or None
|
|
1549
|
+
self.field.update(error=self._error or "")
|
|
1550
|
+
|
|
1551
|
+
def _provider_handler(self) -> Callable[..., Any]:
|
|
1552
|
+
provider = self._provider
|
|
1553
|
+
assert provider is not None
|
|
1554
|
+
|
|
1555
|
+
def start(text: str) -> int:
|
|
1556
|
+
self._seq_no += 1
|
|
1557
|
+
self._set_loading(bool(text))
|
|
1558
|
+
if not text:
|
|
1559
|
+
self.field.update(data=[])
|
|
1560
|
+
return self._seq_no
|
|
1561
|
+
|
|
1562
|
+
def finish(n: int, found: Any) -> None:
|
|
1563
|
+
if n != self._seq_no:
|
|
1564
|
+
return # a newer query superseded this answer
|
|
1565
|
+
data = [str(x)[:_MAX_TEXT] for x in list(cast("Iterable[Any]", found))[:50]]
|
|
1566
|
+
self.field.update(data=data)
|
|
1567
|
+
self._set_loading(False)
|
|
1568
|
+
|
|
1569
|
+
if inspect.iscoroutinefunction(provider):
|
|
1570
|
+
|
|
1571
|
+
async def run_async(ev: Any) -> None:
|
|
1572
|
+
text = ev.value if isinstance(ev.value, str) else ""
|
|
1573
|
+
n = start(text)
|
|
1574
|
+
self._fire_change(ev)
|
|
1575
|
+
if text:
|
|
1576
|
+
try:
|
|
1577
|
+
finish(n, await cast("Awaitable[Any]", provider(text)))
|
|
1578
|
+
except Exception:
|
|
1579
|
+
self._set_loading(False)
|
|
1580
|
+
raise
|
|
1581
|
+
|
|
1582
|
+
return run_async
|
|
1583
|
+
|
|
1584
|
+
def run_sync(ev: Any) -> None:
|
|
1585
|
+
text = ev.value if isinstance(ev.value, str) else ""
|
|
1586
|
+
n = start(text)
|
|
1587
|
+
self._fire_change(ev)
|
|
1588
|
+
if text:
|
|
1589
|
+
try:
|
|
1590
|
+
finish(n, provider(text))
|
|
1591
|
+
except Exception:
|
|
1592
|
+
self._set_loading(False)
|
|
1593
|
+
raise
|
|
1594
|
+
|
|
1595
|
+
return run_sync
|
|
1596
|
+
|
|
1597
|
+
def _set_loading(self, on: bool) -> None:
|
|
1598
|
+
self._loading = on
|
|
1599
|
+
if self.loader is not None:
|
|
1600
|
+
self.loader.update(visible=on)
|
|
1601
|
+
|
|
1602
|
+
def _float(self) -> None:
|
|
1603
|
+
up = self._focused or bool(self.value)
|
|
1604
|
+
self.field.update(
|
|
1605
|
+
label=self._float_text if up and self._float_text else UNSET,
|
|
1606
|
+
placeholder=UNSET if up or not self._float_text else self._float_text,
|
|
1607
|
+
)
|
|
1608
|
+
|
|
1609
|
+
def _on_floating(self, ev: Any) -> None:
|
|
1610
|
+
self._float()
|
|
1611
|
+
self._fire_change(ev)
|
|
1612
|
+
|
|
1613
|
+
def _on_float_focus(self) -> None:
|
|
1614
|
+
self._focused = True
|
|
1615
|
+
self._float()
|
|
1616
|
+
|
|
1617
|
+
def _on_float_blur(self) -> None:
|
|
1618
|
+
self._focused = False
|
|
1619
|
+
self._float()
|
|
1620
|
+
|
|
1621
|
+
def _forgot(self) -> None:
|
|
1622
|
+
_emit(self, "forgot", Event)
|
|
1623
|
+
|
|
1624
|
+
def _submit(self) -> None:
|
|
1625
|
+
_emit(self, "submit", ValueEvent, value=self.value)
|
|
1626
|
+
|
|
1627
|
+
def _missing_text(self, text: str) -> str:
|
|
1628
|
+
miss = [r.label for r in self._reqs if not r.pattern.search(text)]
|
|
1629
|
+
return "Requirements met" if not miss else "Missing: " + ", ".join(miss)
|
|
1630
|
+
|
|
1631
|
+
def _refresh_requirements(self, text: str) -> None:
|
|
1632
|
+
if self.tooltip is not None:
|
|
1633
|
+
self.tooltip.update(label=self._missing_text(text))
|
|
1634
|
+
if self.progress is not None:
|
|
1635
|
+
s = self.strength
|
|
1636
|
+
self.progress.update(
|
|
1637
|
+
value=s, color="red" if s < 50 else "yellow" if s < 100 else "teal"
|
|
1638
|
+
)
|
|
1639
|
+
for r, (ic, tx) in zip(self._reqs, self._rows, strict=True):
|
|
1640
|
+
ok = bool(r.pattern.search(text))
|
|
1641
|
+
ic.update(name="check" if ok else "x", color="teal" if ok else "red")
|
|
1642
|
+
tx.update(c="teal" if ok else "red")
|
|
1643
|
+
|
|
1644
|
+
def _on_strength(self, ev: Any) -> None:
|
|
1645
|
+
self._refresh_requirements(self.value)
|
|
1646
|
+
self._fire_change(ev)
|
|
1647
|
+
|
|
1648
|
+
def _on_tip_change(self, ev: Any) -> None:
|
|
1649
|
+
self._refresh_requirements(self.value)
|
|
1650
|
+
self._tip_visibility()
|
|
1651
|
+
self._fire_change(ev)
|
|
1652
|
+
|
|
1653
|
+
def _on_focus(self) -> None:
|
|
1654
|
+
self._focused = True
|
|
1655
|
+
if self.popover is not None:
|
|
1656
|
+
self.popover.update(opened=True)
|
|
1657
|
+
self._tip_visibility()
|
|
1658
|
+
|
|
1659
|
+
def _on_blur(self) -> None:
|
|
1660
|
+
self._focused = False
|
|
1661
|
+
if self.popover is not None:
|
|
1662
|
+
self.popover.update(opened=False)
|
|
1663
|
+
self._tip_visibility()
|
|
1664
|
+
|
|
1665
|
+
def _tip_visibility(self) -> None:
|
|
1666
|
+
if self.tooltip is not None:
|
|
1667
|
+
unmet = any(not r.pattern.search(self.value) for r in self._reqs)
|
|
1668
|
+
self.tooltip.update(opened=self._focused and unmet)
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
@dataclass
|
|
1672
|
+
class _Params:
|
|
1673
|
+
label: str | None
|
|
1674
|
+
description: str | None
|
|
1675
|
+
placeholder: str | None
|
|
1676
|
+
value: str
|
|
1677
|
+
currency: str | None
|
|
1678
|
+
forgot_label: str
|
|
1679
|
+
icon: str
|
|
1680
|
+
|
|
1681
|
+
|
|
1682
|
+
# ================================================================ LabeledSlider
|
|
1683
|
+
_SLIDER_VARIANTS = ("hover", "icon", "input", "label", "marks", "white")
|
|
1684
|
+
|
|
1685
|
+
|
|
1686
|
+
def _is_num(v: Any) -> bool:
|
|
1687
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
def _mark(m: Any, lo: float, hi: float) -> dict[str, Any]:
|
|
1691
|
+
v: Any
|
|
1692
|
+
lab: Any
|
|
1693
|
+
if isinstance(m, Mapping):
|
|
1694
|
+
mm = cast("Mapping[str, Any]", m)
|
|
1695
|
+
v, lab = mm.get("value"), mm.get("label")
|
|
1696
|
+
elif isinstance(m, (tuple, list)) and len(cast("Sequence[Any]", m)) == 2:
|
|
1697
|
+
v, lab = cast("Sequence[Any]", m)[0], cast("Sequence[Any]", m)[1]
|
|
1698
|
+
else:
|
|
1699
|
+
v, lab = cast("Any", m), None
|
|
1700
|
+
if not _is_num(v) or not lo <= v <= hi:
|
|
1701
|
+
raise ValidationError("LabeledSlider.marks: values must be numbers inside [min, max]")
|
|
1702
|
+
out: dict[str, Any] = {"value": v}
|
|
1703
|
+
if lab is not None:
|
|
1704
|
+
out["label"] = _text(lab, "LabeledSlider.marks label", limit=40)
|
|
1705
|
+
return out
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
def _num(v: Any, lo: float, hi: float) -> float:
|
|
1709
|
+
if not _is_num(v):
|
|
1710
|
+
raise ValidationError("LabeledSlider.value: expected finite numbers")
|
|
1711
|
+
if not lo <= v <= hi:
|
|
1712
|
+
raise ValidationError(f"LabeledSlider.value: {v} outside [{lo}, {hi}]")
|
|
1713
|
+
return float(v)
|
|
1714
|
+
|
|
1715
|
+
|
|
1716
|
+
class LabeledSlider(_Local, Stack):
|
|
1717
|
+
"""Slider / RangeSlider presets. ``value`` is a number (``range=False``) or a
|
|
1718
|
+
``(low, high)`` pair (``range=True``).
|
|
1719
|
+
|
|
1720
|
+
Variants: ``hover`` (label only while hovering/dragging, small thumb),
|
|
1721
|
+
``icon`` (an ``icon`` beside a larger-thumb slider), ``input`` (a NumberInput
|
|
1722
|
+
kept in sync with a thin slider, single value only), ``label`` (labels always
|
|
1723
|
+
visible), ``marks`` (``marks`` on the track), ``white`` (light grey thumb and
|
|
1724
|
+
bar). ``change`` raises with the committed value (``ChangeEvent``) and
|
|
1725
|
+
``change_end`` when the thumb is released.
|
|
1726
|
+
"""
|
|
1727
|
+
|
|
1728
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
1729
|
+
"change": EventSpec("change", "ChangeEvent"),
|
|
1730
|
+
"change_end": EventSpec("change_end", "ChangeEvent"),
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
def __init__(
|
|
1734
|
+
self,
|
|
1735
|
+
variant: str = "label",
|
|
1736
|
+
*,
|
|
1737
|
+
value: float | Sequence[float] | None = None,
|
|
1738
|
+
minimum: float = 0,
|
|
1739
|
+
maximum: float = 100,
|
|
1740
|
+
step: float = 1,
|
|
1741
|
+
range: bool = False,
|
|
1742
|
+
label: str | None = None,
|
|
1743
|
+
icon: str | None = None,
|
|
1744
|
+
marks: Sequence[float | tuple[float, str] | Mapping[str, Any]] = (),
|
|
1745
|
+
color: str | None = None,
|
|
1746
|
+
on_change: Handler[ChangeEvent[Any]] | None = None,
|
|
1747
|
+
on_change_end: Handler[ChangeEvent[Any]] | None = None,
|
|
1748
|
+
visible: bool | Unset = UNSET,
|
|
1749
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
1750
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
1751
|
+
aria_label: str | Unset = UNSET,
|
|
1752
|
+
) -> None:
|
|
1753
|
+
if variant not in _SLIDER_VARIANTS:
|
|
1754
|
+
raise ValidationError(f"LabeledSlider: variant must be one of {list(_SLIDER_VARIANTS)}")
|
|
1755
|
+
for n, v in (("minimum", minimum), ("maximum", maximum), ("step", step)):
|
|
1756
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
1757
|
+
raise ValidationError(f"LabeledSlider.{n}: expected a finite number")
|
|
1758
|
+
if not minimum < maximum or step <= 0:
|
|
1759
|
+
raise ValidationError("LabeledSlider: need minimum < maximum and step > 0")
|
|
1760
|
+
_flag(range, "LabeledSlider.range")
|
|
1761
|
+
_opt_text(label, "LabeledSlider.label")
|
|
1762
|
+
_icon(icon, "LabeledSlider.icon")
|
|
1763
|
+
if color is not None:
|
|
1764
|
+
_text(color, "LabeledSlider.color", limit=40)
|
|
1765
|
+
if variant == "input" and range:
|
|
1766
|
+
raise ValidationError("LabeledSlider(input): single value only")
|
|
1767
|
+
if variant == "icon" and icon is None:
|
|
1768
|
+
raise ValidationError("LabeledSlider(icon): needs an icon")
|
|
1769
|
+
if icon is not None and variant != "icon":
|
|
1770
|
+
raise ValidationError("LabeledSlider: icon is for variant 'icon'")
|
|
1771
|
+
mk = [_mark(m, minimum, maximum) for m in _seq(marks, "LabeledSlider.marks", limit=50)]
|
|
1772
|
+
if variant == "marks" and not mk:
|
|
1773
|
+
raise ValidationError("LabeledSlider(marks): needs marks")
|
|
1774
|
+
if mk and variant != "marks":
|
|
1775
|
+
raise ValidationError("LabeledSlider: marks are for variant 'marks'")
|
|
1776
|
+
init: float | tuple[float, float]
|
|
1777
|
+
raw = value if value is not None else ((minimum, maximum) if range else minimum)
|
|
1778
|
+
if range:
|
|
1779
|
+
if (
|
|
1780
|
+
isinstance(raw, (str, bytes))
|
|
1781
|
+
or not isinstance(raw, Sequence)
|
|
1782
|
+
or len(cast("Sequence[Any]", raw)) != 2
|
|
1783
|
+
):
|
|
1784
|
+
raise ValidationError("LabeledSlider.value: expected a (low, high) pair")
|
|
1785
|
+
pair = cast("Sequence[Any]", raw)
|
|
1786
|
+
init = (_num(pair[0], minimum, maximum), _num(pair[1], minimum, maximum))
|
|
1787
|
+
if init[0] > init[1]:
|
|
1788
|
+
raise ValidationError("LabeledSlider.value: low must not exceed high")
|
|
1789
|
+
else:
|
|
1790
|
+
init = _num(raw, minimum, maximum)
|
|
1791
|
+
super().__init__(
|
|
1792
|
+
gap="xs", visible=visible, classes=classes, styles=styles, aria_label=aria_label
|
|
1793
|
+
)
|
|
1794
|
+
self.variant = variant
|
|
1795
|
+
self.is_range = range
|
|
1796
|
+
self.minimum, self.maximum, self.step = float(minimum), float(maximum), float(step)
|
|
1797
|
+
self._value: float | tuple[float, float] = init
|
|
1798
|
+
self.number: NumberInput | None = None
|
|
1799
|
+
kw: dict[str, Any] = {"min": minimum, "max": maximum, "step": step}
|
|
1800
|
+
if variant == "hover":
|
|
1801
|
+
kw.update(show_label_on_hover=True, thumb_size=12, size="xs")
|
|
1802
|
+
elif variant == "icon":
|
|
1803
|
+
kw.update(thumb_size=26)
|
|
1804
|
+
elif variant == "input":
|
|
1805
|
+
kw.update(size="xs")
|
|
1806
|
+
elif variant == "label":
|
|
1807
|
+
kw.update(label_always_on=True)
|
|
1808
|
+
elif variant == "marks":
|
|
1809
|
+
kw.update(marks=mk)
|
|
1810
|
+
else:
|
|
1811
|
+
kw.update(color="gray.2", thumb_size=20)
|
|
1812
|
+
if color:
|
|
1813
|
+
kw["color"] = color
|
|
1814
|
+
with self:
|
|
1815
|
+
if label:
|
|
1816
|
+
Text(label, size="sm", fw=500)
|
|
1817
|
+
with Group(gap="md", align="center", wrap="nowrap"):
|
|
1818
|
+
if icon:
|
|
1819
|
+
_Icon(icon, size=18)
|
|
1820
|
+
self.slider: Slider | RangeSlider
|
|
1821
|
+
if isinstance(init, tuple):
|
|
1822
|
+
self.slider = RangeSlider(value=list(init), on_change=self._on_slide, **kw)
|
|
1823
|
+
else:
|
|
1824
|
+
self.slider = Slider(value=init, on_change=self._on_slide, **kw)
|
|
1825
|
+
if variant == "input":
|
|
1826
|
+
self.number = NumberInput(
|
|
1827
|
+
value=cast("float", init),
|
|
1828
|
+
min=minimum,
|
|
1829
|
+
max=maximum,
|
|
1830
|
+
step=step,
|
|
1831
|
+
debounce=150,
|
|
1832
|
+
aria_label=label or "Value",
|
|
1833
|
+
on_change=self._on_number,
|
|
1834
|
+
)
|
|
1835
|
+
self.slider.on("change_end", self._on_end)
|
|
1836
|
+
_hook(self, {"change": on_change, "change_end": on_change_end})
|
|
1837
|
+
|
|
1838
|
+
@property
|
|
1839
|
+
def value(self) -> float | tuple[float, float]:
|
|
1840
|
+
"""The committed value (a pair for ranges)."""
|
|
1841
|
+
return self._value
|
|
1842
|
+
|
|
1843
|
+
@value.setter
|
|
1844
|
+
def value(self, v: float | Sequence[float]) -> None:
|
|
1845
|
+
new: float | tuple[float, float]
|
|
1846
|
+
if self.is_range:
|
|
1847
|
+
if isinstance(v, (str, bytes)) or not isinstance(v, Sequence) or len(v) != 2:
|
|
1848
|
+
raise ValidationError("LabeledSlider.value: expected a (low, high) pair")
|
|
1849
|
+
new = (_num(v[0], self.minimum, self.maximum), _num(v[1], self.minimum, self.maximum))
|
|
1850
|
+
if new[0] > new[1]:
|
|
1851
|
+
raise ValidationError("LabeledSlider.value: low must not exceed high")
|
|
1852
|
+
else:
|
|
1853
|
+
new = _num(v, self.minimum, self.maximum)
|
|
1854
|
+
self._value = new
|
|
1855
|
+
self.slider.update(value=list(new) if isinstance(new, tuple) else new)
|
|
1856
|
+
if self.number is not None and not isinstance(new, tuple):
|
|
1857
|
+
self.number.update(value=new)
|
|
1858
|
+
|
|
1859
|
+
def _read(self) -> float | tuple[float, float]:
|
|
1860
|
+
v = self.slider.value
|
|
1861
|
+
if self.is_range:
|
|
1862
|
+
a, b = cast("Sequence[float]", v)
|
|
1863
|
+
return (float(a), float(b))
|
|
1864
|
+
return float(cast("float", v))
|
|
1865
|
+
|
|
1866
|
+
def _on_slide(self, ev: Any) -> None:
|
|
1867
|
+
prev, self._value = self._value, self._read()
|
|
1868
|
+
if self.number is not None and not isinstance(self._value, tuple):
|
|
1869
|
+
self.number.update(value=self._value)
|
|
1870
|
+
_emit(self, "change", ChangeEvent, value=self._value, previous=prev)
|
|
1871
|
+
|
|
1872
|
+
def _on_end(self, ev: Any) -> None:
|
|
1873
|
+
_emit(self, "change_end", ChangeEvent, value=self._read(), previous=self._value)
|
|
1874
|
+
|
|
1875
|
+
def _on_number(self, ev: Any) -> None:
|
|
1876
|
+
v = ev.value
|
|
1877
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
|
1878
|
+
return
|
|
1879
|
+
clamped = float(v)
|
|
1880
|
+
clamped = self.minimum if clamped < self.minimum else min(clamped, self.maximum)
|
|
1881
|
+
prev, self._value = self._value, clamped
|
|
1882
|
+
self.slider.update(value=clamped)
|
|
1883
|
+
_emit(self, "change", ChangeEvent, value=clamped, previous=prev)
|
|
1884
|
+
|
|
1885
|
+
|
|
1886
|
+
# ================================================================== ChoiceCard
|
|
1887
|
+
@dataclass(frozen=True)
|
|
1888
|
+
class ChoiceOption:
|
|
1889
|
+
"""One choice: ``image`` (``image`` variant) is an image source,
|
|
1890
|
+
``badge`` a short tag (``segmented`` variant)."""
|
|
1891
|
+
|
|
1892
|
+
value: str
|
|
1893
|
+
label: str
|
|
1894
|
+
description: str | None = None
|
|
1895
|
+
image: str | None = None
|
|
1896
|
+
badge: str | None = None
|
|
1897
|
+
|
|
1898
|
+
def __post_init__(self) -> None:
|
|
1899
|
+
w = f"ChoiceOption({self.value!r})"
|
|
1900
|
+
_value(self.value, w)
|
|
1901
|
+
_text(self.label, f"{w}.label")
|
|
1902
|
+
_opt_text(self.description, f"{w}.description")
|
|
1903
|
+
_opt_text(self.image, f"{w}.image")
|
|
1904
|
+
if self.badge is not None:
|
|
1905
|
+
_text(self.badge, f"{w}.badge", limit=16)
|
|
1906
|
+
|
|
1907
|
+
|
|
1908
|
+
class ChoiceCard(_Local, Stack):
|
|
1909
|
+
"""Selectable cards and rich segmented choices.
|
|
1910
|
+
|
|
1911
|
+
``checkbox``: bordered cards with title/description (any number selected);
|
|
1912
|
+
``image``: grid of image cards (``columns``); ``segmented``: one choice from
|
|
1913
|
+
a row of buttons with optional badges. ``selected`` is the typed selection
|
|
1914
|
+
(a list, exactly one entry for ``segmented``); ``change`` raises
|
|
1915
|
+
``ChoiceEvent``::
|
|
1916
|
+
|
|
1917
|
+
ui.blocks.ChoiceCard("checkbox", [ui.blocks.ChoiceOption("a", "Alpha", "First")],
|
|
1918
|
+
on_change=lambda e: print(e.selected))
|
|
1919
|
+
"""
|
|
1920
|
+
|
|
1921
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {"change": EventSpec("change", "ChoiceEvent")}
|
|
1922
|
+
|
|
1923
|
+
def __init__(
|
|
1924
|
+
self,
|
|
1925
|
+
variant: Literal["checkbox", "image", "segmented"],
|
|
1926
|
+
options: Iterable[ChoiceOption | Mapping[str, Any]],
|
|
1927
|
+
*,
|
|
1928
|
+
selected: Iterable[str] = (),
|
|
1929
|
+
label: str | None = None,
|
|
1930
|
+
columns: int = 3,
|
|
1931
|
+
color: str = "blue",
|
|
1932
|
+
on_change: Handler[ChoiceEvent] | None = None,
|
|
1933
|
+
visible: bool | Unset = UNSET,
|
|
1934
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
1935
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
1936
|
+
aria_label: str | Unset = UNSET,
|
|
1937
|
+
) -> None:
|
|
1938
|
+
if variant not in ("checkbox", "image", "segmented"):
|
|
1939
|
+
raise ValidationError("ChoiceCard: variant must be checkbox, image or segmented")
|
|
1940
|
+
opts = [
|
|
1941
|
+
_coerce(ChoiceOption, o, "ChoiceCard.options")
|
|
1942
|
+
for o in _seq(options, "ChoiceCard.options", limit=60)
|
|
1943
|
+
]
|
|
1944
|
+
if not opts:
|
|
1945
|
+
raise ValidationError("ChoiceCard: at least one option")
|
|
1946
|
+
_unique([o.value for o in opts], "ChoiceCard.options")
|
|
1947
|
+
if variant == "image" and any(o.image is None for o in opts):
|
|
1948
|
+
raise ValidationError("ChoiceCard(image): every option needs an image")
|
|
1949
|
+
if variant != "image" and any(o.image for o in opts):
|
|
1950
|
+
raise ValidationError("ChoiceCard: images are for variant 'image'")
|
|
1951
|
+
if variant != "segmented" and any(o.badge for o in opts):
|
|
1952
|
+
raise ValidationError("ChoiceCard: badges are for variant 'segmented'")
|
|
1953
|
+
if not isinstance(columns, int) or isinstance(columns, bool) or not 1 <= columns <= 6: # pyright: ignore[reportUnnecessaryIsInstance]
|
|
1954
|
+
raise ValidationError("ChoiceCard.columns: 1..6")
|
|
1955
|
+
_opt_text(label, "ChoiceCard.label")
|
|
1956
|
+
_text(color, "ChoiceCard.color", limit=40)
|
|
1957
|
+
sel = _check_selection(list(_seq(selected, "ChoiceCard.selected")), opts, variant)
|
|
1958
|
+
super().__init__(
|
|
1959
|
+
gap="xs", visible=visible, classes=classes, styles=styles, aria_label=aria_label
|
|
1960
|
+
)
|
|
1961
|
+
self.variant = variant
|
|
1962
|
+
self.options = {o.value: o for o in opts}
|
|
1963
|
+
self._selected: list[str] = sel
|
|
1964
|
+
self._color = color
|
|
1965
|
+
self.cards: dict[str, Any] = {}
|
|
1966
|
+
self.group: CheckboxGroup | None = None
|
|
1967
|
+
with self:
|
|
1968
|
+
if label:
|
|
1969
|
+
Text(label, size="sm", fw=500)
|
|
1970
|
+
if variant == "segmented":
|
|
1971
|
+
with Group(gap=4, wrap="wrap"):
|
|
1972
|
+
for o in opts:
|
|
1973
|
+
self.cards[o.value] = self._pill(o)
|
|
1974
|
+
self._paint()
|
|
1975
|
+
else:
|
|
1976
|
+
with CheckboxGroup(value=list(sel), on_change=self._on_group) as grp:
|
|
1977
|
+
wrap = (
|
|
1978
|
+
SimpleGrid(cols=columns, spacing="sm")
|
|
1979
|
+
if variant == "image"
|
|
1980
|
+
else Stack(gap="xs")
|
|
1981
|
+
)
|
|
1982
|
+
with wrap:
|
|
1983
|
+
for o in opts:
|
|
1984
|
+
self.cards[o.value] = self._card(o)
|
|
1985
|
+
self.group = cast("CheckboxGroup", grp)
|
|
1986
|
+
if on_change is not None:
|
|
1987
|
+
self.on("change", on_change)
|
|
1988
|
+
|
|
1989
|
+
@staticmethod
|
|
1990
|
+
def _card(o: ChoiceOption) -> CheckboxCard:
|
|
1991
|
+
with CheckboxCard(value=o.value, with_border=True, radius="md", aria_label=o.label) as card:
|
|
1992
|
+
with Stack(gap=6, p="sm"):
|
|
1993
|
+
if o.image:
|
|
1994
|
+
Image(src=o.image, alt=o.label, h=80, fit="cover", radius="sm")
|
|
1995
|
+
with Group(gap="sm", wrap="nowrap", align="flex-start"):
|
|
1996
|
+
CheckboxIndicator()
|
|
1997
|
+
with Stack(gap=0):
|
|
1998
|
+
Text(o.label, size="sm", fw=500)
|
|
1999
|
+
if o.description:
|
|
2000
|
+
Text(o.description, size="xs", dimmed=True)
|
|
2001
|
+
return cast("CheckboxCard", card)
|
|
2002
|
+
|
|
2003
|
+
def _pill(self, o: ChoiceOption) -> Button:
|
|
2004
|
+
return Button(
|
|
2005
|
+
o.label,
|
|
2006
|
+
variant="default",
|
|
2007
|
+
size="sm",
|
|
2008
|
+
right_section=Badge(o.badge, size="xs") if o.badge else None,
|
|
2009
|
+
on_click=partial(self._pick, o.value),
|
|
2010
|
+
)
|
|
2011
|
+
|
|
2012
|
+
def _paint(self) -> None:
|
|
2013
|
+
for v, btn in self.cards.items():
|
|
2014
|
+
on = v in self._selected
|
|
2015
|
+
btn.update(variant="filled" if on else "default", color=self._color if on else UNSET)
|
|
2016
|
+
|
|
2017
|
+
@property
|
|
2018
|
+
def selected(self) -> list[str]:
|
|
2019
|
+
"""The selected option values."""
|
|
2020
|
+
return list(self._selected)
|
|
2021
|
+
|
|
2022
|
+
@selected.setter
|
|
2023
|
+
def selected(self, values: Iterable[str]) -> None:
|
|
2024
|
+
sel = _check_selection(
|
|
2025
|
+
list(_seq(values, "ChoiceCard.selected")), list(self.options.values()), self.variant
|
|
2026
|
+
)
|
|
2027
|
+
self._selected = sel
|
|
2028
|
+
if self.group is not None:
|
|
2029
|
+
self.group.update(value=list(sel))
|
|
2030
|
+
else:
|
|
2031
|
+
self._paint()
|
|
2032
|
+
|
|
2033
|
+
def _on_group(self, ev: Any) -> None:
|
|
2034
|
+
v = ev.value
|
|
2035
|
+
now = [x for x in cast("list[Any]", v) if x in self.options] if isinstance(v, list) else []
|
|
2036
|
+
prev, self._selected = self._selected, now
|
|
2037
|
+
if now != prev:
|
|
2038
|
+
ch = tuple(sorted(set(now) ^ set(prev)))
|
|
2039
|
+
_emit(self, "change", ChoiceEvent, selected=list(now), previous=list(prev), changed=ch)
|
|
2040
|
+
|
|
2041
|
+
def _pick(self, value: str) -> None:
|
|
2042
|
+
prev = self._selected
|
|
2043
|
+
if prev == [value]:
|
|
2044
|
+
return
|
|
2045
|
+
self._selected = [value]
|
|
2046
|
+
self._paint()
|
|
2047
|
+
_emit(
|
|
2048
|
+
self,
|
|
2049
|
+
"change",
|
|
2050
|
+
ChoiceEvent,
|
|
2051
|
+
selected=[value],
|
|
2052
|
+
previous=list(prev),
|
|
2053
|
+
changed=tuple(sorted({value, *prev})),
|
|
2054
|
+
)
|
|
2055
|
+
|
|
2056
|
+
|
|
2057
|
+
def _check_selection(sel: list[Any], opts: list[ChoiceOption], variant: str) -> list[str]:
|
|
2058
|
+
known = {o.value for o in opts}
|
|
2059
|
+
if any(not isinstance(s, str) or s not in known for s in sel):
|
|
2060
|
+
raise ValidationError("ChoiceCard.selected: not one of the options")
|
|
2061
|
+
out = cast("list[str]", sel)
|
|
2062
|
+
_unique(out, "ChoiceCard.selected")
|
|
2063
|
+
if variant == "segmented":
|
|
2064
|
+
if len(out) > 1:
|
|
2065
|
+
raise ValidationError("ChoiceCard(segmented): one selection at most")
|
|
2066
|
+
return out or [opts[0].value]
|
|
2067
|
+
return list(out)
|
|
2068
|
+
|
|
2069
|
+
|
|
2070
|
+
# ================================================================= ActionButton
|
|
2071
|
+
_ACTION_VARIANTS = ("color-scheme-toggle", "copy", "progress", "social")
|
|
2072
|
+
|
|
2073
|
+
|
|
2074
|
+
class ActionButton(_Local, Group):
|
|
2075
|
+
"""Buttons with a built-in behaviour (``variant``).
|
|
2076
|
+
|
|
2077
|
+
* ``color-scheme-toggle``: icon button flipping ``scheme`` (``light`` /
|
|
2078
|
+
``dark``); it also switches the window theme unless ``apply_theme=False``.
|
|
2079
|
+
Raises ``change`` (``ChangeEvent[str]``).
|
|
2080
|
+
* ``copy``: copies ``value`` to the clipboard and shows ``copied_label``;
|
|
2081
|
+
raises ``copy`` (``ValueEvent`` with the copied text).
|
|
2082
|
+
* ``progress``: a long-running task button. Click raises ``run``; Python
|
|
2083
|
+
reports ``set_progress(0-100)`` and ``finish()``; clicking while running
|
|
2084
|
+
raises ``cancel``. ``running`` and ``progress`` are readable.
|
|
2085
|
+
* ``social``: one button per provider; raises ``provider`` (``ValueEvent``
|
|
2086
|
+
with the provider id). It never signs in; brand marks are not bundled, a
|
|
2087
|
+
lettered avatar stands in.
|
|
2088
|
+
"""
|
|
2089
|
+
|
|
2090
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
2091
|
+
"change": EventSpec("change", "ChangeEvent"),
|
|
2092
|
+
"copy": EventSpec("copy", "ValueEvent"),
|
|
2093
|
+
"run": EventSpec("run", "ValueEvent"),
|
|
2094
|
+
"cancel": EventSpec("cancel", "ValueEvent"),
|
|
2095
|
+
"provider": EventSpec("provider", "ValueEvent"),
|
|
2096
|
+
}
|
|
2097
|
+
_EVENT_VARIANT: ClassVar[Mapping[str, str]] = {
|
|
2098
|
+
"change": "color-scheme-toggle",
|
|
2099
|
+
"copy": "copy",
|
|
2100
|
+
"run": "progress",
|
|
2101
|
+
"cancel": "progress",
|
|
2102
|
+
"provider": "social",
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
def __init__(
|
|
2106
|
+
self,
|
|
2107
|
+
variant: str,
|
|
2108
|
+
*,
|
|
2109
|
+
label: str | None = None,
|
|
2110
|
+
scheme: Literal["light", "dark"] = "light",
|
|
2111
|
+
apply_theme: bool = True,
|
|
2112
|
+
value: str = "",
|
|
2113
|
+
copied_label: str = "Copied",
|
|
2114
|
+
providers: Iterable[str | tuple[str, str]] = (),
|
|
2115
|
+
on_change: Handler[ChangeEvent[str]] | None = None,
|
|
2116
|
+
on_copy: Handler[ValueEvent] | None = None,
|
|
2117
|
+
on_run: Handler[ValueEvent] | None = None,
|
|
2118
|
+
on_cancel: Handler[ValueEvent] | None = None,
|
|
2119
|
+
on_provider: Handler[ValueEvent] | None = None,
|
|
2120
|
+
visible: bool | Unset = UNSET,
|
|
2121
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
2122
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
2123
|
+
aria_label: str | Unset = UNSET,
|
|
2124
|
+
) -> None:
|
|
2125
|
+
if variant not in _ACTION_VARIANTS:
|
|
2126
|
+
raise ValidationError(f"ActionButton: variant must be one of {list(_ACTION_VARIANTS)}")
|
|
2127
|
+
given: dict[str, Callable[..., Any] | None] = {
|
|
2128
|
+
"change": on_change,
|
|
2129
|
+
"copy": on_copy,
|
|
2130
|
+
"run": on_run,
|
|
2131
|
+
"cancel": on_cancel,
|
|
2132
|
+
"provider": on_provider,
|
|
2133
|
+
}
|
|
2134
|
+
for n, fn in given.items():
|
|
2135
|
+
if fn is not None and self._EVENT_VARIANT[n] != variant:
|
|
2136
|
+
raise ValidationError(
|
|
2137
|
+
f"ActionButton: on_{n} is for variant {self._EVENT_VARIANT[n]!r}"
|
|
2138
|
+
)
|
|
2139
|
+
if scheme not in ("light", "dark"):
|
|
2140
|
+
raise ValidationError("ActionButton.scheme: light or dark")
|
|
2141
|
+
_opt_text(label, "ActionButton.label")
|
|
2142
|
+
_text(value, "ActionButton.value", limit=10000, empty=True)
|
|
2143
|
+
_text(copied_label, "ActionButton.copied_label", limit=40)
|
|
2144
|
+
provs: list[tuple[str, str]] = []
|
|
2145
|
+
if variant == "social":
|
|
2146
|
+
for p in _seq(providers, "ActionButton.providers", limit=12):
|
|
2147
|
+
pid, text = (p, f"Continue with {p.title()}") if isinstance(p, str) else p
|
|
2148
|
+
provs.append((_value(pid, "provider"), _text(text, "provider label")))
|
|
2149
|
+
if not provs:
|
|
2150
|
+
raise ValidationError("ActionButton(social): needs providers")
|
|
2151
|
+
_unique([p[0] for p in provs], "ActionButton.providers")
|
|
2152
|
+
elif providers:
|
|
2153
|
+
raise ValidationError("ActionButton: providers are for variant 'social'")
|
|
2154
|
+
super().__init__(
|
|
2155
|
+
gap="xs", visible=visible, classes=classes, styles=styles, aria_label=aria_label
|
|
2156
|
+
)
|
|
2157
|
+
self.variant = variant
|
|
2158
|
+
self.apply_theme = _flag(apply_theme, "ActionButton.apply_theme")
|
|
2159
|
+
self._scheme: str = scheme
|
|
2160
|
+
self._running = False
|
|
2161
|
+
self._progress = 0.0
|
|
2162
|
+
self._label = label
|
|
2163
|
+
self.button: Any = None
|
|
2164
|
+
self.bar: Progress | None = None
|
|
2165
|
+
self.provider_buttons: dict[str, Button] = {}
|
|
2166
|
+
with self:
|
|
2167
|
+
if variant == "color-scheme-toggle":
|
|
2168
|
+
self.button = ActionIcon(
|
|
2169
|
+
icon="sun" if scheme == "dark" else "moon",
|
|
2170
|
+
variant="default",
|
|
2171
|
+
size="lg",
|
|
2172
|
+
aria_label=label or "Toggle color scheme",
|
|
2173
|
+
on_click=self._toggle,
|
|
2174
|
+
)
|
|
2175
|
+
elif variant == "copy":
|
|
2176
|
+
self.button = CopyButton(
|
|
2177
|
+
value,
|
|
2178
|
+
label=label or "Copy",
|
|
2179
|
+
copied_label=copied_label,
|
|
2180
|
+
timeout=2000,
|
|
2181
|
+
on_copy=self._copied,
|
|
2182
|
+
)
|
|
2183
|
+
elif variant == "progress":
|
|
2184
|
+
with Box(w=260), Stack(gap=4):
|
|
2185
|
+
self.button = Button(label or "Start", on_click=self._click_run)
|
|
2186
|
+
self.bar = Progress(value=0, size="sm", visible=False)
|
|
2187
|
+
else:
|
|
2188
|
+
for pid, text in provs:
|
|
2189
|
+
self.provider_buttons[pid] = Button(
|
|
2190
|
+
text,
|
|
2191
|
+
variant="default",
|
|
2192
|
+
left_section=Avatar(text=pid[:1].upper(), size=18, radius="xl"),
|
|
2193
|
+
on_click=partial(_emit, self, "provider", ValueEvent, value=pid),
|
|
2194
|
+
)
|
|
2195
|
+
_hook(self, given)
|
|
2196
|
+
|
|
2197
|
+
# ---- color-scheme toggle
|
|
2198
|
+
@property
|
|
2199
|
+
def scheme(self) -> str:
|
|
2200
|
+
"""``"light"`` or ``"dark"`` (``color-scheme-toggle``)."""
|
|
2201
|
+
return self._scheme
|
|
2202
|
+
|
|
2203
|
+
@scheme.setter
|
|
2204
|
+
def scheme(self, v: Literal["light", "dark"]) -> None:
|
|
2205
|
+
if v not in ("light", "dark"):
|
|
2206
|
+
raise ValidationError("ActionButton.scheme: light or dark")
|
|
2207
|
+
self._scheme = v
|
|
2208
|
+
if self.variant == "color-scheme-toggle":
|
|
2209
|
+
self.button.update(icon="sun" if v == "dark" else "moon")
|
|
2210
|
+
|
|
2211
|
+
def _toggle(self, ev: Event) -> None:
|
|
2212
|
+
prev = self._scheme
|
|
2213
|
+
self.scheme = "dark" if prev == "light" else "light"
|
|
2214
|
+
w: Any = ev.window
|
|
2215
|
+
if self.apply_theme and w is not None and hasattr(w, "set_theme"):
|
|
2216
|
+
w.set_theme(color_scheme=self._scheme)
|
|
2217
|
+
_emit(self, "change", ChangeEvent, value=self._scheme, previous=prev)
|
|
2218
|
+
|
|
2219
|
+
# ---- copy
|
|
2220
|
+
@property
|
|
2221
|
+
def copy_value(self) -> str:
|
|
2222
|
+
"""The text the ``copy`` variant copies."""
|
|
2223
|
+
if self.variant != "copy":
|
|
2224
|
+
raise ValidationError("ActionButton.copy_value: variant 'copy' only")
|
|
2225
|
+
return cast("str", self.button.get_prop("value"))
|
|
2226
|
+
|
|
2227
|
+
@copy_value.setter
|
|
2228
|
+
def copy_value(self, text: str) -> None:
|
|
2229
|
+
if self.variant != "copy":
|
|
2230
|
+
raise ValidationError("ActionButton.copy_value: variant 'copy' only")
|
|
2231
|
+
self.button.update(value=_text(text, "copy_value", limit=10000, empty=True))
|
|
2232
|
+
|
|
2233
|
+
def _copied(self) -> None:
|
|
2234
|
+
_emit(self, "copy", ValueEvent, value=self.copy_value)
|
|
2235
|
+
|
|
2236
|
+
# ---- progress
|
|
2237
|
+
@property
|
|
2238
|
+
def running(self) -> bool:
|
|
2239
|
+
"""Whether a task is running (``progress`` variant)."""
|
|
2240
|
+
return self._running
|
|
2241
|
+
|
|
2242
|
+
@property
|
|
2243
|
+
def progress(self) -> float:
|
|
2244
|
+
"""0-100 progress of the running task."""
|
|
2245
|
+
return self._progress
|
|
2246
|
+
|
|
2247
|
+
def _click_run(self) -> None:
|
|
2248
|
+
if self._running:
|
|
2249
|
+
self._running = False
|
|
2250
|
+
self._paint_progress()
|
|
2251
|
+
_emit(self, "cancel", ValueEvent, value=None)
|
|
2252
|
+
else:
|
|
2253
|
+
self._running, self._progress = True, 0.0
|
|
2254
|
+
self._paint_progress()
|
|
2255
|
+
_emit(self, "run", ValueEvent, value=None)
|
|
2256
|
+
|
|
2257
|
+
def set_progress(self, percent: float) -> None:
|
|
2258
|
+
"""Report progress of the running task (0-100)."""
|
|
2259
|
+
if self.variant != "progress":
|
|
2260
|
+
raise ValidationError("ActionButton.set_progress: variant 'progress' only")
|
|
2261
|
+
if (
|
|
2262
|
+
isinstance(percent, bool)
|
|
2263
|
+
or not isinstance(percent, (int, float)) # pyright: ignore[reportUnnecessaryIsInstance]
|
|
2264
|
+
or not 0 <= percent <= 100
|
|
2265
|
+
):
|
|
2266
|
+
raise ValidationError("ActionButton.set_progress: a number from 0 to 100")
|
|
2267
|
+
if self._running:
|
|
2268
|
+
self._progress = float(percent)
|
|
2269
|
+
self._paint_progress()
|
|
2270
|
+
|
|
2271
|
+
def finish(self) -> None:
|
|
2272
|
+
"""The task is done: progress shows 100 and the button resets."""
|
|
2273
|
+
if self.variant != "progress":
|
|
2274
|
+
raise ValidationError("ActionButton.finish: variant 'progress' only")
|
|
2275
|
+
self._running, self._progress = False, 100.0
|
|
2276
|
+
self._paint_progress()
|
|
2277
|
+
|
|
2278
|
+
def _paint_progress(self) -> None:
|
|
2279
|
+
assert self.bar is not None
|
|
2280
|
+
self.bar.update(
|
|
2281
|
+
value=self._progress,
|
|
2282
|
+
visible=self._running or self._progress >= 100,
|
|
2283
|
+
animated=self._running,
|
|
2284
|
+
)
|
|
2285
|
+
self.button.update(
|
|
2286
|
+
label="Cancel" if self._running else (self._label or "Start"),
|
|
2287
|
+
variant="light" if self._running else "filled",
|
|
2288
|
+
color="red" if self._running else UNSET,
|
|
2289
|
+
)
|
|
2290
|
+
|
|
2291
|
+
|
|
2292
|
+
# ================================================================= SplitButton
|
|
2293
|
+
@dataclass(frozen=True)
|
|
2294
|
+
class ActionSpec:
|
|
2295
|
+
"""One alternative action of a ``SplitButton``."""
|
|
2296
|
+
|
|
2297
|
+
value: str
|
|
2298
|
+
label: str
|
|
2299
|
+
icon: str | None = None
|
|
2300
|
+
disabled: bool = False
|
|
2301
|
+
danger: bool = False
|
|
2302
|
+
|
|
2303
|
+
def __post_init__(self) -> None:
|
|
2304
|
+
w = f"ActionSpec({self.value!r})"
|
|
2305
|
+
_value(self.value, w)
|
|
2306
|
+
_text(self.label, f"{w}.label")
|
|
2307
|
+
_icon(self.icon, f"{w}.icon")
|
|
2308
|
+
_flag(self.disabled, f"{w}.disabled")
|
|
2309
|
+
_flag(self.danger, f"{w}.danger")
|
|
2310
|
+
|
|
2311
|
+
|
|
2312
|
+
class SplitButton(_Local, Group):
|
|
2313
|
+
"""Primary button joined to a dropdown of alternative actions.
|
|
2314
|
+
|
|
2315
|
+
``variant="split"``: the main button raises ``click`` (``ValueEvent`` with the
|
|
2316
|
+
``default`` action value, or None) and a chevron button opens the menu;
|
|
2317
|
+
``variant="menu"``: one button opens the menu. Choosing an entry raises
|
|
2318
|
+
``select`` (``ValueEvent``)::
|
|
2319
|
+
|
|
2320
|
+
ui.blocks.SplitButton("Send", [ui.blocks.ActionSpec("later", "Send later")],
|
|
2321
|
+
on_select=lambda e: print(e.value))
|
|
2322
|
+
"""
|
|
2323
|
+
|
|
2324
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
2325
|
+
"click": EventSpec("click", "ValueEvent"),
|
|
2326
|
+
"select": EventSpec("select", "ValueEvent"),
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
def __init__(
|
|
2330
|
+
self,
|
|
2331
|
+
label: str,
|
|
2332
|
+
actions: Iterable[ActionSpec | Mapping[str, Any]],
|
|
2333
|
+
*,
|
|
2334
|
+
variant: Literal["split", "menu"] = "split",
|
|
2335
|
+
default: str | None = None,
|
|
2336
|
+
color: str | Unset = UNSET,
|
|
2337
|
+
on_click: Handler[ValueEvent] | None = None,
|
|
2338
|
+
on_select: Handler[ValueEvent] | None = None,
|
|
2339
|
+
visible: bool | Unset = UNSET,
|
|
2340
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
2341
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
2342
|
+
aria_label: str | Unset = UNSET,
|
|
2343
|
+
) -> None:
|
|
2344
|
+
if variant not in ("split", "menu"):
|
|
2345
|
+
raise ValidationError("SplitButton: variant must be 'split' or 'menu'")
|
|
2346
|
+
_text(label, "SplitButton.label", limit=80)
|
|
2347
|
+
acts = [
|
|
2348
|
+
_coerce(ActionSpec, a, "SplitButton.actions")
|
|
2349
|
+
for a in _seq(actions, "SplitButton.actions", limit=50)
|
|
2350
|
+
]
|
|
2351
|
+
if not acts:
|
|
2352
|
+
raise ValidationError("SplitButton: at least one action")
|
|
2353
|
+
_unique([a.value for a in acts], "SplitButton.actions")
|
|
2354
|
+
if default is not None and default not in {a.value for a in acts}:
|
|
2355
|
+
raise ValidationError("SplitButton.default: not one of the actions")
|
|
2356
|
+
if on_click is not None and variant != "split":
|
|
2357
|
+
raise ValidationError("SplitButton: on_click needs variant='split'")
|
|
2358
|
+
if default is not None and variant != "split":
|
|
2359
|
+
raise ValidationError("SplitButton: default is for variant 'split'")
|
|
2360
|
+
super().__init__(
|
|
2361
|
+
gap=0,
|
|
2362
|
+
wrap="nowrap",
|
|
2363
|
+
visible=visible,
|
|
2364
|
+
classes=classes,
|
|
2365
|
+
styles=styles,
|
|
2366
|
+
aria_label=aria_label,
|
|
2367
|
+
)
|
|
2368
|
+
self.variant = variant
|
|
2369
|
+
self.default = default
|
|
2370
|
+
self.actions = {a.value: a for a in acts}
|
|
2371
|
+
self.main: Button | None = None
|
|
2372
|
+
with self:
|
|
2373
|
+
if variant == "split":
|
|
2374
|
+
with ButtonGroup():
|
|
2375
|
+
self.main = Button(label, color=color, on_click=self._clicked)
|
|
2376
|
+
self.toggle: Any = ActionIcon(
|
|
2377
|
+
icon="chevron-down",
|
|
2378
|
+
variant="filled",
|
|
2379
|
+
color=color,
|
|
2380
|
+
size=36,
|
|
2381
|
+
aria_label="More actions",
|
|
2382
|
+
)
|
|
2383
|
+
self._menu(acts)
|
|
2384
|
+
else:
|
|
2385
|
+
self.toggle = Button(
|
|
2386
|
+
label, color=color, right_section=_Icon("chevron-down", size=14)
|
|
2387
|
+
)
|
|
2388
|
+
self._menu(acts)
|
|
2389
|
+
_hook(self, {"click": on_click, "select": on_select})
|
|
2390
|
+
|
|
2391
|
+
def _menu(self, acts: list[ActionSpec]) -> None:
|
|
2392
|
+
with Menu(target=self.toggle, position="bottom-end", width=220) as menu:
|
|
2393
|
+
for a in acts:
|
|
2394
|
+
MenuItem(
|
|
2395
|
+
label=a.label,
|
|
2396
|
+
disabled=a.disabled,
|
|
2397
|
+
color="red" if a.danger else UNSET,
|
|
2398
|
+
left_section=_Icon(a.icon, size=14) if a.icon else None,
|
|
2399
|
+
on_click=partial(_emit, self, "select", ValueEvent, value=a.value),
|
|
2400
|
+
)
|
|
2401
|
+
self.menu = menu
|
|
2402
|
+
|
|
2403
|
+
def _clicked(self) -> None:
|
|
2404
|
+
_emit(self, "click", ValueEvent, value=self.default)
|
|
2405
|
+
|
|
2406
|
+
|
|
2407
|
+
# ===================================================================== Header
|
|
2408
|
+
@dataclass(frozen=True)
|
|
2409
|
+
class HeaderLink:
|
|
2410
|
+
"""A header link. ``children`` turn it into a dropdown (``menu`` variant: plain
|
|
2411
|
+
items; ``mega-menu``: cards with ``icon`` and ``description``)."""
|
|
2412
|
+
|
|
2413
|
+
value: str
|
|
2414
|
+
label: str
|
|
2415
|
+
children: Sequence[HeaderLink | Mapping[str, Any]] = ()
|
|
2416
|
+
description: str | None = None
|
|
2417
|
+
icon: str | None = None
|
|
2418
|
+
|
|
2419
|
+
def __post_init__(self) -> None:
|
|
2420
|
+
w = f"HeaderLink({self.value!r})"
|
|
2421
|
+
_value(self.value, w)
|
|
2422
|
+
_text(self.label, f"{w}.label")
|
|
2423
|
+
_opt_text(self.description, f"{w}.description")
|
|
2424
|
+
_icon(self.icon, f"{w}.icon")
|
|
2425
|
+
kids = tuple(_coerce(HeaderLink, c, w) for c in _seq(self.children, w, limit=30))
|
|
2426
|
+
if any(k.children for k in kids):
|
|
2427
|
+
raise ValidationError(f"{w}: dropdowns nest one level only")
|
|
2428
|
+
object.__setattr__(self, "children", kids)
|
|
2429
|
+
|
|
2430
|
+
|
|
2431
|
+
_HEADER_VARIANTS = ("simple", "double", "menu", "mega-menu", "search", "tabs")
|
|
2432
|
+
|
|
2433
|
+
|
|
2434
|
+
class Header(_Local, Paper):
|
|
2435
|
+
"""Application header: brand, links, dropdowns, search or tabs, with a
|
|
2436
|
+
burger-opened drawer below ``collapse_below``.
|
|
2437
|
+
|
|
2438
|
+
``variant``: ``simple`` (brand + links), ``double`` (``secondary_links`` row
|
|
2439
|
+
above the main links), ``menu`` (links with ``children`` open a dropdown),
|
|
2440
|
+
``mega-menu`` (hover card of linked cards, ``actions`` as call-to-action
|
|
2441
|
+
buttons), ``search`` (links plus a search field with ``search_options``),
|
|
2442
|
+
``tabs`` (tab row under the brand row, optional ``user`` menu). Activating
|
|
2443
|
+
a link/tab/action raises ``link`` (``LinkEvent``) and, for plain links and
|
|
2444
|
+
tabs, sets ``active``; Enter in the search field raises ``search``
|
|
2445
|
+
(``SearchEvent``)::
|
|
2446
|
+
|
|
2447
|
+
hd = ui.blocks.Header("Acme", [ui.blocks.HeaderLink("home", "Home")], active="home",
|
|
2448
|
+
on_link=lambda e: show(e.value))
|
|
2449
|
+
"""
|
|
2450
|
+
|
|
2451
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
2452
|
+
"link": EventSpec("link", "LinkEvent"),
|
|
2453
|
+
"search": EventSpec("search", "SearchEvent"),
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
def __init__(
|
|
2457
|
+
self,
|
|
2458
|
+
brand: str,
|
|
2459
|
+
links: Iterable[HeaderLink | Mapping[str, Any]] = (),
|
|
2460
|
+
*,
|
|
2461
|
+
variant: str = "simple",
|
|
2462
|
+
active: str | None = None,
|
|
2463
|
+
secondary_links: Iterable[HeaderLink | Mapping[str, Any]] = (),
|
|
2464
|
+
actions: Iterable[HeaderLink | Mapping[str, Any]] = (),
|
|
2465
|
+
search_options: Iterable[str] = (),
|
|
2466
|
+
search_placeholder: str = "Search",
|
|
2467
|
+
user: Mapping[str, Any] | None = None,
|
|
2468
|
+
collapse_below: str = "sm",
|
|
2469
|
+
on_link: Handler[LinkEvent] | None = None,
|
|
2470
|
+
on_search: Handler[SearchEvent] | None = None,
|
|
2471
|
+
visible: bool | Unset = UNSET,
|
|
2472
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
2473
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
2474
|
+
aria_label: str | Unset = "Header",
|
|
2475
|
+
) -> None:
|
|
2476
|
+
if variant not in _HEADER_VARIANTS:
|
|
2477
|
+
raise ValidationError(f"Header: variant must be one of {list(_HEADER_VARIANTS)}")
|
|
2478
|
+
_text(brand, "Header.brand", limit=80)
|
|
2479
|
+
bp = _bp(collapse_below, "Header.collapse_below")
|
|
2480
|
+
main = [
|
|
2481
|
+
_coerce(HeaderLink, x, "Header.links") for x in _seq(links, "Header.links", limit=30)
|
|
2482
|
+
]
|
|
2483
|
+
second = [
|
|
2484
|
+
_coerce(HeaderLink, x, "Header.secondary_links")
|
|
2485
|
+
for x in _seq(secondary_links, "Header.secondary_links", limit=30)
|
|
2486
|
+
]
|
|
2487
|
+
acts = [
|
|
2488
|
+
_coerce(HeaderLink, x, "Header.actions")
|
|
2489
|
+
for x in _seq(actions, "Header.actions", limit=6)
|
|
2490
|
+
]
|
|
2491
|
+
opts = [
|
|
2492
|
+
_text(o, "Header.search_options", limit=80)
|
|
2493
|
+
for o in _seq(search_options, "Header.search_options", limit=200)
|
|
2494
|
+
]
|
|
2495
|
+
_text(search_placeholder, "Header.search_placeholder", limit=80)
|
|
2496
|
+
if not main:
|
|
2497
|
+
raise ValidationError("Header: needs links")
|
|
2498
|
+
if variant == "double" and not second:
|
|
2499
|
+
raise ValidationError("Header(double): needs secondary_links")
|
|
2500
|
+
if second and variant != "double":
|
|
2501
|
+
raise ValidationError("Header: secondary_links are for variant 'double'")
|
|
2502
|
+
if opts and variant != "search":
|
|
2503
|
+
raise ValidationError("Header: search_options are for variant 'search'")
|
|
2504
|
+
if acts and variant != "mega-menu":
|
|
2505
|
+
raise ValidationError("Header: actions are for variant 'mega-menu'")
|
|
2506
|
+
if variant in ("menu", "mega-menu") and not any(m.children for m in main):
|
|
2507
|
+
raise ValidationError(f"Header({variant}): at least one link needs children")
|
|
2508
|
+
if variant not in ("menu", "mega-menu") and any(m.children for m in main):
|
|
2509
|
+
raise ValidationError("Header: children are for variants menu/mega-menu")
|
|
2510
|
+
if user is not None and variant not in ("tabs", "simple", "double", "menu", "search"):
|
|
2511
|
+
raise ValidationError("Header: user is not available for this variant")
|
|
2512
|
+
if on_search is not None and variant != "search":
|
|
2513
|
+
raise ValidationError("Header: on_search is for variant 'search'")
|
|
2514
|
+
everything = [*main, *second, *acts]
|
|
2515
|
+
labels: dict[str, str] = {}
|
|
2516
|
+
for x in everything:
|
|
2517
|
+
labels[x.value] = x.label
|
|
2518
|
+
for c in cast("Sequence[HeaderLink]", x.children):
|
|
2519
|
+
labels[c.value] = c.label
|
|
2520
|
+
names = [x.value for x in everything] + [
|
|
2521
|
+
c.value for x in everything for c in cast("Sequence[HeaderLink]", x.children)
|
|
2522
|
+
]
|
|
2523
|
+
_unique(names, "Header")
|
|
2524
|
+
dest = {x.value for x in everything if not x.children} | {
|
|
2525
|
+
c.value for x in everything for c in cast("Sequence[HeaderLink]", x.children)
|
|
2526
|
+
}
|
|
2527
|
+
if active is not None and active not in dest:
|
|
2528
|
+
raise ValidationError("Header.active: not a link of the header")
|
|
2529
|
+
super().__init__(
|
|
2530
|
+
with_border=True,
|
|
2531
|
+
p="sm",
|
|
2532
|
+
radius="md",
|
|
2533
|
+
component="header",
|
|
2534
|
+
visible=visible,
|
|
2535
|
+
classes=classes,
|
|
2536
|
+
styles=styles,
|
|
2537
|
+
aria_label=aria_label,
|
|
2538
|
+
)
|
|
2539
|
+
self.variant = variant
|
|
2540
|
+
self.brand = brand
|
|
2541
|
+
self._active = active
|
|
2542
|
+
self._labels = labels
|
|
2543
|
+
self._anchors: dict[str, Anchor] = {}
|
|
2544
|
+
self._bp: Breakpoint = bp
|
|
2545
|
+
self.tabs: Tabs | None = None
|
|
2546
|
+
self.search_input: Autocomplete | None = None
|
|
2547
|
+
self.user_menu: UserMenu | None = None
|
|
2548
|
+
self.burger: Burger | None = None
|
|
2549
|
+
self.drawer: Drawer | None = None
|
|
2550
|
+
self._search_options = set(opts)
|
|
2551
|
+
with self:
|
|
2552
|
+
if variant == "tabs":
|
|
2553
|
+
with Stack(gap="xs"):
|
|
2554
|
+
with Group(justify="space-between", wrap="nowrap"):
|
|
2555
|
+
Text(brand, fw=700, size="lg")
|
|
2556
|
+
self._tail(user)
|
|
2557
|
+
self.tabs = self._tab_row(main)
|
|
2558
|
+
elif variant == "double":
|
|
2559
|
+
with Stack(gap="xs"):
|
|
2560
|
+
with Group(justify="space-between", wrap="nowrap"):
|
|
2561
|
+
Text(brand, fw=700, size="lg")
|
|
2562
|
+
self._links_row(second)
|
|
2563
|
+
self._tail(user)
|
|
2564
|
+
self._burger([*main, *second], acts)
|
|
2565
|
+
with Group(visible_from=bp):
|
|
2566
|
+
self._links_row(main)
|
|
2567
|
+
else:
|
|
2568
|
+
with Group(justify="space-between", wrap="nowrap"):
|
|
2569
|
+
Text(brand, fw=700, size="lg")
|
|
2570
|
+
self._links_row(main, mega=variant == "mega-menu", acts=acts)
|
|
2571
|
+
if variant == "mega-menu":
|
|
2572
|
+
with Group(gap="xs", visible_from=bp):
|
|
2573
|
+
for i, a in enumerate(acts):
|
|
2574
|
+
Button(
|
|
2575
|
+
a.label,
|
|
2576
|
+
variant="default" if i == 0 else "filled",
|
|
2577
|
+
on_click=partial(self._go, a.value),
|
|
2578
|
+
)
|
|
2579
|
+
if variant == "search":
|
|
2580
|
+
self.search_input = Autocomplete(
|
|
2581
|
+
placeholder=search_placeholder,
|
|
2582
|
+
data=list(opts),
|
|
2583
|
+
left_section=_Icon("search", size=14),
|
|
2584
|
+
visible_from="xs",
|
|
2585
|
+
aria_label=search_placeholder,
|
|
2586
|
+
on_change=self._search_changed,
|
|
2587
|
+
on_enter=self._search_enter,
|
|
2588
|
+
)
|
|
2589
|
+
self._tail(user)
|
|
2590
|
+
self._burger(main, acts)
|
|
2591
|
+
_hook(self, {"link": on_link, "search": on_search})
|
|
2592
|
+
self._paint()
|
|
2593
|
+
|
|
2594
|
+
# ----------------------------------------------------------- pieces
|
|
2595
|
+
def _links_row(
|
|
2596
|
+
self, links: Sequence[HeaderLink], *, mega: bool = False, acts: Sequence[HeaderLink] = ()
|
|
2597
|
+
) -> None:
|
|
2598
|
+
with Group(gap="md", wrap="nowrap", visible_from=self._bp):
|
|
2599
|
+
for ln in links:
|
|
2600
|
+
if not ln.children:
|
|
2601
|
+
self._anchors[ln.value] = Anchor(
|
|
2602
|
+
ln.label, underline="hover", on_click=partial(self._go, ln.value)
|
|
2603
|
+
)
|
|
2604
|
+
elif mega:
|
|
2605
|
+
self._mega(ln, acts)
|
|
2606
|
+
else:
|
|
2607
|
+
self._dropdown(ln)
|
|
2608
|
+
|
|
2609
|
+
@staticmethod
|
|
2610
|
+
def _drop_label(link: HeaderLink) -> UnstyledButton:
|
|
2611
|
+
with UnstyledButton(aria_label=link.label) as b, Group(gap=4, wrap="nowrap"):
|
|
2612
|
+
Text(link.label, size="sm", fw=500)
|
|
2613
|
+
_Icon("chevron-down", size=14)
|
|
2614
|
+
return cast("UnstyledButton", b)
|
|
2615
|
+
|
|
2616
|
+
def _dropdown(self, ln: HeaderLink) -> None:
|
|
2617
|
+
with Menu(target=self._drop_label(ln), position="bottom-start", trigger="hover"):
|
|
2618
|
+
for c in cast("Sequence[HeaderLink]", ln.children):
|
|
2619
|
+
MenuItem(label=c.label, on_click=partial(self._go, c.value))
|
|
2620
|
+
|
|
2621
|
+
def _mega(self, ln: HeaderLink, acts: Sequence[HeaderLink]) -> None:
|
|
2622
|
+
with HoverCard(target=self._drop_label(ln), position="bottom", width=480, with_arrow=True):
|
|
2623
|
+
with Stack(gap="sm"):
|
|
2624
|
+
Text(ln.label, fw=600)
|
|
2625
|
+
with SimpleGrid(cols=2, spacing="xs"):
|
|
2626
|
+
for c in cast("Sequence[HeaderLink]", ln.children):
|
|
2627
|
+
with (
|
|
2628
|
+
UnstyledButton(aria_label=c.label, on_click=partial(self._go, c.value)),
|
|
2629
|
+
Group(wrap="nowrap", align="flex-start", gap="sm"),
|
|
2630
|
+
):
|
|
2631
|
+
if c.icon:
|
|
2632
|
+
with ThemeIcon(variant="light", size=34, radius="md"):
|
|
2633
|
+
_Icon(c.icon, size=18)
|
|
2634
|
+
with Stack(gap=0):
|
|
2635
|
+
Text(c.label, size="sm", fw=500)
|
|
2636
|
+
if c.description:
|
|
2637
|
+
Text(c.description, size="xs", dimmed=True)
|
|
2638
|
+
if acts:
|
|
2639
|
+
Divider()
|
|
2640
|
+
with Group(justify="space-between"):
|
|
2641
|
+
for a in acts:
|
|
2642
|
+
Button(a.label, variant="default", on_click=partial(self._go, a.value))
|
|
2643
|
+
|
|
2644
|
+
def _burger(self, links: Sequence[HeaderLink], acts: Sequence[HeaderLink]) -> None:
|
|
2645
|
+
self.burger = Burger(
|
|
2646
|
+
opened=False,
|
|
2647
|
+
hidden_from=self._bp,
|
|
2648
|
+
aria_label="Toggle navigation",
|
|
2649
|
+
on_click=self._toggle_drawer,
|
|
2650
|
+
)
|
|
2651
|
+
with (
|
|
2652
|
+
Drawer(
|
|
2653
|
+
opened=False,
|
|
2654
|
+
title=self.brand,
|
|
2655
|
+
position="right",
|
|
2656
|
+
size="xs",
|
|
2657
|
+
on_close=self._drawer_closed,
|
|
2658
|
+
) as dr,
|
|
2659
|
+
Stack(gap="xs"),
|
|
2660
|
+
):
|
|
2661
|
+
for ln in links:
|
|
2662
|
+
if ln.children:
|
|
2663
|
+
Text(ln.label, size="xs", dimmed=True, fw=600)
|
|
2664
|
+
for c in cast("Sequence[HeaderLink]", ln.children):
|
|
2665
|
+
Anchor(c.label, on_click=partial(self._go, c.value, close=True))
|
|
2666
|
+
else:
|
|
2667
|
+
Anchor(ln.label, on_click=partial(self._go, ln.value, close=True))
|
|
2668
|
+
for a in acts:
|
|
2669
|
+
Button(a.label, variant="default", on_click=partial(self._go, a.value, close=True))
|
|
2670
|
+
self.drawer = cast("Drawer", dr)
|
|
2671
|
+
|
|
2672
|
+
def _tab_row(self, main: Sequence[HeaderLink]) -> Tabs:
|
|
2673
|
+
with Tabs(value=self._active or main[0].value, on_change=self._tab_changed) as tabs:
|
|
2674
|
+
with TabsList():
|
|
2675
|
+
for ln in main:
|
|
2676
|
+
TabsTab(value=ln.value, label=ln.label)
|
|
2677
|
+
return cast("Tabs", tabs)
|
|
2678
|
+
|
|
2679
|
+
def _tail(self, user: Mapping[str, Any] | None) -> None:
|
|
2680
|
+
if user is not None:
|
|
2681
|
+
self.user_menu = UserMenu(**dict(user))
|
|
2682
|
+
|
|
2683
|
+
# --------------------------------------------------------- behaviour
|
|
2684
|
+
@property
|
|
2685
|
+
def active(self) -> str | None:
|
|
2686
|
+
"""The active link value (highlighted; set by clicks or from Python)."""
|
|
2687
|
+
return self._active
|
|
2688
|
+
|
|
2689
|
+
@active.setter
|
|
2690
|
+
def active(self, value: str | None) -> None:
|
|
2691
|
+
if (
|
|
2692
|
+
value is not None
|
|
2693
|
+
and value not in self._anchors
|
|
2694
|
+
and (self.tabs is None or value not in self._labels)
|
|
2695
|
+
):
|
|
2696
|
+
raise ValidationError("Header.active: not a link of the header")
|
|
2697
|
+
self._active = value
|
|
2698
|
+
self._paint()
|
|
2699
|
+
|
|
2700
|
+
@property
|
|
2701
|
+
def menu_opened(self) -> bool:
|
|
2702
|
+
"""Whether the small-screen drawer is open."""
|
|
2703
|
+
return bool(self.drawer is not None and self.drawer.opened is True)
|
|
2704
|
+
|
|
2705
|
+
@menu_opened.setter
|
|
2706
|
+
def menu_opened(self, on: bool) -> None:
|
|
2707
|
+
if self.drawer is None or self.burger is None:
|
|
2708
|
+
raise ValidationError("Header: this variant has no drawer")
|
|
2709
|
+
self.drawer.update(opened=bool(on))
|
|
2710
|
+
self.burger.update(opened=bool(on))
|
|
2711
|
+
|
|
2712
|
+
def _toggle_drawer(self) -> None:
|
|
2713
|
+
self.menu_opened = not self.menu_opened
|
|
2714
|
+
|
|
2715
|
+
def _drawer_closed(self) -> None:
|
|
2716
|
+
self.menu_opened = False
|
|
2717
|
+
|
|
2718
|
+
def _paint(self) -> None:
|
|
2719
|
+
for v, a in self._anchors.items():
|
|
2720
|
+
on = v == self._active
|
|
2721
|
+
a.update(c="blue" if on else UNSET, underline="always" if on else "hover")
|
|
2722
|
+
if self.tabs is not None and self._active is not None:
|
|
2723
|
+
self.tabs.update(value=self._active)
|
|
2724
|
+
|
|
2725
|
+
def _go(self, value: str, *, close: bool = False) -> None:
|
|
2726
|
+
if close and self.drawer is not None:
|
|
2727
|
+
self.menu_opened = False
|
|
2728
|
+
if value in self._anchors:
|
|
2729
|
+
self._active = value
|
|
2730
|
+
self._paint()
|
|
2731
|
+
_emit(self, "link", LinkEvent, value=value, label=self._labels.get(value, ""))
|
|
2732
|
+
|
|
2733
|
+
def _tab_changed(self, ev: Any) -> None:
|
|
2734
|
+
v = ev.value
|
|
2735
|
+
if isinstance(v, str) and v in self._labels and v != self._active:
|
|
2736
|
+
self._active = v
|
|
2737
|
+
_emit(self, "link", LinkEvent, value=v, label=self._labels[v])
|
|
2738
|
+
|
|
2739
|
+
def _search_changed(self, ev: Any) -> None:
|
|
2740
|
+
v = ev.value
|
|
2741
|
+
if isinstance(v, str) and v in self._search_options:
|
|
2742
|
+
_emit(self, "search", SearchEvent, query=v, selected=True)
|
|
2743
|
+
|
|
2744
|
+
def _search_enter(self) -> None:
|
|
2745
|
+
v = self.search_input.value if self.search_input is not None else ""
|
|
2746
|
+
_emit(self, "search", SearchEvent, query=v if isinstance(v, str) else "", selected=False)
|
|
2747
|
+
|
|
2748
|
+
|
|
2749
|
+
# ===================================================================== Footer
|
|
2750
|
+
@dataclass(frozen=True)
|
|
2751
|
+
class FooterLink:
|
|
2752
|
+
"""A footer link or social action (``icon`` required for socials)."""
|
|
2753
|
+
|
|
2754
|
+
value: str
|
|
2755
|
+
label: str
|
|
2756
|
+
icon: str | None = None
|
|
2757
|
+
|
|
2758
|
+
def __post_init__(self) -> None:
|
|
2759
|
+
_value(self.value, f"FooterLink({self.value!r})")
|
|
2760
|
+
_text(self.label, "FooterLink.label")
|
|
2761
|
+
_icon(self.icon, "FooterLink.icon")
|
|
2762
|
+
|
|
2763
|
+
|
|
2764
|
+
@dataclass(frozen=True)
|
|
2765
|
+
class FooterGroup:
|
|
2766
|
+
"""A titled column of footer links."""
|
|
2767
|
+
|
|
2768
|
+
title: str
|
|
2769
|
+
links: Sequence[FooterLink | Mapping[str, Any]] = ()
|
|
2770
|
+
|
|
2771
|
+
def __post_init__(self) -> None:
|
|
2772
|
+
_text(self.title, "FooterGroup.title", limit=80)
|
|
2773
|
+
object.__setattr__(
|
|
2774
|
+
self,
|
|
2775
|
+
"links",
|
|
2776
|
+
tuple(
|
|
2777
|
+
_coerce(FooterLink, x, "FooterGroup.links")
|
|
2778
|
+
for x in _seq(self.links, "FooterGroup.links", limit=30)
|
|
2779
|
+
),
|
|
2780
|
+
)
|
|
2781
|
+
|
|
2782
|
+
|
|
2783
|
+
_FOOTER_VARIANTS = ("centered", "links", "simple", "social")
|
|
2784
|
+
|
|
2785
|
+
|
|
2786
|
+
class Footer(_Local, Paper):
|
|
2787
|
+
"""Application footer. ``variant``: ``centered`` (brand, link row, socials),
|
|
2788
|
+
``links`` (brand + description beside titled ``groups``), ``simple`` (brand and
|
|
2789
|
+
inline links), ``social`` (brand, social icon actions and a ``subscribe``
|
|
2790
|
+
e-mail field). Raises ``link`` / ``social`` (``LinkEvent``) and ``subscribe``
|
|
2791
|
+
(``SubscribeEvent``, only for a syntactically valid e-mail; an invalid one
|
|
2792
|
+
shows an error and raises nothing)."""
|
|
2793
|
+
|
|
2794
|
+
EVENTS: ClassVar[Mapping[str, EventSpec]] = {
|
|
2795
|
+
"link": EventSpec("link", "LinkEvent"),
|
|
2796
|
+
"social": EventSpec("social", "LinkEvent"),
|
|
2797
|
+
"subscribe": EventSpec("subscribe", "SubscribeEvent"),
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
def __init__(
|
|
2801
|
+
self,
|
|
2802
|
+
brand: str,
|
|
2803
|
+
*,
|
|
2804
|
+
variant: str = "simple",
|
|
2805
|
+
description: str | None = None,
|
|
2806
|
+
links: Iterable[FooterLink | Mapping[str, Any]] = (),
|
|
2807
|
+
groups: Iterable[FooterGroup | Mapping[str, Any]] = (),
|
|
2808
|
+
socials: Iterable[FooterLink | Mapping[str, Any]] = (),
|
|
2809
|
+
subscribe: bool = False,
|
|
2810
|
+
subscribe_label: str = "Subscribe",
|
|
2811
|
+
copyright: str | None = None,
|
|
2812
|
+
on_link: Handler[LinkEvent] | None = None,
|
|
2813
|
+
on_social: Handler[LinkEvent] | None = None,
|
|
2814
|
+
on_subscribe: Handler[SubscribeEvent] | None = None,
|
|
2815
|
+
visible: bool | Unset = UNSET,
|
|
2816
|
+
classes: str | Sequence[str] | Unset = UNSET,
|
|
2817
|
+
styles: Mapping[str, str | int | float] | Unset = UNSET,
|
|
2818
|
+
aria_label: str | Unset = "Footer",
|
|
2819
|
+
) -> None:
|
|
2820
|
+
if variant not in _FOOTER_VARIANTS:
|
|
2821
|
+
raise ValidationError(f"Footer: variant must be one of {list(_FOOTER_VARIANTS)}")
|
|
2822
|
+
_text(brand, "Footer.brand", limit=80)
|
|
2823
|
+
_opt_text(description, "Footer.description")
|
|
2824
|
+
_opt_text(copyright, "Footer.copyright")
|
|
2825
|
+
_text(subscribe_label, "Footer.subscribe_label", limit=40)
|
|
2826
|
+
ls = [_coerce(FooterLink, x, "Footer.links") for x in _seq(links, "Footer.links", limit=30)]
|
|
2827
|
+
gs = [
|
|
2828
|
+
_coerce(FooterGroup, x, "Footer.groups") for x in _seq(groups, "Footer.groups", limit=8)
|
|
2829
|
+
]
|
|
2830
|
+
ss = [
|
|
2831
|
+
_coerce(FooterLink, x, "Footer.socials")
|
|
2832
|
+
for x in _seq(socials, "Footer.socials", limit=10)
|
|
2833
|
+
]
|
|
2834
|
+
if any(s.icon is None for s in ss):
|
|
2835
|
+
raise ValidationError("Footer.socials: every social needs an icon")
|
|
2836
|
+
if gs and variant != "links":
|
|
2837
|
+
raise ValidationError("Footer: groups are for variant 'links'")
|
|
2838
|
+
if variant == "links" and not gs:
|
|
2839
|
+
raise ValidationError("Footer(links): needs groups")
|
|
2840
|
+
if variant in ("centered", "simple") and not ls:
|
|
2841
|
+
raise ValidationError(f"Footer({variant}): needs links")
|
|
2842
|
+
if ls and variant in ("links", "social"):
|
|
2843
|
+
raise ValidationError(f"Footer({variant}): links are for centered/simple")
|
|
2844
|
+
if ss and variant not in ("centered", "social"):
|
|
2845
|
+
raise ValidationError("Footer: socials are for variants centered/social")
|
|
2846
|
+
if variant == "social" and not ss:
|
|
2847
|
+
raise ValidationError("Footer(social): needs socials")
|
|
2848
|
+
if _flag(subscribe, "Footer.subscribe") and variant != "social":
|
|
2849
|
+
raise ValidationError("Footer: subscribe is for variant 'social'")
|
|
2850
|
+
if on_social is not None and not ss:
|
|
2851
|
+
raise ValidationError("Footer: on_social needs socials")
|
|
2852
|
+
if on_subscribe is not None and not subscribe:
|
|
2853
|
+
raise ValidationError("Footer: on_subscribe needs subscribe=True")
|
|
2854
|
+
flat_groups = [x for g in gs for x in cast("Sequence[FooterLink]", g.links)]
|
|
2855
|
+
_unique(
|
|
2856
|
+
[x.value for x in ls] + [x.value for x in flat_groups] + [s.value for s in ss], "Footer"
|
|
2857
|
+
)
|
|
2858
|
+
super().__init__(
|
|
2859
|
+
with_border=True,
|
|
2860
|
+
p="md",
|
|
2861
|
+
radius="md",
|
|
2862
|
+
component="footer",
|
|
2863
|
+
visible=visible,
|
|
2864
|
+
classes=classes,
|
|
2865
|
+
styles=styles,
|
|
2866
|
+
aria_label=aria_label,
|
|
2867
|
+
)
|
|
2868
|
+
self.variant = variant
|
|
2869
|
+
self._labels = {x.value: x.label for x in [*ls, *flat_groups, *ss]}
|
|
2870
|
+
self.email: TextInput | None = None
|
|
2871
|
+
self.subscribe_button: Button | None = None
|
|
2872
|
+
with self:
|
|
2873
|
+
getattr(self, "_build_" + variant)(
|
|
2874
|
+
brand, description, ls, gs, ss, subscribe, subscribe_label, copyright
|
|
2875
|
+
)
|
|
2876
|
+
_hook(self, {"link": on_link, "social": on_social, "subscribe": on_subscribe})
|
|
2877
|
+
|
|
2878
|
+
def _links(self, ls: Sequence[FooterLink]) -> None:
|
|
2879
|
+
for x in ls:
|
|
2880
|
+
Anchor(
|
|
2881
|
+
x.label,
|
|
2882
|
+
size="sm",
|
|
2883
|
+
c="dimmed",
|
|
2884
|
+
on_click=partial(self._emit_link, x.value, "link"),
|
|
2885
|
+
)
|
|
2886
|
+
|
|
2887
|
+
def _socials(self, ss: Sequence[FooterLink]) -> None:
|
|
2888
|
+
with Group(gap="xs", wrap="nowrap"):
|
|
2889
|
+
for s in ss:
|
|
2890
|
+
ActionIcon(
|
|
2891
|
+
icon=cast("Any", s.icon),
|
|
2892
|
+
variant="default",
|
|
2893
|
+
size="lg",
|
|
2894
|
+
aria_label=s.label,
|
|
2895
|
+
on_click=partial(self._emit_link, s.value, "social"),
|
|
2896
|
+
)
|
|
2897
|
+
|
|
2898
|
+
def _build_centered(
|
|
2899
|
+
self, brand: str, desc: Any, ls: Any, gs: Any, ss: Any, sub: Any, sl: Any, copy: Any
|
|
2900
|
+
) -> None:
|
|
2901
|
+
with Stack(align="center", gap="sm"):
|
|
2902
|
+
Text(brand, fw=700, size="lg")
|
|
2903
|
+
with Group(gap="md", justify="center"):
|
|
2904
|
+
self._links(ls)
|
|
2905
|
+
if ss:
|
|
2906
|
+
self._socials(ss)
|
|
2907
|
+
if copy:
|
|
2908
|
+
Text(copy, size="xs", dimmed=True)
|
|
2909
|
+
|
|
2910
|
+
def _build_links(
|
|
2911
|
+
self, brand: str, desc: Any, ls: Any, gs: Any, ss: Any, sub: Any, sl: Any, copy: Any
|
|
2912
|
+
) -> None:
|
|
2913
|
+
with Group(justify="space-between", align="flex-start", wrap="wrap"):
|
|
2914
|
+
with Stack(gap=4):
|
|
2915
|
+
Text(brand, fw=700, size="lg")
|
|
2916
|
+
if desc:
|
|
2917
|
+
Text(desc, size="xs", dimmed=True)
|
|
2918
|
+
if copy:
|
|
2919
|
+
Text(copy, size="xs", dimmed=True)
|
|
2920
|
+
with Group(gap=48, align="flex-start", wrap="wrap"):
|
|
2921
|
+
for g in cast("Sequence[FooterGroup]", gs):
|
|
2922
|
+
with Stack(gap=4):
|
|
2923
|
+
Text(g.title, fw=600, size="sm")
|
|
2924
|
+
self._links(cast("Sequence[FooterLink]", g.links))
|
|
2925
|
+
|
|
2926
|
+
def _build_simple(
|
|
2927
|
+
self, brand: str, desc: Any, ls: Any, gs: Any, ss: Any, sub: Any, sl: Any, copy: Any
|
|
2928
|
+
) -> None:
|
|
2929
|
+
with Group(justify="space-between", wrap="wrap"):
|
|
2930
|
+
Text(brand, fw=700, size="lg")
|
|
2931
|
+
with Group(gap="md"):
|
|
2932
|
+
self._links(ls)
|
|
2933
|
+
if copy:
|
|
2934
|
+
Text(copy, size="xs", dimmed=True)
|
|
2935
|
+
|
|
2936
|
+
def _build_social(
|
|
2937
|
+
self, brand: str, desc: Any, ls: Any, gs: Any, ss: Any, sub: Any, sl: Any, copy: Any
|
|
2938
|
+
) -> None:
|
|
2939
|
+
with Group(justify="space-between", align="flex-start", wrap="wrap"):
|
|
2940
|
+
with Stack(gap=4):
|
|
2941
|
+
Text(brand, fw=700, size="lg")
|
|
2942
|
+
if desc:
|
|
2943
|
+
Text(desc, size="xs", dimmed=True)
|
|
2944
|
+
if copy:
|
|
2945
|
+
Text(copy, size="xs", dimmed=True)
|
|
2946
|
+
with Stack(gap="sm", align="flex-end"):
|
|
2947
|
+
self._socials(ss)
|
|
2948
|
+
if sub:
|
|
2949
|
+
with Group(gap="xs", align="flex-start", wrap="nowrap"):
|
|
2950
|
+
self.email = TextInput(
|
|
2951
|
+
placeholder="you@example.com",
|
|
2952
|
+
aria_label="Email",
|
|
2953
|
+
on_enter=self._subscribe,
|
|
2954
|
+
)
|
|
2955
|
+
self.subscribe_button = Button(sl, on_click=self._subscribe)
|
|
2956
|
+
|
|
2957
|
+
def _emit_link(self, v: str, kind: str) -> None:
|
|
2958
|
+
_emit(self, kind, LinkEvent, value=v, label=self._labels[v])
|
|
2959
|
+
|
|
2960
|
+
def _subscribe(self) -> None:
|
|
2961
|
+
email = cast("TextInput", self.email)
|
|
2962
|
+
text = str(email.value or "").strip()
|
|
2963
|
+
if not _EMAIL_RE.fullmatch(text):
|
|
2964
|
+
email.update(error="Enter a valid e-mail address")
|
|
2965
|
+
return
|
|
2966
|
+
email.update(error="")
|
|
2967
|
+
_emit(self, "subscribe", SubscribeEvent, email=text)
|