diff --git a/.github/workflows/app-ci.yml b/.github/workflows/app-ci.yml index d5d37d0..03edc9e 100644 --- a/.github/workflows/app-ci.yml +++ b/.github/workflows/app-ci.yml @@ -45,7 +45,26 @@ jobs: channel: stable cache: true - run: flutter pub get - - run: flutter test + - run: flutter test --exclude-tags golden + + golden: + name: Golden + runs-on: macos-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + flutter-version: ${{ env.FLUTTER_VERSION }} + channel: stable + cache: true + - run: flutter pub get + - run: flutter test --tags golden + - if: failure() + uses: actions/upload-artifact@v4 + with: + name: golden-failures + path: app/test/golden/failures/ build-android: name: Build Android diff --git a/app/.gitignore b/app/.gitignore index 40edd18..04a8b09 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -64,4 +64,6 @@ android/app/upload-keystore.jks ios/ExportOptions.plist.local *.p8 *.p12 -*.mobileprovision \ No newline at end of file +*.mobileprovision +# Diferenças dos testes golden +**/test/golden/failures/ diff --git a/app/CLAUDE.md b/app/CLAUDE.md index dd9a312..3e6eb1e 100644 --- a/app/CLAUDE.md +++ b/app/CLAUDE.md @@ -52,6 +52,18 @@ lib/ `SessionService.signedIn` (`ValueNotifier`) é restaurado do armazenamento antes do `runApp` e o `GoRouter` observa ele (`refreshListenable`). `sessionRedirect` manda rota privada sem sessão para `/entrar?de=` e, com sessão, devolve para o destino (só caminho interno) ou para `/inicio`. Por isso tela nenhuma navega depois de entrar ou sair: basta salvar ou remover o token. Rota nova entra em `AppRoutes`; rota aberta sem sessão entra em `AppRoutes.public`. Os links que abrem o app (B56, M21) chegam por esse mesmo roteador. +## Tema e componentes + +- `lib/src/core/theme/`: `PhColors` (os tokens `--ph-*` do tema Sertão como `ThemeExtension`, lidos com `context.ph`), `PhTheme.build(colors)` (o `ThemeData`, com Lexend 400/500/600 de `assets/fonts/lexend/` e alvo mínimo de 44 px) e `contrast.dart`. +- Tema por edição (`features/edition_theme/`): `GET /public/editions/{id}/theme`, guardado no aparelho para abrir sem internet. Da edição o app usa só marca, destaque, apoio e logo (`PhColors.withEdition`); texto e cores de estado ficam fixos. Cor que não passa de 4,5:1 com o texto dela (ou de 3:1 da marca sobre o fundo) cai para a do Sertão. O `EditionThemeBloc` (singleton) recebe `EditionThemeRequested(editionId)` quando a edição é escolhida (M05) e `EditionThemeCleared` ao sair; o `AppWidget` monta o `ThemeData` a partir dele. +- `lib/src/core/ui/`: `PhButton` (primário, secundário, perigo, destaque, pequeno, carregando, largura total), `PhChip`, `PhBadge` (estado sempre com texto), `PhCard`, `PhTextField` (rótulo em cima, dica, erro), `PhAppBar` (voltar de 44 px), `PhBottomNav` (5 destinos, Ingresso no centro em destaque), `PhAvatar`, `PhStripe` e os estados `PhOfflineBanner`, `PhMessageState` (vazio), `PhErrorState` e `PhLoadingList`. Tela nova monta com eles antes de estilizar widget do Material na mão. +- Catálogo em `/_dev/componentes` (só em debug, sem login), com a troca entre o Sertão e um tema de edição de exemplo. +- Tema escuro fica fora até o design definir. + +## Testes + +`flutter test` roda tudo. Os golden (`test/golden/`, marcados com `@Tags(['golden'])`) comparam com imagens geradas num Mac; no CI rodam num job em macOS e o resto roda em Linux com `--exclude-tags golden`. `test/flutter_test_config.dart` carrega a Lexend e os ícones e aceita até 0,5% de diferença. Para atualizar as imagens depois de mudar um componente: `flutter test --tags golden --update-goldens`, e conferir as imagens no PR. + ## Comandos ```bash diff --git a/app/assets/fonts/lexend/Lexend-Medium.ttf b/app/assets/fonts/lexend/Lexend-Medium.ttf new file mode 100644 index 0000000..e954d57 Binary files /dev/null and b/app/assets/fonts/lexend/Lexend-Medium.ttf differ diff --git a/app/assets/fonts/lexend/Lexend-Regular.ttf b/app/assets/fonts/lexend/Lexend-Regular.ttf new file mode 100644 index 0000000..4bd270a Binary files /dev/null and b/app/assets/fonts/lexend/Lexend-Regular.ttf differ diff --git a/app/assets/fonts/lexend/Lexend-SemiBold.ttf b/app/assets/fonts/lexend/Lexend-SemiBold.ttf new file mode 100644 index 0000000..4528893 Binary files /dev/null and b/app/assets/fonts/lexend/Lexend-SemiBold.ttf differ diff --git a/app/assets/fonts/lexend/OFL.txt b/app/assets/fonts/lexend/OFL.txt new file mode 100644 index 0000000..b1477aa --- /dev/null +++ b/app/assets/fonts/lexend/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Lexend Project Authors (https://github.com/googlefonts/lexend), with Reserved Font Name “RevReading Lexend”. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/dart_test.yaml b/app/dart_test.yaml new file mode 100644 index 0000000..f01b955 --- /dev/null +++ b/app/dart_test.yaml @@ -0,0 +1,2 @@ +tags: + golden: diff --git a/app/lib/app_widget.dart b/app/lib/app_widget.dart index e43358c..1740f3a 100644 --- a/app/lib/app_widget.dart +++ b/app/lib/app_widget.dart @@ -1,9 +1,11 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:phpeste_app/routes.dart'; import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart'; import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; import 'package:phpeste_app/src/core/config/app_config.dart'; -import 'package:material_ui/material_ui.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; class AppWidget extends StatelessWidget { const AppWidget({super.key}); @@ -12,18 +14,17 @@ class AppWidget extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider( - create: (context) => injector(), - ), + BlocProvider(create: (context) => injector()), + BlocProvider.value(value: injector()), ], - child: MaterialApp.router( - title: 'PHPeste', - debugShowCheckedModeBanner: !AppConfig.isProduction, - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, + child: BlocBuilder( + buildWhen: (previous, current) => previous.colors != current.colors, + builder: (context, state) => MaterialApp.router( + title: 'PHPeste', + debugShowCheckedModeBanner: !AppConfig.isProduction, + theme: PhTheme.build(state.colors), + routerConfig: router, ), - routerConfig: router, ), ); } diff --git a/app/lib/routes.dart b/app/lib/routes.dart index e713b74..b6bc460 100644 --- a/app/lib/routes.dart +++ b/app/lib/routes.dart @@ -1,7 +1,11 @@ +import 'package:flutter/foundation.dart'; import 'package:go_router/go_router.dart'; import 'package:material_ui/material_ui.dart'; import 'package:phpeste_app/src/app/features/auth/presentation/pages/login_page.dart'; import 'package:phpeste_app/src/app/features/base/presentation/pages/base_page.dart'; +import 'package:phpeste_app/src/app/features/base/presentation/pages/coming_soon_page.dart'; +import 'package:phpeste_app/src/app/features/base/presentation/texts/base_texts.dart'; +import 'package:phpeste_app/src/app/features/component_catalog/presentation/pages/component_catalog_page.dart'; import 'package:phpeste_app/src/app/features/home/presentation/pages/home_page.dart'; import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; import 'package:phpeste_app/src/core/services/session_service.dart'; @@ -9,9 +13,13 @@ import 'package:phpeste_app/src/core/services/session_service.dart'; class AppRoutes { static const String login = '/entrar'; static const String home = '/inicio'; + static const String program = '/programacao'; + static const String ticket = '/ingresso'; + static const String agenda = '/agenda'; static const String profile = '/perfil'; + static const String componentCatalog = '/_dev/componentes'; - static const Set public = {login}; + static const Set public = {login, if (kDebugMode) componentCatalog}; } String? sessionRedirect({required bool signedIn, required Uri location}) { @@ -38,18 +46,14 @@ GoRouter createRouter(SessionService session) => GoRouter( StatefulShellRoute.indexedStack( builder: (context, state, shell) => BasePage(shell: shell), branches: [ - StatefulShellBranch( - routes: [ - GoRoute(path: AppRoutes.home, name: 'home', builder: (context, state) => const HomePage()), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute(path: AppRoutes.profile, name: 'profile', builder: (context, state) => const Placeholder()), - ], - ), + StatefulShellBranch(routes: [GoRoute(path: AppRoutes.home, name: 'home', builder: (context, state) => const HomePage())]), + StatefulShellBranch(routes: [GoRoute(path: AppRoutes.program, name: 'program', builder: (context, state) => const ComingSoonPage(title: BaseTexts.program, icon: Icons.calendar_month_outlined))]), + StatefulShellBranch(routes: [GoRoute(path: AppRoutes.ticket, name: 'ticket', builder: (context, state) => const ComingSoonPage(title: BaseTexts.ticket, icon: Icons.confirmation_number_outlined))]), + StatefulShellBranch(routes: [GoRoute(path: AppRoutes.agenda, name: 'agenda', builder: (context, state) => const ComingSoonPage(title: BaseTexts.agenda, icon: Icons.bookmark_border_rounded))]), + StatefulShellBranch(routes: [GoRoute(path: AppRoutes.profile, name: 'profile', builder: (context, state) => const ComingSoonPage(title: BaseTexts.profile, icon: Icons.person_outline_rounded))]), ], ), + if (kDebugMode) GoRoute(path: AppRoutes.componentCatalog, builder: (context, state) => const ComponentCatalogPage()), GoRoute(path: '/', redirect: (context, state) => AppRoutes.home), GoRoute(path: AppRoutes.login, name: 'login', builder: (context, state) => const LoginPage()), ], diff --git a/app/lib/src/app/features/base/presentation/pages/base_page.dart b/app/lib/src/app/features/base/presentation/pages/base_page.dart index d83dbfa..5c3e353 100644 --- a/app/lib/src/app/features/base/presentation/pages/base_page.dart +++ b/app/lib/src/app/features/base/presentation/pages/base_page.dart @@ -1,8 +1,19 @@ -import 'package:material_ui/material_ui.dart'; import 'package:go_router/go_router.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:phpeste_app/src/app/features/base/presentation/texts/base_texts.dart'; +import 'package:phpeste_app/src/core/ui/ph_bottom_nav.dart'; class BasePage extends StatelessWidget { + static const int ticketIndex = 2; + + static const List destinations = [ + PhNavDestination(label: BaseTexts.home, icon: Icons.home_outlined), + PhNavDestination(label: BaseTexts.program, icon: Icons.calendar_month_outlined), + PhNavDestination(label: BaseTexts.ticket, icon: Icons.confirmation_number_outlined), + PhNavDestination(label: BaseTexts.agenda, icon: Icons.bookmark_border_rounded), + PhNavDestination(label: BaseTexts.profile, icon: Icons.person_outline_rounded), + ]; + const BasePage({super.key, required this.shell}); final StatefulNavigationShell shell; @@ -11,22 +22,11 @@ class BasePage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( body: shell, - bottomNavigationBar: BottomNavigationBar( + bottomNavigationBar: PhBottomNav( + destinations: destinations, currentIndex: shell.currentIndex, - onTap: shell.goBranch, - showUnselectedLabels: true, - items: const [ - BottomNavigationBarItem( - backgroundColor: Colors.white, - icon: Icon(Icons.home_outlined), - label: BaseTexts.home, - ), - BottomNavigationBarItem( - icon: Icon(Icons.person), - backgroundColor: Colors.white, - label: BaseTexts.profile, - ), - ], + highlightedIndex: ticketIndex, + onSelected: (index) => shell.goBranch(index, initialLocation: index == shell.currentIndex), ), ); } diff --git a/app/lib/src/app/features/base/presentation/pages/coming_soon_page.dart b/app/lib/src/app/features/base/presentation/pages/coming_soon_page.dart new file mode 100644 index 0000000..0781799 --- /dev/null +++ b/app/lib/src/app/features/base/presentation/pages/coming_soon_page.dart @@ -0,0 +1,19 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/app/features/base/presentation/texts/base_texts.dart'; +import 'package:phpeste_app/src/core/ui/ph_app_bar.dart'; +import 'package:phpeste_app/src/core/ui/ph_states.dart'; + +class ComingSoonPage extends StatelessWidget { + final String title; + final IconData icon; + + const ComingSoonPage({super.key, required this.title, required this.icon}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: PhAppBar(title: title), + body: PhMessageState(icon: icon, title: BaseTexts.soonTitle, text: BaseTexts.soonText), + ); + } +} diff --git a/app/lib/src/app/features/base/presentation/texts/base_texts.dart b/app/lib/src/app/features/base/presentation/texts/base_texts.dart index 9c7d414..e824e0b 100644 --- a/app/lib/src/app/features/base/presentation/texts/base_texts.dart +++ b/app/lib/src/app/features/base/presentation/texts/base_texts.dart @@ -1,4 +1,9 @@ class BaseTexts { static const String home = 'Início'; + static const String program = 'Programação'; + static const String ticket = 'Ingresso'; + static const String agenda = 'Agenda'; static const String profile = 'Perfil'; + static const String soonTitle = 'Chega em breve'; + static const String soonText = 'Esta parte do app está sendo feita e aparece numa próxima versão.'; } diff --git a/app/lib/src/app/features/component_catalog/presentation/pages/component_catalog_page.dart b/app/lib/src/app/features/component_catalog/presentation/pages/component_catalog_page.dart new file mode 100644 index 0000000..5878e36 --- /dev/null +++ b/app/lib/src/app/features/component_catalog/presentation/pages/component_catalog_page.dart @@ -0,0 +1,129 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; +import 'package:phpeste_app/src/core/ui/ph_app_bar.dart'; +import 'package:phpeste_app/src/core/ui/ph_avatar.dart'; +import 'package:phpeste_app/src/core/ui/ph_badge.dart'; +import 'package:phpeste_app/src/core/ui/ph_bottom_nav.dart'; +import 'package:phpeste_app/src/core/ui/ph_button.dart'; +import 'package:phpeste_app/src/core/ui/ph_card.dart'; +import 'package:phpeste_app/src/core/ui/ph_chip.dart'; +import 'package:phpeste_app/src/core/ui/ph_states.dart'; +import 'package:phpeste_app/src/core/ui/ph_text_field.dart'; + +class ComponentCatalogPage extends StatefulWidget { + static final PhColors sampleEdition = PhColors.sertao.withEdition( + brand: const Color(0xFF1F4E79), + onBrand: const Color(0xFFFFFFFF), + accent: const Color(0xFF7FC8C2), + onAccent: const Color(0xFF10263A), + support: const Color(0xFF2E6B5E), + ); + + const ComponentCatalogPage({super.key}); + + @override + State createState() => _ComponentCatalogPageState(); +} + +class _ComponentCatalogPageState extends State { + bool _edition = false; + int _chip = 0; + int _tab = 2; + + @override + Widget build(BuildContext context) { + final colors = _edition ? ComponentCatalogPage.sampleEdition : PhColors.sertao; + return Theme( + data: PhTheme.build(colors), + child: Builder(builder: (context) => _catalog(context)), + ); + } + + Widget _catalog(BuildContext context) { + final c = context.ph; + const gap = SizedBox(height: 12, width: 12); + return Scaffold( + backgroundColor: c.bg, + appBar: PhAppBar(title: 'Componentes', onBack: Navigator.of(context).canPop() ? () => Navigator.of(context).pop() : null), + bottomNavigationBar: PhBottomNav( + destinations: const [ + PhNavDestination(label: 'Início', icon: Icons.home_outlined), + PhNavDestination(label: 'Programação', icon: Icons.calendar_month_outlined), + PhNavDestination(label: 'Ingresso', icon: Icons.confirmation_number_outlined), + PhNavDestination(label: 'Agenda', icon: Icons.bookmark_border_rounded), + PhNavDestination(label: 'Perfil', icon: Icons.person_outline_rounded), + ], + currentIndex: _tab, + highlightedIndex: 2, + onSelected: (index) => setState(() => _tab = index), + ), + body: ListView( + children: [ + const PhStripe(), + const PhOfflineBanner(), + Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Tema de uma edição de exemplo'), + value: _edition, + onChanged: (value) => setState(() => _edition = value), + ), + gap, + Wrap(spacing: 12, runSpacing: 12, children: [ + PhButton(label: 'Primário', onPressed: () {}), + PhButton(label: 'Secundário', variant: PhButtonVariant.secondary, onPressed: () {}), + PhButton(label: 'Destaque', variant: PhButtonVariant.accent, onPressed: () {}), + PhButton(label: 'Excluir', variant: PhButtonVariant.danger, onPressed: () {}), + PhButton(label: 'Pequeno', small: true, onPressed: () {}), + const PhButton(label: 'Desativado', onPressed: null), + PhButton(label: 'Enviando', loading: true, onPressed: () {}), + ]), + gap, + PhButton(label: 'Botão de largura total', icon: Icons.qr_code_2_rounded, block: true, onPressed: () {}), + gap, + Wrap(spacing: 8, runSpacing: 8, children: [ + for (final (index, label) in ['Todas', 'Backend', 'Arquitetura', 'Testes'].indexed) + PhChip(label: label, selected: _chip == index, onTap: () => setState(() => _chip = index)), + ]), + gap, + const Wrap(spacing: 8, runSpacing: 8, children: [ + PhBadge(label: 'Válido', tone: PhTone.ok), + PhBadge(label: 'Pendente', tone: PhTone.warn), + PhBadge(label: 'Recusado', tone: PhTone.danger), + PhBadge(label: 'Em avaliação', tone: PhTone.info), + PhBadge(label: 'Rascunho'), + ]), + gap, + PhCard( + child: Row(children: [ + const PhAvatar(name: 'Ana Beatriz Lima'), + gap, + Expanded( + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Ana Beatriz Lima', style: Theme.of(context).textTheme.titleSmall), + Text('Engenheira de software', style: Theme.of(context).textTheme.bodySmall), + ]), + ), + ]), + ), + gap, + const PhTextField(label: 'E-mail', placeholder: 'voce@exemplo.com', hint: 'O mesmo e-mail da compra.'), + gap, + const PhTextField(label: 'Senha', obscureText: true, error: 'Informe a senha.'), + gap, + SizedBox(height: 320, child: PhCard(padding: EdgeInsets.zero, child: PhErrorState(onRetry: () {}))), + gap, + const SizedBox(height: 360, child: PhCard(padding: EdgeInsets.zero, child: PhLoadingList(items: 2))), + ], + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart b/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart new file mode 100644 index 0000000..efbb43e --- /dev/null +++ b/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart @@ -0,0 +1,22 @@ +import 'package:phpeste_app/src/app/features/edition_theme/data/models/edition_branding_model.dart'; +import 'package:phpeste_app/src/core/cache/cache.dart'; + +class EditionBrandingLocalDatasource { + final ICache _cache; + + EditionBrandingLocalDatasource({required ICache cache}) : _cache = cache; + + String _key(String editionId) => 'edition_branding.$editionId'; + + Future save(EditionBrandingModel model) => _cache.setData(params: CacheParams(key: _key(model.editionId), value: model.toJson())); + + Future read(String editionId) async { + final value = await _cache.getData(_key(editionId)); + if (value is! String || value.isEmpty) return null; + try { + return EditionBrandingModel.fromJson(value); + } catch (_) { + return null; + } + } +} diff --git a/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart b/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart new file mode 100644 index 0000000..bf9757c --- /dev/null +++ b/app/lib/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart @@ -0,0 +1,10 @@ +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/utils/endpoints.dart'; + +class EditionBrandingRemoteDatasource { + final IRestClient _restClient; + + EditionBrandingRemoteDatasource({required IRestClient restClient}) : _restClient = restClient; + + Future theme(String editionId) => _restClient.get(RestClientRequest(path: Endpoints.editionTheme(editionId))); +} diff --git a/app/lib/src/app/features/edition_theme/data/models/edition_branding_model.dart b/app/lib/src/app/features/edition_theme/data/models/edition_branding_model.dart new file mode 100644 index 0000000..0a41101 --- /dev/null +++ b/app/lib/src/app/features/edition_theme/data/models/edition_branding_model.dart @@ -0,0 +1,73 @@ +import 'dart:convert'; + +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; + +class EditionBrandingModel extends EditionBrandingEntity { + const EditionBrandingModel({ + required super.editionId, + super.brand, + super.onBrand, + super.accent, + super.onAccent, + super.support, + super.logoUrl, + super.publishedAt, + }); + + static int? _color(Object? value) { + if (value is! String || !RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(value)) return null; + return 0xFF000000 | int.parse(value.substring(1), radix: 16); + } + + static String? _hex(int? value) => value == null ? null : '#${(value & 0xFFFFFF).toRadixString(16).padLeft(6, '0').toUpperCase()}'; + + static String? _https(Object? value) { + if (value is! String) return null; + final uri = Uri.tryParse(value); + return uri != null && uri.scheme == 'https' && uri.host.isNotEmpty ? value : null; + } + + factory EditionBrandingModel.fromApi(Map payload) { + final data = payload['data'] as Map; + final theme = (data['theme'] as Map?) ?? const {}; + final colors = (theme['colors'] as Map?) ?? const {}; + final logos = (theme['logos'] as Map?) ?? const {}; + + return EditionBrandingModel( + editionId: data['edition_id'] as String, + brand: _color(colors['brand']), + onBrand: _color(colors['on_brand']), + accent: _color(colors['accent']), + onAccent: _color(colors['on_accent']), + support: _color(colors['support']), + logoUrl: _https(logos['primary']), + publishedAt: data['published_at'] as String?, + ); + } + + Map toMap() => { + 'edition_id': editionId, + 'brand': _hex(brand), + 'on_brand': _hex(onBrand), + 'accent': _hex(accent), + 'on_accent': _hex(onAccent), + 'support': _hex(support), + 'logo_url': logoUrl, + 'published_at': publishedAt, + }; + + factory EditionBrandingModel.fromMap(Map map) => EditionBrandingModel( + editionId: map['edition_id'] as String, + brand: _color(map['brand']), + onBrand: _color(map['on_brand']), + accent: _color(map['accent']), + onAccent: _color(map['on_accent']), + support: _color(map['support']), + logoUrl: _https(map['logo_url']), + publishedAt: map['published_at'] as String?, + ); + + String toJson() => json.encode(toMap()); + + factory EditionBrandingModel.fromJson(String source) => EditionBrandingModel.fromMap(json.decode(source) as Map); +} diff --git a/app/lib/src/app/features/edition_theme/data/repositories/edition_branding_repository_impl.dart b/app/lib/src/app/features/edition_theme/data/repositories/edition_branding_repository_impl.dart new file mode 100644 index 0000000..b1a6d30 --- /dev/null +++ b/app/lib/src/app/features/edition_theme/data/repositories/edition_branding_repository_impl.dart @@ -0,0 +1,39 @@ +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/models/edition_branding_model.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart'; +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; +import 'package:result_dart/result_dart.dart'; + +class EditionBrandingRepositoryImpl implements IEditionBrandingRepository { + final EditionBrandingRemoteDatasource _remote; + final EditionBrandingLocalDatasource _local; + + EditionBrandingRepositoryImpl({required EditionBrandingRemoteDatasource remote, required EditionBrandingLocalDatasource local}) + : _remote = remote, + _local = local; + + @override + AsyncResult branding(String editionId) async { + try { + final response = await _remote.theme(editionId); + if (response.statusCode == 200 && response.data is Map) { + final model = EditionBrandingModel.fromApi(response.data as Map); + await _local.save(model); + return Success(model); + } + return await _saved(editionId, NotFoundException(message: 'Tema da edição não encontrado.', statusCode: response.statusCode)); + } on RestClientException catch (e) { + return await _saved(editionId, DefaultException(message: e.message, statusCode: e.statusCode)); + } catch (e) { + return await _saved(editionId, DefaultException(message: 'Erro inesperado: $e')); + } + } + + AsyncResult _saved(String editionId, BaseException error) async { + final saved = await _local.read(editionId); + return saved != null ? Success(saved) : Failure(error); + } +} diff --git a/app/lib/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart b/app/lib/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart new file mode 100644 index 0000000..46889a5 --- /dev/null +++ b/app/lib/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart @@ -0,0 +1,26 @@ +import 'package:equatable/equatable.dart'; + +class EditionBrandingEntity extends Equatable { + final String editionId; + final int? brand; + final int? onBrand; + final int? accent; + final int? onAccent; + final int? support; + final String? logoUrl; + final String? publishedAt; + + const EditionBrandingEntity({ + required this.editionId, + this.brand, + this.onBrand, + this.accent, + this.onAccent, + this.support, + this.logoUrl, + this.publishedAt, + }); + + @override + List get props => [editionId, brand, onBrand, accent, onAccent, support, logoUrl, publishedAt]; +} diff --git a/app/lib/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart b/app/lib/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart new file mode 100644 index 0000000..c6dda5a --- /dev/null +++ b/app/lib/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart @@ -0,0 +1,6 @@ +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; +import 'package:result_dart/result_dart.dart'; + +abstract interface class IEditionBrandingRepository { + AsyncResult branding(String editionId); +} diff --git a/app/lib/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart b/app/lib/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart new file mode 100644 index 0000000..063df78 --- /dev/null +++ b/app/lib/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart @@ -0,0 +1,13 @@ +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart'; +import 'package:phpeste_app/src/core/interfaces/usecase_interface.dart'; +import 'package:result_dart/result_dart.dart'; + +class GetEditionBrandingUsecase implements UseCase { + final IEditionBrandingRepository _repository; + + GetEditionBrandingUsecase({required IEditionBrandingRepository repository}) : _repository = repository; + + @override + AsyncResult call(String editionId) => _repository.branding(editionId); +} diff --git a/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart new file mode 100644 index 0000000..752b8ae --- /dev/null +++ b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart @@ -0,0 +1,41 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; + +part 'edition_theme_event.dart'; +part 'edition_theme_state.dart'; + +class EditionThemeBloc extends Bloc { + final GetEditionBrandingUsecase _getBranding; + + EditionThemeBloc({required GetEditionBrandingUsecase getBranding}) + : _getBranding = getBranding, + super(const EditionThemeState()) { + on((event, emit) async { + final result = await _getBranding(event.editionId); + result.fold( + (branding) => emit(stateFor(branding)), + (_) => emit(EditionThemeState(editionId: event.editionId)), + ); + }); + on((event, emit) => emit(const EditionThemeState())); + } + + static EditionThemeState stateFor(EditionBrandingEntity branding) { + Color? color(int? value) => value == null ? null : Color(value); + return EditionThemeState( + editionId: branding.editionId, + colors: PhColors.sertao.withEdition( + brand: color(branding.brand), + onBrand: color(branding.onBrand), + accent: color(branding.accent), + onAccent: color(branding.onAccent), + support: color(branding.support), + ), + logoUrl: branding.logoUrl, + ); + } +} diff --git a/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_event.dart b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_event.dart new file mode 100644 index 0000000..1b14d8b --- /dev/null +++ b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_event.dart @@ -0,0 +1,21 @@ +part of 'edition_theme_bloc.dart'; + +sealed class EditionThemeEvent extends Equatable { + const EditionThemeEvent(); + + @override + List get props => []; +} + +class EditionThemeRequested extends EditionThemeEvent { + final String editionId; + + const EditionThemeRequested(this.editionId); + + @override + List get props => [editionId]; +} + +class EditionThemeCleared extends EditionThemeEvent { + const EditionThemeCleared(); +} diff --git a/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_state.dart b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_state.dart new file mode 100644 index 0000000..9eda275 --- /dev/null +++ b/app/lib/src/app/features/edition_theme/presentation/bloc/edition_theme_state.dart @@ -0,0 +1,12 @@ +part of 'edition_theme_bloc.dart'; + +class EditionThemeState extends Equatable { + final String? editionId; + final PhColors colors; + final String? logoUrl; + + const EditionThemeState({this.editionId, this.colors = PhColors.sertao, this.logoUrl}); + + @override + List get props => [editionId, colors, logoUrl]; +} diff --git a/app/lib/src/app/features/home/presentation/pages/home_page.dart b/app/lib/src/app/features/home/presentation/pages/home_page.dart index f068d0e..b9d1e8d 100644 --- a/app/lib/src/app/features/home/presentation/pages/home_page.dart +++ b/app/lib/src/app/features/home/presentation/pages/home_page.dart @@ -1,7 +1,9 @@ +import 'package:material_ui/material_ui.dart'; import 'package:phpeste_app/src/app/features/home/presentation/texts/home_texts.dart'; import 'package:phpeste_app/src/core/DI/dependency_injector.dart'; import 'package:phpeste_app/src/core/services/session_service.dart'; -import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/ui/ph_app_bar.dart'; +import 'package:phpeste_app/src/core/ui/ph_states.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @@ -9,23 +11,17 @@ class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text(HomeTexts.title), - centerTitle: true, + appBar: PhAppBar( + title: HomeTexts.title, actions: [ IconButton( - onPressed: () async { - final sessionService = injector(); - await sessionService.removeToken(); - }, + onPressed: () => injector().removeToken(), tooltip: HomeTexts.logout, - icon: const Icon(Icons.logout_sharp), + icon: const Icon(Icons.logout_rounded), ), ], ), - body: const Center( - child: Text(HomeTexts.body), - ), + body: const PhMessageState(icon: Icons.festival_outlined, title: HomeTexts.body), ); } } diff --git a/app/lib/src/core/DI/dependency_injector.dart b/app/lib/src/core/DI/dependency_injector.dart index 137f44d..6253b25 100644 --- a/app/lib/src/core/DI/dependency_injector.dart +++ b/app/lib/src/core/DI/dependency_injector.dart @@ -5,6 +5,12 @@ import 'package:phpeste_app/src/app/features/auth/domain/repositories/auth_repos import 'package:phpeste_app/src/app/features/auth/domain/usecases/login_usecase.dart'; import 'package:phpeste_app/src/app/features/auth/infrastructure/auth_interceptor.dart'; import 'package:phpeste_app/src/app/features/auth/presentation/bloc/auth_bloc.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/repositories/edition_branding_repository_impl.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart'; import 'package:phpeste_app/src/core/cache/shared_preferences/shared_preferences_impl.dart'; import 'package:phpeste_app/src/core/client_http/dio/rest_client_dio_impl.dart'; import 'package:phpeste_app/src/core/client_http/logger/client_interceptor_logger_impl.dart'; @@ -57,4 +63,13 @@ void setupDependencyInjector({bool loggerApi = false, bool useMocks = true, Logg sessionService: injector(), ), )); + + injector.registerLazySingleton(() => EditionBrandingRepositoryImpl( + remote: EditionBrandingRemoteDatasource(restClient: injector()), + local: EditionBrandingLocalDatasource(cache: SharedPreferencesImpl()), + )); + + injector.registerLazySingleton(() => EditionThemeBloc( + getBranding: GetEditionBrandingUsecase(repository: injector()), + )); } diff --git a/app/lib/src/core/theme/contrast.dart b/app/lib/src/core/theme/contrast.dart new file mode 100644 index 0000000..de141e1 --- /dev/null +++ b/app/lib/src/core/theme/contrast.dart @@ -0,0 +1,19 @@ +import 'dart:math' as math; +import 'dart:ui'; + +double _channel(double value) => value <= 0.03928 ? value / 12.92 : math.pow((value + 0.055) / 1.055, 2.4).toDouble(); + +double relativeLuminance(Color color) => 0.2126 * _channel(color.r) + 0.7152 * _channel(color.g) + 0.0722 * _channel(color.b); + +double contrastRatio(Color a, Color b) { + final first = relativeLuminance(a); + final second = relativeLuminance(b); + final lighter = math.max(first, second); + final darker = math.min(first, second); + return (lighter + 0.05) / (darker + 0.05); +} + +Color? parseHexColor(Object? value) { + if (value is! String || !RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(value)) return null; + return Color(0xFF000000 | int.parse(value.substring(1), radix: 16)); +} diff --git a/app/lib/src/core/theme/ph_colors.dart b/app/lib/src/core/theme/ph_colors.dart new file mode 100644 index 0000000..f79f404 --- /dev/null +++ b/app/lib/src/core/theme/ph_colors.dart @@ -0,0 +1,190 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/contrast.dart'; + +class PhColors extends ThemeExtension { + static const double textMinimum = 4.5; + + final Color bg; + final Color surface; + final Color surface2; + final Color line; + final Color ink; + final Color ink2; + final Color ink3; + final Color link; + final Color brand; + final Color brandHover; + final Color onBrand; + final Color accent; + final Color accentSoft; + final Color onAccent; + final Color terra; + final Color ok; + final Color okSoft; + final Color warn; + final Color warnSoft; + final Color danger; + final Color dangerSoft; + final Color info; + final Color infoSoft; + + const PhColors({ + required this.bg, + required this.surface, + required this.surface2, + required this.line, + required this.ink, + required this.ink2, + required this.ink3, + required this.link, + required this.brand, + required this.brandHover, + required this.onBrand, + required this.accent, + required this.accentSoft, + required this.onAccent, + required this.terra, + required this.ok, + required this.okSoft, + required this.warn, + required this.warnSoft, + required this.danger, + required this.dangerSoft, + required this.info, + required this.infoSoft, + }); + + static const PhColors sertao = PhColors( + bg: Color(0xFFFBF4E4), + surface: Color(0xFFFFFBF2), + surface2: Color(0xFFF5EAD0), + line: Color(0xFFE4D3AB), + ink: Color(0xFF3A1607), + ink2: Color(0xFF6F4A38), + ink3: Color(0xFF7F5A47), + link: Color(0xFF9C4220), + brand: Color(0xFF6B2A12), + brandHover: Color(0xFF55200C), + onBrand: Color(0xFFFFF8E8), + accent: Color(0xFFE8B544), + accentSoft: Color(0xFFF6E3B0), + onAccent: Color(0xFF3A1607), + terra: Color(0xFFB4532A), + ok: Color(0xFF4B6A24), + okSoft: Color(0xFFE6EBCF), + warn: Color(0xFF8A5A00), + warnSoft: Color(0xFFF8E7B9), + danger: Color(0xFFA12B1F), + dangerSoft: Color(0xFFF6D9D2), + info: Color(0xFF2F5D6B), + infoSoft: Color(0xFFD9E7E9), + ); + + PhColors withEdition({Color? brand, Color? onBrand, Color? accent, Color? onAccent, Color? support}) { + final readableBrand = brand != null && + onBrand != null && + contrastRatio(onBrand, brand) >= textMinimum && + contrastRatio(brand, bg) >= 3 && + contrastRatio(brand, surface) >= 3; + final readableAccent = accent != null && onAccent != null && contrastRatio(onAccent, accent) >= textMinimum; + final readableSupport = support != null && contrastRatio(readableBrand ? onBrand : this.onBrand, support) >= textMinimum; + + return copyWith( + brand: readableBrand ? brand : null, + brandHover: readableBrand ? Color.lerp(brand, const Color(0xFF000000), 0.2) : null, + onBrand: readableBrand ? onBrand : null, + accent: readableAccent ? accent : null, + accentSoft: readableAccent ? Color.lerp(accent, surface, 0.6) : null, + onAccent: readableAccent ? onAccent : null, + terra: readableSupport ? support : null, + ); + } + + @override + PhColors copyWith({ + Color? bg, + Color? surface, + Color? surface2, + Color? line, + Color? ink, + Color? ink2, + Color? ink3, + Color? link, + Color? brand, + Color? brandHover, + Color? onBrand, + Color? accent, + Color? accentSoft, + Color? onAccent, + Color? terra, + Color? ok, + Color? okSoft, + Color? warn, + Color? warnSoft, + Color? danger, + Color? dangerSoft, + Color? info, + Color? infoSoft, + }) { + return PhColors( + bg: bg ?? this.bg, + surface: surface ?? this.surface, + surface2: surface2 ?? this.surface2, + line: line ?? this.line, + ink: ink ?? this.ink, + ink2: ink2 ?? this.ink2, + ink3: ink3 ?? this.ink3, + link: link ?? this.link, + brand: brand ?? this.brand, + brandHover: brandHover ?? this.brandHover, + onBrand: onBrand ?? this.onBrand, + accent: accent ?? this.accent, + accentSoft: accentSoft ?? this.accentSoft, + onAccent: onAccent ?? this.onAccent, + terra: terra ?? this.terra, + ok: ok ?? this.ok, + okSoft: okSoft ?? this.okSoft, + warn: warn ?? this.warn, + warnSoft: warnSoft ?? this.warnSoft, + danger: danger ?? this.danger, + dangerSoft: dangerSoft ?? this.dangerSoft, + info: info ?? this.info, + infoSoft: infoSoft ?? this.infoSoft, + ); + } + + @override + PhColors lerp(covariant ThemeExtension? other, double t) { + if (other is! PhColors) return this; + Color mix(Color a, Color b) => Color.lerp(a, b, t)!; + return PhColors( + bg: mix(bg, other.bg), + surface: mix(surface, other.surface), + surface2: mix(surface2, other.surface2), + line: mix(line, other.line), + ink: mix(ink, other.ink), + ink2: mix(ink2, other.ink2), + ink3: mix(ink3, other.ink3), + link: mix(link, other.link), + brand: mix(brand, other.brand), + brandHover: mix(brandHover, other.brandHover), + onBrand: mix(onBrand, other.onBrand), + accent: mix(accent, other.accent), + accentSoft: mix(accentSoft, other.accentSoft), + onAccent: mix(onAccent, other.onAccent), + terra: mix(terra, other.terra), + ok: mix(ok, other.ok), + okSoft: mix(okSoft, other.okSoft), + warn: mix(warn, other.warn), + warnSoft: mix(warnSoft, other.warnSoft), + danger: mix(danger, other.danger), + dangerSoft: mix(dangerSoft, other.dangerSoft), + info: mix(info, other.info), + infoSoft: mix(infoSoft, other.infoSoft), + ); + } +} + +extension PhColorsContext on BuildContext { + PhColors get ph => Theme.of(this).extension() ?? PhColors.sertao; +} diff --git a/app/lib/src/core/theme/ph_theme.dart b/app/lib/src/core/theme/ph_theme.dart new file mode 100644 index 0000000..288307f --- /dev/null +++ b/app/lib/src/core/theme/ph_theme.dart @@ -0,0 +1,129 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; + +class PhTheme { + static const String fontFamily = 'Lexend'; + static const double radius = 10; + static const double radiusLg = 14; + static const double minTouch = 44; + + static ThemeData build(PhColors c) { + final scheme = ColorScheme( + brightness: Brightness.light, + primary: c.brand, + onPrimary: c.onBrand, + secondary: c.accent, + onSecondary: c.onAccent, + tertiary: c.terra, + onTertiary: c.onBrand, + error: c.danger, + onError: const Color(0xFFFFFFFF), + surface: c.surface, + onSurface: c.ink, + onSurfaceVariant: c.ink2, + surfaceContainerHighest: c.surface2, + outline: c.line, + outlineVariant: c.line, + ); + + final text = TextTheme( + headlineMedium: TextStyle(fontSize: 28, height: 1.15, fontWeight: FontWeight.w600, color: c.ink), + headlineSmall: TextStyle(fontSize: 24, height: 1.2, fontWeight: FontWeight.w600, color: c.ink), + titleLarge: TextStyle(fontSize: 20, height: 1.2, fontWeight: FontWeight.w600, color: c.ink), + titleMedium: TextStyle(fontSize: 16, height: 1.35, fontWeight: FontWeight.w600, color: c.ink), + titleSmall: TextStyle(fontSize: 15, height: 1.35, fontWeight: FontWeight.w600, color: c.ink), + bodyLarge: TextStyle(fontSize: 16, height: 1.5, fontWeight: FontWeight.w400, color: c.ink), + bodyMedium: TextStyle(fontSize: 14, height: 1.5, fontWeight: FontWeight.w400, color: c.ink), + bodySmall: TextStyle(fontSize: 12, height: 1.45, fontWeight: FontWeight.w400, color: c.ink3), + labelLarge: TextStyle(fontSize: 14, height: 1.2, fontWeight: FontWeight.w500, color: c.ink), + labelMedium: TextStyle(fontSize: 12, height: 1.2, fontWeight: FontWeight.w500, color: c.ink2), + labelSmall: TextStyle(fontSize: 12, height: 1.2, fontWeight: FontWeight.w500, color: c.ink2), + ); + + final shape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(radius)); + const buttonText = TextStyle(fontFamily: fontFamily, fontSize: 14, fontWeight: FontWeight.w500); + + OutlineInputBorder border(Color color, [double width = 1]) => + OutlineInputBorder(borderRadius: BorderRadius.circular(radius), borderSide: BorderSide(color: color, width: width)); + + return ThemeData( + useMaterial3: true, + fontFamily: fontFamily, + colorScheme: scheme, + scaffoldBackgroundColor: c.bg, + textTheme: text, + extensions: [c], + materialTapTargetSize: MaterialTapTargetSize.padded, + dividerTheme: DividerThemeData(color: c.line, thickness: 1, space: 1), + appBarTheme: AppBarTheme( + backgroundColor: c.bg, + foregroundColor: c.ink, + elevation: 0, + scrolledUnderElevation: 0, + centerTitle: false, + titleTextStyle: text.titleLarge!.copyWith(fontFamily: fontFamily), + ), + cardTheme: CardThemeData( + color: c.surface, + elevation: 0, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(radiusLg), side: BorderSide(color: c.line)), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + backgroundColor: c.brand, + foregroundColor: c.onBrand, + minimumSize: const Size(minTouch, minTouch), + padding: const EdgeInsets.symmetric(horizontal: 18), + shape: shape, + textStyle: buttonText, + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: c.ink, + backgroundColor: Colors.transparent, + minimumSize: const Size(minTouch, minTouch), + padding: const EdgeInsets.symmetric(horizontal: 18), + side: BorderSide(color: c.line), + shape: shape, + textStyle: buttonText, + ), + ), + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom(foregroundColor: c.link, minimumSize: const Size(minTouch, minTouch), textStyle: buttonText), + ), + iconButtonTheme: IconButtonThemeData( + style: IconButton.styleFrom(foregroundColor: c.ink, minimumSize: const Size(minTouch, minTouch), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))), + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: c.surface, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + hintStyle: TextStyle(color: c.ink3, fontSize: 14), + errorStyle: TextStyle(color: c.danger, fontSize: 12), + border: border(c.line), + enabledBorder: border(c.line), + focusedBorder: border(c.brand, 2), + errorBorder: border(c.danger), + focusedErrorBorder: border(c.danger, 2), + ), + chipTheme: ChipThemeData( + backgroundColor: c.surface, + selectedColor: c.brand, + labelStyle: TextStyle(fontFamily: fontFamily, fontSize: 14, fontWeight: FontWeight.w500, color: c.ink2), + secondaryLabelStyle: TextStyle(fontFamily: fontFamily, fontSize: 14, fontWeight: FontWeight.w500, color: c.onBrand), + side: BorderSide(color: c.line), + shape: const StadiumBorder(), + showCheckmark: false, + ), + switchTheme: SwitchThemeData( + thumbColor: WidgetStatePropertyAll(c.surface), + trackColor: WidgetStateProperty.resolveWith((states) => states.contains(WidgetState.selected) ? c.brand : c.line), + trackOutlineColor: const WidgetStatePropertyAll(Colors.transparent), + ), + snackBarTheme: SnackBarThemeData(backgroundColor: c.ink, contentTextStyle: TextStyle(fontFamily: fontFamily, color: c.surface, fontSize: 14)), + progressIndicatorTheme: ProgressIndicatorThemeData(color: c.brand), + ); + } +} diff --git a/app/lib/src/core/ui/ph_app_bar.dart b/app/lib/src/core/ui/ph_app_bar.dart new file mode 100644 index 0000000..ef7306e --- /dev/null +++ b/app/lib/src/core/ui/ph_app_bar.dart @@ -0,0 +1,40 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/ui/ui_texts.dart'; + +class PhAppBar extends StatelessWidget implements PreferredSizeWidget { + final String title; + final VoidCallback? onBack; + final List actions; + + const PhAppBar({super.key, required this.title, this.onBack, this.actions = const []}); + + @override + Size get preferredSize => const Size.fromHeight(60); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return SafeArea( + bottom: false, + child: Container( + color: c.bg, + constraints: const BoxConstraints(minHeight: 56), + padding: const EdgeInsets.fromLTRB(12, 12, 12, 4), + child: Row( + children: [ + if (onBack != null) + IconButton(onPressed: onBack, tooltip: UiTexts.back, icon: const Icon(Icons.chevron_left)) + else + const SizedBox(width: 8), + const SizedBox(width: 4), + Expanded( + child: Semantics(header: true, child: Text(title, style: Theme.of(context).textTheme.titleLarge, overflow: TextOverflow.ellipsis)), + ), + ...actions, + ], + ), + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_avatar.dart b/app/lib/src/core/ui/ph_avatar.dart new file mode 100644 index 0000000..e6d1542 --- /dev/null +++ b/app/lib/src/core/ui/ph_avatar.dart @@ -0,0 +1,32 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +class PhAvatar extends StatelessWidget { + final String name; + final double size; + + const PhAvatar({super.key, required this.name, this.size = 36}); + + static String initials(String name) { + final words = name.trim().split(RegExp(r'\s+')).where((word) => word.isNotEmpty).toList(); + if (words.isEmpty) return ''; + final first = words.first[0]; + final last = words.length > 1 ? words.last[0] : ''; + return (first + last).toUpperCase(); + } + + @override + Widget build(BuildContext context) { + final c = context.ph; + return ExcludeSemantics( + child: Container( + width: size, + height: size, + alignment: Alignment.center, + decoration: BoxDecoration(color: c.accentSoft, shape: BoxShape.circle), + child: Text(initials(name), style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: size * 0.36, fontWeight: FontWeight.w600, color: c.brand)), + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_badge.dart b/app/lib/src/core/ui/ph_badge.dart new file mode 100644 index 0000000..bb2c78f --- /dev/null +++ b/app/lib/src/core/ui/ph_badge.dart @@ -0,0 +1,39 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +enum PhTone { ok, warn, danger, info, neutral } + +class PhBadge extends StatelessWidget { + final String label; + final PhTone tone; + final IconData? icon; + + const PhBadge({super.key, required this.label, this.tone = PhTone.neutral, this.icon}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + final (background, foreground) = switch (tone) { + PhTone.ok => (c.okSoft, c.ok), + PhTone.warn => (c.warnSoft, c.warn), + PhTone.danger => (c.dangerSoft, c.danger), + PhTone.info => (c.infoSoft, c.info), + PhTone.neutral => (c.surface2, c.ink2), + }; + + return Container( + constraints: const BoxConstraints(minHeight: 26), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(color: background, borderRadius: BorderRadius.circular(999)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) Icon(icon, size: 14, color: foreground) else Container(width: 6, height: 6, decoration: BoxDecoration(color: foreground, shape: BoxShape.circle)), + const SizedBox(width: 6), + Flexible(child: Text(label, style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 12, fontWeight: FontWeight.w500, color: foreground))), + ], + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_bottom_nav.dart b/app/lib/src/core/ui/ph_bottom_nav.dart new file mode 100644 index 0000000..3b1b948 --- /dev/null +++ b/app/lib/src/core/ui/ph_bottom_nav.dart @@ -0,0 +1,89 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; +import 'package:phpeste_app/src/core/ui/ui_texts.dart'; + +class PhNavDestination { + final String label; + final IconData icon; + + const PhNavDestination({required this.label, required this.icon}); +} + +class PhBottomNav extends StatelessWidget { + final List destinations; + final int currentIndex; + final int? highlightedIndex; + final ValueChanged onSelected; + + const PhBottomNav({super.key, required this.destinations, required this.currentIndex, required this.onSelected, this.highlightedIndex}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Semantics( + container: true, + label: UiTexts.navigation, + explicitChildNodes: true, + child: DecoratedBox( + decoration: BoxDecoration(color: c.surface, border: Border(top: BorderSide(color: c.line))), + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(4, 6, 4, 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + for (var i = 0; i < destinations.length; i++) + Expanded(child: _item(context, c, i)), + ], + ), + ), + ), + ), + ); + } + + Widget _item(BuildContext context, PhColors c, int index) { + final destination = destinations[index]; + final selected = index == currentIndex; + final highlighted = index == highlightedIndex; + final color = selected ? c.brand : c.ink2; + + final icon = highlighted + ? Transform.translate( + offset: const Offset(0, -14), + child: Container( + width: 56, + height: 56, + decoration: BoxDecoration(color: c.brand, shape: BoxShape.circle, border: Border.all(color: c.bg, width: 4)), + child: Icon(destination.icon, color: c.onBrand), + ), + ) + : Icon(destination.icon, color: color, weight: selected ? 700 : 400); + + return Semantics( + button: true, + selected: selected, + label: destination.label, + onTap: () => onSelected(index), + excludeSemantics: true, + child: InkWell( + onTap: () => onSelected(index), + borderRadius: BorderRadius.circular(12), + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52, minWidth: PhTheme.minTouch), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + SizedBox(height: 28, child: OverflowBox(maxHeight: 70, child: icon)), + const SizedBox(height: 2), + FittedBox(fit: BoxFit.scaleDown, child: Text(destination.label, maxLines: 1, style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 11, fontWeight: FontWeight.w500, color: color))), + ], + ), + ), + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_button.dart b/app/lib/src/core/ui/ph_button.dart new file mode 100644 index 0000000..b1a3ccd --- /dev/null +++ b/app/lib/src/core/ui/ph_button.dart @@ -0,0 +1,69 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +enum PhButtonVariant { primary, secondary, danger, accent } + +class PhButton extends StatelessWidget { + final String label; + final VoidCallback? onPressed; + final PhButtonVariant variant; + final IconData? icon; + final bool block; + final bool small; + final bool loading; + + const PhButton({ + super.key, + required this.label, + required this.onPressed, + this.variant = PhButtonVariant.primary, + this.icon, + this.block = false, + this.small = false, + this.loading = false, + }); + + @override + Widget build(BuildContext context) { + final c = context.ph; + final (background, foreground, border) = switch (variant) { + PhButtonVariant.primary => (c.brand, c.onBrand, c.brand), + PhButtonVariant.secondary => (Colors.transparent, c.ink, c.line), + PhButtonVariant.danger => (c.danger, const Color(0xFFFFFFFF), c.danger), + PhButtonVariant.accent => (c.accent, c.onAccent, c.accent), + }; + + final child = loading + ? SizedBox.square(dimension: 18, child: CircularProgressIndicator(strokeWidth: 2, color: foreground)) + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[Icon(icon, size: 20), const SizedBox(width: 8)], + Flexible(child: Text(label, textAlign: TextAlign.center)), + ], + ); + + final button = TextButton( + onPressed: loading ? null : onPressed, + style: TextButton.styleFrom( + backgroundColor: background, + foregroundColor: foreground, + disabledBackgroundColor: variant == PhButtonVariant.secondary ? Colors.transparent : background.withValues(alpha: 0.55), + disabledForegroundColor: foreground.withValues(alpha: 0.8), + minimumSize: const Size(PhTheme.minTouch, PhTheme.minTouch), + padding: EdgeInsets.symmetric(horizontal: small ? 12 : 18, vertical: small ? 8 : 12), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PhTheme.radius), side: BorderSide(color: border)), + textStyle: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: small ? 13 : 14, fontWeight: FontWeight.w500), + ), + child: child, + ); + + return Semantics( + button: true, + label: loading ? label : null, + excludeSemantics: loading, + child: block ? SizedBox(width: double.infinity, child: button) : button, + ); + } +} diff --git a/app/lib/src/core/ui/ph_card.dart b/app/lib/src/core/ui/ph_card.dart new file mode 100644 index 0000000..9da1241 --- /dev/null +++ b/app/lib/src/core/ui/ph_card.dart @@ -0,0 +1,24 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +class PhCard extends StatelessWidget { + final Widget child; + final EdgeInsetsGeometry padding; + final Color? color; + final VoidCallback? onTap; + + const PhCard({super.key, required this.child, this.padding = const EdgeInsets.all(16), this.color, this.onTap}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + final shape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(PhTheme.radiusLg), side: BorderSide(color: c.line)); + return Material( + color: color ?? c.surface, + shape: shape, + clipBehavior: Clip.antiAlias, + child: InkWell(onTap: onTap, child: Padding(padding: padding, child: child)), + ); + } +} diff --git a/app/lib/src/core/ui/ph_chip.dart b/app/lib/src/core/ui/ph_chip.dart new file mode 100644 index 0000000..dbd2582 --- /dev/null +++ b/app/lib/src/core/ui/ph_chip.dart @@ -0,0 +1,42 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +class PhChip extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback? onTap; + + const PhChip({super.key, required this.label, this.selected = false, this.onTap}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Semantics( + button: true, + selected: selected, + child: InkWell( + onTap: onTap, + customBorder: const StadiumBorder(), + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: PhTheme.minTouch, minWidth: PhTheme.minTouch), + child: Center( + widthFactor: 1, + child: Container( + constraints: const BoxConstraints(minHeight: 36), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: ShapeDecoration( + color: selected ? c.brand : c.surface, + shape: StadiumBorder(side: BorderSide(color: selected ? c.brand : c.line)), + ), + child: Text( + label, + style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 14, fontWeight: FontWeight.w500, color: selected ? c.onBrand : c.ink2), + ), + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_states.dart b/app/lib/src/core/ui/ph_states.dart new file mode 100644 index 0000000..a9e13b2 --- /dev/null +++ b/app/lib/src/core/ui/ph_states.dart @@ -0,0 +1,173 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; +import 'package:phpeste_app/src/core/ui/ph_button.dart'; +import 'package:phpeste_app/src/core/ui/ui_texts.dart'; + +class PhOfflineBanner extends StatelessWidget { + final String message; + + const PhOfflineBanner({super.key, this.message = UiTexts.offline}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Semantics( + liveRegion: true, + child: Container( + width: double.infinity, + color: c.warnSoft, + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + child: Row( + children: [ + Icon(Icons.wifi_off_rounded, color: c.warn, size: 20), + const SizedBox(width: 10), + Expanded(child: Text(message, style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 13, color: c.ink))), + ], + ), + ), + ); + } +} + +class PhMessageState extends StatelessWidget { + final IconData icon; + final String title; + final String? text; + final List actions; + + const PhMessageState({super.key, required this.icon, required this.title, this.text, this.actions = const []}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ExcludeSemantics( + child: Container( + width: 72, + height: 72, + decoration: BoxDecoration(color: c.surface2, shape: BoxShape.circle), + child: Icon(icon, color: c.brand, size: 32), + ), + ), + const SizedBox(height: 14), + Semantics(header: true, child: Text(title, textAlign: TextAlign.center, style: Theme.of(context).textTheme.titleLarge)), + if (text != null) ...[ + const SizedBox(height: 14), + Text(text!, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: c.ink2)), + ], + for (final action in actions) ...[const SizedBox(height: 14), action], + ], + ), + ), + ); + } +} + +class PhErrorState extends StatelessWidget { + final VoidCallback onRetry; + final String title; + final String text; + + const PhErrorState({super.key, required this.onRetry, this.title = UiTexts.errorTitle, this.text = UiTexts.errorText}); + + @override + Widget build(BuildContext context) { + return PhMessageState( + icon: Icons.cloud_off_rounded, + title: title, + text: text, + actions: [PhButton(label: UiTexts.retry, icon: Icons.refresh_rounded, onPressed: onRetry)], + ); + } +} + +class PhSkeleton extends StatelessWidget { + final double width; + final double height; + + const PhSkeleton({super.key, this.width = double.infinity, required this.height}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Container( + width: width, + height: height, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + gradient: LinearGradient(colors: [c.surface2, c.line, c.surface2]), + ), + ); + } +} + +class PhLoadingList extends StatelessWidget { + final String label; + final int items; + + const PhLoadingList({super.key, this.label = UiTexts.loading, this.items = 4}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Semantics( + label: label, + liveRegion: true, + child: ExcludeSemantics( + child: ListView( + padding: const EdgeInsets.all(20), + physics: const NeverScrollableScrollPhysics(), + children: [ + const FractionallySizedBox(alignment: Alignment.centerLeft, widthFactor: 0.6, child: PhSkeleton(height: 36)), + for (var i = 0; i < items; i++) + Container( + margin: const EdgeInsets.only(top: 14), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration(color: c.surface, borderRadius: BorderRadius.circular(PhTheme.radiusLg), border: Border.all(color: c.line)), + child: const Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: 52, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [PhSkeleton(height: 18), SizedBox(height: 8), PhSkeleton(width: 36, height: 12)])), + SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FractionallySizedBox(widthFactor: 0.9, child: PhSkeleton(height: 18)), + SizedBox(height: 10), + FractionallySizedBox(widthFactor: 0.6, child: PhSkeleton(height: 12)), + SizedBox(height: 10), + FractionallySizedBox(widthFactor: 0.4, child: PhSkeleton(height: 12)), + ], + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class PhStripe extends StatelessWidget { + const PhStripe({super.key}); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return ExcludeSemantics( + child: SizedBox( + height: 8, + child: Row(children: [for (var i = 0; i < 40; i++) Expanded(child: ColoredBox(color: i.isEven ? c.accent : c.terra))]), + ), + ); + } +} diff --git a/app/lib/src/core/ui/ph_text_field.dart b/app/lib/src/core/ui/ph_text_field.dart new file mode 100644 index 0000000..21595e1 --- /dev/null +++ b/app/lib/src/core/ui/ph_text_field.dart @@ -0,0 +1,67 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; + +class PhTextField extends StatelessWidget { + final String label; + final String? hint; + final String? placeholder; + final String? error; + final TextEditingController? controller; + final ValueChanged? onChanged; + final TextInputType? keyboardType; + final bool obscureText; + final int maxLines; + final Iterable? autofillHints; + final TextInputAction? textInputAction; + final Widget? suffix; + + const PhTextField({ + super.key, + required this.label, + this.hint, + this.placeholder, + this.error, + this.controller, + this.onChanged, + this.keyboardType, + this.obscureText = false, + this.maxLines = 1, + this.autofillHints, + this.textInputAction, + this.suffix, + }); + + @override + Widget build(BuildContext context) { + final c = context.ph; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 14, fontWeight: FontWeight.w500, color: c.ink)), + const SizedBox(height: 6), + TextField( + controller: controller, + onChanged: onChanged, + keyboardType: keyboardType, + obscureText: obscureText, + maxLines: obscureText ? 1 : maxLines, + autofillHints: autofillHints, + textInputAction: textInputAction, + style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 16, color: c.ink), + decoration: InputDecoration( + semanticCounterText: '', + hintText: placeholder, + errorText: error, + suffixIcon: suffix, + constraints: const BoxConstraints(minHeight: PhTheme.minTouch), + ), + ), + if (hint != null && error == null) ...[ + const SizedBox(height: 4), + Text(hint!, style: TextStyle(fontFamily: PhTheme.fontFamily, fontSize: 12, color: c.ink3)), + ], + ], + ); + } +} diff --git a/app/lib/src/core/ui/ui_texts.dart b/app/lib/src/core/ui/ui_texts.dart new file mode 100644 index 0000000..031eb41 --- /dev/null +++ b/app/lib/src/core/ui/ui_texts.dart @@ -0,0 +1,9 @@ +class UiTexts { + static const String back = 'Voltar'; + static const String retry = 'Tentar de novo'; + static const String offline = 'Sem internet. Mostrando o que está salvo.'; + static const String errorTitle = 'Não deu para carregar'; + static const String errorText = 'Algo falhou do nosso lado. Seus dados salvos continuam seguros.'; + static const String loading = 'Carregando'; + static const String navigation = 'Principal'; +} diff --git a/app/lib/src/core/utils/endpoints.dart b/app/lib/src/core/utils/endpoints.dart index 537f354..78a82c6 100644 --- a/app/lib/src/core/utils/endpoints.dart +++ b/app/lib/src/core/utils/endpoints.dart @@ -4,4 +4,6 @@ class Endpoints { static const String baseUrl = AppConfig.apiUrl; static const String login = '$baseUrl/auth/login'; static const String register = '$baseUrl/auth/register'; + + static String editionTheme(String editionId) => '$baseUrl/public/editions/$editionId/theme'; } diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 14384d5..114b41a 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -78,6 +78,16 @@ flutter: # the material Icons class. uses-material-design: true + fonts: + - family: Lexend + fonts: + - asset: assets/fonts/lexend/Lexend-Regular.ttf + weight: 400 + - asset: assets/fonts/lexend/Lexend-Medium.ttf + weight: 500 + - asset: assets/fonts/lexend/Lexend-SemiBold.ttf + weight: 600 + # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg diff --git a/app/test/flutter_test_config.dart b/app/test/flutter_test_config.dart new file mode 100644 index 0000000..d962d8a --- /dev/null +++ b/app/test/flutter_test_config.dart @@ -0,0 +1,47 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Future testExecutable(FutureOr Function() testMain) async { + TestWidgetsFlutterBinding.ensureInitialized(); + + final lexend = FontLoader('Lexend'); + for (final file in ['Regular', 'Medium', 'SemiBold']) { + lexend.addFont(rootBundle.load('assets/fonts/lexend/Lexend-$file.ttf')); + } + await lexend.load(); + + final flutterRoot = Platform.environment['FLUTTER_ROOT']; + final icons = File('$flutterRoot/bin/cache/artifacts/material_fonts/MaterialIcons-Regular.otf'); + if (flutterRoot != null && icons.existsSync()) { + final loader = FontLoader('MaterialIcons')..addFont(Future.value(ByteData.sublistView(icons.readAsBytesSync()))); + await loader.load(); + } + + if (goldenFileComparator is LocalFileComparator) { + goldenFileComparator = TolerantGoldenComparator((goldenFileComparator as LocalFileComparator).basedir.resolve('golden_test.dart')); + } + + await testMain(); +} + +class TolerantGoldenComparator extends LocalFileComparator { + static const double tolerance = 0.005; + + TolerantGoldenComparator(super.testFile); + + @override + Future compare(Uint8List imageBytes, Uri golden) async { + final result = await GoldenFileComparator.compareLists(imageBytes, await getGoldenBytes(golden)); + if (result.passed || result.diffPercent <= tolerance) { + result.dispose(); + return true; + } + final error = await generateFailureOutput(result, golden, basedir); + result.dispose(); + throw FlutterError(error); + } +} diff --git a/app/test/golden/components_golden_test.dart b/app/test/golden/components_golden_test.dart new file mode 100644 index 0000000..ffb988d --- /dev/null +++ b/app/test/golden/components_golden_test.dart @@ -0,0 +1,56 @@ +@Tags(['golden']) +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/app/features/component_catalog/presentation/pages/component_catalog_page.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; +import 'package:phpeste_app/src/core/ui/ph_app_bar.dart'; +import 'package:phpeste_app/src/core/ui/ph_button.dart'; +import 'package:phpeste_app/src/core/ui/ph_states.dart'; + +Future screen(WidgetTester tester, Widget child, {PhColors colors = PhColors.sertao, Size size = const Size(390, 844)}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(MaterialApp(debugShowCheckedModeBanner: false, theme: PhTheme.build(colors), home: child)); + await tester.pump(const Duration(milliseconds: 400)); +} + +void main() { + testWidgets('catálogo no tema Sertão', (tester) async { + await screen(tester, const ComponentCatalogPage(), size: const Size(390, 1900)); + await expectLater(find.byType(ComponentCatalogPage), matchesGoldenFile('goldens/catalogo_sertao.png')); + }); + + testWidgets('catálogo com o tema de uma edição', (tester) async { + await screen(tester, const ComponentCatalogPage(), size: const Size(390, 1900)); + await tester.tap(find.byType(Switch)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + await expectLater(find.byType(ComponentCatalogPage), matchesGoldenFile('goldens/catalogo_edicao.png')); + }); + + testWidgets('estados: sem ingresso, offline e erro', (tester) async { + await screen( + tester, + Scaffold( + appBar: const PhAppBar(title: 'Meu ingresso'), + body: Column(children: [ + const PhOfflineBanner(), + Expanded( + child: PhMessageState( + icon: Icons.confirmation_number_outlined, + title: 'Você ainda não tem ingresso', + text: 'Quando a compra for confirmada, o QR aparece aqui. Comprou com outro e-mail?', + actions: [PhButton(label: 'Entrar com outro e-mail', onPressed: () {})], + ), + ), + SizedBox(height: 300, child: PhErrorState(onRetry: () {})), + ]), + ), + ); + await expectLater(find.byType(Scaffold), matchesGoldenFile('goldens/estados.png')); + }); +} diff --git a/app/test/golden/goldens/catalogo_edicao.png b/app/test/golden/goldens/catalogo_edicao.png new file mode 100644 index 0000000..bf4cce5 Binary files /dev/null and b/app/test/golden/goldens/catalogo_edicao.png differ diff --git a/app/test/golden/goldens/catalogo_sertao.png b/app/test/golden/goldens/catalogo_sertao.png new file mode 100644 index 0000000..653b6b2 Binary files /dev/null and b/app/test/golden/goldens/catalogo_sertao.png differ diff --git a/app/test/golden/goldens/estados.png b/app/test/golden/goldens/estados.png new file mode 100644 index 0000000..2a111f5 Binary files /dev/null and b/app/test/golden/goldens/estados.png differ diff --git a/app/test/unit/core/theme/ph_colors_test.dart b/app/test/unit/core/theme/ph_colors_test.dart new file mode 100644 index 0000000..13df11f --- /dev/null +++ b/app/test/unit/core/theme/ph_colors_test.dart @@ -0,0 +1,77 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/contrast.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; + +void main() { + const sertao = PhColors.sertao; + + group('contraste', () { + test('preto sobre branco é 21:1 e cores iguais são 1:1', () { + expect(contrastRatio(const Color(0xFF000000), const Color(0xFFFFFFFF)), closeTo(21, 0.01)); + expect(contrastRatio(sertao.brand, sertao.brand), closeTo(1, 0.001)); + }); + + test('pares de texto do tema Sertão passam de 4,5:1', () { + final pairs = [ + (sertao.ink, sertao.bg), (sertao.ink, sertao.surface), (sertao.ink2, sertao.bg), (sertao.ink3, sertao.surface), + (sertao.onBrand, sertao.brand), (sertao.onAccent, sertao.accent), (sertao.link, sertao.surface), + (sertao.ok, sertao.okSoft), (sertao.warn, sertao.warnSoft), (sertao.danger, sertao.dangerSoft), (sertao.info, sertao.infoSoft), + ]; + for (final (foreground, background) in pairs) { + expect(contrastRatio(foreground, background), greaterThanOrEqualTo(4.5), reason: '$foreground sobre $background'); + } + }); + + test('só aceita cor #RRGGBB', () { + expect(parseHexColor('#1F4E79'), const Color(0xFF1F4E79)); + expect(parseHexColor('1F4E79'), isNull); + expect(parseHexColor('#FFF'), isNull); + expect(parseHexColor('red;}'), isNull); + expect(parseHexColor(null), isNull); + }); + }); + + group('withEdition', () { + test('usa marca, destaque e apoio da edição quando são legíveis', () { + final edition = sertao.withEdition( + brand: const Color(0xFF1F4E79), + onBrand: const Color(0xFFFFFFFF), + accent: const Color(0xFF7FC8C2), + onAccent: const Color(0xFF10263A), + support: const Color(0xFF2E6B5E), + ); + + expect(edition.brand, const Color(0xFF1F4E79)); + expect(edition.onBrand, const Color(0xFFFFFFFF)); + expect(edition.accent, const Color(0xFF7FC8C2)); + expect(edition.terra, const Color(0xFF2E6B5E)); + expect(edition.ink, sertao.ink); + expect(edition.ok, sertao.ok); + expect(edition.danger, sertao.danger); + }); + + test('marca sem contraste com o texto ou com o fundo cai para o Sertão', () { + final lowText = sertao.withEdition(brand: const Color(0xFF4FA3E0), onBrand: const Color(0xFFFFFFFF)); + final lowBackground = sertao.withEdition(brand: const Color(0xFFF7EFD9), onBrand: const Color(0xFF3A1607)); + + expect(lowText.brand, sertao.brand); + expect(lowText.onBrand, sertao.onBrand); + expect(lowBackground.brand, sertao.brand); + }); + + test('destaque sem texto legível cai para o Sertão, sem mexer na marca', () { + final edition = sertao.withEdition(brand: const Color(0xFF1F4E79), onBrand: const Color(0xFFFFFFFF), accent: const Color(0xFFFFEE58), onAccent: const Color(0xFFFFFFFF)); + + expect(edition.brand, const Color(0xFF1F4E79)); + expect(edition.accent, sertao.accent); + }); + + test('sem cores da edição fica igual ao Sertão', () { + final edition = sertao.withEdition(); + expect(edition.brand, sertao.brand); + expect(edition.accent, sertao.accent); + expect(edition.terra, sertao.terra); + }); + }); +} diff --git a/app/test/unit/edition_theme/edition_theme_test.dart b/app/test/unit/edition_theme/edition_theme_test.dart new file mode 100644 index 0000000..25a1ef1 --- /dev/null +++ b/app/test/unit/edition_theme/edition_theme_test.dart @@ -0,0 +1,168 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_local_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/datasources/edition_branding_remote_datasource.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/models/edition_branding_model.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/data/repositories/edition_branding_repository_impl.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/entities/edition_branding_entity.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/repositories/edition_branding_repository_interface.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/domain/usecases/get_edition_branding_usecase.dart'; +import 'package:phpeste_app/src/app/features/edition_theme/presentation/bloc/edition_theme_bloc.dart'; +import 'package:phpeste_app/src/core/cache/cache.dart'; +import 'package:phpeste_app/src/core/client_http/client_http.dart'; +import 'package:phpeste_app/src/core/errors/errors.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:result_dart/result_dart.dart'; + +class MockRemote extends Mock implements EditionBrandingRemoteDatasource {} + +class MockRepository extends Mock implements IEditionBrandingRepository {} + +class MemoryCache implements ICache { + final Map data = {}; + + @override + Future clean() async { + data.clear(); + return true; + } + + @override + Future getData(String key) async => data[key]; + + @override + Future removeData(String key) async { + data.remove(key); + return true; + } + + @override + Future setData({required CacheParams params}) async { + data[params.key] = params.value; + return true; + } +} + +Map payload({Map? colors, Map? logos}) => { + 'data': { + 'edition_id': 'ed-1', + 'theme': { + 'colors': colors ?? {'brand': '#1F4E79', 'on_brand': '#FFFFFF', 'accent': '#7FC8C2', 'on_accent': '#10263A', 'support': '#2E6B5E', 'ink': '#000000'}, + 'fonts': {'heading': 'Inter', 'body': 'Inter'}, + 'radius': 6, + 'logos': logos ?? {'primary': 'https://cdn.exemplo.dev/logo.png', 'dark': null, 'favicon': null, 'app_icon': null}, + }, + 'published_at': '2027-01-10T12:00:00Z', + }, + }; + +RestClientResponse response(int status, dynamic data) => RestClientResponse(request: RestClientRequest(path: '/theme'), data: data, statusCode: status); + +void main() { + group('EditionBrandingModel', () { + test('lê marca, destaque, apoio e logo do tema publicado', () { + final model = EditionBrandingModel.fromApi(payload()); + expect(model.editionId, 'ed-1'); + expect(model.brand, 0xFF1F4E79); + expect(model.onAccent, 0xFF10263A); + expect(model.support, 0xFF2E6B5E); + expect(model.logoUrl, 'https://cdn.exemplo.dev/logo.png'); + }); + + test('ignora cor fora de #RRGGBB e logo sem https', () { + final model = EditionBrandingModel.fromApi(payload(colors: {'brand': 'red;}', 'accent': '#FFF'}, logos: {'primary': 'javascript:alert(1)'})); + expect(model.brand, isNull); + expect(model.accent, isNull); + expect(model.logoUrl, isNull); + }); + + test('ida e volta pelo armazenamento local', () { + final model = EditionBrandingModel.fromApi(payload()); + expect(EditionBrandingModel.fromJson(model.toJson()), model); + }); + }); + + group('EditionBrandingRepositoryImpl', () { + late MockRemote remote; + late MemoryCache cache; + late EditionBrandingRepositoryImpl repository; + + setUp(() { + remote = MockRemote(); + cache = MemoryCache(); + repository = EditionBrandingRepositoryImpl(remote: remote, local: EditionBrandingLocalDatasource(cache: cache)); + }); + + test('busca na API e guarda para abrir sem internet', () async { + when(() => remote.theme('ed-1')).thenAnswer((_) async => response(200, payload())); + + final result = await repository.branding('ed-1'); + + expect(result.getOrNull()?.brand, 0xFF1F4E79); + expect(cache.data['edition_branding.ed-1'], isA()); + }); + + test('sem internet, devolve o tema guardado', () async { + when(() => remote.theme('ed-1')).thenAnswer((_) async => response(200, payload())); + await repository.branding('ed-1'); + when(() => remote.theme('ed-1')).thenThrow(RestClientException(message: 'offline', error: null)); + + final result = await repository.branding('ed-1'); + + expect(result.getOrNull()?.logoUrl, 'https://cdn.exemplo.dev/logo.png'); + }); + + test('edição não publicada e nada guardado é falha', () async { + when(() => remote.theme('ed-2')).thenAnswer((_) async => response(404, {'code': 'not_found'})); + + final result = await repository.branding('ed-2'); + + expect(result.exceptionOrNull(), isA()); + }); + }); + + group('EditionThemeBloc', () { + late MockRepository repository; + + setUp(() => repository = MockRepository()); + + blocTest( + 'aplica as cores legíveis da edição', + build: () { + when(() => repository.branding('ed-1')).thenAnswer((_) async => Success(EditionBrandingModel.fromApi(payload()))); + return EditionThemeBloc(getBranding: GetEditionBrandingUsecase(repository: repository)); + }, + act: (bloc) => bloc.add(const EditionThemeRequested('ed-1')), + verify: (bloc) { + expect(bloc.state.editionId, 'ed-1'); + expect(bloc.state.colors.brand, const Color(0xFF1F4E79)); + expect(bloc.state.colors.ink, PhColors.sertao.ink); + expect(bloc.state.logoUrl, 'https://cdn.exemplo.dev/logo.png'); + }, + ); + + blocTest( + 'sem tema da edição fica no Sertão', + build: () { + when(() => repository.branding('ed-1')).thenAnswer((_) async => Failure(NotFoundException(message: 'x'))); + return EditionThemeBloc(getBranding: GetEditionBrandingUsecase(repository: repository)); + }, + act: (bloc) => bloc.add(const EditionThemeRequested('ed-1')), + verify: (bloc) { + expect(bloc.state.editionId, 'ed-1'); + expect(bloc.state.colors.brand, PhColors.sertao.brand); + expect(bloc.state.logoUrl, isNull); + }, + ); + + blocTest( + 'trocar de conta volta ao Sertão', + build: () => EditionThemeBloc(getBranding: GetEditionBrandingUsecase(repository: repository)), + seed: () => EditionThemeBloc.stateFor(const EditionBrandingEntity(editionId: 'ed-1', brand: 0xFF1F4E79, onBrand: 0xFFFFFFFF)), + act: (bloc) => bloc.add(const EditionThemeCleared()), + expect: () => [const EditionThemeState()], + ); + }); +} diff --git a/app/test/widget/ui/components_test.dart b/app/test/widget/ui/components_test.dart new file mode 100644 index 0000000..a5a3d9d --- /dev/null +++ b/app/test/widget/ui/components_test.dart @@ -0,0 +1,136 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:phpeste_app/src/core/theme/ph_colors.dart'; +import 'package:phpeste_app/src/core/theme/ph_theme.dart'; +import 'package:phpeste_app/src/core/ui/ph_app_bar.dart'; +import 'package:phpeste_app/src/core/ui/ph_avatar.dart'; +import 'package:phpeste_app/src/core/ui/ph_badge.dart'; +import 'package:phpeste_app/src/core/ui/ph_bottom_nav.dart'; +import 'package:phpeste_app/src/core/ui/ph_button.dart'; +import 'package:phpeste_app/src/core/ui/ph_chip.dart'; +import 'package:phpeste_app/src/core/ui/ph_states.dart'; + +Widget wrap(Widget child, {PhColors colors = PhColors.sertao}) => MaterialApp(theme: PhTheme.build(colors), home: Scaffold(body: Center(child: child))); + +void expectTouchTarget(WidgetTester tester, Finder finder) { + final size = tester.getSize(finder); + expect(size.height, greaterThanOrEqualTo(PhTheme.minTouch), reason: 'altura de ${finder.describeMatch(Plurality.one)}'); + expect(size.width, greaterThanOrEqualTo(PhTheme.minTouch), reason: 'largura de ${finder.describeMatch(Plurality.one)}'); +} + +const destinations = [ + PhNavDestination(label: 'Início', icon: Icons.home_outlined), + PhNavDestination(label: 'Programação', icon: Icons.calendar_month_outlined), + PhNavDestination(label: 'Ingresso', icon: Icons.confirmation_number_outlined), + PhNavDestination(label: 'Agenda', icon: Icons.bookmark_border_rounded), + PhNavDestination(label: 'Perfil', icon: Icons.person_outline_rounded), +]; + +void main() { + testWidgets('botões, inclusive o pequeno, têm alvo de 44 px', (tester) async { + await tester.pumpWidget(wrap(Column(mainAxisSize: MainAxisSize.min, children: [ + PhButton(label: 'Entrar', onPressed: () {}), + PhButton(label: 'Ok', small: true, onPressed: () {}), + PhButton(label: 'Sair', variant: PhButtonVariant.secondary, onPressed: () {}), + ]))); + + for (final label in ['Entrar', 'Ok', 'Sair']) { + expectTouchTarget(tester, find.ancestor(of: find.text(label), matching: find.byType(TextButton))); + } + }); + + testWidgets('botão carregando não dispara de novo e mantém o nome para leitor de tela', (tester) async { + var taps = 0; + await tester.pumpWidget(wrap(PhButton(label: 'Enviar', loading: true, onPressed: () => taps++))); + + await tester.tap(find.byType(TextButton)); + expect(taps, 0); + expect(find.bySemanticsLabel('Enviar'), findsOneWidget); + }); + + testWidgets('chip tem alvo de 44 px e anuncia quando está selecionado', (tester) async { + final semantics = tester.ensureSemantics(); + var tapped = false; + await tester.pumpWidget(wrap(PhChip(label: 'Backend', selected: true, onTap: () => tapped = true))); + + expectTouchTarget(tester, find.byType(InkWell)); + expect(tester.getSemantics(find.byType(PhChip)), matchesSemantics(label: 'Backend', isButton: true, isSelected: true, hasSelectedState: true, hasTapAction: true, isFocusable: true, hasFocusAction: true)); + await tester.tap(find.text('Backend')); + expect(tapped, isTrue); + semantics.dispose(); + }); + + testWidgets('estado do badge sempre vem com texto', (tester) async { + await tester.pumpWidget(wrap(const Column(mainAxisSize: MainAxisSize.min, children: [ + PhBadge(label: 'Válido', tone: PhTone.ok), + PhBadge(label: 'Recusado', tone: PhTone.danger, icon: Icons.close), + ]))); + + expect(find.text('Válido'), findsOneWidget); + expect(find.text('Recusado'), findsOneWidget); + }); + + testWidgets('barra inferior: 5 destinos com 44 px, o atual selecionado e o ingresso em destaque', (tester) async { + final semantics = tester.ensureSemantics(); + int? selected; + await tester.pumpWidget(MaterialApp( + theme: PhTheme.build(PhColors.sertao), + home: Scaffold(bottomNavigationBar: PhBottomNav(destinations: destinations, currentIndex: 1, highlightedIndex: 2, onSelected: (index) => selected = index)), + )); + + for (final destination in destinations) { + expectTouchTarget(tester, find.ancestor(of: find.text(destination.label), matching: find.byType(InkWell))); + } + expect(tester.getSemantics(find.bySemanticsLabel('Programação')), matchesSemantics(label: 'Programação', isButton: true, isSelected: true, hasSelectedState: true, hasTapAction: true)); + + await tester.tap(find.text('Ingresso')); + expect(selected, 2); + final highlight = tester.widget(find.descendant(of: find.ancestor(of: find.text('Ingresso'), matching: find.byType(Column)), matching: find.byWidgetPredicate((w) => w is Container && w.decoration is BoxDecoration && (w.decoration as BoxDecoration).shape == BoxShape.circle))); + expect((highlight.decoration as BoxDecoration).color, PhColors.sertao.brand); + semantics.dispose(); + }); + + testWidgets('barra superior com voltar de 44 px e título como cabeçalho', (tester) async { + var back = false; + await tester.pumpWidget(MaterialApp(theme: PhTheme.build(PhColors.sertao), home: Scaffold(appBar: PhAppBar(title: 'Sessão', onBack: () => back = true)))); + + expectTouchTarget(tester, find.byTooltip('Voltar')); + await tester.tap(find.byTooltip('Voltar')); + expect(back, isTrue); + }); + + testWidgets('erro oferece tentar de novo e offline avisa o que está salvo', (tester) async { + var retried = false; + await tester.pumpWidget(MaterialApp( + theme: PhTheme.build(PhColors.sertao), + home: Scaffold(body: Column(children: [const PhOfflineBanner(), Expanded(child: PhErrorState(onRetry: () => retried = true))])), + )); + + expect(find.text('Sem internet. Mostrando o que está salvo.'), findsOneWidget); + expect(find.text('Não deu para carregar'), findsOneWidget); + await tester.tap(find.text('Tentar de novo')); + expect(retried, isTrue); + }); + + testWidgets('carregando é anunciado uma vez, sem ler os blocos', (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(MaterialApp(theme: PhTheme.build(PhColors.sertao), home: const Scaffold(body: PhLoadingList(label: 'Carregando programação')))); + + expect(find.bySemanticsLabel('Carregando programação'), findsOneWidget); + semantics.dispose(); + }); + + test('iniciais do avatar', () { + expect(PhAvatar.initials('Ana Beatriz Lima'), 'AL'); + expect(PhAvatar.initials('marina'), 'M'); + expect(PhAvatar.initials(' '), ''); + }); + + testWidgets('tema da edição muda a marca dos componentes', (tester) async { + final edition = PhColors.sertao.withEdition(brand: const Color(0xFF1F4E79), onBrand: const Color(0xFFFFFFFF)); + await tester.pumpWidget(wrap(PhButton(label: 'Entrar', onPressed: () {}), colors: edition)); + + final style = tester.widget(find.byType(TextButton)).style!; + expect(style.backgroundColor!.resolve({}), const Color(0xFF1F4E79)); + }); +} diff --git a/docs/arquitetura/PHPeste_Arquitetura.pdf b/docs/arquitetura/PHPeste_Arquitetura.pdf index 5d98132..21bc80f 100644 Binary files a/docs/arquitetura/PHPeste_Arquitetura.pdf and b/docs/arquitetura/PHPeste_Arquitetura.pdf differ diff --git a/docs/arquitetura/README.md b/docs/arquitetura/README.md index 37592dd..43b7441 100644 --- a/docs/arquitetura/README.md +++ b/docs/arquitetura/README.md @@ -25,7 +25,7 @@ | 19 | Telas: organização (patrocinadores, fornecedores, finanças, tarefas, comunicação; cresce a cada tela do Marco 2) | | 20 | Onde estamos e o que falta | -Retrato de 28/11/2026, com a base do app Flutter (M01) e o Marco 5 no roadmap. +Retrato de 28/11/2026, com a base, o tema e os componentes do app Flutter (M01 e M02). ## Como atualizar diff --git a/docs/arquitetura/fonte/arquitetura.html b/docs/arquitetura/fonte/arquitetura.html index b875710..4ce2c43 100644 --- a/docs/arquitetura/fonte/arquitetura.html +++ b/docs/arquitetura/fonte/arquitetura.html @@ -108,7 +108,7 @@

Conteúdo

chamada ou dependência assíncrono (evento, fila, webhook) -
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.28/11/2026 · M01 (base do app) · página 1
+
Fonte: código da main, backend/CLAUDE.md, docs/produto.md e ADRs 0001–0009.28/11/2026 · M02 (tema e componentes do app) · página 1
@@ -135,7 +135,7 @@

Visão geral do sistema

App Flutter participante, palestrante -e check-in · base pronta +e check-in · base e tema Gateways (webhooks) Asaas e Mercado Pago @@ -216,7 +216,7 @@

Visão geral do sistema

  • Painel e site são projetos separados (decisão: front-admin SPA, front-public SSR). O token é Bearer do Sanctum nos dois (ADR 0005).
  • Fila e agendador rodam a mesma imagem do backend (horizon e scheduler no infra/docker-compose.yml).
-
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 2
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 2
@@ -291,7 +291,7 @@

Tenancy: comunidade, edição e o que é global

community_id
  • Por que não um banco por comunidade: a mesma pessoa palestra no PHPeste de um ano e compra ingresso no outro, e o perfil dela é um só.
  • Dado de edição que vai para a próxima ("criar edição a partir da anterior") é copiado por um EditionCloner de cada módulo, nunca dado de pessoa.
-
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 3
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 3
@@ -359,7 +359,7 @@

Como uma requisição encontra a edição

O site chama /public/resolve com o host da requisição, recebe edition_id e o domínio principal e redireciona se for preciso (ADR 0008). O host é normalizado (minúsculas, sem porta, IDN em punycode) e nunca é usado para montar URL sem passar pela tabela edition_domains. -
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 4
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 4
@@ -425,7 +425,7 @@

Ciclo de vida da edição

palestrantes, patrocínio, fornecedores), pendências com caminho e filtro (propostas sem revisor, divergência na conciliação, entregas e despesas vencidas) e marcos. O Community filtra cada pendência pela permissão de quem vê: o voluntário não vê pendência de finanças. -
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 5
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 5
@@ -524,7 +524,7 @@

Os 15 módulos do backend

casca -
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 6
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 6
@@ -591,7 +591,7 @@

Como os módulos conversam

EditionMailer::send(...): todo e-mail, com o tema; ::preview mostra sem enviar
  • Ponto de extensão é registrado com $app->tag([...], Contrato::TAG): o Community não conhece os módulos, só a tag. Módulo novo aparece na Visão geral e na clonagem sem mexer no Community. O mesmo vale para TaskLinkProvider (Tasks): Suppliers e Sponsors registram o que uma tarefa pode apontar, e o Program vai registrar a sessão.
-
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 7
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 7
@@ -693,7 +693,7 @@

Banco de dados por domínio

cache · cache_locks sessions
  • Dinheiro sempre em centavos (inteiro). Dado sensível cifrado no banco: CPF de quem compra, credenciais do gateway, acessibilidade, corpo de webhook, linhas de importação. APP_PREVIOUS_KEYS + comandos *:reencrypt-* para trocar a chave.
  • Estoque e cupom nunca são lidos e depois gravados: UPDATE … WHERE allocated + q <= quantity. Testes com 12 processos simultâneos provam que não vende além do lote.
-
PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 8
+
PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 8
@@ -714,7 +714,7 @@

Como funciona

  • Palestrante e participante não têm papel: entram pelas rotas de edição publicada.
  • -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 9
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 9
    @@ -789,7 +789,7 @@

    Ingresso: da compra ao QR

    ticketing:expire-orders (1/min) devolve estoque de reserva vencida · ticketing:rotate-batches abre o próximo lote payments:retry-webhooks (1, 5, 15, 60 min) · ticketing:reconcile (diário) grava divergência com o gateway
    • No site, /ingressos confere o cupom na hora e valida os dados de cada participante antes de reservar; a mesma tentativa repete a mesma Idempotency-Key. A reserva aparece em /checkout/pedido/{id} com contagem regressiva (o token do pedido fica só no navegador de quem comprou); ao expirar, volta para a escolha com a mensagem e a escolha anterior. O pagamento mostra quem recebe, gera o Pix (QR, copia e cola, validade) ou leva o cartão para a página do gateway; no Mercado Pago o cartão é digitado nos campos do próprio SDK e só o token chega à API. O status é consultado com espera crescente e, pago, a tela mostra os ingressos com QR (GET …/orders/{id}/tickets, com o token do pedido).
    • Depois da compra, a conta do participante (/conta/ingressos, o link dos e-mails de ingresso) lista os ingressos com QR pelas rotas /attendee/editions/{id}/tickets: salvar a imagem, imprimir, editar o crachá e transferir por e-mail. A transferência sobe a versão do QR e o anterior passa a ser recusado no check-in (replaced) na hora; a tela apaga o QR antigo também da cópia guardada no aparelho. Essa cópia, mais um service worker que guarda só /conta/ingressos e os arquivos dela, mantém o QR visível sem internet depois da primeira abertura. GET /attendee/editions/{id}/orders traz os pedidos e reembolsos de quem comprou.
    • Reembolso: PaymentLedger::refund reserva o valor antes de chamar o gateway (dois reembolsos ao mesmo tempo nunca passam do pago). Pedido importado de outra plataforma entra pago, sem cobrança, e não passa por reembolso nem conciliação. Pagamento recebido fora do gateway é marcado à mão pela organização (MarkOrderPaid), com justificativa na auditoria, emissão dos ingressos e cancelamento da cobrança aberta.
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 10
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 10
    @@ -865,7 +865,7 @@

    CFP: da proposta à grade

    Configurar CFP (A10) · Avaliar propostas com teclado (A11) · Palestrantes: lista, cobertura e detalhe (A12) · no site público: formulário de proposta e área do palestrante com entrar pelo GitHub (P03, P11). -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 11
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 11
    @@ -918,7 +918,7 @@

    Dinheiro: patrocínio, fornecedores e finanças

    ADR 0009: a plataforma não recebe nem repassa dinheiro Cada edição cadastra a conta do próprio gateway; a API valida as chaves e um webhook assinado antes de abrir vendas. Credenciais cifradas; a API só mostra os 4 últimos caracteres. -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 12
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 12
    @@ -948,7 +948,7 @@

    Auditoria

  • Segredo removido, dado pessoal mascarado; o model recusa update e delete.
  • -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 13
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 13
    @@ -958,7 +958,7 @@

    Segurança

    TemaComo está
    AutenticaçãoSanctum Bearer, um token por dispositivo com expiração (SANCTUM_EXPIRATION_MINUTES); revogar é imediato. Senha mínima de 10 e checagem de vazamento.
    IsolamentoEscopo global por edição; outra comunidade recebe 404; arch test impede módulo de depender de App\ e controller de usar $request->all().
    Rate limitLimiters nomeados: login, password-reset, checkout, webhooks, configuráveis por .env.
    Headers e CORSCSP, HSTS, nosniff, Referrer-Policy, Permissions-Policy. CORS por ambiente e, em /public/*, só a origem do site próprio da edição.
    Dados sensíveisCifrados no banco (CPF, credenciais, acessibilidade, webhooks). Logs JSON com password, token, secret e cartão redigidos automaticamente.
    ArquivosDisco privado; download só por URL assinada que expira (10 min), sempre como anexo, com nosniff e CSP sandbox. SVG sanitizado.
    PagamentoSem dado de cartão na API; webhook com assinatura do driver e reconsulta ao gateway; idempotência no banco (unique(edition_id, idempotency_key)).
    SegredosADR 0006: nada de segredo no repositório; APP_PREVIOUS_KEYS para trocar a chave sem perder o que já foi cifrado.
    LGPDEncarregado e política por edição, anonimização após o evento (B43 em aberto). Decisão em aberto: comunidade controladora, PHPeste operador.
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 14
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 14
    @@ -1033,7 +1033,7 @@

    Desenvolvimento, CI e deploy

    Em aberto para o evento teste de carga, backups, runbook do dia do evento (B45) · dados de demonstração e documentação publicada (B46) -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 15
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 15
    @@ -1046,7 +1046,7 @@

    Telas: o design do painel

    Tokens do tema Sertão
    Design: tokens do tema Sertão
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 16
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 16
    @@ -1060,7 +1060,7 @@

    Telas: o painel em uso

    Login
    Entrar com e-mail e senha ou GitHub
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 17
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 17
    @@ -1070,7 +1070,7 @@

    Telas: vendas

    Ingressos: tipos e lotes com o preço, o que a edição recebe depois da taxa do gateway, vendidos e situação. Cupons e regras da venda nas outras abas.
    Pedidos: números da edição no topo (pagos, aguardando, reembolsos, taxa do gateway), busca e filtro por situação, e o detalhe com itens, pagamento, reembolsos e histórico (auditoria). Reembolso com aviso de taxa e confirmação explícita; marcar como pago exige justificativa.
    Pagamentos (só a organização): gateway da comunidade com chave mascarada, etapas para abrir vendas e Testar conexão, prévia do recebedor no checkout, métodos aceitos, webhook com o último evento e os últimos eventos do gateway com reprocessar.
    Participantes (só a organização): uma linha por ingresso com crachá, acessibilidade (só a organização vê) e camiseta, filtros de dados faltando e transferidos, edição registrada na auditoria, cobrança de dados com prévia do e-mail e CSV dos crachás.
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 18
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 18
    @@ -1080,7 +1080,7 @@

    Telas: organização

    Patrocinadores (só a organização): meta, fechado, pago e em negociação, funil com o último contato de cada empresa, mover que desfaz se a API recusa e pede confirmação de cota sem vaga, e as cotas. O detalhe tem acordo, pagamentos, entregas, histórico e anexos por URL assinada.
    Fornecedores (só a organização): orçado e contratado da lista filtrada, que batem com o total no pé da tabela, filtros, contato restrito e trazer de outra edição da comunidade. O detalhe tem orçamentos, contratar e recusar, anexos e histórico.
    Finanças (organização e financeiro): receita, despesas pagas, saldo e previsão, orçamento por categoria com barra e texto equivalente, receita por origem e por conta com as taxas do gateway, despesas com comprovante por URL assinada e exportação em planilha.
    Tarefas (toda a equipe vê; o responsável move a própria): colunas com contagem, filtros, atrasada em destaque e mover com o mouse ou Alt + setas, anunciado e desfeito se a API recusa.
    Comunicação (só a organização): modelos de e-mail com gatilho e último envio, variável desconhecida bloqueia salvar, prévia gerada pelo backend com o tema e os dados de exemplo, teste para si mesmo e restaurar o padrão.
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 19
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 19
    @@ -1088,8 +1088,8 @@

    Telas: organização

    Onde estamos e o que falta

    Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.

    -
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPConcluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosConcluídobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    Marco 5 · App mobileEm andamentobase do app Flutter (M01); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)
    +
    MarcoSituaçãoO que tem
    Marco 0 · FundaçãoConcluídoesqueleto Laravel 13, módulos, Docker, convenções de API, segurança base, painel e componentes
    Marco 1 · Núcleo e CFPConcluídoIdentity, Community, Branding, Notifications, CFP inteiro, Audit; telas A05–A12, A24, A25; site P01, P03
    Marco 2 · IngressosConcluídobackend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)
    Marco 3 · Evento prontoA fazergrade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)
    Marco 4 · OperaçãoA fazerengajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)
    Marco 5 · App mobileEm andamentobase do app Flutter (M01), tema Sertão, tema por edição e componentes (M02); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)
    -
    PHPeste Platform · Arquitetura28/11/2026 · M01 (base do app) · página 20
    +
    PHPeste Platform · Arquitetura28/11/2026 · M02 (tema e componentes do app) · página 20
    diff --git a/docs/arquitetura/fonte/gerar.py b/docs/arquitetura/fonte/gerar.py index 13281b6..b5ae709 100644 --- a/docs/arquitetura/fonte/gerar.py +++ b/docs/arquitetura/fonte/gerar.py @@ -13,7 +13,7 @@ from pathlib import Path OUT = Path(__file__).with_name("arquitetura.html") -RETRATO = "28/11/2026 · M01 (base do app)" +RETRATO = "28/11/2026 · M02 (tema e componentes do app)" # ---------------------------------------------------------------- estilo --- # Cores do tema Sertão (front-admin) para o que é da plataforma, e neutras @@ -171,7 +171,7 @@ def legend(): b.append(box(24, 62, 202, 92, "Painel da organização", ["front-admin · Nuxt 4 SPA", "organizador, financeiro,", "avaliador, check-in"], "client")) b.append(box(24, 168, 202, 104, "Site da edição", ["front-public · Nuxt 4 SSR", "site, CFP, checkout,", "área do palestrante e", "do participante"], "client")) b.append(box(24, 286, 202, 78, "Site próprio da comunidade", ["opcional: chama só a", "API pública (CORS por edição)"], "client", dashed=True)) -b.append(box(24, 378, 202, 64, "App Flutter", ["participante, palestrante", "e check-in · base pronta"], "todo", dashed=True)) +b.append(box(24, 378, 202, 64, "App Flutter", ["participante, palestrante", "e check-in · base e tema"], "todo", dashed=True)) b.append(box(24, 456, 202, 62, "Gateways (webhooks)", ["Asaas e Mercado Pago"], "external")) b.append(box(275, 200, 120, 150, "Caddy", ["proxy reverso", "TLS sob demanda", "para domínio de", "cada edição", "(tls-check)"], "infra", center=True)) @@ -590,7 +590,7 @@ def legend(): ("Marco 2 · Ingressos", "Concluído", "backend: ingressos, cupons, pedidos, Asaas, Mercado Pago, webhooks, reembolso, conciliação, QR, importação, patrocínio, fornecedores, finanças, tarefas, webhooks do Resend; telas: A14 (ingressos), A15 (pedidos e reembolso), A16 (pagamentos e gateway), A17 (participantes), A19 (patrocinadores), A20 (fornecedores), A21 (finanças), A22 (tarefas), A23 (modelos de e-mail); no site, P04 e P05 (checkout com Pix e cartão) e P06 (conta do participante)"), ("Marco 3 · Evento pronto", "A fazer", "grade e programação (B35–B37, A13), check-in com modo offline (B38–B39, A18), push (B40), API pública e checkout embutível (B41, P07), site da edição (P02, P08–P10), viagem do palestrante (P11)"), ("Marco 4 · Operação", "A fazer", "engajamento (B42), LGPD (B43), relatórios (B44), carga, backups e runbook (B45), dados de demonstração (B46), acessibilidade e e2e (A26, A27)"), - ("Marco 5 · App mobile", "Em andamento", "base do app Flutter (M01); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)"), + ("Marco 5 · App mobile", "Em andamento", "base do app Flutter (M01), tema Sertão, tema por edição e componentes (M02); telas do participante, palestrante e check-in (M02–M23); o backend que o app precisa está no Marco 3 (B50–B56)"), ] pages.append(page(20, "Roadmap", "Onde estamos e o que falta", "Os milestones do GitHub e o board PHPeste Platform são a fonte da verdade do andamento; esta página é o retrato no dia da geração.",