Compare commits

...
241 Commits
Author SHA1 Message Date
bruno 0f86294abc merge: main → develop (sync) 2026-07-20 11:02:42 -04:00
bruno cefc7eb356 fix: admin password permanent + Help/My Tasks content rendering
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- main.py: lifespan insère toujours le hash de 'FlowDeck2026!' pour admin
- dashboard.py + my_tasks.py: content_html passe via {% block content %} (Jinja)
- Avant: content_html ignoré car base.html utilise des blocs, pas des variables
- 143 tests passent
2026-07-20 11:02:37 -04:00
bruno 4806097bc5 feat: Help page complète — 6 cartes, raccourcis, auth, tips
- Grille 2 colonnes de cartes: Getting Started, Pages, Workspaces, Gitea, Sharing, Library
- Section Keyboard Shortcuts avec style kbd + hover
- Section Authentication avec badges colorés (Local/Gitea/GitHub)
- Section Tips & Tricks
- Style Notion dark élégant, responsive
2026-07-20 10:47:30 -04:00
bruno de62628cb7 merge: develop → main (help page)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 10:47:30 -04:00
bruno 1fc4c21e2a merge: develop → main (my-tasks + help)
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 10:46:29 -04:00
bruno 0d9c1bf9ee feat: My Tasks dans base.html (sidebar visible) + Help page complète
- /my-tasks: wrappé dans base.html pour garder le sidebar visible
- /help: page d'aide complète avec 5 sections (démarrage, pages, workspaces, intégrations, raccourcis)
- Style élégant Notion dark avec cartes, grille 2 colonnes, badges
- 143 tests passent
2026-07-20 10:46:24 -04:00
bruno a49a9bae9b merge: develop → main (sidebar links + /help)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 10:12:59 -04:00
bruno d5ba29714c feat: remplacer section Notion apps par liens statiques Library/My Tasks/Trash/Help
- Section 'Notion apps' retirée
- Liens statiques en bas du sidebar (toujours visibles): Library, My Tasks, Trash, Help
- Nouvelle route /help avec page d'aide (raccourcis, guide rapide)
- Trash visible pour tous (plus de condition sur auth_method)
- 143 tests passent
2026-07-20 10:12:55 -04:00
bruno feb29cbff3 merge: develop → main (fix: sidebar create buttons guard)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 09:12:08 -04:00
bruno 79bc1bf1fd fix: cacher tous les boutons create du sidebar quand aucun workspace actif
- Meetings '+' button → gardé avec has_active_workspace
- Sidebar footer 'New page' → gardé avec has_active_workspace
- Context menu New File/New Folder → déjà gardé car l'arbre est caché sans workspace
- Workspace section déjà gardée (commit précédent)
- 143 tests passent
2026-07-20 09:12:03 -04:00
bruno 63c9a5fced merge: develop → main (fix: sidebar no-workspace guard)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 08:59:06 -04:00
bruno cbebd1f537 merge: fix/no-workspace-sidebar → develop 2026-07-20 08:59:06 -04:00
bruno b2486a6e11 fix: sidebar workspace section — hide create buttons quand aucun workspace actif
- Ajout flag has_active_workspace dans _sidebar_data (dashboard.py + board.py)
- Template base.html: quand has_active_workspace=False:
  - Titre section → '📁 No workspace open'
  - Boutons New File/New Folder cachés
  - Message 'Open a workspace to see your files'
- Guard JS newPageInWorkspace()/newFolderInWorkspace(): toast + redirect si pas de workspace
- 143 tests passent
2026-07-20 08:59:00 -04:00
bruno 0e99dc2251 docs: ROADMAP v4.0.2 marqué complété
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 08:08:06 -04:00
bruno 68f7f97b0d merge: feat/quality → develop (v4.0.2) 2026-07-20 08:07:28 -04:00
bruno 8514386a9b merge: develop → main (v4.0.2 — quality & robustness)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 08:07:28 -04:00
bruno ed465333e4 feat: v4.0.2 — qualité & robustesse (session expiry UX, validation, mobile, tests)
- Session expiry: redirects ajoutent ?expired=1 → bannière "Session expired" sur login
- Page titles: titre vide → 'Untitled' par défaut (au lieu de chaîne vide)
- Error handling: try/catch dans create_page avec message user-friendly (500)
- Mobile responsive: sidebar slide-in, modales centrées, landing page adaptative
- 10 nouveaux tests de non-régression: landing, register, 404, validation, duplicate
- 143 tests passent (133 + 10)
2026-07-20 08:07:22 -04:00
bruno c49e152e7c docs: ROADMAP v4.0.1 marqué complété
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 07:55:39 -04:00
bruno 8e6ed1e251 merge: develop → main (v4.0.1 — onboarding & polish)
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 07:55:18 -04:00
bruno a5831456e1 merge: feat/onboarding → develop (v4.0.1) 2026-07-20 07:55:14 -04:00
bruno 0a675a94f7 feat: v4.0.1 — onboarding, landing page, smart redirect, register GET, 404 stylé, API unifiée
- Landing page / pour visiteurs non-auth (template landing.html)
- Redirection / intelligente: non-auth → landing, auth sans Gitea → local workspace, auth+Gitea → dashboard
- GET /auth/register — page d'inscription dédiée (tab register actif)
- 404 handler stylisé thème Notion sombre (JSON pour /api/*, HTML pour le reste)
- Alias /api/pages GET/POST → /board/api/pages (307 redirect)
- 133 tests passent
2026-07-20 07:55:09 -04:00
bruno 47b0f80dfe docs: ROADMAP restructuré pour focus MVP + stratégie de branches Gitea
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- ROADMAP.md: réorganisé avec priorités claires (v4.0.0=complété, v4.0.1=onboarding PRIO MAX)
- Ajout BRANCHING.md: convention main/develop/feat/*, workflow complet
- Branche develop créée et poussée sur Gitea
- Sections Parité Notion réparties en v4.1–v4.10 ordonnées par priorité
- Résumé des phases mis à jour
2026-07-20 07:28:41 -04:00
bruno c94dac2bbf Remove per-file 📚 icon from Recents/Favorites/Shared/Published section items
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 06:55:49 -04:00
bruno 29d1ccb3dc Sidebar: replace '→ Library' text with 📚 icon, remove per-file 📚 in workspace tree
FlowDeck CI / test (push) Failing after 6s
FlowDeck CI / docker (push) Has been skipped
2026-07-20 06:47:45 -04:00
bruno 8d3bb36982 Remove prompt() from createPage() — creates Untitled file directly in correct workspace
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 22:01:34 -04:00
bruno 98bda37484 Make createPage() and createFolder() context-aware
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- createPage() now detects active workspace context (library, local-workspace page, sidebar)
- In a local/Gitea workspace: creates workspace item via /api/local-workspace/items with prompt
- No workspace: creates general Notion page via /board/api/pages (no prompt)
- Added hidden #fd-local-ws-id in local_workspace.html to expose workspace_id
- _confirmCreateFolder() passes workspace_id for Gitea workspaces
- Added _getContext() helper that checks multiple context sources in priority order
- Added _toast() helper for cross-component notifications
2026-07-19 21:56:46 -04:00
bruno 9100da74f3 Unify all New Page / New Folder buttons across the app
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Add global window.FlowDeck namespace with createPage() and showCreateFolderModal()
- createPage() creates a Notion-style page via /board/api/pages (same as sidebar bottom-right button)
- showCreateFolderModal() opens a global themed modal (dark/light) instead of browser prompt()
- All New Page buttons now call window.FlowDeck.createPage()
- All New Folder buttons now call window.FlowDeck.showCreateFolderModal()
- Global New Folder modal uses existing .flowdeck-modal CSS classes for theme consistency
- Updated Ctrl+N keyboard shortcut to use unified createPage()
2026-07-19 21:40:39 -04:00
bruno 74883688ef fix(library): filtres source/tri/vue + recherche + colonnes masquables + icônes SVG + drag-drop visuel
FlowDeck CI / test (push) Failing after 12s
FlowDeck CI / docker (push) Has been skipped
Ajout dropdowns filter/sort/view dans toolbar, recherche inline, colonnes author/source masquables, remplacement emojis par SVG, amélioration styles hover/drag, modal move-to, menus contextuels enrichis.
2026-07-19 21:22:59 -04:00
bruno a5242ee79b fix(library): augmenter opacité hover-only 0.4→0.55, dots plus visibles, bouton OPEN amélioré
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 15:15:44 -04:00
bruno 10d10b28c8 debug: log offsetHeight
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 15:09:27 -04:00
bruno 2471119b4a fix(library): supprimer tous les x-show (loading, empty) — _renderTable contrôle tout
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 15:07:48 -04:00
bruno 02cf759ec8 debug(library): add console.log in _renderTable
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 15:04:44 -04:00
bruno 978b286990 fix(library): supprimer x-show du tableau + gestion visibilité dans _renderTable
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le x-show sur #lib-table dépendait de flatItems.length,
qu'Alpine 3.14.9 ne détecte pas. Maintenant _renderTable()
contrôle l'affichage/masquage directement via style.display.
2026-07-19 14:58:34 -04:00
bruno 74102f00ab fix(library): rendu DOM direct (innerHTML) + suppression SortableJS
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Abandon complet d'Alpine pour le rendu du tableau :
- _renderTable() fait innerHTML directement sur #lib-table-body
- Plus de x-for, plus de x-html, plus de getters
- SortableJS supprimé (causait removeEventListener sur null)
- Fix startRename/commitRenameById pour utiliser les IDs DOM
2026-07-19 14:53:17 -04:00
bruno 5dc8bd5a33 fix(library): x-html au lieu de x-for — contourne bug Alpine 3.14.9
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le x-for d'Alpine 3.14.9 ne détecte pas les changements d'array.
Remplacement complet par x-html avec génération HTML manuelle.
Ajout de window._libData pour les onclick handlers globaux.
Fonctions _byId pour toggle/expand/rename/open depuis le HTML.
2026-07-19 14:49:17 -04:00
bruno c2eb088bb2 fix(library): splice au lieu d'assignation pour Alpine 3.14.9 x-for
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Alpine 3.14.9 ne détecte pas le changement de référence d'array
(this.flatItems = result). Utilisation de splice() pour muter
l'array en place. Ajout de $nextTick pour forcer le re-render.
2026-07-19 14:45:06 -04:00
bruno 5967dd9056 debug(library): ajouter console.log pour tracer init + loadTab + flatItems
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Ajoute des logs dans init(), loadTab() et _recomputeFlatItems()
pour identifier pourquoi flatItems reste vide malgré le chargement API.
CSP: ajout fonts.googleapis.com/gstatic.com pour débloquer Google Fonts.
2026-07-19 14:41:21 -04:00
bruno c681018262 fix(library): icônes toujours visibles (opacity 0.4) + full au hover
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Remplacé visibility:hidden par opacity:0.4 pour les hover-only.
Cela garantit que les éléments sont RENDUS et visibles en permanence,
avec accentuation au hover (opacity 1).
2026-07-19 14:30:59 -04:00
bruno a94794ec81 fix(library): SQL workspace — (workspace != '' OR workspace_id IS NOT NULL)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Les pages du workspace local ont workspace='' mais workspace_id=27.
Le filtre workspace != '' les excluait, retournant 0 items.
Ajout de OR workspace_id IS NOT NULL pour inclure les pages locales.
Simplification du frontend: le workspace tab appelle l'API standard avec workspace_id.
2026-07-19 14:14:07 -04:00
bruno 1bafbf1eff fix(library): tab Workspace affiche le contenu du workspace local actif
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Nouvel endpoint /api/library/local-workspace?workspace_id=X
  interroge local_workspace_items et formate pour la Library
- Nouvel endpoint /api/library/local-workspace-children/{id}
  pour l'expansion d'arborescence des items du workspace local
- Frontend: détecte workspaceId + !isGiteaActive → appelle local-workspace
- Frontend: toggleExpand route vers le bon endpoint selon source_type
2026-07-19 14:12:04 -04:00
bruno d3923c1d9a fix(library): workspace tab — ne pas filtrer par workspace_id (NULL dans la DB)
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Les pages ont workspace_id=NULL, donc le filtre ne retournait rien.
Le tab Workspace affiche maintenant toutes les pages avec workspace != ''.
2026-07-19 13:53:57 -04:00
bruno 9f17c39599 fix(library): supprimer getters Alpine 3.14.9 + Private tab caché quand workspace actif
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
- Tous les getters (flatItems, selectedCount, allSelected, emptyIcon/Title/Text)
  remplacés par des propriétés + fonctions _recompute().
  Les getters causent un bug connu d'Alpine 3.14.9 qui bloque l'init.
- Private tab: x-show="!workspaceId && !isGiteaActive"
  (caché quand un workspace local OU distant est ouvert)
2026-07-19 13:45:27 -04:00
bruno 2ee0a05efd fix(library): visibility hover + workspace filter + tab Repository pour Gitea
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- CSS hover-only: visibility:hidden/visible au lieu de opacity (infaillible)
- Workspace tab: filtré par workspace_id quand un workspace est actif
- Tab Private remplacé par Repository (visible seulement si Gitea workspace actif)
- Nouvel endpoint /api/library/repository pour le contenu Gitea
- dashboard.py passe is_gitea_workspace, owner, repo au template
2026-07-19 13:32:08 -04:00
bruno 04c059341d fix(workspace): corriger les séquences d'échappement cassées dans renderChildren
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Les échappements de quotes dans le patch précédent étaient cassés
(\\' au lieu de \'), causant des erreurs de syntaxe JS qui
empêchaient l'initialisation de _wsInitData et donc d'Alpine.
2026-07-19 13:20:29 -04:00
bruno 31fba6da39 fix(library): layout Notion-style — drag+checkbox+OPEN dans colonne name, hover-only CSS corrigé
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Drag handle (6 dots), checkbox, OPEN bouton intégrés dans la colonne Page name
- CSS hover-only: opacity 0 → 1 au mouseover (pas de visibilité permanente)
- Checkbox checked toujours visible (opacity:1) même sans hover
- OPEN bouton aligné à droite via margin-left:auto dans le name cell
- Double-clic sur le nom ouvre la page, simple clic = rename
- toggleExpand() force la réactivité Alpine via this.items = [...this.items]
- Colonnes drag/select/open séparées supprimées (layout Notion)
2026-07-19 13:12:44 -04:00
bruno b7c9401c92 fix(library): remove is_folder from children endpoint (pages table has no is_folder column)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-19 12:54:17 -04:00
bruno 33933352a8 fix(library+workspace): arborescence dans Workspace tab, icônes drag+multi-select visibles, inline rename au clic
FlowDeck CI / test (push) Failing after 13s
FlowDeck CI / docker (push) Has been skipped
- Library: ajout /api/library/children/{id} pour charger les enfants à la demande
- Library: drag handle (.drag-handle) et checkbox (.lib-checkbox) toujours visibles
- Library: SortableJS init pour drag-and-drop réordonner les rows
- Library: toggleExpand() async avec chargement des enfants depuis l'API
- Local workspace: drag handle 6-dots + checkbox toujours visible dans les tree items
- Local workspace: renderChildren() inclut checkbox + drag handle + inline rename
- Local workspace: clic sur nom de fichier = inline rename (plus navigation directe)
- Local workspace: bouton Open pour ouvrir le fichier (double-clic aussi)
- CSS: .item-checkbox toujours visible (plus opacity:0)
- CSS: .drag-handle avec opacité .45 par défaut, 1.0 au hover
2026-07-19 12:53:09 -04:00
bruno 6a2d56a7bd fix: Library page — hover effects, workspace filter, tree, rename
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
1. Hover effects fixed: converted table to div-based flexbox layout
   (tr/td don't support display:flex). .lib-row now properly shows
   drag handle, checkbox, and OPEN button on hover.

2. Recents filter by workspace: /api/library/recents now accepts
   workspace_id parameter. Template passes active_workspace_id from
   sidebar context to API calls.

3. Tree hierarchy: API now enriches items with has_children via
   _enrich_children() batch query — shows expand chevrons for
   pages with sub-pages.

4. Rename on click: single click on title starts inline rename
   (was opening page). OPEN button still opens side peek.

5. Code cleanup: extracted _enrich_children() helper to eliminate
   duplicate code across 6 endpoints.
2026-07-18 11:10:55 -04:00
bruno 28a41a30da feat: Notion-style Library page — complete redesign
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Complete rewrite of /library page to match Notion's Library design:

1. Table view with columns: Page name (with icon), Created by (avatar),
   Source, Last edited time, Last visited time
2. Hover effects showing drag handle (6 dots), checkbox, OPEN button
3. Side peek panel: opens on right, shows page content preview,
   close button, favorite toggle, copy link, more menu
4. Multi-selection: checkbox per row, select-all header, 'X selected' bar
   with Delete and '...' menu
5. ... menu: Remove from Recents, Copy links to all, Move to, Move to Trash
6. Inline rename: double-click title → edit field
7. 6 tabs: Recents, Favorites, Shared, Published, Private, Workspace
8. Tree expand/collapse for nested pages (has_children support)
9. + Add new row at bottom
10. Search bar toggleable

API additions:
- library.py: enhanced _build_item with icon, source_label, author
- dashboard.py: new /api/pages/{id}/content, /rename, /trash endpoints
- All 133 tests pass
2026-07-18 10:57:10 -04:00
bruno 08c823d758 Add screenshots for Notion Library UI interactions
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
2026-07-18 10:35:33 -04:00
bruno d97a515eef Remove unused Notion library screenshots
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-18 10:35:05 -04:00
bruno 5b56f970ee feat: compact breadcrumb menu + 'X more' Notion-style in workspace
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. Compact breadcrumb hover menu:
   - Reduced font-size: header-breadcrumb 14→13px, breadcrumb-link 14→13px
   - Dropdown menus: fd-nav-menu min-width 240→200px, padding reduced
   - fd-nav-item: padding 6px8→4px6, font 14→13px, gap 8→6px
   - fd-nav-section: font 11→10px, padding reduced
   - fd-nav-ico: size 16→14px, width 20→18px
   - fd-nav-arrow: size 16→14px, margin-left 4→2px

2. 'X more' Notion-style (tree view):
   - Shows first 5 items in displayTree, hides rest
   - 6th item shows 'X more...' with count of remaining items
   - Click to expand and show all items
   - 'Show less' button to collapse back to 5
   - showAll state auto-resets on folder navigation, sort, filter
   - Styling: semi-transparent hover effect on ws-more-item
2026-07-18 10:18:08 -04:00
bruno 37c8e99151 refactor: remove dead code _render_file_viewer from board.py
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
The standalone file viewer page (with '← Workspace' topbar) was dead code —
never called after the rollback. 192 lines removed, zero references left.
2026-07-18 10:03:09 -04:00
bruno 298617af58 revert: rollback _render_file_viewer wiring and URL encoding
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Rollback des commits 2226e5e et 2534e2b — les fichiers continuent
de s'ouvrir dans page_editor.html (layout normal avec sidebar),
pas dans le viewer standalone _render_file_viewer.
2026-07-18 09:44:48 -04:00
bruno 2226e5e2c8 fix: PDF viewer - also wire up _render_file_viewer in dashboard.py view_page_root
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
The real route for /pages/{page_id} is in dashboard.py (no prefix router),
not board.py (prefix /board). Both routes now call _render_file_viewer
for content_format='file' pages.
2026-07-18 09:37:38 -04:00
bruno 2534e2b425 fix: PDF viewer - wire up _render_file_viewer + URL-encode filenames
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- view_page now calls _render_file_viewer for content_format='file' pages
  instead of rendering the full page_editor template (which was the old path)
- URL-encode filenames in file_url using urllib.parse.quote() to handle
  spaces and special characters correctly
- Fixed in both board.py (viewer + page_data) and dashboard.py

The _render_file_viewer was dead code — defined but never called. File pages
were going through page_editor.html which rendered PDFs in an iframe embedded
in the editor UI. Now they get a clean standalone HTML viewer.
2026-07-18 09:34:24 -04:00
bruno bd02c9ea8a fix: startup log version v2.1.0 → v4.0.0
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-18 00:28:06 -04:00
bruno e85161dfc1 v4.0.0 — Route publique /p/<slug>, correctifs publish/share UI
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Ajout route /p/<slug> qui sert les pages publiées (no auth, rendu HTML blocks)
- Template public_page.html — design épuré Notion-style
- Fix publishPage()/unpublishPage(): vérifient d.is_published au lieu de d.status==='ok'
- Fix shareInvite(): vérifie d.status==='shared'
- Fix removeShare(): vérifie d.status==='removed'
- ROADMAP.md: toutes les sections 4.0a-4.0e cochées ✅ (déjà implémentées)
- Version bump 2.5.0 → 4.0.0
2026-07-18 00:27:14 -04:00
bruno fe64617677 feat: star favoris dynamique + sidebar refresh sans reload
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- page_editor: étoile ⭐/☆ dynamique selon favorited (x-text)
- toggleFavorite() appelle refreshFavorites() du sidebar
- base.html: refreshFavorites() fetch /api/library/favorites + rebuild DOM
- Context menu 'Add to Favorites' → refreshFavorites() au lieu de location.reload()
- Les items dynamiques ont onclick/oncontextmenu pour fonctionner hors Alpine
2026-07-17 23:50:37 -04:00
bruno 25386bc79f feat: breadcrumb hover Notion-style + nav_workspace_id sur toutes les pages
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- _header.html: remplace click par hover (mouseenter/mouseleave)
  avec timer 200ms anti-flicker, cascade sous-menus au hover
- dashboard.py: ajoute nav_workspace_id à trash, library, workspace,
  gitea-workspace, local-workspace, workspaces, settings, pages/{id}
- La section du popover affiche 'Workspaces' pour Home, 'Private' pour le reste
- Les clics dans les popovers ferment le menu + naviguent
2026-07-17 23:43:16 -04:00
bruno d751415308 feat: add Notion-style breadcrumb navigation with dropdown menus
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Backend:
- Added _nav_breadcrumb() to build page hierarchy chain (root → current)
- New /api/nav/menu endpoint returns workspace/folder children with has_children flag
- view_page() and view_page_root() now pass breadcrumb_items, nav_workspace_id, nav_page_id to template

Header template (_header.html):
- Replaced static breadcrumb with Alpine.js fdBreadcrumb() component
- Breadcrumb items now clickable with dropdown menus showing
2026-07-17 23:30:59 -04:00
bruno 6f1eabf91d fix: Windows path handling, light theme default, file viewer in editor, first-user admin logic
FlowDeck CI / test (push) Failing after 18s
FlowDeck CI / docker (push) Has been skipped
Config:
- Fixed SQLite path parsing on Windows (handle drive letters without prepending /)
- Changed default theme from dark to light
- Updated OAuth test credentials (gitea_oauth_client_id/secret)

Auth:
- First real user (excluding default admin with no password) becomes admin
- Changed user count query to exclude users without password_hash

File viewer:
- Removed separate _render_file_viewer() —
2026-07-17 20:38:39 -04:00
bruno 84a126cfd1 Merge branch 'main' of https://git.dracodev.net/bruno/flowdeck
FlowDeck CI / test (push) Failing after 18s
FlowDeck CI / docker (push) Has been skipped
2026-07-17 09:00:09 -04:00
bruno 7ea1c852dc chore: remove 44 Notion reference images — cleanup research artifacts
Deleted all Notion UI screenshots and .url shortcut from /images/:
- Kanban views (board, table, team load, status, detailed, sort/filter panels)
- Share menu (general access, permissions, publish section)
- Editor states (H1/paragraph/quote empty, format layouts)
- Navigation (sidebar, context menus, mouse-over states, collapse/expand)
- Misc UI (trash, config panel, library, user menu, filters)

These were research/reference
2026-07-17 08:59:44 -04:00
bruno c2ef7bfaa0 fix: show auto-created workspace name instead of 'Private' in sidebar
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
For Gitea workspaces, the sidebar section now displays the actual
workspace name (e.g. '📁 Projets/Ares') instead of the generic '📁 Private'.
The workspace name is auto-created from the Gitea project's owner/repo
when the remote workspace is first opened.
2026-07-16 14:27:47 -04:00
bruno c990382085 fix: use Alpine.data() to register giteaWorkspace component
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Replaced global function giteaWorkspace() with Alpine.data('giteaWorkspace', ...)
registered via document.addEventListener('alpine:init', ...). This is the
recommended Alpine 3 approach that guarantees the component factory is
available before Alpine processes x-data directives.

Changed x-data="giteaWorkspace()" to x-data="giteaWorkspace" (Alpine.data
calls the factory automatically, no parentheses needed).
2026-07-16 14:12:53 -04:00
bruno b141af886d fix: move giteaWorkspace() script before x-data div to fix init race
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
The <script> defining giteaWorkspace() was placed AFTER the <div x-data>
in the DOM, causing Alpine to try to evaluate giteaWorkspace() before
the function was defined. This resulted in 'Uncaught ReferenceError' for
all component properties (fileLoading, fileLanguage, showFile, etc.).

Fix: moved the <script> block to appear BEFORE the x-data div in the
HTML source, ensuring the function is defined when Alpine initializes.
2026-07-16 14:07:17 -04:00
bruno 56c5739605 fix: remove getter from giteaWorkspace() to fix Alpine 3.14.9 init error
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
The 'get sortedTreeItems()' getter caused Alpine's Proxy to fail during
component initialization, resulting in all properties being undefined
(fileLoading, fileLanguage, showFile, etc. — Uncaught ReferenceError).

Fix:
- Replaced getter with _sortTree() method + sortedTreeItems property
- _sortTree() called after treeItems is updated in loadMainTree()
- sortedTreeItems explicitly set to [] on error/empty paths
2026-07-16 13:48:47 -04:00
bruno 7613129204 fix: Gitea sidebar now has separate Repository section below Private
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Backend:
- _sidebar_data() no longer clears workspace_pages for Gitea workspaces
  The local tree stays intact in the 'Private' section
- workspace_pages is always loaded from DB (local files)

Sidebar template (base.html):
- Workspace section renamed to 'Private' when gitea_workspace is true
- New 'Repository (Gitea)' section added below, visible only for Gitea
  workspaces, with its own toggle (sectionsOpen.gitea) and refresh button
- Uses #sidebar-gitea-items container for the remote file tree

Gitea workspace:
- loadSidebarTree() now targets #sidebar-gitea-items
- window._gwData exposed for sidebar refresh button
- sectionsOpen now includes gitea: true by default
2026-07-16 13:44:10 -04:00
bruno f61f8b61ae fix: Gitea sidebar tree + header actions inline with title
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Gitea workspace sidebar:
- loadSidebarTree() now uses innerHTML replacement instead of DOM
  manipulation (avoids Alpine reactivity overwrites)
- Ensures workspace section is visible when tree loads
- Shows error message when Gitea API fails (no token/gateway)
- Better error handling with console.error catch

Header actions inline:
- page_editor: moved Edited/Share/Copy/Favorite/More buttons into
  the unified header (right_actions), accessible via window.E
  (editorState global reference set in init)
- Removed duplicate page-topbar div from content area
- Share dialog, More menu, and Activity popover stay in content
  area (triggered by header buttons via window.E references)
- Gitea workspace: header now uses page-action-btn for consistency
2026-07-16 13:08:14 -04:00
bruno 3210ac65a6 feat: Move to, Gitea context menu, Activity popover
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Move to workspace:
- movePage() opens a dialog listing all workspaces via /api/workspaces
- doMove(wsId) calls PUT /api/pages/{id}/move with workspace_id
- Updated move API to accept JSON body with workspace_id for cross-workspace moves

Gitea workspace context menu:
- Right-click on any file/folder shows Rename + Delete options
- gwRename() prompts for new name, calls PUT /api/gitea/.../file
- gwDelete() confirms then calls DELETE /api/gitea/.../file
- Both trigger refreshTree() after success

Activity popover:
- 'Edited X ago' timestamp is now clickable (▾ indicator)
- Opens popover showing edited time + created date
- formatDate() helper for readable date formatting
2026-07-16 12:53:38 -04:00
bruno cef267d7b5 feat: real timestamp + working Export + polished More menu in page editor
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- 'Edited X ago' now shows real relative time from page.updated_at
- timeAgo computed getter in editorState() calculates relative time
- Export now generates a Markdown file from blocks and triggers download
- blocksToMarkdown() helper converts blocks to proper Markdown syntax
  (headings, lists, todos, quotes, dividers, code blocks)
- More menu items: Duplicate (was working), Export (now works),
  Move to Trash (was working), Copy link (via shortcut)
2026-07-16 12:49:45 -04:00
bruno 043dd4871c feat: gitea-workspace now has file tree browser like local-workspace
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Main content area now shows file/folder tree with breadcrumb navigation
- Click folders to drill down, click files to open
- Breadcrumb shows current path with clickable segments
- Sorted tree: folders first, then files alphabetically
- refreshTree() now reloads without full page reload
- Empty state with 'New file' button when folder is empty
2026-07-16 12:42:48 -04:00
bruno b5dd37a652 fix: remove duplicate action bar from page_editor (double header)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
The unified _header.html already renders the topbar with breadcrumb. The
page_editor had a second 'page-topbar' div in the content area with the
same buttons (Share, Copy link, Favorite, More). Removed the duplicate
actions from the header, keeping them only in the content area where
they are in the correct Alpine scope (editorState()).

This fixes:
- Double header visual duplication
- Share/Copy/Favorite/More buttons now work (in editorState scope)
2026-07-16 12:41:25 -04:00
bruno d4fb095baf feat: unified header across all pages (Notion-inspired breadcrumb + actions)
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Created a shared _header.html template with:
- Hamburger button (toggle sidebar)
- Breadcrumb navigation with clickable segments and separators
- Page icon + title display
- Right-side action buttons (configurable per page)
- Dropdown panel CSS for More/New menus

Updated all pages to use the unified header:
- workspaces.html: Home / Workspaces + login/settings
- workspace.html: Workspace — Projects + login/settings
- local_workspace.html: workspace name
- gitea_workspace.html: Home / owner/repo + New/Upload/Refresh/Settings
- page_editor.html: title + Edited/Share/Copy/Favorite/More dropdown
- settings.html: Settings

Added CSS for breadcrumb, dropdown panel components.
2026-07-16 12:30:18 -04:00
bruno 8c0b55635c feat: soft-delete and undo/restore for local-workspace items
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Backend:
- DELETE /api/local-workspace/items/{id} now soft-deletes (sets deleted_at
  instead of hard DELETE) — items go to trash, not permanently gone
- New POST /api/local-workspace/items/{id}/restore to undo a delete
- _load_workspace_pages() and _load_children() now filter deleted_at IS NULL
  so soft-deleted items disappear from sidebar and tree queries

Frontend:
- undoDelete() now calls the restore API per item (single or bulk)
- bulkDelete() now shows the same undo banner as context menu delete
- All delete paths (ctxMenu, bulk, modal) use the same soft-delete + undo flow
2026-07-16 10:28:17 -04:00
bruno 631c106b01 fix: context menu uses Alpine proxy (window._wsData) instead of raw object
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
The context menu component (_ctxMenuData) was calling methods on
window._wsInitData (the raw JS object), NOT on Alpine's reactive proxy.
This meant that changes made by ctxMenuDelete/ctxMenuDuplicate (like
updating displayTree) were applied to the raw object but not reflected
in Alpine's reactive proxy that controls DOM rendering.

Fix: _ctxMenuData now uses a _ws() helper that returns window._wsData
(Alpine proxy, set in init()) with fallback to window._wsInitData for
safety. All context menu actions now go through the reactive proxy.
2026-07-16 09:59:07 -04:00
bruno 30e1879ac2 fix: deleteWithUndo uses _reloadAfterAction() instead of manual tree manipulation
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Replaced fragile _removeFromTree() + displayTree spread (which had Alpine
reactivity issues) with a clean _reloadAfterAction() call that reloads the
tree from the API. This is the same approach used by doDelete() and
doRename(), which work reliably. _reloadAfterAction also triggers the
sidebar refresh via window.appState.refreshSidebarTree().
2026-07-16 09:45:45 -04:00
bruno 6e4adaad8b fix: direct sidebar refresh via window.appState instead of events
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Replaced the fragile event-based sidebar refresh with direct function calls:
- appState.init() now sets window.appState = this
- _reloadAfterAction(), doCreate(), deleteWithUndo() call
  window.appState.refreshSidebarTree() directly (no DOM event)
- Sidebar handlers (drop, deleteWorkspacePage, wsCtxAction, newFolder)
  call window._wsData._reloadAfterAction() directly (no DOM event)
- Removed event listeners for flowdeck:workspace-changed and
  flowdeck:sidebar-refresh from local_workspace.html

This is more reliable than CustomEvent which had timing/scope issues.
2026-07-16 09:41:46 -04:00
bruno 50f8e0a938 fix: sidebar drag-drop uses dynamic refresh instead of full page reload
FlowDeck CI / test (push) Failing after 6s
FlowDeck CI / docker (push) Has been skipped
- Sidebar 'drop' handler now calls refreshSidebarTree() + dispatches
  'flowdeck:workspace-changed' instead of window.location.reload()
- Global refreshSidebarFromEvent() now targets .app-layout[x-data] first
  to avoid picking up the wrong Alpine component when multiple x-data
  elements exist on the page
2026-07-16 09:29:34 -04:00
bruno 4217978eaa fix: ctxMenuDelete triggers sidebar refresh via flowdeck:sidebar-refresh
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
deleteWithUndo() (called by ctxMenuDelete) was removing the node from the
local tree but never notifying the sidebar to refresh. Added dispatch of
'flowdeck:sidebar-refresh' event so the sidebar tree updates dynamically
without requiring a full page reload.
2026-07-16 09:24:24 -04:00
bruno ae2b1c5664 fix: use backslash-escape for single quotes (not HTML entity)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
HTML entities like &#39; are decoded by the browser BEFORE Alpine evaluates
the expression, so the JS parser still sees a raw single quote. Backslash
escape (\') is the correct approach: the HTML parser preserves it, then
JavaScript interprets \' as an escaped quote in the string literal.
2026-07-16 09:18:20 -04:00
bruno 5b6b251119 fix: escape single quotes in workspace tree macro to prevent JS parse errors
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Page names containing apostrophes (e.g. "02-Structure d'entrainements.md")
broke Alpine.js directives because Jinja2's |e filter doesn't escape single
quotes. Replaced ' with &#39; HTML entity in Alpine expression attributes
(showWsContext, wsTouchEnd).
2026-07-16 09:16:33 -04:00
bruno 0edcdbe82a fix: le menu contextuel Delete/Rename rafraîchit maintenant les deux arbres
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Nouvel événement 'flowdeck:workspace-changed' dispatché depuis les actions
  sidebar (deleteWorkspacePage, wsCtxAction rename/delete, newFolderInWorkspace)
- La vue principale local_workspace.html écoute 'flowdeck:workspace-changed'
  et appelle _reloadAfterAction() pour rafraîchir son arbre
- _reloadAfterAction() continue à dispatcher 'flowdeck:sidebar-refresh'
  pour le rafraîchissement sidebar uniquement (évite la boucle infinie)
- Correction du double confirm dans deleteWorkspacePage (skipConfirm=true
  depuis wsCtxAction qui a déjà confirmé)
2026-07-16 09:02:49 -04:00
bruno f6a022edf2 fix: extract render_workspace_tree macro, fix sidebar-tree endpoint
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Extracted render_workspace_tree macro into _workspace_tree_macro.html
  so it can be imported independently from base.html (which has many
  template variables like user, workspace_name, etc.)
- Fixed GET /api/sidebar/workspace-tree to use the extracted macro
- Added error logging for easier debugging
2026-07-16 08:58:05 -04:00
bruno 6f40c8953a feat: sidebar tree dynamically refreshes after CRUD in local-workspace
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- New endpoint GET /api/sidebar/workspace-tree returns sidebar tree HTML fragment
- refreshSidebarTree() in appState() fetches and replaces #sidebar-workspace-items
- Custom event 'flowdeck:sidebar-refresh' dispatched after doCreate/doRename/doDelete
- newFolderInWorkspace, deleteWorkspacePage, wsCtxAction('rename') now use
  refreshSidebarTree() instead of window.location.reload()
- Sidebar stays in sync without full page refresh
2026-07-16 08:53:44 -04:00
bruno 72636a77ea test: met à jour les tests suite à la suppression du fallback admin token
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Tous les tests *_no_auth doivent maintenant retourner 401 au lieu de 200/502
car _require_gitea() ne fait plus de fallback vers le token admin global.
2026-07-16 08:39:49 -04:00
bruno 76c8a9a53c fix: supprime le fallback admin token dans _require_gitea()
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
_require_gitea() ne doit plus utiliser le token admin global comme fallback
quand l'utilisateur n'a pas lié son compte Gitea. Chaque utilisateur doit
connecter son propre compte Gitea pour voir les projets.

Les endpoints /api/gitea/projects et /api/gitea/orgs retournent maintenant
401 si l'utilisateur n'a pas lié Gitea, et la page /workspaces affiche
'Connect your Gitea account' au lieu de lister les repos du admin.
2026-07-16 08:37:27 -04:00
bruno 07a4f5ece6 fix: sidebar vide sur /workspaces — pas de contexte workspace actif
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
_sidebar_data() prend un nouveau parametre include_workspace (default True).
La page /workspaces passe include_workspace=False pour que la sidebar
n'affiche ni le nom du workspace actif, ni ses pages/folders.
2026-07-16 08:29:52 -04:00
bruno d645126b53 fix: /api/workspace/projects uses per-user Gitea token instead of global admin token
FlowDeck CI / test (push) Failing after 17s
FlowDeck CI / docker (push) Has been skipped
A local account without Gitea connection was seeing all Gitea repos
because the endpoint used the module-level gitea client (global admin token).
Now it checks get_user_gitea_client(request) and returns empty gitea_repos
if the user has no OAuth token for Gitea.
2026-07-16 08:20:45 -04:00
bruno 7cefc08abc fix: Gitea tree loading + auth system overhaul (v2.5.0)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
ROOT CAUSE: Local accounts ([email protected]) had no Gitea token linked,
so /api/gitea/.../tree returned 401 → loadGiteaTree() failed silently.

FIXES:
1. _require_gitea() now falls back to admin token for read ops
   → Any logged-in user can browse Gitea repos without linking account
2. get_user_gitea_client() filters by provider='gitea'
   → Prevents using wrong token if user has GitHub+Gitrea linked
3. OAuth callback now stores auth_method correctly
   → gitea_bruno gets auth_method='gitea' instead of 'local'
4. Linked Gitea token to [email protected] (user_id=127)
   → Local account can now use personal token for Gitea API

PREVIOUS FIXES (from prior commit):
- loadGiteaTree: skip if giteaWorkspace already loaded, error logging, .bind(this)
- gitea_workspace.html: use captured 'self' instead of querySelector('[x-data]')
- 12 test assertions updated to reflect admin fallback behavior
2026-07-15 18:17:49 -04:00
bruno 61174ee967 fix: correct version number 2.4.7
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-15 16:55:27 -04:00
bruno aa64863bf7 fix: sidebar Gitea tree loading — race condition + silent errors + wrong Alpine scope
FlowDeck CI / test (push) Failing after 6s
FlowDeck CI / docker (push) Has been skipped
- loadGiteaTree: skip if giteaWorkspace component already loaded tree
- loadGiteaTree: check r.ok, add console.error logging, show error in UI
- loadGiteaTree: use .bind(this) for correct this in callbacks
- gitea_workspace.html: replace querySelector('[x-data]') with captured self
  in loadSidebarTree, loadSubdir, Private Pages click handlers
- Prevents loadGiteaTree from overwriting loadSidebarTree results
  on /gitea-workspace page
2026-07-15 16:54:20 -04:00
bruno efd957e827 fix: revert JS modal changes — preserve native prompt/confirm, add CSS+HTML modal only
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Root cause: callback wrappers introduced JS syntax errors ('appState is not defined')
Fix: keep modal HTML+CSS styles ready for future use, restore all JS functions
2026-07-15 09:28:35 -04:00
bruno 78092e6111 feat: custom modal system replaces browser prompt() and confirm()
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- Added themed dark modal with CSS matching FlowDeck design
- showPrompt(title, message, placeholder, callback) replaces prompt()
- showConfirm(title, message, callback) replaces confirm()
- Updated: newPageInWorkspace, newFolderInWorkspace, deleteWorkspacePage
- Modal closes on escape, overlay click, or cancel button
- Consistent look across all dialogs on the site
2026-07-15 09:03:25 -04:00
bruno ec96fb86a5 fix: KeyError 'workspace_key' in create_local_workspace_item
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Root cause: ws dict from _get_active_workspace doesn't have 'workspace_key' column
           → ws['workspace_key'] → KeyError → 500 on New Page/New Folder

Fix: use ws['name'] instead (the workspace name from workspaces table)
2026-07-15 08:41:06 -04:00
bruno 3fdcc41d10 fix: auto-refresh page when closing Settings with X
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
closeSettings() now:
- Refreshes the parent page (history.back + reload)
- Handles tab navigation between settings sections
- Falls back to /workspaces redirect if no history
2026-07-15 08:10:01 -04:00
bruno 17666b51c2 fix: two UX issues
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. Settings X button: closeSettings() goes back, skipping hash-only navigation
   → No more double-click to close

2. Workspaces page: Connect Gitea link now includes &mode=link
   → Same link as Settings → Integrations (was missing mode=link)
2026-07-15 07:56:21 -04:00
bruno aedb07c962 fix: redirect to /workspaces after login (instead of /)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Local login JS: window.location='/workspaces' instead of '/'
- Root route /: if no workspace exists, redirect to /workspaces
- Existing users with workspaces: still go to /local-workspace
2026-07-15 07:41:22 -04:00
bruno bf19af2347 fix: restore missing template=env.get_template in gitea_workspace_page
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-15 07:33:31 -04:00
bruno fc6f2531b7 fix: gitea_workspace page now explicitly sets gitea_workspace=True
FlowDeck CI / test (push) Failing after 6s
FlowDeck CI / docker (push) Has been skipped
Root cause: _sidebar_data reads cookie from REQUEST, but cookie is set on RESPONSE
           → first visit: cookie empty → gitea_workspace=False → tree doesn't load

Fix: gitea_workspace_page ctx always sets gitea_workspace=True
     Also passes gitea_owner/gitea_repo for Alpine tree loading
2026-07-15 07:32:08 -04:00
bruno 0d8507a5c7 feat: Gitea file tree visible in sidebar on ALL pages
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- base.html Alpine: added giteaWorkspace, giteaOwner, giteaRepo data
- loadGiteaTree() fetches /api/gitea/.../tree and renders in sidebar
- board._sidebar_data returns gitea_owner/gitea_repo
- dashboard._sidebar_data returns gitea_owner/gitea_repo
- alpine:initialized triggers loadGiteaTree on every page load
2026-07-14 22:05:53 -04:00
bruno b83d9b6d35 fix: board._sidebar_data now handles Gitea workspace cookie — tree persists across all pages
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Root cause: board._sidebar_data tried int(gitea:owner:repo) → ValueError → lost context
           Library, Trash, page editor pages showed empty workspace tree

Fix: board._sidebar_data now mirrors dashboard._sidebar_data logic:
     - Detects gitea: prefixed cookie
     - Preserves active_ws_name, workspace_key, gitea_workspace
     - Loads local_ws_id for mirror workspace
     - Tree stays visible on /library, /trash, page editor, etc.
2026-07-14 21:13:37 -04:00
bruno 3c8529fd12 fix: OAuth callback — recover mode from state when session cookie is lost
FlowDeck CI / test (push) Failing after 16s
FlowDeck CI / docker (push) Has been skipped
Root cause: request.session cookie expires during Gitea OAuth redirect
           → oauth_mode lost → link mode falls through to login mode
           → Creates gitea_bruno user instead of linking to local account

Fix: state now carries mode suffix (state:mode)
     Callback recovers mode from state parameter even if session lost
     Allows full session loss but still correctly enters link mode
2026-07-14 20:34:43 -04:00
bruno c5ffab1e39 fix: encode OAuth mode in state parameter — survives session loss
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Before: oauth_mode stored only in request.session cookie
        → Lost if session expires during Gitea OAuth redirect
        → Link mode falls through to login mode → creates gitea_bruno user

After:  state format: <random>:<mode> (e.g., abc123:link)
        → Mode survives session cookie loss
        → Link mode correctly links to current local user
2026-07-14 16:52:36 -04:00
bruno f4cd301f52 fix: _sidebar_data verifies workspace ownership before loading pages
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Stale numeric workspace cookie from another user now rejected
- workspace_pages only loaded if owner_id matches current user
- Prevents sidebar tree leak of other users' content
2026-07-14 16:25:13 -04:00
bruno de86457f90 fix: prevent cross-user workspace leak via stale cookie
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- _get_active_workspace now verifies workspace owner matches current user
- Fallback: only picks workspace owned by current user (not any user)
- /local-workspace redirects to /workspaces when no workspace exists
- New users no longer see other users' workspaces/projects
2026-07-14 16:09:03 -04:00
bruno 364560c84b fix: Private section populates from mirror workspace when Gitea active
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- private_pages now queried from DB when gitea_workspace=True
- Pages with parent_section='Private' and workspace_id=mirror_ws_id
- Shown in sidebar Private section alongside remote 🔗 tree
2026-07-14 15:44:51 -04:00
bruno 0429ffd824 fix: remove hardcoded workspace_key override in homepage
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Line 146: workspace_key: '' overrideait la valeur correcte de _sidebar_data
→ 🔗 icon now shown for remote workspaces on homepage
2026-07-14 15:28:38 -04:00
bruno a7767f3a94 fix: add missing json import
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-14 15:25:44 -04:00
bruno e8f4cfb631 feat: auto-create local workspace mirror for Gitea projects
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Opening /gitea-workspace auto-creates a local workspace with same name
- New Page/New Folder in remote context → saves to local mirror workspace
- Sidebar stays focused on remote workspace (🔗 icon, remote tree)
- local_ws_id passed to Alpine for API calls
- /api/local-workspace/items accepts workspace_id in body
2026-07-14 15:24:43 -04:00
bruno 7c3f62d094 fix: workspace_key set from cookie → 🔗 icon on homepage for remote workspaces
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-14 12:49:54 -04:00
bruno 9a063bc766 fix: toujours poser cookie gitea workspace côté serveur
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
2026-07-14 12:47:57 -04:00
bruno 234b880c5b fix: Gitea workspace — correct sidebar name, newPage stays remote, cookie persisted
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Bug 1: newPageInWorkspace() allait toujours vers local-workspace API
→ Maintenant détecte workspaceKey contient '/' → Gitea API PUT file

Bug 2: workspace_name dans gitea_workspace ne persistait pas
→ Cookie flowdeck_workspace posé côté serveur au premier chargement

Bug 3: icône 📁 fixe dans sidebar — pas d'indication remote
→ 🔗 affiché quand workspace_key contient '/' (remote), 📁 sinon

newFolderInWorkspace() : avertissement si workspace distant
(car les dossiers n'existent pas dans un repo Git)
2026-07-14 12:47:08 -04:00
bruno 724ff4c880 feat(v4.0): wire Share/Publish modal with real API calls
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- publishPage() → POST /api/pages/{id}/publish
- unpublishPage() → DELETE /api/pages/{id}/publish
- shareInvite() → POST /api/pages/{id}/share
- loadShares() → GET /api/pages/{id}/shares
- removeShare() → DELETE /api/pages/{id}/share/{sid}
- All buttons now call real API instead of local state toggle
2026-07-14 12:23:05 -04:00
bruno 15bd9d5ed9 fix: github_routes use access_token (not github_token)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
user_oauth_tokens has generic access_token column, not github_token/gitea_token
2026-07-14 12:21:10 -04:00
bruno 29ef0fb054 feat(v4.0): GitHub routes + CSRF exemptions for share/publish
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- app/routers/github_routes.py: /api/github/status + disconnect
- CSRF: ajout /api/github, /api/pages, /api/recents aux exclusions
- main.py: registration github_router
2026-07-14 12:19:37 -04:00
bruno bd6fd62734 feat(v4.0): Library tabs + Sidebar OAuth badge + Sharing routes
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
app/routers/library.py: /api/library/recents|favorites|shared|published|private|workspace
app/routers/sharing.py: /api/pages/{id}/share|publish + page_shares
app/templates/base.html: OAuth badge 🦎/🐙, '→ Library' buttons
app/templates/library.html: page avec tabs + filtres source
app/routers/dashboard.py: auth_method + github_linked dans context
tests/test_app.py: tests library + sharing + recents
2026-07-14 12:16:28 -04:00
bruno 802d681212 feat(v4.0): Settings/Integrations — Gitea + GitHub connect/disconnect matrix
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- GitHub integration row ajoutée (🦎 Gitea + 🐙 GitHub)
- Badge 'Primary' sur le provider principal (auth_method)
- Disconnect masqué pour le provider principal
- authMethod, githubLinked, giteaLinked dans Alpine data
- loadGithubStatus() + disconnectGithub() methods
- Matrice respectée: local→déco OK, gitea→déco github OK, github→déco gitea OK
2026-07-14 12:14:41 -04:00
bruno 8eb7049460 docs: ARCHITECTURE v3.0 + ROADMAP v4.0 — comptes, intégrations, sidebar
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
ARCHITECTURE.md:
- Section 6.5: modèle de comptes (local/gitea/github)
- Matrice d'intégrations & règles de déconnexion
- 3 scénarios de workspace (A/B/C)
- Sidebar: règles d'affichage par type de compte
- Share & Publish: modale 2 tabs + schéma DB
- Library: /library?tab= + filtres source
- Trash local-only, édition unifiée, stockage Private
- Plan de migration 5 phases

ROADMAP.md:
- v4.0.0 section prioritaire: Account Model, Intégrations,
  Sidebar rules, Share/Publish, Library, Édition unifiée
2026-07-14 12:07:13 -04:00
bruno e2043123f0 fix: title_prefix block for browser tab — évite conflit Jinja2 page_title double
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Erreur: block 'page_title' defined twice → TemplateAssertionError
Fix: title_prefix (nouveau bloc) pour <title>, page_title (existant) pour Alpine

10 templates mis à jour avec title_prefix.
2026-07-14 09:35:52 -04:00
bruno 8cca247fcd fix: browser tab title uses page_title block — reflète le workspace actif
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
<title>FlowDeck</title> → <title>FlowDeck — {% block page_title %}Home{% endblock %}</title>

Maintenant l'onglet navigateur affiche:
- 'FlowDeck — Home' (page d'accueil)
- 'FlowDeck — bruno/flowdeck' (workspace Gitea)
- 'FlowDeck — Mon workspace local' (workspace local)
2026-07-14 09:34:38 -04:00
bruno cb44652554 fix: Gitea workspace affiche owner/repo dans le titre et topbar
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- Le titre de page (onglet) : 'bruno/flowdeck' au lieu de 'Gitea Workspace'
- Le topbar breadcrumb : owner/repo correctement peuplé
- workspace_name + workspace_initial passés au template
2026-07-14 09:34:02 -04:00
bruno 921f1b7bc1 fix: servir JS/CSS en local — plus de dépendance CDN externe
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Téléchargés et servis depuis /static/js/:
- alpine.min.js (44 KB) — remplace unpkg.com
- htmx.min.js (51 KB) — remplace unpkg.com
- sortable.min.js (45 KB) — remplace cdn.jsdelivr.net
- prism.min.js (19 KB) + prism.css (1.3 KB) — remplace cdnjs

Corrige le bug 'rien ne fonctionne' quand le réseau est lent/absent:
sans CDN, Alpine.js/HTMX/SortableJS ne chargeaient pas →
tous les @click, x-show, x-data, drag-drop inopérants.
2026-07-14 07:44:28 -04:00
bruno 8458cf4a29 fix: defensive display:none on all modals — prevents phantom display
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Si Alpine échoue à s'initialiser, x-show n'était pas traité
et les modals apparaissaient par défaut. display:none en fallback
garantit qu'ils sont cachés, Alpine les montre via x-show.
2026-07-14 07:36:36 -04:00
bruno b755f75f15 fix: rollback Alpine.data registration — keep _wsInitData as global var only
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
L'enregistrement Alpine.data() pouvait créer un conflit avec x-data
qui utilise déjà la variable globale. Revert au comportement original.
2026-07-14 07:23:13 -04:00
bruno b771708bdc fix: @click.away→@click.outside GLOBAL — 16 instances across 5 templates
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Alpine 3.x a renommé .away en .outside. Toutes les occurrences dans:
- base.html (3: user menu, context menu, ws ctx)
- page_editor.html (5: share, perm, access, more, gsMore)
- workspaces.html (1: dialog overlay)
- workspace.html (1: modal overlay)
- local_workspace.html (6: create, rename, delete modals, context menus)

Ces .away cassées empêchaient tous les @click Alpine de fonctionner
sur ces pages (Cancel, Delete, et tous les autres boutons modaux).
2026-07-14 07:16:56 -04:00
bruno 1e15e44a00 fix: Alpine 3.x — @click.away→@click.outside + register _wsInitData
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- @click.away n'existe pas dans Alpine 3.x (renommé @click.outside)
  6 occurrences corrigées dans local_workspace.html
- Ajout Alpine.data('_wsInitData') pour un binding fiable des @click
  (le IIFE seul ne garantissait pas une reconnaissance Alpine propre)
2026-07-14 07:16:27 -04:00
bruno 7edeb373f1 fix: guard delete confirm with null id check — prevents phantom dialog
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le confirm('Delete') dans contextActions pouvait se déclencher sans
item valide (id null/undefined). Ajout d'un guard if (!id) break.
2026-07-14 07:10:26 -04:00
bruno 449550ac90 fix: wire CSP + RateLimit middleware in main.py (étaient définis mais pas branchés)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Audit v3.0.1: 2/21 features ✗ → CSP/rate-limit middleware
non importés dans main.py. Maintenant branchés.
2026-07-14 00:47:08 -04:00
bruno 72dc4771b4 ROADMAP v4.0.0: ajout Database avancée, Kanban adaptable, Calendar & Meetings
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
4.8 Database Avancée: inline DB, full-page DB, templates de DB,
    validation propriétés, types manquants (Person, Last edited, Created by),
    Timeline/Gantt, Board swimlanes, Calendar drag-drop, Gallery covers

4.9 Kanban Adaptable: colonnes config., cartes configurables,
    couverture, sous-tâches visibles, WIP limits, vues sauvegardées,
    mode compact/détaillé

4.10 Calendar & Meetings: Day/Week/Month, drag-drop reschedule,
    récurrence, timezone, rappels, template Meeting Notes,
    auto-création action items
2026-07-14 00:41:08 -04:00
bruno ec9eb99c98 ROADMAP v4.0.0: delta analysis Notion vs FlowDeck
FlowDeck CI / test (push) Failing after 7s
FlowDeck CI / docker (push) Has been skipped
Analyse exhaustive: 60+ fonctionnalités Notion (2025) vs FlowDeck v3.0.1
→ 45 manquantes identifiées, 30 retenues pour v4.0.0

Tier 1 (Critique — 16 features):
- AI Assistant (LLM intégré, auto-complétion, slash AI)
- Embeds (60+ services, lightbox, previews PDF/vidéo)
- Export (PDF, Markdown, HTML) + Import (Confluence/Evernote)

Tier 2 (Important — 8 features):
- Realtime collaboration (WebSocket, curseurs)
- Comments + @mentions + email notifications
- Callout blocks, table of contents, LaTeX, toggle lists

Tier 3 (Avancé — 6 features):
- Linked databases, charts/dashboards, multi-colonnes
- Command palette Ctrl+P, automations, buttons

v4.1.0 (futur): PWA, SSO, API publique, web clipper
2026-07-14 00:28:26 -04:00
bruno de40c2d83e v3.0.1: qualité & stabilité — tests, sécurité, UX consolidée
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
🧪 Tests: 73 → 130 (+57 tests)
- Upload API, labels sync, commit history (401/400/502/cached)
- File create/update (sha=null, sha=abc)
- Admin delete cascade (12 tests: oauth, tags, workspaces, pages…)
- Gitea status (linked/unlinked/disconnect)
- OAuth link mode (session, redirect, callback)

🔒 Sécurité
- ContentSecurityPolicyMiddleware (CSP headers)
- RateLimitMiddleware (100 req/min/IP)
- Pydantic models: ErrorResponse, SuccessResponse
- Input validation upload (10MB, allowed extensions)
- Pydantic request models

🎨 UX
- static/css/design-tokens.css (500 lines, thèmes + skeletons)
- Toast system: 16 alert() remplacés par toast()
- 59 lignes CSS dupliquées retirées (6 templates)
- Skeletons cohérents sur toutes les vues

⚡ Performance
- Cache TTL sur get_file_commits (consistant avec les autres méthodes)
2026-07-13 23:08:53 -04:00
bruno e04b3a38a4 fix: get_file_commits use consistent caching (_cached/_set_cache)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 22:57:46 -04:00
bruno b863afab59 ROADMAP: v2.8.0-v3.0.0 complétées — roadmap terminée 🎉
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 22:36:01 -04:00
bruno a497c129d3 Upload via FlowDeck
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 22:34:37 -04:00
bruno 6f15ad3ad4 v2.8.0 WIP: create/upload files + commit history + labels sync
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- POST /api/gitea/projects/{owner}/{repo}/upload (binary upload)
- get_file_commits() in GiteaClient
- GET /api/gitea/projects/{owner}/{repo}/commits (per-file history)
- POST .../sync-labels (Gitea labels → FlowDeck tags)
- New file form + upload button in gitea_workspace.html topbar
2026-07-13 22:33:47 -04:00
bruno f25c8ebaf0 feat: force Gitea ré-auth en mode link (_force timestamp)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Ajout d'un paramètre _force avec timestamp dans l'URL d'autorisation
quand mode=link, pour forcer Gitea à ne pas utiliser le cache.

NOTE: Gitea ne supporte pas prompt=login. Si auto-approve persiste,
il faudra ajouter un champ token manuel en fallback.
2026-07-13 22:18:31 -04:00
bruno 06bf016392 fix: bfcache restore — theme persistant après navigation retour
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Problème: window.history.back() restaurait la page depuis bfcache
→ le IIFE initTheme() ne se ré-exécutait pas
→ le thème dark s'affichait même après avoir sélectionné light

Fix:
- applySavedTheme() → fonction nommée, pas IIFE
- window.addEventListener('pageshow', e.persisted → reapply)
- Proper else branch: removeProperty pour le dark mode
2026-07-13 21:45:29 -04:00
bruno 17824deae2 fix: déconnexion Gitea effective + menu user light mode
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. _require_gitea: retrait fallback admin token → 401 si pas connecté
2. user-menu-dropdown: background var(--bg-primary) au lieu de #1E1E1E
3. applyTheme() déjà immédiat via style.setProperty sur documentElement
2026-07-13 21:39:16 -04:00
bruno e3851b4f12 feat: OAuth link mode + settings light mode CSS variables
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. /auth/login?provider=gitea&mode=link:
   - Sauve 'oauth_mode=link' dans la session
   - Callback: link OAuth token à l'utilisateur courant (pas de nouveau compte)
   - Redirige vers /settings#integrations

2. Bouton Connect dans Settings → mode=link

3. Settings light mode: remplacé 12 couleurs codées en dur par CSS variables
   - .settings-panel, .modal-box, .settings-input
   - .admin-table th/td, .stat-card
   - .btn-sm, .btn-sm:hover
2026-07-13 21:24:04 -04:00
bruno 6c8327c021 fix: delete_user cascade — ajout comments, page_history, favorites, gitea_private_pages, tags
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 21:02:39 -04:00
bruno 1e36b03532 fix: delete_user cascade — pages n'a pas de owner_id, passe par workspace_id
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 21:02:10 -04:00
bruno aa2354a25a fix: exempt /api/admin + /api/gitea du CSRF middleware
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Les endpoints admin ont déjà leur propre protection admin_required.
Le CSRF middleware bloquait les DELETE/PUT sur ces routes.
2026-07-13 21:01:21 -04:00
bruno ef88ee4c55 fix: virgule manquante après saveDefaultView() — SyntaxError cassait tout le JS
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
settings.html:773: '} async' → '}, async'
Cette SyntaxError empêchait Alpine.data('settingsInit') d'être parsé
→ toutes les variables Alpine étaient undefined
2026-07-13 20:56:42 -04:00
bruno 86b34dc063 test via FD
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 20:48:40 -04:00
bruno 6d98070986 fix: ajout X-CSRF-Token dans les requêtes save/delete Gitea
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 20:48:40 -04:00
bruno 0d66b5d543 fix: scope Alpine gitea_workspace + commit admin fallback + settings cleanup
FlowDeck CI / test (push) Failing after 6s
FlowDeck CI / docker (push) Has been skipped
1. gitea_workspace.html: owner/repo en Jinja2 dans la topbar (pas Alpine)
2. gitea.py: save_file/delete_file → _require_gitea (admin token can write)
3. settings.html: retrait doublon defaultView, fix workspace_name Jinja2
2026-07-13 20:47:46 -04:00
bruno e22efc1d9c fix: retirer bouton dark/light mode du sidebar, ajouter dans Settings
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Sidebar: retrait du bouton 🌓 (dark/light) + bouton 🚪 logout
- Settings → Account → Preferences: nouveau sélecteur de thème (Dark/Light)
- Persistance localStorage 'fd_theme' — appliqué au chargement de chaque page
- initTheme() dans base.html + applyTheme() dans settings.html
- toggleTheme() conservé dans le JS mais plus utilisé dans l'UI
2026-07-13 17:08:30 -04:00
bruno c1f854a54a docs: mise à jour ROADMAP.md, CHANGELOG.md et docs/ROADMAP.md
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
ROADMAP.md:
- Ajout v2.4.0 (tags/user), v2.5.0 (admin panel), v2.6.0 (my account)
- Ajout v2.7.0 (Gitea P1), v2.7.1 (private pages)
- Roadmap future: v2.8.0 (Gitea P2), v2.9.0 (GitHub), v3.0.0 (Pro UX)

CHANGELOG.md:
- Entries v2.4.0 → v2.7.1 avec tous les détails
- Structure Added/Fixed cohérente

docs/ROADMAP.md (v3.0):
- Phase 1-5 checkboxes mises à jour (45/52 items done)
- Reste: GitHub OAuth, Quick switch, API tokens, sessions actives
2026-07-13 17:05:45 -04:00
bruno 5cc27b4535 fix: get_user_repos(limit=100) — bruno/flowdeck était sur page 2
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 17:02:11 -04:00
bruno caa00c54bc feat: fallback token admin GET + Private Pages persistantes
FlowDeck CI / test (push) Failing after 17s
FlowDeck CI / docker (push) Has been skipped
1. _require_gitea: fallback token admin pour les GET (orgs, projects, tree, file)
   _require_user_gitea: token OAuth requis pour les write (save, delete)

2. Private Pages: table gitea_private_pages (user_id, owner, repo, title, content)
   API CRUD: GET/POST/PUT/DELETE /api/gitea/projects/{o}/{r}/private-pages
   UI: liste + éditeur dans le workspace Gitea, lien 🔒 Private Pages dans sidebar
   Lié logiquement au projet (owner+repo), conservé entre sessions
2026-07-13 17:01:19 -04:00
bruno 6b000d892b fix: chargement tree sidebar 100% client-side (pas de asyncio.run)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Avant: _sidebar_data() utilisait asyncio.run() → RuntimeWarning + 302 redirects
Après: gitea_workspace.html appelle loadSidebarTree() → fetch API → injecte dans #sidebar-workspace-items

- base.html: ajout id='sidebar-workspace-items' sur le <ul> workspace
- dashboard.py: _sidebar_data() ne fait plus de fetch serveur, juste passe owner/repo
2026-07-13 16:43:34 -04:00
bruno e78ca4b775 feat: sidebar arborescence Gitea + tab user repos avec vrai username
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
1. Tab user repos: fetch username via /auth/user → affiche 'bruno' au lieu de 'Personal'
2. Sidebar: ws_cookie='gitea:owner:repo' → _sidebar_data() fetch le tree depuis Gitea API
3. base.html: data-gitea-path/type/sha sur les items workspace pour les projets Gitea
4. gitea_workspace.html: refonte sans tree panel → navigation via sidebar
   - Clic fichier → ouvre dans le contenu (lecture + edit + commit)
   - Clic dossier → lazy-load les enfants dans le sidebar
5. openGitea(): set cookie flowdeck_workspace avant navigation
2026-07-13 16:42:11 -04:00
bruno 5fe31aeffa feat: redirect_uri dynamique basé sur Host header
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Avant: oauth_redirect_uri codé en dur à localhost:8080
→ impossible d'utiliser l'OAuth depuis une autre machine du réseau

Après: le redirect_uri est construit à partir du header Host de la requête
→ localhost:8080 → http://localhost:8080/auth/callback
→ 192.168.30.101:8080 → http://192.168.30.101:8080/auth/callback

⚠️ L'utilisateur doit ajouter les 2 URIs dans Gitea OAuth App settings.
2026-07-13 15:59:39 -04:00
bruno 7cbb226e62 fix: Register/Link with Gitea ne crée plus de session admin fantôme
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Avant: get_provider('gitea') → None (pas de client OAuth configuré)
       → fallback créait automatiquement une session admin
       → le bouton 'Register with Gitea' connectait l'utilisateur en admin !

Après: affiche une page d'erreur propre:
       '⚠ Gitea OAuth not configured — The Gitea integration has not
        been set up by the server administrator. ↩ Use local login'
2026-07-13 15:23:10 -04:00
bruno e9d1c32b4f feat: Gitea — register, settings connect, tabs org, search
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. Pas de Gitea sans config: _require_gitea() → 401 si pas de token OAuth
2. Register Gitea: boutons "Login/Register with Gitea" dynamiques selon l'onglet
3. Settings → Integrations: ✅ Active / 🔗 Connect / Disconnect + API status/disconnect
4. Workspaces: tabs par org (All | org1 | org2) + barre recherche 🔍 filtrage live
5. API: GET /api/gitea/status, DELETE /api/gitea/disconnect
2026-07-13 15:17:17 -04:00
bruno 46336df21b feat: frontend Gitea — workspaces 2 sections + gitea workspace vue
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
workspaces.html:
- Section 📁 Local Workspaces (existante, avec badges)
- Section 🔗 Gitea Projects (par organisation, lazy load)
- États: loading, not_linked (lien pour login OAuth), error (retry), ok

gitea_workspace.html:
- Arbre fichiers (lazy: un dossier à la fois)
- Vue fichier (lecture seule → bouton Edit)
- Éditeur avec zone de commit (message + historique dropdown)
- Section 🔒 Private Pages (placeholder pour pages FlowDeck locales)
- Bouton Delete fichier

Routing: /gitea-workspace?owner=X&repo=Y

Fallback: token admin serveur si pas de token OAuth utilisateur
2026-07-13 14:58:01 -04:00
bruno 00860417a8 fix: param order in gitea routes (request first)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 14:52:33 -04:00
bruno 5baae598bf fix: indentation gitea_client + request defaults
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 14:51:58 -04:00
bruno 9f667ae9e0 feat(gitea): API routes + per-user client + repo contents
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
GiteaClient:
- __init__(user_token=None) — per-user OAuth token ou admin token
- get_repo_contents(owner, repo, path) — lazy: un niveau à la fois
- get_file_content(owner, repo, path) — base64 décodé
- create_or_update_file(...) — PUT avec sha pour update
- delete_file(owner, repo, path, sha, message)
- _invalidate_tree_cache() — invalidation après write

Routes (/api/gitea):
- GET /orgs — liste des organisations
- GET /projects?org=x — repos user ou org
- GET /projects/{owner}/{repo}/tree?path=x — arborescence lazy
- GET /projects/{owner}/{repo}/file?path=x — contenu fichier
- PUT /projects/{owner}/{repo}/file — save + commit
- DELETE /projects/{owner}/{repo}/file?path=x&sha=x — delete
- GET /projects/{owner}/{repo}/labels — labels → tags

Helper: get_user_gitea_client(request) → GiteaClient ou None
2026-07-13 14:50:46 -04:00
bruno 5d1857941e feat: tags personnalisés par utilisateur (user_id)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
DB:
- tags.user_id REFERENCES users(id)
- UNIQUE(name, user_id) au lieu de UNIQUE(name)
- Migration v2.6: alter + recreate table

API (tous les endpoints tags):
- POST/PUT/DELETE /api/settings/tags: filtré par user_id
- GET /api/settings/tags/all: retourne uniquement les tags du user
- GET/POST /api/local-workspace/*/tags: scope user

→ Les tags de l'utilisateur 1 ne sont pas visibles par l'utilisateur 2
2026-07-13 13:58:13 -04:00
bruno f262076545 fix: refresh session cookie après update_account
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le cookie de session n'était pas mis à jour après modification du compte
→ le template re-rendait avec les anciennes données au rechargement.
Maintenant le serveur émet un nouveau cookie avec les données fraîches.
2026-07-13 13:49:13 -04:00
bruno 4ea512d007 feat: My Account — modifier username, nom, email, mot de passe
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Backend:
- PUT /api/settings/account (full_name, login, email, password)
- Vérifie que le username n'est pas déjà pris
- Password min 6 caractères

Frontend (Settings → My Account):
- Champs éditables: Username, Full name, Email
- Section Change password avec toggle 👁/🙈
- Bouton Save changes + Update password
- Message de confirmation ✓ / ✗ avec timeout 3s
2026-07-13 13:42:11 -04:00
bruno e42c5e1e4b fix: toggle voir/cacher mot de passe + label 'Email or username'
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Bouton 👁/🙈 dans le champ password (login + register)
- Label changé de 'Email' à 'Email or username' (les users créés via admin ont un login, pas forcément un email)
- Type email → type text pour accepter les usernames
2026-07-13 13:34:18 -04:00
bruno e01e410d43 fix: CSRF token dans toutes les requêtes admin (adminFetch)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Tous les appels /api/admin/* passent maintenant par adminFetch()
qui ajoute X-CSRF-Token depuis le cookie csrf_token
2026-07-13 13:26:07 -04:00
bruno 9e9ea181e6 fix: admin_required check DB direct en fallback (session cookie stale)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le cookie de session peut dater d'avant le flag is_admin →
vérification DB directe si la session ne contient pas is_admin
2026-07-13 13:19:38 -04:00
bruno 057ff9f524 ui: settings panel 1050px (était 820px) pour afficher tous les champs admin
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 13:14:26 -04:00
bruno 253f5b215c fix: admin query adaptée au schéma réel (pas de owner_id/is_folder)
FlowDeck CI / test (push) Failing after 13s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 13:00:42 -04:00
bruno 97d6ad7a91 feat: administration — users, roles, stats, audit
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
DB:
- login_history table (user_id, ip, user_agent, timestamp)
- Migration v2.5: alter users + create login_history

Auth:
- Premier utilisateur = admin (is_admin=1)
- _log_login() après chaque connexion (register, local-login, OAuth)

Backend (app/routers/admin.py):
- admin_required middleware (vérifie is_admin)
- GET  /api/admin/users     → liste users + stats par user
- POST /api/admin/users     → créer user
- PUT  /api/admin/users/:id → modifier (name, email, password, admin, active)
- DELETE /api/admin/users/:id → supprimer + cascade
- GET  /api/admin/stats     → totaux globaux
- GET  /api/admin/audit     → historique login

Frontend (settings.html):
- Nav Admin visible seulement si userIsAdmin
- Users & Roles: stats cards, create/edit/delete users, table complète
- Audit Log: historique login avec date, IP, user-agent
- CSS professionnel: table-wrap, admin-table, stat-card, role-badge, status-dot
2026-07-13 12:59:36 -04:00
bruno ea591bd577 fix: input rename tag en dark theme
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Ajout .settings-input: fond #2A2A2A, bordure #555, texte #ddd, focus bleu
2026-07-13 12:42:19 -04:00
bruno 91032de704 fix: 5 corrections — modals opaques, tags visibles, fermeture menu, filtrage, pastilles
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. Settings modals: fond rgba(0,0,0,.85) + boîte #1E1E1E (plus opaque)
2. Tags existants: sync forcé via menuEl._x_dataStack en plus de _ctxMenuData
3. Ajout tag: ferme .ctx-menu après succès (style.display='none')
4. Filtrage tags: toggleTagFilter() appelle doFilter() + _filterTreeByTag
5. Pastilles: tag-dot supprimé, :style="{background: t.color}" sur tag-chip
   → 7 occurrences mises à jour (filter bar, tree, preview, JS gen)
2026-07-13 11:55:29 -04:00
bruno 51c6002f08 fix: 5 bugs — couleur tag, tags existants, modal settings, rename, filtrage
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
1. ctxAddNewTag lit window._ctxMenuData.ctxNewTagColor (pas this.ctxNewTagColor)
   → la couleur sélectionnée dans le menu est maintenant sauvegardée

2. onContextMenu: charge workspaceTags si vide avant de calculer ctxAvailTags
   → les tags existants apparaissent dans le dropdown

3. Settings: CSS modal-overlay/modal-box/.btn-danger ajouté
   → le modal delete n'est plus transparent

4. Rename tag: modal avec input au lieu de prompt()
   → double-clic → modal avec couleur + input + autofocus

5. doFilter: _filterTreeByTag filtre displayTree quand tagFilter est actif
   → le filtrage par tags fonctionne dans toutes les vues
2026-07-13 11:34:43 -04:00
bruno 53865f136d fix: tags contextuels + rename/delete confirm dans Settings
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
Context menu (_ctxMenuData):
- Remplacé getters par propriétés simples (Alpine ne réagit pas aux getters)
- Sync _wsInitData → _ctxMenuData dans onContextMenu, ctxAddNewTag, ctxRemoveTag
- Les 4 tags existants apparaissent maintenant dans le dropdown

Settings > Tags:
- Double-clic sur un tag → prompt rename (PUT /api/settings/tags/<id>)
- Suppression: modal de confirmation au lieu de confirm() natif
- Affiche le nombre d'items impactés si tag utilisé
2026-07-13 11:20:51 -04:00
bruno c524478ff2 fix: _ctxMenuData — objet léger sans conflit Alpine
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
_wsInitData (162 keys) causait "Cannot redefine property: $nextTick"
quand réutilisé comme x-data sur .ctx-menu. Alpine ajoute des propriétés
magiques ($nextTick, $el, etc.) et certaines entrent en conflit avec
les propriétés de l'objet massif.

Solution: window._ctxMenuData — objet minimal avec getters/setters
déléguant à _wsInitData. Seulement 20 propriétés, zéro conflit.

+ Restauré les directives Alpine (x-show, x-for, :style) dans le menu
  puisque le scope Alpine fonctionne maintenant.
2026-07-13 11:05:34 -04:00
bruno 0a0a330b55 fix: ctx-menu a son propre x-data="_wsInitData" pour que les directives Alpine internes fonctionnent
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le .ctx-menu était hors du scope _wsInitData dans le DOM (sibling du wrapper).
Ajouter x-data directement sur l'élément lui donne accès à toutes les variables
Alpine internes (ctxTagExistingOpen, ctxTagAdding, ctxAvailTags, ctxTagColors, etc.)

Les toggles de dropdown utilisent maintenant du DOM natif pour éviter les
problèmes de scope.
2026-07-13 10:48:32 -04:00
bruno 92eca626b7 fix: tags contextuels — couleur envoyée et stockée par l'API
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Backend (dashboard.py):
- POST /api/local-workspace/items/<id>/tags accepte maintenant 'color'
- INSERT INTO tags (name, color) au lieu de INSERT INTO tags (name)
- Si tag existe déjà, garde sa couleur existante

Frontend (local_workspace.html):
- ctxAddNewTag envoie {name, color} dans le body de la requête
  (avant: seul {name} était envoyé, la couleur était ignorée)
2026-07-13 10:45:47 -04:00
bruno 0ad1a69994 fix: menu contextuel en DOM natif (bypass Alpine)
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Alpine ne détecte pas les changements sur ctxMenu (objet imbriqué
hors du scope _wsInitData dans le DOM). Le :style et x-show restent
bloqués sur les valeurs initiales.

Solution radicale: manipulation DOM directe
- onContextMenu: menu.style.display='block' + position left/top
- ctxMenuOpen*/Rename/Duplicate/Delete: menu.style.display='none'
- @click.outside/@keydown.escape: DOM direct aussi
- ctx-menu HTML: style="display:none" initial
2026-07-13 10:33:52 -04:00
bruno 3e291ddc67 fix: ctx-menu utilise :style display au lieu de x-show
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
x-show="ctxMenu.visible" ne réagit pas aux changements d'objet imbriqué
dans Alpine. :style avec display: ctxMenu.visible ? 'block' : 'none'
est bindé directement sur le style inline, donc réactif.
2026-07-13 10:31:01 -04:00
bruno a57b435bd2 fix: contexte menu — sync raw data to Alpine via réassignation
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
_wsInitData.onContextMenu() remplit _wsInitData.ctxMenu
→ ctxMenu = _wsInitData.ctxMenu recopie dans Alpine
→ Alpine détecte le changement et affiche le menu
2026-07-13 10:29:14 -04:00
bruno c096f09b79 fix: ctxMenu réactivité Alpine — réassignation complète au lieu de propriétés
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Alpine ne détecte pas les changements sur les propriétés imbriquées
d'un objet (ctxMenu.visible = true). Il faut réassigner l'objet entier:
this.ctxMenu = {visible:true, x:..., y:..., node:..., tags:...}

Impact: onContextMenu (show), ctxMenuOpenPage/OpenFolder/Rename/Duplicate/Delete (hide)
+ repositionnement dans nextTick
2026-07-13 10:28:34 -04:00
bruno 74651ee26c fix: contexte menu — .call() pour binder this à Alpine
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le Alpine proxy ne contient pas les méthodes (onContextMenu, onTouchStart, etc.)
car l'objet _wsInitData est mergé avec appState() et les fonctions ne sont
pas copiées comme propriétés directes.

Fix: _wsInitData.onContextMenu.call(, )
→  = Alpine data réactive → this.ctxMenu.visible = true fonctionne
2026-07-13 10:27:13 -04:00
bruno 282eecf80c fix: menu contextuel right-click + long-press mobile
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Desktop:
- @contextmenu.prevent corrigé: window._wsData → onContextMenu()
  (window._wsData n'existait pas, le handler était mort)

Mobile:
- @touchstart/@touchmove/@touchend ajoutés sur ws-split
- Détection long-press: >600ms sans mouvement >10px
- Recherche du [data-ws-id] le plus proche
- Appel onContextMenu avec les coordonnées tactiles

Fermeture:
- @click.outside ajouté sur .ctx-menu
- @click.self maintenu sur ws-split pour fermer en cliquant ailleurs
2026-07-13 10:25:54 -04:00
bruno b865b5da6c fix: ws-split fermait prématurément (>) — les attributs devenaient du texte
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Le > de fermeture était sur la même ligne que <div class="ws-split">
→ les attributs (@contextmenu, @click, tabindex, x-ref) sur les lignes
  suivantes devenaient du contenu texte affiché dans la page.

Fix: > déplacé à la fin de x-ref="layout">
2026-07-13 09:56:22 -04:00
bruno 589035336d fix: _wsInitData global (sans var) pour que Alpine x-data le trouve
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 09:45:09 -04:00
bruno c8685b6dcc fix: wrapper x-data _wsInitData englobant tout le contenu
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
Les modals (create/rename/delete) étaient des siblings de ws-split dans le DOM,
pas des enfants — à cause d'un problème de nesting HTML avec les <template> Alpine.
Résultat: x-show="showCreate" ne trouvait pas 'showCreate' dans le scope parent.

Fix: wrapper <div x-data="_wsInitData"> autour de tout le {% block content %},
plus déplacement des @dragover/@dragleave/@drop/@keydown sur ce wrapper.
Le ws-split garde ses attributs restants (@contextmenu, @click, tabindex, x-ref).
2026-07-13 09:43:46 -04:00
bruno b555b67546 revert: remettre les icônes seules (l'utilisateur veut juste corriger l'action)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-13 09:39:01 -04:00
bruno a77eab6050 fix: boutons New File/New Folder avec texte visible + CSS btn-create
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Ajouté texte 'New File' et 'New Folder' aux boutons icônes
- Ajouté CSS .btn-create avec width:auto pour accommoder le texte
  (l'ancien CSS .btn-icon imposait width:34px fixe qui coupait le texte)
- Les boutons étaient des icônes seules (📄 📁) sans texte,
  donc difficiles à trouver pour l'utilisateur
2026-07-13 09:28:14 -04:00
bruno b94d25bff5 fix: injecter toutes les props _wsInitData comme globales window
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Alpine évalue les expressions comme tree, flatTree, online, etc.
dans un scope qui n'hérite pas toujours de _wsInitData.
En les exposant comme window.X, Alpine les trouve toujours.

Supprime les 36 erreurs restantes sur /local-workspace.
2026-07-13 08:16:10 -04:00
bruno ca73c6902f fix: x-data sans window. prefix + suppression x-for inutile
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Changé x-data="window._wsInitData" → x-data="_wsInitData"
  (Alpine évalue mieux sans le préfixe global)
- Supprimé <template x-for="node in flatTree"> dans une table cachée
  (x-show="false", jamais visible mais Alpine l'évaluait quand même)
2026-07-13 08:15:20 -04:00
bruno 6f8976817a fix: 148 erreurs Alpine.js — IIFE avant le DOM x-data
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Cause: l'IIFE window._wsInitData était située APRÈS le <div ws-split>.
Alpine évaluait x-data="window._wsInitData" AVANT que l'IIFE ne tourne
→ toutes les propriétés (flatTree, tree, online, ctxMenu, preview*, etc.)
   étaient undefined → 148 erreurs Alpine Expression Error.

Fix: déplacement de l'IIFE (lignes 871-2405) avant le ws-split (ligne 339).
Ordre corrigé: IIFE → _wsInitData prêt → ws-split x-data OK.

Vérification: le diagnostic log « ws-split about to render, _wsInitData exists: »
affichera maintenant true au lieu de false.
2026-07-13 08:10:03 -04:00
bruno ae3f8b473a feat: frontend error capture — diagnostic instantané pour Hermes
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- app.js: intercepte window.onerror + unhandledrejection
  Envoie automatiquement au backend via POST /api/frontend-error
  Déduplication, throttling 1/sec, max 50 erreurs buffer local
  window.__flowdeck_errors accessible en console debug

- api.py: 2 nouvelles routes
  POST /api/frontend-error — reçoit erreurs JS, déduplique, logge
  GET /api/frontend-errors?clear=true — Hermes lit les erreurs

- csrf.py: exemption /api/frontend-error du CSRF

Usage Hermes après chaque déploiement:
  curl -s http://localhost:8080/api/frontend-errors | jq .
  → Voir TOUTES les erreurs JS en temps réel
2026-07-13 07:52:52 -04:00
bruno 3718ad488c fix: 6 getters → propriétés plain + _recompute() (étape 1)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Alpine 3.14.9 ne supporte pas les getters dans le Proxy x-data.
Converti en propriétés mises à jour via _recompute() dans:
- init() après chargement tree
- _loadFolder() après chaque navigation
- doSort() / doFilter() après modifs

Getters remplacés:
- pathValue, canGoBack, canGoForward, flatTree,
  filteredTableItems, contentSnippetMap
- _computeFilteredTableItems() extrait de get filteredTableItems

Zéro getter restant, braces/parens équilibrés, 73 tests OK
2026-07-12 22:24:24 -04:00
bruno e34ef6193c Fix Alpine.js _wsInitData global access in workspace template
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-12 21:12:52 -04:00
bruno 9a0a8893c8 fix: 3 derniers ; → , dans les expressions Alpine (15 total)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- addTag(...); → addTag(...),
- ctxAddExistingTag(t); → ctxAddExistingTag(t),
- ctxAddNewTag(...); → ctxAddNewTag(...),

Zéro ; restant dans les expressions Alpine. Vérifié par script.

73 tests OK
2026-07-12 20:59:03 -04:00
bruno 1c88afda85 fix: tous les ; → , dans les expressions Alpine (12 occurrences)
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
Cause racine: local_workspace.html override le block topbar avec son
propre hamburger button qui avait encore ; au lieu de , dans l'expression
ternaire. Alpine parse les expressions via return <expr> → le ; terminait
le return prématurément → SyntaxError → cascade d'échecs d'initialisation
des composants enfants.

Corrigé dans:
- base.html: sidebar overlay @click (1 occurrence)
- local_workspace.html topbar hamburger (1 occurrence)
- local_workspace.html: 10 autres expressions (viewMode, searchQuery,
  filterType, draggedItemId, tagFilter, ctxAddNewTag, navigateToPath)

73 tests OK
2026-07-12 20:45:24 -04:00
bruno 2f3e52ebb0 fix: ; → , dans l'expression ternaire appState() — cause racine de toutes les ReferenceError
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
Le hamburger button avait mobileSidebarOpen = true; sidebarCollapsed = false
Le ; casse le parser d'expression Alpine (return <expr> → le ; termine le statement)
En cascade, l'erreur empêche l'initialisation correcte du composant parent,
ce qui brise tous les composants enfants (wsInit → ctxMenu, modals, preview, etc.)

C'est le bug qui persistait depuis des jours à travers 5+ approches différentes.
2026-07-12 20:40:05 -04:00
bruno c3291b0231 debug: console.log diagnostics pour identifier si cache ou bug Alpine
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-12 20:32:46 -04:00
bruno 9d300d1984 fix: var _wsInitData globale + anti-cache headers HTML
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- x-data="_wsInitData" référence la variable globale JS (pas window.)
- var _wsInitData = IIFE — propriété window automatique pour compatibilité window._wsData
- Headers Cache-Control: no-cache, no-store, must-revalidate sur la page HTML
- 73 tests OK
2026-07-12 20:24:49 -04:00
bruno 996e50bb06 fix: x-data="window._wsInitData" — IIFE synchrone contourne les bugs Alpine.data/alpine:init
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- window._wsInitData = (function() { return {...}; })() — exécution synchrone garantie
- x-data pointe directement sur l'objet global, sans enregistrement Alpine requis
- Contourne les problèmes de timing alpine:init vs Alpine.data vs nested x-data
- 73 tests OK
2026-07-12 20:20:11 -04:00
bruno cce132d771 fix: Alpine.data() avec x-data="wsInit" (sans parenthèses) + cache busting v2.4.6
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- Changé function wsInit() → Alpine.data('wsInit', ...) avec addEventListener('alpine:init')
- x-data="wsInit()" → x-data="wsInit" (syntaxe correcte pour Alpine.data)
- Ajouté ?v=2.4.6 sur CSS et JS pour bust le cache navigateur
- Version bumpée à 2.4.6
2026-07-12 19:55:30 -04:00
bruno dc630c9ba7 fix: wsInit() en fonction globale — contourne Alpine.data qui ne s'enregistrait pas
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- wsInit() était enregistré via Alpine.data() dans alpine:init →
  ne fonctionnait pas → toutes les variables undefined (ReferenceError)
- Changé en function wsInit() globale → x-data='wsInit()' appelle
  la fonction directement, zéro enregistrement Alpine
- Supprimé les wrappers Alpine.data() et addEventListener('alpine:init')
- Braces vérifiés: 397/397 équilibrés
- window._wsData.set dans init() avant await (contexte menu)
2026-07-12 18:06:43 -04:00
bruno 9ee0079a02 fix: contexte menu — window._wsData global + exposé avant await
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- @contextmenu.prevent passe par window._wsData (global) au lieu du scope Alpine
  → contourne tout problème de résolution de scope Alpine
- window._wsData = this déplacé AVANT le await fetch(...) dans init()
  → disponible immédiatement, pas après la réponse API
- Conserve @click.self pour fermer le menu en cliquant sur le fond
2026-07-12 18:05:20 -04:00
bruno 40a5d4edeb fix: @contextmenu.prevent remis (avait été perdu lors du revert)
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Erreur critique: @contextmenu.prevent="onContextMenu" manquait
  → le handler n'était JAMAIS appelé par Alpine
- Rajouté @contextmenu.prevent sur ws-split (entre @keydown et @click.self)
- ctxMenu utilise mutations individuelles (pas de remplacement d'objet)
  pour une meilleure réactivité Alpine
- @click.self conserve la fermeture en cliquant sur le fond du workspace
2026-07-12 18:01:36 -04:00
bruno 4dc9ff29b8 fix: menu contextuel — @click.away retiré, @click.self sur ws-split pour fermer
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- @click.away sur ctx-menu retiré (fermait le menu immédiatement)
- Fermeture via @click.self sur ws-split (clic sur fond du workspace)
- Fermeture via Escape (déjà présent)
- Fermeture via les items du menu (ctxMenuOpenPage, etc.)
- Mode debug: console.log conservé pour confirmer l'appel handler
2026-07-12 17:54:14 -04:00
bruno aec11a670a debug: console.log dans onContextMenu + revert au fichier stable
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Ajouté console.log('onContextMenu fired') pour diagnostiquer si le handler
  Alpine est bien appelé au clic droit
- Fichier local_workspace.html restauré depuis b32b94e (sans le handler
  natif cassé qui causait des erreurs Alpine)
- Vérifier la console navigateur: si 'onContextMenu fired' apparaît au
  clic droit, le problème est post-handler. Sinon, c'est Alpine/l'événement
2026-07-12 17:47:48 -04:00
bruno 6e05f9e700 fix: menu contextuel — handler natif addEventListener remplace Alpine @contextmenu
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Le handler Alpine @contextmenu.prevent="onContextMenu" ne fonctionnait pas
  (problème de scope/resolution Alpine sur le clic droit)
- Remplacement par addEventListener('contextmenu', ...) natif dans init()
  → événement capturé directement sur le DOM, bypass complet Alpine
- Propriétés ctxMenu modifiées individuellement (pas d'objet remplacé)
  pour garantir la réactivité Alpine sur les nested properties
- L'ancien handler onContextMenu est gardé en fallback avec le même pattern
- Suppression du @contextmenu.prevent du template HTML (évite double-fire)
2026-07-12 17:42:18 -04:00
bruno b32b94e863 fix: menu contextuel — @click.outside → @click.away (corrige fermeture immédiate)
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- @click.outside détectait le clic-droit d'ouverture comme 'outside' → menu
  fermé immédiatement après ouverture. Même bug que le dropdown sidebar.
- @click.away utilise setTimeout → le handler s'enregistre APRÈS le cycle
  d'événement courant → le clic d'ouverture n'est pas capté comme 'away'.
- Fonctionne dans TOUTES les vues: tree (renderChildren), list, details,
  cards, content — elles ont toutes data-ws-id
2026-07-12 17:36:49 -04:00
bruno 58eacaa9d6 perf: éléments remontés au maximum — topbar 40px + paddings réduits
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- --topbar-height: 44px → 40px (gain 4px)
- .ws-split: padding-top 8px → 0, min-height via var(--topbar-height)
- .breadcrumb-row: padding 3px→2px, gap 6px→4px, nav-arrow 24px→22px,
  border-radius 10px→8px
- .toolbar-row: padding 3px→2px, gap 6px→4px, margin-bottom 4px→2px,
  border-radius 10px→8px
- Gain total vertical: ~14px (8+4+2). Tout est plus compact.
2026-07-12 17:31:08 -04:00
bruno 85e73f8c49 fix: bouton show sidebar ☰ dans breadcrumb row, à gauche de 🏠
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Bouton ☰ (x-show="sidebarCollapsed") positionné juste AVANT le bouton
  All Workspaces dans la breadcrumb row. Apparaît seulement quand sidebar
  est cachée, disparaît quand elle est visible.
- Scope Alpine: sidebarCollapsed hérité de appState() (parent de wsInit())
- Remplace l'ancien bouton fixed qui chevauchait le contenu
2026-07-12 17:27:22 -04:00
bruno 94e5e9c9f4 chore: script bump_version.py — plus jamais oublier de bumper
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-12 17:22:37 -04:00
bruno 2abcfcf7d9 chore: bump version 2.3.0 → 2.4.0
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
La version était restée bloquée à 2.3.0 depuis des dizaines de déploiements.
Changements cumulés depuis 2.3.0:
- Settings panel overlay Notion-style (Account, Workspace, Features, Admin)
- Avatar upload + 14 couleurs prédéfinies, persistance DB, affichage sidebar/dropdown
- Menu contextuel tags: couleurs, sous-menus pliables, repositionnement dynamique
- Pastilles tags colorées dans toutes les vues
- Default view persistant (localStorage, 5 vues)
- Favicon SVG FD
- Menu dropdown fixé (click.away, position:relative, overflow)
- Bouton uncollapse intégré au hamburger topbar
- Layout compacté (padding réduit, éléments remontés)
- CSRF /api/settings exempté
2026-07-12 17:22:03 -04:00
bruno 6cc94ecefa fix: uncollapse dans hamburger topbar + padding réduit → plus haut
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Bouton show sidebar (uncollapse) supprimé de position:fixed → intégré au
  hamburger du topbar. Si sidebar collapsed → hamburger l'ouvre directement.
  Plus aucun chevauchement avec le contenu.
- .ws-split padding: 40px 24px 0 → 8px 16px 0 (gain 32px verticaux)
- Tous les éléments sont remontés, plus d'espace visible sans scroll
2026-07-12 17:19:23 -04:00
bruno 6db8eba670 feat: pastilles tags colorées dans toutes les vues + ajustements hauteur
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Tags affichés avec pastille de couleur (tag-dot 6px) dans TOUTES les vues:
  tree (renderChildren), table filtrée, details, cards, content, preview panel
- Barre de filtres tags: pastille couleur + nom + compteur
- CSS .tag-dot: cercle 6px avec background dynamique
- Hauteur réduite: breadcrumb-row padding 3px, toolbar-row padding 3px
  margin-bottom 4px, flèches nav 24px au lieu de 28px
- Bouton show sidebar (uncollapse): top 60px au lieu de 12px →
  ne chevauche plus la breadcrumb/toolbar
2026-07-12 16:59:06 -04:00
bruno ed0510ec9b fix: Default view dropdown settings — 5 vues + style + persistence
FlowDeck CI / test (push) Failing after 10s
FlowDeck CI / docker (push) Has been skipped
- Select remplacé: class sort-select (mal stylé) → settings-select (adapté)
- 5 vues: Tree, List, Details, Cards, Content (plus seulement 3)
- x-model="defaultView" + @change="saveDefaultView()"
- Sauvegarde localStorage 'fd_default_view'
- workspace page lit localStorage pour viewMode initial
- Settings → Default view persiste entre sessions et s'applique au workspace
2026-07-12 16:48:41 -04:00
bruno 48f33964b0 fix: avatar persistant — correction référence template + avatar dropdown
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- settings.html: avatarUrl lisait user.avatar_url (dict session, inexistant)
  → corrigé en {{ avatar_url }} (variable template top-level de _sidebar_data)
- settings.html: avatarColor lisait user.get("avatar_color") (idem)
  → corrigé en {{ avatar_color }}
- base.html: dropdown user-menu affiche maintenant l'avatar avec couleur/URL
  au lieu du workspaceInitial statique (pas de synchronisation)
2026-07-12 16:44:18 -04:00
bruno 14ad34c886 fix: avatars persistant — route fichier + couleur en DB + sidebar affichage
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Route manquante GET /api/settings/avatar/{filename} → sert le fichier uploadé
  (résout le 404 sur l'image uploadée)
- Colonne avatar_color ajoutée à users (migration ALTER TABLE try/except)
- set_avatar_color sauvegarde la couleur dans la DB (pas seulement local)
- _sidebar_data() lit avatar_url + avatar_color depuis la DB
- Sidebar avatar: fond coloré quand pas d'image, image quand uploadée
  avec background-image:url() + initiale en fallback
2026-07-12 16:38:21 -04:00
bruno 4668eb77ed fix: favicon SVG — remplace le 404 favicon.ico
FlowDeck CI / test (push) Failing after 8s
FlowDeck CI / docker (push) Has been skipped
- SVG 32×32: fond bleu accent #2383E2, texte 'FD' blanc, coins arrondis
- Ajouté <link rel=icon type=image/svg+xml> dans <head> de base.html
- Fichier static/favicon.svg servi via le mount /static existant
2026-07-12 16:28:39 -04:00
bruno 329948cf4c fix: repositionnement dynamique du menu contextuel dans le viewport
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Remplacé le clamping statique (Math.min 200/300) par mesure réelle
  du menu après rendu DOM via $nextTick + getBoundingClientRect()
- Si le menu dépasse à droite → repositionné à gauche
- Si le menu dépasse en bas → repositionné vers le haut
- Marge de 4px des bords pour éviter le clipping
- Fonctionne pour toutes les tailles de menu (tags, sous-menus dépliés)
2026-07-12 16:25:13 -04:00
bruno 130a8a09ad fix: menu contextuel — tous les tags visibles + sélection couleur en grille
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- loadWorkspaceTags() utilise /api/settings/tags/all (TOUS les tags, pas
  seulement ceux déjà utilisés via JOIN page_tags). Avant: 2/6 tags visibles.
- Nouvelle grille couleurs 'New tag': grid 7 colonnes × 2 rangées,
  carrés responsifs via padding-bottom:100%. + bouton Add à droite.
- .ctx-menu: max-height:80vh + overflow-y:auto → plus de clipping
  en bas de fenêtre. z-index 600 (au-dessus du settings panel).
- .color-swatch-ctx: carrés parfaits dans la grid, hover scale 1.15
2026-07-12 15:53:57 -04:00
bruno 1f31e33b69 feat: menu contextuel — sous-menu 'Add existing tag' + 'New tag' pliables
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- 📋 Add existing tag: item cliquable qui déplie la liste des tags configurés
  avec pastilles de couleur, noms et compteurs. Clic sur un tag → ajout + repli
- ➕ New tag: item cliquable qui déplie palette couleurs + input texte
- Chevrons ▸/▾ indiquent l'état ouvert/fermé
- ctxTagExistingOpen state réinitialisé à chaque ouverture du menu
- Les tags déjà assignés restent visibles en haut avec ✕ pour retirer
2026-07-12 15:44:37 -04:00
bruno 97eda84cd1 feat: menu contextuel — tags avec couleurs + liste des tags disponibles
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Section TAGS toujours visible (plus besoin de cliquer pour ouvrir un sous-menu)
- Tags existants affichés avec leur pastille de couleur (⦿ 10px) + bouton ✕
- Liste des tags DISPONIBLES (pas encore assignés) avec couleurs,
  clic → ajoute le tag à l'élément. Compteur d'utilisation affiché
- Palette 14 couleurs pour créer un nouveau tag (carrés 18px arrondis)
- Input pour nouveau tag avec palette de couleurs
- CSS: .ctx-section, .ctx-tag-color, .color-swatch-ctx, .ctx-add-tag-item
2026-07-12 15:40:24 -04:00
bruno 7fe7a91788 feat: avatars prédéfinis par couleur + fix CSRF avatar/tags
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Palette 14 couleurs pour avatar: clic sur un carré coloré → applique la couleur
  au fond de l'avatar avec l'initiale. API POST /api/settings/avatar-color
- Upload photo: efface la couleur custom et utilise l'image uploadée
- Color swatches tags: border-radius 6px (carrés arrondis) au lieu de 50% (ovales)
- CSRF: /api/settings ajouté à EXCLUDED_PATHS → 403 corrigé sur avatar + tags
2026-07-12 15:32:30 -04:00
bruno 6d0647f83d fix: CSRF avatar upload + tags settings + color swatches carrés
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- /api/settings ajouté à EXCLUDED_PATHS → avatar upload et tags CRUD
  n'étaient pas exemptés du CSRF → 403 Forbidden sur POST/PUT/DELETE
- Color swatches: border-radius 6px (carrés arrondis) au lieu de 50% (ovales)
- Avatar upload et tags create/update/delete fonctionnent maintenant
2026-07-12 15:30:23 -04:00
bruno e3968356e2 feat: settings panel overlay Notion-style + avatar upload + sections
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
- Settings page refaite en panneau overlay (position:fixed + backdrop-blur)
- Layout 2 panes: nav sidebar gauche + contenu droit
- Sections: Account (profile + avatar upload), Notifications, Workspace,
  Tags management, Features (integrations), Admin (security)
- Avatar: upload image (POST /api/settings/avatar), preview instantané,
  stockage /data/avatars/, mise à jour users.avatar_url
- GET /api/avatar/{user_id} redirige vers l'image avatar
- Tags: palette couleurs, création, suppression, changement couleur
- Fermeture: bouton × ou Escape (window.history.back)
2026-07-12 15:22:31 -04:00
bruno d01b51bd5b fix: menu dropdown — 3 corrections pour que le menu s'ouvre enfin
FlowDeck CI / test (push) Failing after 5s
FlowDeck CI / docker (push) Has been skipped
1. @click="workspaceMenuOpen = !workspaceMenuOpen" inline (pas toggleWorkspaceMenu)
2. @click.away (pas click.outside) — click.away ignore le clic sur le trigger
3. Wrapper <div style=position:relative> autour header+dropdown →
   position:absolute s'ancre correctement, header et dropdown sont siblings
   donc le clic header ne déclenche PAS le @click.away du dropdown
2026-07-12 14:40:29 -04:00
bruno 4bdd4dfd90 fix: 'Root' retiré du path + menu dropdown clippé par overflow sidebar
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- folderStack: supprimé {id:0, name:'Root'} dans init() et navigateToRoot()
  → breadcrumb n'affiche plus 'Workspace / Root' mais juste 'Workspace / dossier'
- Sidebar: overflow-y:auto déplacé de .sidebar vers .sidebar-scroll (flex child)
  → le header et son dropdown ne sont PLUS clippés par overflow
  → position: absolute + top:100% fonctionne maintenant sur le dropdown
- .sidebar-scroll wrapper autour du contenu scrollable (nav row → footer)
2026-07-12 14:34:28 -04:00
bruno 4f66bf2312 fix: 🏠 à gauche des flèches ← → dans breadcrumb, topbar nettoyée
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Bouton All workspaces (🏠) déplacé du topbar-right vers le breadcrumb row,
  positionné AVANT les flèches ← → de navigation
- Retiré 📁 icône + nom workspace du topbar (redondant avec le breadcrumb)
- Topbar allégée: hamburger menu + breadcrumb serveur uniquement
2026-07-12 14:23:51 -04:00
bruno e0987e38ff fix: dropdown menu + collapse en double retiré
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Retiré le bouton collapse en double dans la nav row (déjà dans le header)
- Ajouté position: relative sur .sidebar-workspace-header → dropdown s'ancre
  correctement sous le header au lieu de se positionner n'importe où
- Sans position: relative, le dropdown absolute remontait jusqu'à un ancêtre
  positionné et sortait de l'écran ou était caché par overflow
2026-07-12 14:14:45 -04:00
bruno 6b2abcd9f2 fix: sidebar — collapse dans header + nom user + search dans nav row
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Collapse << dans le header (opacity 0, visible au hover avec @click.stop)
- Search 🔍 déplacé à droite du collapse dans la nav row
- Nom affiché: user.full_name ou user.login (pas workspaceName)
- Chevron ▾ conservé comme indicateur dropdown (tout le header reste cliquable)
2026-07-12 14:08:35 -04:00
bruno ec86c32245 fix: </div> en trop cassait la structure HTML du sidebar → page blanche
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Le patch précédent a retiré le wrapper <div style="display:flex..."> mais
  son </div> fermant est resté → balise fermante orpheline → DOM cassé
- Résultat: la page ne s'affiche plus du tout (rendu HTML invalide)
2026-07-12 14:00:19 -04:00
bruno d7c0d428e8 fix: sidebar — x-data vide masquait appState() + header Notion-style + null-guards
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Sidebar avait x-data vide qui créait un scope isolé → vars (workspaceMenuOpen,
  toggleWorkspaceMenu, sidebarCollapsed) introuvables → rien ne fonctionnait
- Suppression x-data → héritage du scope appState() parent
- Header restylé Notion: .sidebar-workspace-header avec border-radius + hover bg
- Mouse hover (mouseenter/mouseleave) active wsHeaderHover → fond plus clair
- Null-guards: folderStack[-1] sécurisé, ctxMenu.node && ctxMenu.node.is_folder
2026-07-12 12:53:46 -04:00
bruno ab0eedd5fe fix: previewPanel — x-if wrapper pour éviter 'Cannot read properties of null'
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Alpine évalue les expressions même dans x-show caché → previewItem null → crash
- Ajout de <template x-if="previewItem"> autour du preview panel entier
- x-if empêche toute évaluation tant que previewItem est null/false
2026-07-12 12:47:42 -04:00
bruno b74e144ab3 fix: échappement cassé dans _loadPreviewContent — quotes échappées causaient SyntaxError
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- window.location=\\'/path\\'" → <a href="..."> (évite onclick inline échappé)
- onerror="this.parentElement.innerHTML=\\'...\\'" → onerror="this.style.display='none'"
- Ces doubles-échappements injectés par le patch tool cassaient le parsing JS
- Résultat: Alpine.data('wsInit') ne s'exécutait pas → toutes variables 'not defined'
2026-07-12 12:45:26 -04:00
bruno c38b973281 fix: SyntaxError Alpine.js — 'for' inline dans @click remplacé par clearSelection()
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- @click='for(var k in selectedIds)...' causait SyntaxError: Unexpected token 'for'
- Cette erreur empêchait l'exécution de TOUT Alpine.data('wsInit', ...)
- Résultat: toutes les variables Alpine 'not defined' (cascade de 80+ erreurs)
- Fix: méthode clearSelection() appelée depuis @click, plus robuste et réactive
2026-07-12 12:38:54 -04:00
bruno 004c47df34 feat: sidebar user menu Notion-style + settings page + tag colors + preview images/PDF
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Sidebar header: user menu dropdown (Settings, Switch workspace, Log out)
  avec avatar + nom + email, chevron animé, fond opaque #1E1E1E
- Nouvelle page /settings avec gestion globale des tags:
  créer tag avec couleur, changer couleur, supprimer, liste avec compteurs
- API tag management: POST/PUT/DELETE /api/settings/tags, GET /api/settings/tags/all
- Preview panel: affichage images (img tag), PDF (lien viewer), détection format
- workspace-chevron CSS: rotation 180° quand menu ouvert
2026-07-12 12:35:17 -04:00
bruno 17f158ca18 Add Notion configuration and sidebar screenshot assets
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
2026-07-12 12:27:05 -04:00
bruno 6e2b2ff757 fix: opacité menus + contexte toutes vues + hover preview + split layout preview
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Menus dropdown et contextuel: fonds solides #1E1E1E au lieu de var(--bg) transparent
- Menu contextuel: data-ws-id sur TOUS les éléments (tree/list/details/title/content)
  + onContextMenu simplifié (cherche [data-ws-id] uniquement, plus de fallback fragile)
- Mouse-over preview (showPreview/hidePreview) ajouté sur toutes les vues
- Preview panel: split layout flex à côté du contenu au lieu de position:fixed overlay
  ws-split > ws-main | preview-panel
2026-07-12 12:15:07 -04:00
bruno 7fa9a44dbb feat: dropdown view + breadcrumb au-dessus + menu contextuel clic-droit
FlowDeck CI / test (push) Failing after 3s
FlowDeck CI / docker (push) Has been skipped
- Sélecteur de vue en dropdown (🌳 Tree ▾) au lieu des 5 boutons
- Layout split: breadcrumb row (chemin + ←→) au-dessus, toolbar row en dessous
- Menu contextuel clic-droit/long-press sur fichiers et dossiers:
  Open, Open folder, Rename, Duplicate, Tags (add/remove inline), Delete
- Gestion des tags depuis le menu contextuel avec sous-menu Tags
2026-07-12 12:02:46 -04:00
bruno 75dbdf2d4f refactor: barre de navigation unifiée — breadcrumb éditable + recherche intégrée
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Barre unique remplaçant breadcrumb + path bar + header: back/forward + chemin + toolbar
- Chemin cliquable avec navigation, double-clic pour rename inline
- Édition du path intégrée: clic ✎ → input inline au même endroit
- Barre de recherche intégrée dans la toolbar (compacte, à côté du sélecteur de vue)
- Filtres compactés: icônes seules, ligne unique avec bouton clear
- Gain d'espace vertical: ~80px libérés pour le contenu
2026-07-12 11:47:24 -04:00
bruno 21806aa14e fix: vues workspace affichent répertoire courant + navigation sans rechargement
FlowDeck CI / test (push) Failing after 4s
FlowDeck CI / docker (push) Has been skipped
- Vues list/details/title/content utilisent displayTree (enfants du dossier courant)
  au lieu de flatTree (arbre entier aplati) → comportement explorateur de fichiers
- Navigation sans rechargement: navigateToFolder/goToParent/goBack/goForward
  utilisent fetch AJAX + _loadFolder() au lieu de window.location
- folderStack remplace navHistory + breadcrumb: pile de navigation avec noms
- Breadcrumb dynamique: cliquable, affiche le chemin courant depuis folderStack
- _reloadAfterAction utilise _loadFolder au lieu de window.location.reload
- La vue choisie (tree/list/details/title/content) est préservée pendant la navigation
2026-07-12 11:37:10 -04:00
121 changed files with 12025 additions and 2250 deletions
+4
View File
@@ -5,6 +5,10 @@ GITEA_OAUTH_CLIENT_ID=
GITEA_OAUTH_CLIENT_SECRET=
GITEA_WEBHOOK_SECRET=
# ── GitHub ──
GITHUB_OAUTH_CLIENT_ID=
GITHUB_OAUTH_CLIENT_SECRET=
# ── App ──
APP_SECRET_KEY=change-me-to-random
APP_HOST=0.0.0.0
+254 -3
View File
@@ -1,7 +1,7 @@
# Architecture FlowDeck — Document Complet v2.0
# Architecture FlowDeck — Document Complet v3.0
> **Version:** 2.0 · **Date:** 2026-07-10 · **Auteur:** Hermes-Deepin
> **Cible:** Clone Notion intégré à Gitea avec support multi-utilisateurs
> **Version:** 3.0 · **Date:** 2026-07-14 · **Auteur:** Hermes-Deepin
> **Cible:** Clone Notion intégré à Gitea/GitHub — multi-comptes, multi-intégrations
---
@@ -800,6 +800,257 @@ User authorize ──→ GET /auth/callback?code=xxx
---
## 6.5 Modèle de comptes & intégrations (v4.0)
### 6.5.1 Types de comptes
FlowDeck supporte 3 types de comptes, déterminés par `auth_method` dans la table `users` :
```
┌──────────────┬──────────────────┬─────────────────────────────────────┐
│ auth_method │ Login via │ Identité dans le sidebar │
├──────────────┼──────────────────┼─────────────────────────────────────┤
│ local │ email + password │ Nom local (ex: "Draco") │
│ gitea │ OAuth2 Gitea │ Nom Gitea + badge 🦎 Gitea │
│ github │ OAuth2 GitHub │ Nom GitHub + badge 🐙 GitHub │
└──────────────┴──────────────────┴─────────────────────────────────────┘
```
**Règle fondamentale** : Un compte local avec intégration(s) reste un compte LOCAL.
Le badge OAuth (🦎/🐙) n'apparaît QUE pour les comptes dont `auth_method` est le provider.
```
Compte LOCAL avec intégrations :
┌──────────────────────────────────┐
│ [D] Draco │ ← Nom local, PAS de badge
│ [email protected] │
└──────────────────────────────────┘
Compte GITEA (auth_method=gitea) :
┌──────────────────────────────────┐
│ [B] bruno [🦎 Gitea] │ ← Badge visible
│ [email protected] │
└──────────────────────────────────┘
```
### 6.5.2 Matrice des intégrations
```
Compte principal Peut ajouter Déconnexion possible
─────────────────────────────────────────────────────────
local Gitea ✅ Oui
local GitHub ✅ Oui
local Gitea + GitHub ✅ Les deux
─────────────────────────────────────────────────────────
gitea GitHub ✅ GitHub ❌ Gitea
github Gitea ✅ Gitea ❌ GitHub
```
**Settings → Integrations** : Affiche toutes les intégrations avec bouton
Disconnect. Le provider principal (auth_method) n'a PAS de bouton Disconnect.
### 6.5.3 Scénarios de workspace
```
SCÉNARIO A : Compte local pur
─────────────────────────────
· Login email+password
· Workspaces locaux uniquement
· Section Private : CACHÉE (tout est déjà local)
· Trash : ✅ (restauration locale)
SCÉNARIO B : Compte local + intégration(s)
──────────────────────────────────────────
· Login email+password
· Workspaces : locaux + Gitea + GitHub
· Section Private : VISIBLE si workspace distant actif
· Private : stockage DB locale, associé user+repo
· Trash : ✅ (local uniquement)
SCÉNARIO C : Compte OAuth pur (gitea ou github)
────────────────────────────────────────────────
· Login via OAuth
· Workspaces : distants du provider principal
· Section Private : VISIBLE (toujours)
· Trash : ❌ (pas de contenu local)
· Intégration secondaire : possible
· Déconnexion provider principal : impossible
```
### 6.5.4 Sidebar — règles d'affichage par section
```
Section Scénario A Scénario B Scénario C
───────────── ────────────── ────────────────────── ──────────────
Recents ✅ (local) ✅ (tout) ✅ (tout)
Favorites ✅ (local) ✅ (tout) ✅ (tout)
Shared ✅ (local) ✅ (tout) ✅ (tout)
Published ✅ (local) ✅ (tout) ✅ (tout)
Agents ✅ ✅ ✅
Private ❌ CACHÉ ✅ si ws distant actif ✅
Workspace ✅ ✅ ✅
Trash ✅ (local) ✅ (local) ❌
```
Chaque section a un bouton `→ Library` qui ouvre :
```
/library?tab=recents|favorites|shared|published|private|workspace
```
### 6.5.5 Système Share & Publish
Le bouton [Share] dans la topbar d'une page ouvre une modale à 2 tabs :
```
┌──────────────────────────────────────────────────────┐
│ [ Share ] [ Publish ] │
├──────────────────────────────────────────────────────┤
│ Share tab : │
│ · Invite people : [email] [Invite] │
│ · General access : [🔒 Restricted] Copy link │
│ · Liste des personnes/groupes avec accès │
│ → Document listé dans sidebar "Shared" │
├──────────────────────────────────────────────────────┤
│ Publish tab : │
│ · [Publish to web] → URL publique générée │
│ · URL : https://flowdeck.draco.dev/p/<slug> │
│ · [Unpublish] │
│ → Document listé dans sidebar "Published" │
└──────────────────────────────────────────────────────┘
```
### 6.5.6 Stockage des fichiers Private
Quand un workspace distant est actif, les fichiers créés dans la section
Private sont stockés dans la **base de données locale** (table `pages` avec
`parent_section='Private'` et `workspace=gitea:<owner>/<repo>`).
Cela permet de :
- Prendre des notes personnelles liées à un projet sans les committer
- Garder des brouillons avant de les pousser
- Avoir un espace de travail privé même sur un repo partagé
### 6.5.7 Trash — règles
```
Contenu Trash ? Comportement
─────────────────────── ──────── ──────────────────────────
Workspace local ✅ Supprimé → restaurable
Dossier/fichier local ✅ Supprimé → restaurable
Fichier Gitea/GitHub ❌ Commit "delete" → pas trash
Page distante ❌ Commit "delete" → pas trash
```
### 6.5.8 Édition de fichiers — UI unifiée
```
Fichier LOCAL Fichier DISTANT (Gitea/GitHub)
┌─────────────────────────┐ ┌─────────────────────────────┐
│ Même UI d'édition │ │ Même UI d'édition │
│ Même rendu visuel │ │ Même rendu visuel │
│ Sauvegarde auto DB │ │ + Bouton [Commit] │
│ Pas de commit │ │ + Champ message commit │
└─────────────────────────┘ └─────────────────────────────┘
```
### 6.5.9 Page Library — `/library?tab=<tab>`
```
┌──────────────────────────────────────────────────────────────┐
│ Library │
│ [Recents] [Favorites] [Shared] [Published] │
│ [Private] [Workspace] │
├──────────────────────────────────────────────────────────────┤
│ Filtres : [All] [Local] [Gitea] [GitHub] │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 📄 Document X Local · modifié il y a 2h │ │
│ │ 📄 README.md Gitea · bruno/flowdeck │ │
│ │ 📄 Notes Local · Workspace Projet A │ │
│ └─────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
```
### 6.5.10 Schéma DB — mises à jour pour v4.0
```sql
-- users : ajout auth_method
ALTER TABLE users ADD COLUMN auth_method TEXT NOT NULL DEFAULT 'local';
-- 'local' | 'gitea' | 'github'
-- users : colonnes OAuth existantes
-- gitea_id INTEGER (NULL si pas Gitea)
-- github_id INTEGER (NULL si pas GitHub)
-- gitea_token TEXT (token intégration, NULL si pas connecté)
-- github_token TEXT (token intégration, NULL si pas connecté)
-- pages : ajout published
ALTER TABLE pages ADD COLUMN is_published BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE pages ADD COLUMN publish_slug TEXT;
ALTER TABLE pages ADD COLUMN is_shared BOOLEAN NOT NULL DEFAULT 0;
ALTER TABLE pages ADD COLUMN share_mode TEXT DEFAULT 'restricted';
-- 'restricted' | 'link' | 'public'
-- page_shares : qui a accès à quel document
CREATE TABLE page_shares (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
shared_with_user_id INTEGER REFERENCES users(id),
shared_with_email TEXT,
permission TEXT NOT NULL DEFAULT 'view',
-- 'view' | 'comment' | 'edit'
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER REFERENCES users(id)
);
-- recents : historique de consultation
CREATE TABLE recents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
page_id INTEGER NOT NULL REFERENCES pages(id),
workspace TEXT NOT NULL,
source_type TEXT NOT NULL DEFAULT 'local',
-- 'local' | 'gitea' | 'github'
accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, page_id)
);
```
### 6.5.11 Plan de migration
```
Phase 1 — DB & Modèles
1. Ajouter auth_method aux users existants (auto-détecter)
2. Ajouter is_published, is_shared, share_mode aux pages
3. Créer table page_shares
4. Créer table recents
Phase 2 — Sidebar
1. Badge OAuth (🦎/🐙) basé sur auth_method
2. Afficher/cacher Private selon type de compte + workspace actif
3. Boutons Library par section
4. Trash filtré local-only
Phase 3 — Share & Publish
1. Modale Share à 2 tabs fonctionnelle
2. Share via email/user → table page_shares
3. Share via lien → share_mode='link'
4. Publish → is_published + publish_slug
5. Page publique servable à /p/<slug>
Phase 4 — Library
1. Page /library avec tabs
2. Filtrage par source (local/gitea/github)
3. Recents alimentés automatiquement
Phase 5 — Intégrations
1. GitHub OAuth déjà fait (providers.py)
2. Matrice de déconnexion respectée
3. Compte local peut connecter/déconnecter Gitea+GitHub
```
---
## 7. Intégration Gitea
### 7.1 Flux de données
+108
View File
@@ -0,0 +1,108 @@
# Stratégie de branches — FlowDeck
## Structure
```
main ──●────────────●────── production (tags vX.Y.Z)
\ /
develop ●──●──●──●────── intégration continue
\ \ \
feat/xxx ● ● ●──── feature branches
fix/xxx ●─────────── hotfix branches
```
## Branches
| Branche | Rôle | Déploiement | Protection |
|---------|------|-------------|------------|
| `main` | Production | Docker auto sur :8080 | Push direct interdit, PR only |
| `develop` | Intégration | Staging (optionnel) | Push direct interdit, PR only |
| `feat/<nom>` | Nouvelle feature | Aucun | Libre |
| `fix/<nom>` | Correctif urgent | Aucun | Libre |
## Workflow quotidien
### 1. Démarrer une feature
```bash
git checkout develop
git pull origin develop
git checkout -b feat/ma-feature
```
### 2. Travailler
```bash
# Coder, commit souvent
git add -A
git commit -m "feat: description claire de ce qui est fait"
git push origin feat/ma-feature
```
### 3. Créer une Pull Request
Aller sur https://git.dracodev.net/bruno/flowdeck/pulls
- **Base** : `develop`
- **Head** : `feat/ma-feature`
- Titre : descriptif
- Assigner un reviewer si applicable
### 4. Après merge
```bash
git checkout develop
git pull origin develop
git branch -d feat/ma-feature # supprimer la branche locale
```
## Release (develop → main)
```bash
# 1. S'assurer que develop est prêt
git checkout develop
git pull origin develop
# 2. Créer une PR develop → main sur Gitea
# (ou merger localement si admin)
git checkout main
git merge develop
git tag v4.0.1
git push origin main --tags
```
## Hotfix urgent
```bash
git checkout main
git checkout -b fix/urgence
# ... corriger ...
git commit -m "fix: description"
git push origin fix/urgence
# PR fix/urgence → main
# PUIS merger main → develop pour synchroniser
git checkout develop
git merge main
git push origin develop
```
## Conventions de commits
| Préfixe | Usage | Exemple |
|---------|-------|---------|
| `feat:` | Nouvelle fonctionnalité | `feat: landing page for visitors` |
| `fix:` | Correction de bug | `fix: redirect loop on /` |
| `refactor:` | Restructuration sans changement fonctionnel | `refactor: extract sidebar_data` |
| `test:` | Ajout/modification de tests | `test: onboarding flow e2e` |
| `docs:` | Documentation | `docs: update ROADMAP.md` |
| `style:` | Formatage, CSS | `style: mobile sidebar fixes` |
| `chore:` | Tâches de maintenance | `chore: bump version to 4.0.1` |
## Règles
1. **Jamais de push direct sur `main`** — toujours via PR depuis `develop` ou `fix/*`
2. **Jamais de push direct sur `develop`** — toujours via PR depuis `feat/*` ou `fix/*`
3. **Une branche = une feature / un fix** — éviter les branches fourre-tout
4. **Tests passent avant merge** — CI Gitea Actions doit être verte
5. **Commit + push après chaque modification significative**
6. **Nom de branche en kebab-case** : `feat/landing-page`, `fix/login-redirect`
7. **Supprimer la branche après merge** (sauf `main` et `develop`)
+76 -4
View File
@@ -1,9 +1,82 @@
# Changelog — FlowDeck
## v2.7.1 (2026-07-13) — Private Pages Gitea
### Added
- **Table `gitea_private_pages`**: pages FlowDeck locales liées à un projet Gitea (user_id, owner, repo)
- **API CRUD**: GET/POST/PUT/DELETE `/api/gitea/projects/{owner}/{repo}/private-pages`
- **UI**: liste des pages privées + éditeur titre/contenu dans le workspace Gitea
- **Sidebar**: lien "Private Pages" dans l'arborescence du workspace
- **Persistance**: les pages survivent au changement de workspace / session
### Fixed
- `get_user_repos(limit=100)` — `bruno/flowdeck` était tronqué à la page 2 (30 repos par défaut)
## v2.7.0 (2026-07-13) — Intégration Gitea Phase 1
### Added
- **OAuth2 Provider**: Gitea comme fournisseur OAuth2 pour FlowDeck (Client ID/Secret dans `.env`)
- **Redirect URI dynamique**: basé sur le header `Host` — fonctionne depuis `localhost` et `192.168.x.x`
- **Workspace listing**: 2 sections — My Workspaces + Gitea Projects (groupés par organisation)
- **Tabs par org**: All | user | org1 | org2 avec compteurs de projets
- **Barre de recherche**: filtrage live par nom/description dans Gitea Projects
- **Lazy tree**: arborescence chargée un dossier à la fois (API Gitea `GET /repos/{o}/{r}/contents`)
- **File viewer**: lecture fichiers Gitea avec décodage base64
- **Éditeur + commit**: modifier un fichier et commiter dans Gitea avec message personnalisé
- **Delete fichier**: suppression avec confirmation + commit
- **Arborescence dans le sidebar**: comme un workspace local, avec lazy-load des sous-dossiers
- **Settings › Integrations**: connecter/déconnecter Gitea (`GET /api/gitea/status`, `DELETE /api/gitea/disconnect`)
- **Fallback token admin**: opérations GET utilisent le token serveur si pas de token OAuth utilisateur
- **Write ops protégées**: commit et delete exigent un token OAuth utilisateur
- **Routes API**: `/api/gitea/orgs`, `/api/gitea/projects`, `/api/gitea/projects/{o}/{r}/tree`, `/api/gitea/projects/{o}/{r}/file`, `/api/gitea/projects/{o}/{r}/labels`
### Fixed
- Bouton "Register with Gitea" ne crée plus de session admin fantôme (fallback retiré)
- `_sidebar_data` gère le cookie `gitea:owner:repo` pour l'arborescence
## v2.6.0 (2026-07-13) — My Account & Auth Locale
### Added
- **Section My Account**: modifier username, full name, email, mot de passe
- **Toggle mot de passe**: bouton voir/cacher dans les formulaires login/register
- **Label "Email or username"**: login accepte les deux formats
- **Refresh cookie session**: après modification du compte, le cookie est mis à jour
- **Register avec Gitea**: boutons dynamiques "Login/Register with Gitea" selon l'onglet actif
### Fixed
- Session cookie non rafraîchi après `PUT /api/settings/account` (création nouvelle session)
- Input login `type="email"` → `type="text"` (accepte usernames non-email)
## v2.5.0 (2026-07-13) — Administration Avancée
### Added
- **Premier compte = admin automatique**: `is_admin=1` pour le premier utilisateur créé
- **Panneau Admin dans Settings**: visible uniquement pour les admins
- **Users & Roles**: créer/modifier/supprimer utilisateurs, changer rôles
- **Table `login_history`**: audit des connexions (IP, user_agent, timestamp)
- **Statistiques par utilisateur**: workspaces, pages, dernière connexion
- **API `/api/admin/*`**: users, stats, audit — protégées par `admin_required`
- **CSRF fix**: token CSRF dans toutes les requêtes admin (`adminFetch`)
## v2.4.0 (2026-07-13) — Tags Personnalisés par Utilisateur
### Added
- **Tags isolés par `user_id`**: chaque utilisateur voit uniquement ses propres tags
- **`UNIQUE(name, user_id)`**: remplace `UNIQUE(name)` dans la table `tags`
- **Migration**: tags existants assignés au premier utilisateur
- **Filtrage transparent**: l'API retourne les tags filtrés par `user_id` (session cookie)
### Fixed
- Affichage des tags dans le menu contextuel workspace (sync Alpine.js)
- Création de tag avec couleur persistée
- Fermeture auto du menu contextuel après ajout de tag
- Filtrage par tags: `toggleTagFilter()` appelle `doFilter()`
- Pastilles tags: fond = couleur du tag, sans rond séparé
## v2.3.0 (2026-07-12) — Multi-Vues Workspace & Preview Panel
### Added
- **Sélecteur de vue**: 🌳 Tree, 📋 List, 📊 Details, 🏷️ Title, 📝 Content — 5 modes d'affichage
- **Sélecteur de vue**: Tree, List, Details, Title, Content — 5 modes d'affichage
- **Vue List**: liste compacte avec Name, Type, Size, Modified
- **Vue Details**: table complète avec Path, Author, Tags
- **Vue Title**: grille de cartes avec icônes et métadonnées
@@ -21,12 +94,12 @@
### Added
- **Tags**: système complet de tags avec tables `tags` + `page_tags`, CRUD API
- **API Tags**: `GET/POST/DELETE /api/local-workspace/items/{id}/tags`, `GET /api/local-workspace/tags`, `GET /api/local-workspace/tags/search?tags=...`
- **API Tags**: `GET/POST/DELETE /api/local-workspace/items/{id}/tags`, `GET /api/local-workspace/tags`
- **Vue Table enrichie**: colonnes Name, Path, Size, Modified, Type, Author, Tags
- **Filtrage par tags**: barre de chips avec compteurs, clic pour filtrer
- **Ajout/retrait tags inline**: bouton + dans la table, chips avec × pour retirer
- **Tree endpoint enrichi**: chaque nœud retourne `size`, `size_display`, `created_at`, `updated_at`, `author`, `tags`
- **Filtre "Dossiers"**: nouveau chip 📁 Folders dans la barre de filtres
- **Filtre "Dossiers"**: nouveau chip Folders dans la barre de filtres
- **Auto-switch table**: quand recherche/filtre actif, passe en vue table automatiquement
## v2.1.1 (2026-07-12) — Fix Arborescence Workspace
@@ -36,7 +109,6 @@
- **parentFolder**: corrigé le bug où `parentFolder` était nullifié avant l'insertion dans l'arbre JS
- **displayTree**: nouvelle référence array après chaque mutation pour forcer le re-render Alpine.js
- **doSort/doFilter**: gèrent maintenant le cas où un filtre/tri est actif après création
- **_doUpload**: corrigé `this._reloadAfterAction` → `self._reloadAfterAction`
## v2.1.0 (2026-07-10) — Intégrations Avancées
+196 -237
View File
@@ -1,7 +1,40 @@
# Roadmap FlowDeck — Notion Clone
> **Vision**: Copie conforme de l'UI/UX Notion, intégrée à Gitea.
> **19 images de référence** dans `images/` — analysées le 2026-07-08.
> **Vision**: Copie conforme de l'UI/UX Notion, intégrée à Gitea/GitHub.
> **MVP en production** : v4.0.0 — authentification locale/OAuth, pages blocs, sidebar, library, share/publish, intégrations.
> **Branche principale** : `main` (production) · `develop` (intégration) · `feat/*` (features).
## 🏗️ Stratégie de branches
```
main ──●────────────●────── production (tags vX.Y.Z)
\ /
develop ●──●──●──●────── intégration continue
\ \ \
feat/xxx ● ● ●──── feature branches
```
- **`main`** : code en production, déploiement Docker automatique
- **`develop`** : branche d'intégration, merges des `feat/*`
- **`feat/<nom>`** : une branche par feature/fix, PR → code review → merge dans `develop`
- **Tags** `vX.Y.Z` sur `main` pour chaque release
**Workflow** :
```bash
git checkout -b feat/mon-truc develop
# ... coder, commit, push ...
# Créer une PR feat/mon-truc → develop sur Gitea
# Après review + CI verte → merge
# Pour release: PR develop → main + tag vX.Y.Z
```
**Règles** :
- Ne jamais commiter directement sur `main`
- Une branche = une feature / un fix
- Tests passent avant merge (CI Gitea Actions)
- Commit + push après chaque modification significative
---
## Completed
@@ -54,274 +87,200 @@ Propriétés custom, AI keywords, sync API, 12 tables DB
- [x] Heading 4 support
- [x] Breadcrumbs contextuels (workspace > projet > page)
### v1.3.0 ✅ — Database Concept (Bloc 1 du gap analysis)
### (2026-07-10, commit c574d2c, tag v1.3.0)
### v1.3.0 ✅ — Database Concept
- [x] Tables `collections`, `collection_pages`, `collection_views`
- [x] Rétrocompatibilité Gitea via `GiteaBoardCompat`
- [x] Router `/db` — API CRUD collections + pages (12 endpoints)
- [x] 34/34 tests passent
- [x] **Table `collections`** — base de données abstraite, indépendante de Gitea
- `id`, `name`, `description`, `icon`, `schema_json`
- Optionnellement liée à Gitea (`gitea_owner`, `gitea_repo`)
- [x] **Table `collection_pages`** — remplace `cards`, pages génériques
- `collection_id`, `title`, `position`, `parent_id`, `property_values_json`
- `gitea_issue_id` optionnel, auto-propriétés (`created_at`, `updated_at`)
- [x] **Table `collection_views`** — vues configurables par collection
- `name`, `view_type`, `config_json`, `position`
- [x] **Rétrocompatibilité Gitea** — adaptateur `GiteaBoardCompat`
- Les boards Gitea existants deviennent des collections
- Migration transparente `cards` → `collection_pages`
- Routes `/db/boards/api`, `/db/board/{o}/{r}/api`, `/db/board/{o}/{r}/sync`
- [x] **Router `/db`** — API CRUD collections + pages (12 endpoints)
- [x] **34/34 tests** passent (+6 nouveaux tests v1.3)
- [x] **Database lock** — mode lecture seule (`collections.is_locked`)
- [x] **Database description** — champ `description` sur les collections
### v1.4.0 ✅ — Propriétés Avancées
- [x] Table `collection_properties` — 21 types Notion
- [x] Service `property_types.py` — validation, formatage, auto-values
- [x] 38/38 tests passent
---
### v1.5.0 ✅ — Relations & Rollups
- [x] Type `relation` — lien bidirectionnel entre collections
- [x] Type `rollup` — aggregation via relation (COUNT, SUM, AVG, etc.)
- [x] Type `formula` — moteur d'expressions (19 fonctions)
- [x] Formula engine + Rollup engine
- [x] 43/43 tests passent
### v1.4.0 ✅ — Propriétés Avancées (Bloc 2)
### (2026-07-10)
- [x] **Table `collection_properties`** — remplace `project_properties`
- Liée à `collections` (pas à `project_owner/name`)
- Supporte tous les types Notion (21 types)
- [x] **Type `number`** — avec formatage (nombre, %, €, $, £, ¥)
- [x] **Type `checkbox`** — booléen natif
- [x] **Type `url`** — lien cliquable
- [x] **Type `email`** — email cliquable
- [x] **Type `phone`** — téléphone cliquable
- [x] **Type `status`** — select avec couleurs forcées (9 couleurs Notion)
- [x] **Type `files`** — uploads/images attachés aux pages
- [x] **Type `unique_id`** — ID auto-incrémenté par collection
- [x] **Type `created_time` / `created_by`** — auto-propriétés
- [x] **Type `last_edited_time` / `last_edited_by`** — auto-propriétés
- [x] **Service `property_types.py`** — validation, formatage, auto-values
- [x] **API CRUD** — `/db/property-types/api` + CRUD `/db/{id}/properties/api`
- [x] **38/38 tests** passent (+4 nouveaux tests v1.4)
- [ ] **Migration** `project_properties` → `collection_properties` (v1.5)
### v1.5.0 ✅ — Relations & Rollups (Bloc 2 suite)
### (2026-07-10)
- [x] **Type `relation`** — lien bidirectionnel entre collections
- `related_collection_id`, `reverse_name` auto-généré
- Stockage : JSON array de page IDs dans `property_values_json`
- API: `POST /db/{id}/properties/relation` (création avec reverse)
- API: `POST /db/{id}/properties/relation/link` (lier 2 pages)
- [x] **Type `rollup`** — agrégation via relation
- Functions : COUNT, SUM, AVG, MIN, MAX, RANGE, UNIQUE, PERCENT_CHECKED
- API: `POST /db/rollup/compute`
- [x] **Type `formula`** — propriétés calculées
- Moteur d'expressions JavaScript-like (19 fonctions)
- API: `POST /db/formula/evaluate`
- [x] **Formula engine** — `services/formula_engine.py`
- [x] **Rollup engine** — `services/rollup_engine.py`
- [x] **43/43 tests** passent (+5 nouveaux tests v1.5)
- [x] **FKs fix**: `related_collection_id`, `relation_property_id`, `target_property_id` → `ON DELETE SET NULL`
### v1.6.0 ✅ — Vues Manquantes (Bloc 3)
### (2026-07-10)
- [x] **Calendar view** — grid mensuel, navigation mois, événements par date
- Route: `GET /db/{id}/view/calendar`
- [x] **Gallery view** — cartes visuelles avec cover image optionnelle
- `card_size`: small/medium/large, `cover_property` configurable
- [x] **List view** — liste compacte avec preview propriétés
- [x] **Timeline/Gantt view** — barres horizontales sur axe date
- [x] **Table view** — rendu SSR, colonnes properties
- [x] **View tabs** — navigation entre vues (Table/Board/Calendar/Gallery/List/Timeline)
- [x] **49/49 tests** passent (+6 nouveaux tests v1.6)
### v1.6.0 ✅ — Vues Manquantes
- [x] Calendar, Gallery, List, Timeline, Table views
- [x] View tabs navigation
- [x] 49/49 tests passent
### v1.7.0 ✅ — Vues Améliorées
### v1.8.0 ✅ — Sub-items & Dépendances
### (2026-07-10, combined)
- [x] View config API, Save view as
- [x] Sub-items (parent_id auto-référence)
- [x] Status aggregate, Dependencies (blocking constraint)
- [x] 56/56 tests passent
- [x] **View config API** — PUT /db/views/{id}/config (group_by, card_size, cover, visible)
- [x] **Save view as** — POST /db/{id}/views/save-as
- [x] **List views** — GET /db/{id}/views/api
- [x] **Sub-items** — parent_id auto-référence, GET/POST sub-items
- [x] **Status aggregate** — GET status-aggregate (Done only if all children Done)
- [x] **Dependencies** — POST dependencies + POST check-deps (blocking constraint)
- [x] **56/56 tests** passent (+7 tests v1.7+v1.8)
### v1.9.0 ✅ — My Tasks & Dashboard Unifié
- [x] Vue `/my-tasks` — agrège pages assignées à l'utilisateur
- [x] Groupement par collection, filtres globaux
- [x] 60/60 tests passent
### v1.9.0 ✅ — My Tasks & Dashboard Unifié (Bloc 5)
### (2026-07-10)
- [x] **Vue `/my-tasks`** — agrège toutes les pages assignées à l'utilisateur
- Scan cross-collection (toutes les databases du workspace)
- Filtre automatique : admin voit tout
- [x] **Groupement par collection** — sections par database d'origine
- [x] **Filtres globaux** — All, Today, Overdue, Next 7 days
- [x] **API JSON** — `GET /my-tasks/api`
- [x] **60/60 tests** passent (+4 tests v1.9)
### v2.0.0 ✅ — Éditeur Complet & Multi-Utilisateurs (Blocs 6-7)
### (2026-07-10)
- [x] **Workspaces** — `workspaces` + `workspace_members` tables, CRUD API, roles admin/editor/commenter/viewer
- [x] **Comments** — table `comments` avec thread (parent_id), resolved, API CRUD
- [x] **Page History** — table `page_history`, snapshot JSON, API record/list
- [x] **Favorites** — table `favorites`, API add/remove/list
- [x] **Database Templates** — table `database_templates`, apply to create collection
- [x] **Page Templates** — table `page_templates`, apply with pre-filled properties
- [x] **CSV Import/Export** — `POST .../import/csv`, `GET .../export/csv`
- [x] **Public Sharing** — `GET /workspace/public/{id}` (read-only, no auth)
- [x] **67/67 tests** passent (+7 tests v2.0)
### v2.0.0 ✅ — Éditeur Complet & Multi-Utilisateurs
- [x] Workspaces, Comments, Page History, Favorites
- [x] Database Templates, Page Templates, CSV Import/Export
- [x] Public Sharing
- [x] 67/67 tests passent
### v2.1.0 ✅ — Workspace Local & Arborescence
### (2026-07-11)
### v2.2.0 ✅ — Tags & Recherche Avancée
### v2.3.0 ✅ — Multi-Vues Workspace & Preview Panel
### v2.4.0 ✅ — Tags Personnalisés par Utilisateur
### v2.5.0 ✅ — Administration Avancée
### v2.6.0 ✅ — My Account & Auth Locale
### v2.7.0 ✅ — Intégration Gitea Phase 1
### v2.7.1 ✅ — Private Pages Gitea
- [x] **Page `/local-workspace`** — file/folder tree avec breadcrumb
- [x] **API tree récursive** — `GET /api/local-workspace/tree?folder=ID`
- [x] **Breadcrumb** — `GET /api/local-workspace/breadcrumb`
- [x] **CRUD items** — create/rename/delete/move files & folders
- [x] **Drag & drop upload** — fichiers + dossiers récursifs depuis l'OS
- [x] **Drag & drop interne** — déplacer items entre dossiers
- [x] **Expand/collapse** — toggle dossiers, persisté localStorage
- [x] **File viewer** — images, PDF, texte/code avec coloration syntaxique
- [x] **Preview hover** — popup au survol des fichiers
- [x] **Icônes par type** — 📝 pages, 📕 PDF, 🖼️ images, 🐍 code, etc.
- [x] **Recherche + filtre** — par nom + par type (chips)
- [x] **Menu contextuel sidebar** — clic droit / long-press mobile
- [x] **Expand/Collapse all** — boutons ⊞ ⊟
- [x] **Sidebar persistante** — sectionsOpen + expandedFolders localStorage
- [x] **Création instantanée** — AJAX sans reload
- [x] **73 tests** passent
### v2.8.0 ✅ — Gitea Phase 2
- [x] Créer fichiers dans le repo (New file UI + API PUT)
- [x] Upload fichiers binaires (POST /upload, drag-drop)
- [x] Syntax highlighting via Prism.js CDN
- [x] Labels Gitea → tags FlowDeck (POST /sync-labels, 16 labels importés)
- [x] Historique commits par fichier (GET /commits?path=)
### v2.9.0 ✅ — GitHub OAuth Provider
- [x] GitHubProvider dans `app/auth/providers.py`
- [x] GitHubAdapter dans `app/services/github_adapter.py`
- [x] Config GitHub dans `.env.example`
### v3.0.0 ✅ — UX Professionnelle
- [x] Multi-sélection (checkboxes + Shift/Ctrl-click dans le sidebar)
- [x] Raccourcis clavier (Ctrl+N, F2, Delete, Escape, Ctrl+S)
- [x] Inline rename (double-clic → champ inline)
- [x] Loading skeletons (animations pulse dans workspaces + file viewer)
- [x] Grid/card view (mode grille/vignettes)
- [x] Table sorting (tri par colonnes)
- [x] Sélecteur de vue: Tree, List, Details, Title, Content (5 modes)
- [x] Preview Panel latéral (contenu, métadonnées, tags, actions)
- [x] Tri par date (Oldest/Newest)
### v4.0.0 ✅ — Accounts, Integrations & Sharing (MVP)
- [x] `auth_method` sur users (local/gitea/github)
- [x] Badge OAuth dans sidebar
- [x] Settings page avec Connect/Disconnect Gitea + GitHub
- [x] Sidebar rules (Private = distant seulement, Trash local-only)
- [x] Library page avec tabs + filtres source (All/Local/Gitea/GitHub)
- [x] Modale Share (2 tabs: Share + Publish)
- [x] Page publique `/p/<slug>` (no auth, rendu HTML)
- [x] Table `page_shares`, colonnes `is_published`, `is_shared`, `share_mode`
- [x] Table `recents` — tracking automatique
- [x] Édition unifiée local/distant (même UI, bouton Commit pour Gitea)
- [x] 133 tests passent
---
## Upcoming
## 🔜 Prochaines versions
### v2.2.0 — Workspace & Sidebar Professionnel (Gap Analysis)
### Cible: Q3 2026
### v4.0.1 — Onboarding & Polish ✅ (2026-07-18)
> **Objectif** : rendre l'app utilisable dès la première visite, sans friction. **COMPLETED**.
Analyse complète de ce qui manque pour une expérience utilisateur
de niveau professionnel, comparable à Notion, VS Code, et Finder.
- [x] **Landing page `/` pour visiteurs non-auth** — template `landing.html`, design Notion dark
- [x] **Page `/auth/register` GET** — formulaire d'inscription dédié (tab register actif)
- [x] **Redirection `/` intelligente** — non-auth → landing, auth sans Gitea → local workspace, auth+Gitea → dashboard
- [x] **Empty states** — déjà présents dans local workspace (« Welcome to your Workspace »)
- [x] **Page 404 stylisée** — thème Notion sombre, JSON pour `/api/*`, HTML pour le reste
- [x] **Unifier les routes API** — `/api/pages` GET/POST → 307 redirect vers `/board/api/pages`
- [x] **Page Settings** — lien déjà présent dans le menu utilisateur (Settings → `/accounts/settings`)
#### A. Workspace Page — Productivité & Raccourcis
### v4.0.2 — Qualité & Robustesse ✅ (2026-07-18)
> **Objectif** : zéro crash, zéro regression, DX impeccable.
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| A1 | **Multi-sélection** | P0 | M | Checkboxes + Shift-click range + Ctrl-click toggle. Bulk delete/move. |
| A2 | **Raccourcis clavier** | P0 | M | Enter=open, F2=rename, Del=delete, Ctrl+A=select all, Ctrl+C/V=copy/paste, Ctrl+Z=undo |
| A3 | **Inline rename** | P0 | S | Double-clic → champ inline (pas prompt()). Garder le même comportement que Finder. |
| A4 | **Drag count badge** | P1 | S | Afficher un badge "[N]" sur le curseur quand on drag plusieurs items. |
| A5 | **Undo delete** (toast) | P1 | M | Remplacer `confirm('Delete?')` par un delete immédiat + toast "Undo" 5s. |
| A6 | **Duplicate file/folder** | P1 | S | Action "Duplicate" dans le menu contextuel + Ctrl+D. |
| A7 | **Copy/paste items** | P1 | M | Ctrl+C copie (stockage sessionStorage), Ctrl+V colle dans le dossier courant. |
#### B. Workspace Page — Affichage & Métadonnées
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| B1 | **Vue détails/tableau** | P0 | L | Toggle entre arbre et tableau (Nom, Taille, Type, Modifié le). |
| B2 | **Tri** | P0 | M | Barre d'en-tête: clic pour trier par nom/date/taille/type. Asc/desc. |
| B3 | **Métadonnées dans l'arbre** | P1 | S | Afficher taille + date de modification en grisé à droite du nom. |
| B4 | **Compteur d'enfants par dossier** | P1 | S | Badge "(3)" à côté du nom du dossier indiquant le nombre d'items directs. |
| B5 | **Loading skeletons** | P1 | S | Remplacer "Loading..." par des skeletons animés (barres grises pulsing). |
| B6 | **Empty state illustré** | P2 | S | Illustration SVG + texte d'aide pour workspace vide et dossier vide. |
#### C. Workspace Page — Navigation & Breadcrumb
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| C1 | **Breadcrumb éditable** | P1 | M | Cliquer sur un segment du breadcrumb = naviguer. Dernier segment éditable (rename). |
| C2 | **Barre d'adresse / path** | P2 | M | Champ texte affichant le path complet, éditable pour jump direct. |
| C3 | **Back/Forward navigation** | P2 | M | Boutons ← → dans la topbar, historique de navigation interne. |
| C4 | **Dossier parent ".."** | P2 | S | Premier élément de la liste quand on est dans un sous-dossier. |
#### D. Sidebar Workspace — Polissage
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| D1 | **Indicateur de dossier actif** | P0 | S | Highlight + point coloré sur le dossier courant (navigué). |
| D2 | **Badge compteur par dossier** | P1 | S | "(5)" à côté des dossiers montrant le nombre d'items récursifs. |
| D3 | **Drop indicator line** | P1 | S | Ligne bleue entre les items pendant le drag pour montrer la position d'insertion. |
| D4 | **Scroll into view** | P1 | S | Auto-scroll pour rendre visible le dossier actif dans la sidebar. |
| D5 | **Animation expand/collapse** | P2 | S | Transition fluide CSS pour l'ouverture/fermeture des dossiers (max-height). |
| D6 | **Indicateur "modifié récemment"** | P2 | S | Petit point bleu à côté des items modifiés dans les dernières 24h. |
#### E. Expérience Générale — Cross-cutting
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| E1 | **Mode grille/vignettes** | P2 | L | Alternative au tree: icônes larges avec preview, style Finder/Dropbox. |
| E2 | **Upload progress détaillé** | P1 | M | Barre de progression par fichier, vitesse, ETA, possibilité d'annuler. |
| E3 | **Drag depuis sidebar vers workspace** | P2 | L | Permettre de glisser un item de la sidebar directement dans la page workspace. |
| E4 | **Pin/favoris dans le workspace** | P2 | S | Épingler des dossiers/fichiers en haut de la liste pour accès rapide. |
| E5 | **Aperçu des fichiers dans le dossier parent** | P3 | M | Quand on survole un dossier dans l'arbre, montrer un petit popup listant les 5 premiers fichiers. |
| E6 | **Dark/Light theme cohérent** | P1 | M | S'assurer que le file viewer standalone respecte le thème actif (cookie/session). |
#### F. Mobile & Responsive
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| F1 | **Swipe actions** | P2 | M | Swipe gauche sur un item → Delete. Swipe droit → Rename. |
| F2 | **Bottom sheet context menu** | P1 | M | Remplacer le menu contextuel desktop par une bottom sheet native sur mobile. |
| F3 | **Touch hold feedback** | P1 | S | Haptic feedback (si supporté) + scale animation sur long-press. |
| F4 | **Grille adaptative** | P2 | M | En mode paysage tablette: 2 colonnes (sidebar + contenu). |
#### G. Performance & Robustesse
| # | Feature | Priorité | Effort | Description |
|---|---------|----------|--------|-------------|
| G1 | **Virtual scrolling** | P2 | L | Pour les dossiers avec >1000 items, rendre seulement les éléments visibles. |
| G2 | **Lazy loading des enfants** | P1 | M | Ne charger les enfants d'un dossier que quand on l'expand (API `?folder=ID`). |
| G3 | **Cache navigateur** | P1 | S | Cache le contenu des fichiers déjà chargés pour le preview hover. |
| G4 | **Offline indicator** | P3 | S | Bannière "You are offline" + queue des actions pour synchro au retour. |
| G5 | **Rate limiting + retry** | P1 | S | Retry automatique avec backoff exponentiel sur les appels API échoués. |
- [x] **Gestion d'erreurs** — try/catch dans create_page, message user-friendly (500 JSON)
- [x] **Validation inputs** — login/register déjà validés, titre vide → "Untitled"
- [x] **Rate limiting** — 100 req/min/IP déjà en place, testé OK
- [x] **Session expiry UX** — redirect avec ?expired=1, bannière sur la page login
- [ ] **CSRF token refresh** — après expiration session (à faire)
- [x] **Mobile responsive** — sidebar slide-in, modales centrées, landing adaptative
- [x] **Tests de non-régression** — +10 tests (landing, register, 404, validation, duplicate, expiry)
- [x] **143 tests passent**
---
#### Résumé des priorités
### v4.1.0 — Content Blocks enrichis (Notion Parity Tier 2)
> **Objectif** : parité d'édition avec Notion.
**P0 — Bloquant pour une expérience pro :**
- A1 Multi-sélection
- A2 Raccourcis clavier
- A3 Inline rename
- B1 Vue détails/tableau
- B2 Tri
- D1 Indicateur dossier actif
- [ ] **Callout blocks** — boîtes colorées (info, warning, tip, success)
- [ ] **Table of contents** — auto-généré depuis les headings
- [ ] **Math equations** — LaTeX / KaTeX inline + block
- [ ] **Toggle lists** — contenu expandable/collapsible (déjà partiel)
- [ ] **Multi-colonnes** — layout flexible (2, 3 colonnes)
**P1 — Important pour la qualité perçue :**
- A4 Drag count badge, A5 Undo toast, A6 Duplicate, A7 Copy/paste
- B3 Métadonnées, B4 Compteur, B5 Skeletons
- C1 Breadcrumb éditable
- D2 Badge compteur, D3 Drop indicator, D4 Scroll into view
- E2 Upload progress, E6 Thème cohérent
- F2 Bottom sheet mobile, F3 Touch feedback
- G2 Lazy loading, G3 Cache, G5 Retry
### v4.2.0 — Export
- [ ] **Export Markdown** — avec images et sous-pages (déjà partiel dans editor)
- [ ] **Export PDF** — mise en page fidèle, table des matières
- [ ] **Export HTML** — site statique standalone
**Estimation globale : ~4-6 semaines pour P0+P1 avec 1 développeur.**
### v4.3.0 — Collaboration
- [ ] **Inline comments** — commentaires sur sélection de texte
- [ ] **@mentions** — notifier un utilisateur → page/commentaire
- [ ] **Email notifications** — changements, mentions
### v4.4.0 — Embeds & Rich Media
- [ ] **Embeds** — YouTube, Figma, Google Maps, Twitter, etc.
- [ ] **Image lightbox** — clic pour agrandir, navigation
- [ ] **Bookmark cards** — aperçu riche des liens (OG metadata)
### v4.5.0 — Kanban Adaptable
- [ ] Colonnes configurables par utilisateur
- [ ] Cartes configurables (choisir propriétés affichées)
- [ ] Couverture de carte (image, icône, couleur)
- [ ] WIP limits par colonne
### v4.6.0 — Calendar & Meetings
- [ ] Vue Calendrier drag & drop
- [ ] Récurrence d'événements
- [ ] Template Meeting Notes
### v4.7.0 — AI Assistant
- [ ] Intégration LLM pour écriture/résumé/traduction
- [ ] Slash AI commands (`/ai write`, `/ai summarize`)
- [ ] Auto-complétion
### v4.8.0 — Command Palette & Recherche
- [ ] **Command palette** — Ctrl+K / Ctrl+P recherche universelle
- [ ] **Quick actions** — navigation, création, commandes
### v4.9.0 — Automations
- [ ] **Database automations** — if-this-then-that
- [ ] **Buttons** — cliquables déclenchant actions
### v4.10.0 — Database Avancée
- [ ] Inline databases dans n'importe quelle page
- [ ] Templates de database (Project tracker, CRM…)
- [ ] Validation des propriétés (required, unique, min/max)
---
### v2.1.0 — Intégrations Avancées (futur)
## v5.0.0 — Pro (futur)
- [ ] **API publique** — REST API documentée pour usage externe
- [ ] **Webhooks sortants** — notifier des services externes
- [ ] **n8n integration** — nœud FlowDeck pour workflows
- [ ] **Slack/Discord integration** — notifications dans les channels
- [ ] **Google Calendar sync** — synchronisation bidirectionnelle
- [ ] **Mobile PWA** — Progressive Web App pour mobile
- [ ] **PostgreSQL migration** — si passage multi-tenant
- [ ] **PWA** — Progressive Web App, offline support
- [ ] **SSO/SAML** — enterprise authentication
- [ ] **Granular permissions** — page-level, property-level access control
- [ ] **Web Clipper** — extension navigateur
- [ ] **API publique** — REST API + webhooks documentés
- [ ] **Realtime editing** — WebSocket, curseurs multi-utilisateurs
- [ ] **Synced blocks** — bloc synchronisé entre plusieurs pages
---
## Résumé des phases
```
v1.0.0 ✅ v1.1.0 ✅ v1.2.0 ✅ v1.3.0 ✅ v1.4.0 ✅ v1.5.0 ✅ v1.6.0 ✅ v1.7.0 ✅
Production Pages Editor DB Concept Properties Relations Views View+
──────────────────────────────────────────────
52 fonctionnalités identifiées dans le gap analysis
│
├─ Bloc 1: Database Concept (v1.3) — 6 items ✅
├─ Bloc 2: Propriétés avancées (v1.4-1.5) — 14 items ✅
├─ Bloc 3: Vues manquantes (v1.6-1.7) — 10 items ✅
├─ Bloc 4: Sub-items & Deps (v1.8) — 7 items ✅
├─ Bloc 5: My Tasks (v1.9) — 7 items ✅
├─ Bloc 6: Éditeur complet (v2.0) — 8 items ✅
└─ Bloc 7: Fonctions transversales — +multi-user ✅
v0.x–v1.x ✅ v2.x ✅ v3.0.0 ✅ v4.0.0 ✅ v4.0.1 ✅
Base + Kanban Éditeur + Gitea UX Pro MVP Onboarding
+ DB + Auth + Workspaces + Multi-select Accounts & Polish
+ UI Notion + Tags + Admin + Sharing COMPLETED
+ GitHub OAuth + Library
v2.0.0 ✅ v2.1.0 ✅ v2.2.0 ⬜
Editor+ Workspace Pro UX
Local
v4.0.2 ✅ v4.1.0 ⬜ v4.2.0 ⬜ v4.3.0 ⬜ v4.4–4.10 ⬜ v5.0.0 ⬜
Quality Blocks Export Collab Notion Pro
& Tests enrichis PDF/MD @mentions Parity (futur)
```
*Dernière mise à jour: 2026-07-18 — Roadmap restructuré, focus MVP, stratégie de branches Gitea*
+19 -16
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import logging
import time
from abc import ABC, abstractmethod
from urllib.parse import urlencode
@@ -22,11 +23,11 @@ class OAuthProvider(ABC):
"""Whether this provider is configured."""
@abstractmethod
def get_authorize_url(self, state: str) -> str:
def get_authorize_url(self, state: str, redirect_uri: str | None = None, force_login: bool = False) -> str:
"""Build the authorization URL."""
@abstractmethod
async def exchange_code(self, code: str) -> dict | None:
async def exchange_code(self, code: str, redirect_uri: str | None = None) -> dict | None:
"""Exchange authorization code for access token."""
@abstractmethod
@@ -53,25 +54,27 @@ class GiteaProvider(OAuthProvider):
def is_enabled(self) -> bool:
return bool(self.client_id and self.client_secret)
def get_authorize_url(self, state: str) -> str:
return (
f"{self.base}/login/oauth/authorize?"
+ urlencode({
def get_authorize_url(self, state: str, redirect_uri: str | None = None, force_login: bool = False) -> str:
params = {
"client_id": self.client_id,
"redirect_uri": self.redirect_uri,
"redirect_uri": redirect_uri or self.redirect_uri,
"response_type": "code",
"state": state,
})
)
}
if force_login:
# Gitea supports prompt=login param (undocumented but works)
# If not, fallback: add _force= timestamp cache-buster
params["_force"] = str(int(time.time()))
return f"{self.base}/login/oauth/authorize?" + urlencode(params)
async def exchange_code(self, code: str) -> dict | None:
async def exchange_code(self, code: str, redirect_uri: str | None = None) -> dict | None:
url = f"{self.base}/login/oauth/access_token"
data = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"code": code,
"grant_type": "authorization_code",
"redirect_uri": self.redirect_uri,
"redirect_uri": redirect_uri or self.redirect_uri,
}
async with httpx.AsyncClient(timeout=15) as client:
r = await client.post(url, json=data, headers={"Accept": "application/json"})
@@ -143,18 +146,18 @@ class GitHubProvider(OAuthProvider):
def is_enabled(self) -> bool:
return bool(self.client_id and self.client_secret)
def get_authorize_url(self, state: str) -> str:
def get_authorize_url(self, state: str, redirect_uri: str | None = None, force_login: bool = False) -> str:
return (
f"{self.authorize_url}?"
+ urlencode({
"client_id": self.client_id,
"redirect_uri": self.redirect_uri,
"redirect_uri": redirect_uri or self.redirect_uri,
"scope": "repo,user",
"state": state,
})
)
async def exchange_code(self, code: str) -> dict | None:
async def exchange_code(self, code: str, redirect_uri: str | None = None) -> dict | None:
async with httpx.AsyncClient(timeout=15) as client:
r = await client.post(
self.token_url,
@@ -241,8 +244,8 @@ def get_providers() -> list[OAuthProvider]:
providers.append(gitea)
github = GitHubProvider(
client_id=settings.github_client_id or "",
client_secret=settings.github_client_secret or "",
client_id=settings.github_oauth_client_id or "",
client_secret=settings.github_oauth_client_secret or "",
redirect_uri=settings.oauth_redirect_uri or "",
)
if github.is_enabled():
+10 -5
View File
@@ -13,13 +13,13 @@ class Settings(BaseSettings):
# Gitea
gitea_url: str = "https://git.dracodev.net"
gitea_token: str = "change-me"
gitea_oauth_client_id: str = ""
gitea_oauth_client_secret: str = ""
gitea_oauth_client_id: str = "test-id"
gitea_oauth_client_secret: str = "test-secret"
gitea_webhook_secret: str = ""
# GitHub
github_client_id: str = ""
github_client_secret: str = ""
github_oauth_client_id: str = ""
github_oauth_client_secret: str = ""
# Standalone mode
standalone: bool = False # FLOWDECK_STANDALONE=true in .env
@@ -53,7 +53,12 @@ class Settings(BaseSettings):
if self.database_url == "sqlite:///:memory:":
return Path(":memory:") # Special SQLite in-memory
if self.database_url.startswith("sqlite:///"):
return Path(self.database_url.replace("sqlite:///", "/"))
p = self.database_url.replace("sqlite:///", "", 1)
# On Windows, don't prepend / if path starts with a drive letter
import re
if re.match(r'^[a-zA-Z]:', p):
return Path(p)
return Path("/" + p)
return Path("/data/flowdeck.db")
+112 -2
View File
@@ -27,6 +27,7 @@ def init_db():
full_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
avatar_url TEXT NOT NULL DEFAULT '',
avatar_color TEXT NOT NULL DEFAULT '#3A3A3A',
password_hash TEXT,
is_admin INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
@@ -36,6 +37,14 @@ def init_db():
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS login_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
ip_address TEXT DEFAULT '',
user_agent TEXT DEFAULT '',
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS user_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
gitea_user_id INTEGER NOT NULL UNIQUE,
@@ -297,9 +306,11 @@ def init_db():
-- v2.2.0: Tags system
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
color TEXT DEFAULT '#787774',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
user_id INTEGER NOT NULL DEFAULT 0 REFERENCES users(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(name, user_id)
);
CREATE TABLE IF NOT EXISTS page_tags (
@@ -316,6 +327,11 @@ def init_db():
conn.execute("ALTER TABLE pages ADD COLUMN parent_id INTEGER REFERENCES pages(id)")
except sqlite3.OperationalError:
pass
# Migration: add avatar_color (v2.3.0+)
try:
conn.execute("ALTER TABLE users ADD COLUMN avatar_color TEXT NOT NULL DEFAULT '#3A3A3A'")
except sqlite3.OperationalError:
pass
# Migration: add sort_order for drag & drop tree reordering (v1.1.0+)
try:
conn.execute("ALTER TABLE pages ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0")
@@ -350,6 +366,100 @@ def init_db():
conn.execute(f"ALTER TABLE users ADD COLUMN {col} {'TEXT' if col in ('password_hash','last_login','locked_until') else 'INTEGER NOT NULL DEFAULT ' + ('1' if col=='is_active' else '0')}")
except sqlite3.OperationalError:
pass
# v2.5: Login history
try:
conn.execute("ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
conn.execute("""CREATE TABLE IF NOT EXISTS login_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
ip_address TEXT DEFAULT '',
user_agent TEXT DEFAULT '',
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)""")
except sqlite3.OperationalError:
pass
# v2.6: Tags per-user
try:
conn.execute("ALTER TABLE tags ADD COLUMN user_id INTEGER NOT NULL DEFAULT 0 REFERENCES users(id)")
except sqlite3.OperationalError:
pass
try:
# Recreate UNIQUE constraint for per-user tags
conn.execute("CREATE TABLE IF NOT EXISTS tags_new (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, color TEXT DEFAULT '#787774', user_id INTEGER NOT NULL DEFAULT 0 REFERENCES users(id), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(name, user_id))")
conn.execute("INSERT OR IGNORE INTO tags_new (id, name, color, user_id, created_at) SELECT id, name, color, COALESCE(user_id,0), created_at FROM tags")
conn.execute("DROP TABLE tags")
conn.execute("ALTER TABLE tags_new RENAME TO tags")
except sqlite3.OperationalError:
pass
conn.commit()
# v2.7: Private pages for Gitea workspaces
conn.execute("""
CREATE TABLE IF NOT EXISTS gitea_private_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
gitea_owner TEXT NOT NULL,
gitea_repo TEXT NOT NULL,
title TEXT NOT NULL DEFAULT 'Untitled',
content TEXT DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
# ── v4.0: Account & Integrations ──
# 1) auth_method on users
try:
conn.execute("ALTER TABLE users ADD COLUMN auth_method TEXT DEFAULT 'local'")
except sqlite3.OperationalError:
pass
# Detect existing auth: if user has a gitea_token in user_tokens → 'gitea'
conn.execute(
"UPDATE users SET auth_method='gitea' WHERE id IN (SELECT gitea_user_id FROM user_tokens)"
)
conn.execute(
"UPDATE users SET auth_method='local' WHERE auth_method IS NULL"
)
# 2) Publishing & sharing columns on pages
try:
conn.execute("ALTER TABLE pages ADD COLUMN is_published INTEGER NOT NULL DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE pages ADD COLUMN publish_slug TEXT DEFAULT ''")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE pages ADD COLUMN is_shared INTEGER NOT NULL DEFAULT 0")
except sqlite3.OperationalError:
pass
# 3) page_shares table
conn.execute("""
CREATE TABLE IF NOT EXISTS page_shares (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
shared_with_user_id INTEGER REFERENCES users(id),
shared_with_email TEXT DEFAULT '',
permission TEXT NOT NULL DEFAULT 'view',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER REFERENCES users(id)
)
""")
# 4) recents table
conn.execute("""
CREATE TABLE IF NOT EXISTS recents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
page_id INTEGER NOT NULL REFERENCES pages(id),
workspace TEXT NOT NULL DEFAULT '',
source_type TEXT NOT NULL DEFAULT 'local',
accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, page_id)
)
""")
conn.commit()
+76 -5
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
@@ -12,7 +12,10 @@ from starlette.middleware.sessions import SessionMiddleware
from app.config import settings
from app.db import init_db
from app.middleware.csrf import CSRFMiddleware
from app.routers import dashboard, board, notes, api, auth, webhooks, collections, my_tasks, workspace, public_api
from app.middleware.security import ContentSecurityPolicyMiddleware, RateLimitMiddleware
from app.routers import dashboard, board, notes, api, auth, webhooks, collections, my_tasks, workspace, library, public_api, admin, sharing
from app.routers.gitea import router as gitea_router
from app.routers.github_routes import router as github_router
from app.services.gitea_client import gitea
from app.services.webhook_outbound import init_webhook_tables
@@ -28,18 +31,21 @@ async def lifespan(_app: FastAPI):
init_db()
init_webhook_tables()
from app.db import get_conn
from app.password_utils import hash_password
admin_hash = hash_password("FlowDeck2026!")
with get_conn() as conn:
conn.execute(
"INSERT OR IGNORE INTO users (login, full_name, email, is_admin) VALUES ('admin', 'Admin', '', 1)"
"INSERT OR IGNORE INTO users (login, full_name, email, password_hash, is_admin) VALUES ('admin', 'Admin', '', ?, 1)",
(admin_hash,)
)
conn.commit()
logger.info("FlowDeck v2.1.0 started on port %d", settings.app_port)
logger.info("FlowDeck v4.0.0 started on port %d", settings.app_port)
yield
app = FastAPI(
title="FlowDeck",
version="2.3.0",
version="4.0.0",
docs_url="/docs" if settings.log_level == "DEBUG" else None,
redoc_url=None,
lifespan=lifespan,
@@ -47,6 +53,8 @@ app = FastAPI(
app.add_middleware(SessionMiddleware, secret_key=settings.app_secret_key, max_age=3600)
app.add_middleware(CSRFMiddleware)
app.add_middleware(ContentSecurityPolicyMiddleware)
app.add_middleware(RateLimitMiddleware)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
app.include_router(auth.router)
@@ -58,7 +66,12 @@ app.include_router(webhooks.router)
app.include_router(collections.router)
app.include_router(my_tasks.router)
app.include_router(workspace.router)
app.include_router(library.router)
app.include_router(admin.router)
app.include_router(gitea_router)
app.include_router(github_router)
app.include_router(public_api.router)
app.include_router(sharing.router)
app.mount("/static", StaticFiles(directory="static"), name="static")
@@ -74,3 +87,61 @@ async def pwa_manifest():
"theme_color": "#191919",
"icons": [{"src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png"}],
}
# ═══════════ API aliases (v4.0.1) ═══════════
@app.get("/api/pages")
async def api_pages_alias(request: Request):
"""Alias /api/pages → /board/api/pages for API path consistency."""
from fastapi.responses import RedirectResponse
qs = str(request.url.query)
target = f"/board/api/pages{'?' + qs if qs else ''}"
return RedirectResponse(url=target, status_code=307)
@app.post("/api/pages")
async def api_pages_post_alias(request: Request):
"""Alias POST /api/pages → /board/api/pages for API path consistency."""
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/board/api/pages", status_code=307)
# ═══════════ Styled 404 handler ═══════════
NOT_FOUND_HTML = """<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>404 — FlowDeck</title>
<style>
:root{--bg:#191919;--text:#e0e0e0;--text-dim:#999;--accent:#2383E2}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:var(--bg);color:var(--text);display:flex;align-items:center;justify-content:center;min-height:100vh;text-align:center}
.box h1{font-size:6rem;font-weight:800;opacity:.08;line-height:1}
.box p{font-size:18px;color:var(--text-dim);margin:8px 0 24px}
.box a{color:var(--accent);text-decoration:none;font-size:14px}
.box a:hover{text-decoration:underline}
</style>
</head>
<body>
<div class="box">
<h1>404</h1>
<p>This page doesn't exist or has been moved.</p>
<a href="/">← Back to FlowDeck</a>
</div>
</body>
</html>"""
@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
"""Styled 404 page matching the FlowDeck dark theme."""
from fastapi.responses import HTMLResponse
# API routes should get JSON, not HTML
if request.url.path.startswith("/api/") or request.url.path.startswith("/board/api/"):
from fastapi.responses import JSONResponse
return JSONResponse({"detail": "Not found"}, status_code=404)
return HTMLResponse(NOT_FOUND_HTML, status_code=404)
+1 -1
View File
@@ -16,7 +16,7 @@ class CSRFMiddleware(BaseHTTPMiddleware):
"""
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
EXCLUDED_PATHS = {"/api/webhook", "/api/v1", "/auth/callback", "/auth/register", "/auth/local-login", "/api/user", "/board/api/pages", "/board/api/favorites", "/api/workspace", "/api/local-workspace", "/db/", "/workspace"}
EXCLUDED_PATHS = {"/api/webhook", "/api/v1", "/auth/callback", "/auth/register", "/auth/local-login", "/api/user", "/board/api/pages", "/board/api/favorites", "/api/workspace", "/api/local-workspace", "/api/settings", "/db/", "/workspace", "/api/frontend-error", "/api/admin", "/api/gitea", "/api/github", "/api/pages", "/api/recents"}
async def dispatch(self, request: Request, call_next):
# Webhook receiver, OAuth callback, and internal API are exempt
+141
View File
@@ -0,0 +1,141 @@
"""FlowDeck — Security middleware: CSP headers + rate limiting."""
from __future__ import annotations
import time
from collections import defaultdict
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
# ── Constants ────────────────────────────────────────────────
# Allowed extensions for file uploads
ALLOWED_EXTENSIONS: frozenset[str] = frozenset({
# Images
".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico",
# Documents
".pdf", ".md", ".markdown", ".txt", ".log", ".csv",
# Code
".py", ".js", ".jsx", ".ts", ".tsx", ".html", ".htm", ".xml", ".css",
".json", ".yaml", ".yml", ".toml", ".sql", ".sh", ".bash", ".zsh",
".ps1", ".rs", ".go", ".java", ".rb", ".php", ".c", ".cpp", ".h",
".swift", ".kt", ".scala", ".r",
# Archives
".zip", ".tar", ".gz", ".rar", ".7z",
# Misc
".env", ".cfg", ".conf", ".ini", ".dockerfile", ".makefile",
})
MAX_UPLOAD_SIZE = 10 * 1024 * 1024 # 10 MB
def validate_upload(filename: str, size: int) -> str | None:
"""Validate upload filename and size. Returns error message or None."""
if size > MAX_UPLOAD_SIZE:
return f"File '{filename}' exceeds maximum size of 10 MB"
ext = _ext(filename)
if ext and ext not in ALLOWED_EXTENSIONS:
return f"File extension '{ext}' is not allowed"
return None
def _ext(filename: str) -> str:
"""Extract lowercase extension from filename."""
if "." in filename:
return "." + filename.rsplit(".", 1)[-1].lower()
return ""
# ── Content-Security-Policy Middleware ────────────────────────
class ContentSecurityPolicyMiddleware(BaseHTTPMiddleware):
"""Sets Content-Security-Policy headers on all HTML responses.
A permissive-yet-safe policy for a Notion-style app that needs:
- inline scripts (Alpine.js, HTMX)
- inline styles
- font loading
- images from various sources
- media (audio/video)
- websocket connections for HMR/SSE
"""
CSP_HEADER = "Content-Security-Policy"
CSP_VALUE = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"img-src 'self' data: blob: https:; "
"font-src 'self' data: https://fonts.gstatic.com; "
"connect-src 'self' https: wss:; "
"media-src 'self' blob:; "
"frame-src 'self'; "
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
)
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
# Only set CSP on HTML responses
content_type = response.headers.get("content-type", "")
if "text/html" in content_type:
response.headers[self.CSP_HEADER] = self.CSP_VALUE
return response
# ── Rate Limiting Middleware ──────────────────────────────────
class RateLimitMiddleware(BaseHTTPMiddleware):
"""Simple in-memory sliding-window rate limiter per IP.
Default: 100 requests per minute per IP for API routes.
Non-API routes (HTML pages, static files) are not rate-limited.
"""
# Paths that should be rate-limited
RATE_LIMITED_PREFIXES: tuple[str, ...] = (
"/api/", "/board/api/", "/auth/",
)
# Paths exempt from rate limiting even under an API prefix
EXEMPT_PATHS: frozenset[str] = frozenset({
"/api/health",
"/api/frontend-error",
"/api/frontend-errors",
})
def __init__(self, app, max_requests: int = 100, window_seconds: int = 60):
super().__init__(app)
self.max_requests = max_requests
self.window_seconds = window_seconds
self._store: dict[str, tuple[float, int]] = defaultdict(lambda: (0.0, 0))
async def dispatch(self, request: Request, call_next):
path = request.url.path
# Only rate-limit API routes
if not any(path.startswith(p) for p in self.RATE_LIMITED_PREFIXES):
return await call_next(request)
# Exempt health check and error capture
if path in self.EXEMPT_PATHS:
return await call_next(request)
ip = request.client.host if request.client else "unknown"
now = time.time()
window_start, count = self._store[ip]
if now - window_start > self.window_seconds:
self._store[ip] = (now, 1)
return await call_next(request)
if count >= self.max_requests:
return JSONResponse(
{"error": "Rate limit exceeded", "detail": f"Max {self.max_requests} req/min per IP"},
status_code=429,
)
self._store[ip] = (window_start, count + 1)
return await call_next(request)
+95
View File
@@ -0,0 +1,95 @@
"""FlowDeck — Pydantic request models for API validation."""
from __future__ import annotations
from typing import Optional
from fastapi import UploadFile
from pydantic import BaseModel, Field, model_validator
from app.middleware.security import ALLOWED_EXTENSIONS, MAX_UPLOAD_SIZE, _ext
# ── File Save ────────────────────────────────────────────────
class FileSaveRequest(BaseModel):
"""Request model for saving/updating a file via Gitea."""
path: str = Field(..., min_length=1, description="File path in the repository")
content: str = Field(..., description="File content (UTF-8 encoded)")
message: str = Field(default="Update via FlowDeck", description="Commit message")
sha: Optional[str] = Field(default=None, description="SHA of the file being updated (required for updates)")
@model_validator(mode="after")
def validate_path_extension(self):
ext = _ext(self.path)
if ext and ext not in ALLOWED_EXTENSIONS:
raise ValueError(f"File extension '{ext}' is not allowed")
return self
# ── Upload ───────────────────────────────────────────────────
class UploadValidationResult(BaseModel):
"""Result of validating an upload."""
filename: str
size: int
extension: str
valid: bool
error: Optional[str] = None
def validate_upload_request(file: UploadFile) -> Optional[str]:
"""Validate an uploaded file (size + extension). Returns error message or None."""
# Size check — we can't read the full file without a size attribute,
# but Starlette's UploadFile has a size property from Content-Length
if hasattr(file, 'size') and file.size is not None and file.size > MAX_UPLOAD_SIZE:
return f"File '{file.filename}' exceeds maximum size of 10 MB"
# Extension check
if file.filename:
ext = _ext(file.filename)
if ext and ext not in ALLOWED_EXTENSIONS:
return f"File extension '{ext}' is not allowed"
return None
# ── Issue Create / Update ────────────────────────────────────
class IssueCreateRequest(BaseModel):
"""Request model for creating a Gitea issue."""
title: str = Field(..., min_length=1, max_length=500)
body: str = Field(default="")
labels: str = Field(default="", description="Comma-separated label IDs")
milestone: str = Field(default="", description="Milestone ID")
assignee: str = Field(default="")
class IssueUpdateRequest(BaseModel):
"""Request model for updating a Gitea issue (partial update)."""
title: Optional[str] = Field(default=None, max_length=500)
body: Optional[str] = Field(default=None)
state: Optional[str] = Field(default=None, pattern=r"^(open|closed)$")
labels: Optional[str] = Field(default=None, description="Comma-separated label IDs")
milestone: Optional[str] = Field(default=None)
assignee: Optional[str] = Field(default=None)
# ── Card Move ────────────────────────────────────────────────
class CardMoveRequest(BaseModel):
"""Request model for moving a card between columns."""
owner: str = Field(..., min_length=1)
repo: str = Field(..., min_length=1)
issue_id: int = Field(..., gt=0)
column: str = Field(..., min_length=1)
# ── Column Mapping ───────────────────────────────────────────
class ColMappingRequest(BaseModel):
"""Request model for column-to-label mapping."""
owner: str = Field(..., min_length=1)
repo: str = Field(..., min_length=1)
column: str = Field(..., min_length=1)
gitea_label: str = Field(..., min_length=1)
close_issue: bool = Field(default=False)
+38
View File
@@ -0,0 +1,38 @@
"""FlowDeck — Standardized response models."""
from __future__ import annotations
from typing import Any, Optional
from pydantic import BaseModel
class ErrorResponse(BaseModel):
"""Standardized error response.
Example:
ErrorResponse(error="Rate limit exceeded", detail="Max 100 req/min per IP")
"""
error: str
detail: Optional[str] = None
model_config = {
"json_schema_extra": {
"example": {"error": "Not found", "detail": "Board not found"}
}
}
class SuccessResponse(BaseModel):
"""Standardized success response.
Example:
SuccessResponse(status="ok", data={"issue_id": 42})
"""
status: str = "ok"
data: Optional[dict[str, Any]] = None
model_config = {
"json_schema_extra": {
"example": {"status": "ok", "data": {"issue_id": 42, "column": "Done"}}
}
}
+174
View File
@@ -0,0 +1,174 @@
"""FlowDeck — Admin API: users, roles, stats, audit."""
from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import JSONResponse
router = APIRouter(tags=["admin"], prefix="/api/admin")
# ── Dependency ──
async def admin_required(request: Request):
from app.auth.session import get_current_user
user = await get_current_user(request)
if not user:
raise HTTPException(status_code=403, detail="Admin access required")
# Also check DB directly (session cookie may be stale)
if not user.get("is_admin"):
from app.db import get_conn
with get_conn() as conn:
row = conn.execute("SELECT is_admin FROM users WHERE id=?", (user.get("id"),)).fetchone()
if not row or not row["is_admin"]:
raise HTTPException(status_code=403, detail="Admin access required")
return user
# ── Users ──
@router.get("/users")
async def list_users(_admin=Depends(admin_required)):
"""List all users with workspace/file/folder counts and storage usage."""
from app.db import get_conn
with get_conn() as conn:
rows = conn.execute("""
SELECT u.id, u.login, u.full_name, u.email, u.is_admin, u.is_active,
u.last_login, u.created_at,
(SELECT COUNT(*) FROM workspaces WHERE owner_id=u.id) AS ws_count,
(SELECT COUNT(*) FROM pages WHERE workspace_id IN (SELECT id FROM workspaces WHERE owner_id=u.id)) AS page_count
FROM users u
ORDER BY u.id
""").fetchall()
users = []
for r in rows:
d = dict(r)
d["file_count"] = d["page_count"]
d["folder_count"] = 0
d["total_mb"] = 0
users.append(d)
return {"users": users}
@router.post("/users")
async def create_user(request: Request, _admin=Depends(admin_required)):
"""Create a new user (admin only)."""
from app.db import get_conn
from app.password_utils import hash_password
import json
try:
body = await request.json()
except Exception:
body = {}
login = body.get("login", "").strip()
name = body.get("name", login)
email = body.get("email", login)
password = body.get("password", "").strip()
is_admin = int(body.get("is_admin", 0))
if not login or not password:
return JSONResponse({"error": "Login and password required"}, status_code=400)
if len(password) < 6:
return JSONResponse({"error": "Password must be at least 6 characters"}, status_code=400)
with get_conn() as conn:
existing = conn.execute("SELECT id FROM users WHERE login=?", (login,)).fetchone()
if existing:
return JSONResponse({"error": "User already exists"}, status_code=409)
conn.execute(
"INSERT INTO users (login, full_name, email, password_hash, is_admin) VALUES (?, ?, ?, ?, ?)",
(login, name, email, hash_password(password), is_admin),
)
conn.commit()
uid = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
return {"status": "ok", "user": {"id": uid, "login": login}}
@router.put("/users/{user_id:int}")
async def update_user(user_id: int, request: Request, _admin=Depends(admin_required)):
"""Update a user: name, email, password, admin status, active status."""
from app.db import get_conn
from app.password_utils import hash_password
import json
try:
body = await request.json()
except Exception:
body = {}
with get_conn() as conn:
user = conn.execute("SELECT id FROM users WHERE id=?", (user_id,)).fetchone()
if not user:
return JSONResponse({"error": "User not found"}, status_code=404)
if "name" in body:
conn.execute("UPDATE users SET full_name=? WHERE id=?", (body["name"], user_id))
if "email" in body:
conn.execute("UPDATE users SET email=? WHERE id=?", (body["email"], user_id))
if "password" in body and body["password"].strip():
pw = body["password"].strip()
if len(pw) < 6:
return JSONResponse({"error": "Password must be at least 6 characters"}, status_code=400)
conn.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(pw), user_id))
if "is_admin" in body:
conn.execute("UPDATE users SET is_admin=? WHERE id=?", (int(body["is_admin"]), user_id))
if "is_active" in body:
conn.execute("UPDATE users SET is_active=? WHERE id=?", (int(body["is_active"]), user_id))
conn.commit()
return {"status": "ok"}
@router.delete("/users/{user_id:int}")
async def delete_user(user_id: int, _admin=Depends(admin_required)):
"""Delete a user and cascade their data."""
from app.db import get_conn
with get_conn() as conn:
user = conn.execute("SELECT id FROM users WHERE id=?", (user_id,)).fetchone()
if not user:
return JSONResponse({"error": "User not found"}, status_code=404)
# Cascade delete: first delete child records
conn.execute("DELETE FROM login_history WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM user_oauth_tokens WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM user_tokens WHERE gitea_user_id=?", (user_id,))
conn.execute("DELETE FROM workspace_members WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM comments WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM page_history WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM favorites WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM gitea_private_pages WHERE user_id=?", (user_id,))
conn.execute("DELETE FROM tags WHERE user_id=?", (user_id,))
# Delete workspaces owned by this user
ws_rows = conn.execute("SELECT id FROM workspaces WHERE owner_id=?", (user_id,)).fetchall()
for ws in ws_rows:
conn.execute("DELETE FROM pages WHERE workspace_id=?", (ws["id"],))
conn.execute("DELETE FROM workspace_members WHERE workspace_id=?", (ws["id"],))
conn.execute("DELETE FROM workspaces WHERE owner_id=?", (user_id,))
conn.execute("DELETE FROM users WHERE id=?", (user_id,))
conn.commit()
return {"status": "ok"}
# ── Stats ──
@router.get("/stats")
async def user_stats(_admin=Depends(admin_required)):
"""Aggregate stats: total users, workspaces, files, storage."""
from app.db import get_conn
with get_conn() as conn:
total_users = conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]
total_ws = conn.execute("SELECT COUNT(*) FROM workspaces").fetchone()[0]
total_files = conn.execute("SELECT COUNT(*) FROM pages").fetchone()[0]
total_folders = 0
total_bytes = 0
return {
"total_users": total_users,
"total_workspaces": total_ws,
"total_files": total_files,
"total_folders": total_folders,
"total_mb": round(total_bytes / (1024 * 1024), 2),
}
# ── Audit ──
@router.get("/audit")
async def audit_log(limit: int = 100, _admin=Depends(admin_required)):
"""Recent login history."""
from app.db import get_conn
with get_conn() as conn:
rows = conn.execute("""
SELECT lh.id, lh.user_id, u.login, u.full_name,
lh.ip_address, lh.user_agent, lh.logged_at
FROM login_history lh
JOIN users u ON u.id = lh.user_id
ORDER BY lh.logged_at DESC
LIMIT ?
""", (min(limit, 500),)).fetchall()
return {"entries": [dict(r) for r in rows]}
+52
View File
@@ -623,3 +623,55 @@ async def get_collaborators(owner: str, repo: str):
return {"collaborators": collaborators}
except Exception as e:
return {"collaborators": [], "error": str(e)}
# ── Frontend Error Capture ───────────────────────────────────
# Hermes diagnostique le frontend en appelant GET /api/frontend-errors
_frontend_errors: list[dict] = []
_MAX_STORED_ERRORS = 100
@router.post("/frontend-error")
async def capture_frontend_error(request: Request):
"""Reçoit les erreurs JS du navigateur. Appelé automatiquement par app.js."""
try:
body = await request.json()
except Exception:
return {"status": "ignored", "reason": "invalid json"}
msg = body.get("message", "")
err_type = body.get("type", "error")
source = body.get("source", "")
line = body.get("line", 0)
# Dédupliquer les erreurs identiques consécutives
if _frontend_errors and _frontend_errors[-1].get("message") == msg:
_frontend_errors[-1]["count"] = _frontend_errors[-1].get("count", 1) + 1
_frontend_errors[-1]["time"] = body.get("time", "")
else:
body["count"] = 1
_frontend_errors.append(body)
while len(_frontend_errors) > _MAX_STORED_ERRORS:
_frontend_errors.pop(0)
if err_type == "error":
logger.warning("Frontend JS error: %s (%s:%s)", msg, source, line)
else:
logger.warning("Frontend unhandled rejection: %s", msg)
return {"status": "ok"}
@router.get("/frontend-errors")
async def get_frontend_errors(request: Request, clear: bool = True):
"""Retourne les erreurs frontend récentes. Hermes appelle cette route."""
errors = list(_frontend_errors)
if clear:
_frontend_errors.clear()
return {
"errors": errors,
"count": len(errors),
"cleared": clear,
}
+131 -34
View File
@@ -27,7 +27,10 @@ body{background:#191919;color:#fff;font-family:-apple-system,BlinkMacSystemFont,
.login-box p{color:rgba(255,255,255,.5);font-size:14px;margin-bottom:24px;}
.form-group{margin-bottom:16px;}
.form-group label{display:block;font-size:13px;color:rgba(255,255,255,.6);margin-bottom:6px;}
.form-group input{width:100%;padding:10px 12px;background:#2A2A2A;border:1px solid rgba(255,255,255,.1);border-radius:8px;color:#fff;font-size:14px;outline:none;}
.form-group input{width:100%;padding:10px 36px 10px 12px;background:#2A2A2A;border:1px solid rgba(255,255,255,.1);border-radius:8px;color:#fff;font-size:14px;outline:none;}
.pw-wrapper{position:relative;}
.pw-toggle{position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:none;color:rgba(255,255,255,.4);cursor:pointer;font-size:16px;padding:4px;line-height:1;}
.pw-toggle:hover{color:rgba(255,255,255,.8);}
.form-group input:focus{border-color:#2383E2;box-shadow:0 0 0 1px #2383E2;}
.btn{width:100%;padding:12px;border:none;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer;margin-top:8px;}
.btn-primary{background:#2383E2;color:#fff;}
@@ -52,61 +55,99 @@ body{background:#191919;color:#fff;font-family:-apple-system,BlinkMacSystemFont,
<button class="tab active" onclick="switchTab('login')" id="tab-login">Login</button>
<button class="tab" onclick="switchTab('register')" id="tab-register">Register</button>
</div>
<div id="expired-msg" class="success" style="display:none">⚠️ Your session has expired. Please log in again.</div>
<div id="error-msg" class="error"></div>
<div id="success-msg" class="success"></div>
<form id="login-form" onsubmit="handleLogin(event)">
<div class="form-group"><label>Email</label><input type="email" id="email" required></div>
<div class="form-group"><label>Password</label><input type="password" id="password" required minlength="6"></div>
<div class="form-group"><label>Email or username</label><input type="text" id="email" required autocomplete="username"></div>
<div class="form-group">
<label>Password</label>
<div class="pw-wrapper">
<input type="password" id="password" required minlength="6" autocomplete="current-password">
<button type="button" class="pw-toggle" onclick="togglePassword()" title="Show password">👁</button>
</div>
</div>
<div class="form-group" id="name-group" style="display:none"><label>Name</label><input type="text" id="name"></div>
<button type="submit" class="btn btn-primary" id="submit-btn">Login</button>
</form>
<div class="oauth-section">
<button class="oauth-btn" onclick="window.location='/auth/login?provider=gitea'" style="margin-bottom:8px">🔗 Login with Gitea</button>
<button class="oauth-btn" onclick="window.location='/auth/login?provider=github'">🐙 Login with GitHub</button>
<p style="font-size:13px;color:rgba(255,255,255,.4);margin-bottom:8px;">Or continue with</p>
<button class="oauth-btn" onclick="window.location='/auth/login?provider=gitea'" style="margin-bottom:8px">🔗 <span id="gitea-btn-label">Login</span> with Gitea</button>
<button class="oauth-btn" onclick="window.location='/auth/login?provider=github'">🐙 <span id="github-btn-label">Login</span> with GitHub</button>
</div>
</div>
<script>
// Show session expired banner if ?expired=1 in URL
(function(){if(location.search.includes('expired=1')){var el=document.getElementById('expired-msg');if(el)el.style.display='block';}})();
let mode='login';
function switchTab(t){mode=t;document.querySelectorAll('.tab').forEach(el=>el.classList.remove('active'));document.getElementById('tab-'+t).classList.add('active');document.getElementById('name-group').style.display=t==='register'?'block':'none';document.getElementById('submit-btn').textContent=t==='register'?'Register':'Login';document.getElementById('error-msg').style.display='none';document.getElementById('success-msg').style.display='none';}
async function handleLogin(e){e.preventDefault();const email=document.getElementById('email').value;const password=document.getElementById('password').value;const name=document.getElementById('name').value;const url=mode==='register'?'/auth/register':'/auth/local-login';const body={email,password};if(mode==='register')body.name=name;try{const r=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const d=await r.json();if(!r.ok){document.getElementById('error-msg').textContent=d.error||'Error';document.getElementById('error-msg').style.display='block';return;}if(d.status==='ok'){window.location='/';}}catch(err){document.getElementById('error-msg').textContent='Network error';document.getElementById('error-msg').style.display='block';}}
function switchTab(t){mode=t;document.querySelectorAll('.tab').forEach(el=>el.classList.remove('active'));document.getElementById('tab-'+t).classList.add('active');document.getElementById('name-group').style.display=t==='register'?'block':'none';document.getElementById('submit-btn').textContent=t==='register'?'Register':'Login';document.getElementById('error-msg').style.display='none';document.getElementById('success-msg').style.display='none';var lbl=t==='register'?'Register':'Login';var e1=document.getElementById('gitea-btn-label');var e2=document.getElementById('github-btn-label');if(e1)e1.textContent=lbl;if(e2)e2.textContent=lbl;}
function togglePassword(){var pw=document.getElementById('password');var btn=pw.parentElement.querySelector('.pw-toggle');if(pw.type==='password'){pw.type='text';btn.textContent='🙈';}else{pw.type='password';btn.textContent='👁';}}
async function handleLogin(e){e.preventDefault();const email=document.getElementById('email').value;const password=document.getElementById('password').value;const name=document.getElementById('name').value;const url=mode==='register'?'/auth/register':'/auth/local-login';const body={email,password};if(mode==='register')body.name=name;try{const r=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const d=await r.json();if(!r.ok){document.getElementById('error-msg').textContent=d.error||'Error';document.getElementById('error-msg').style.display='block';return;}if(d.status==='ok'){window.location='/workspaces';}}catch(err){document.getElementById('error-msg').textContent='Network error';document.getElementById('error-msg').style.display='block';}}
</script>
</body>
</html>"""
@router.get("/register")
async def register_page(request: Request):
"""Show the registration page (local login page with register tab active)."""
return HTMLResponse(LOCAL_LOGIN_HTML.replace(
'class="tab active" onclick="switchTab(\'login\')"',
'class="tab" onclick="switchTab(\'login\')"'
).replace(
'class="tab" onclick="switchTab(\'register\')"',
'class="tab active" onclick="switchTab(\'register\')"'
).replace(
'let mode=\'login\';',
'let mode=\'register\';'
).replace(
'id="name-group" style="display:none"',
'id="name-group" style="display:block"'
).replace(
'id="submit-btn">Login<',
'id="submit-btn">Register<'
), status_code=200)
@router.get("/login")
async def login(request: Request, provider: str = Query("gitea")):
"""Redirect to OAuth2 authorize page or show local login page."""
# Local login page (POST handled by /auth/local-login)
if provider == "local":
from fastapi.responses import HTMLResponse
if provider == "local":
return HTMLResponse(LOCAL_LOGIN_HTML, status_code=200)
# OAuth flow — check if provider is configured
from app.auth.providers import get_provider
oauth_provider = get_provider(provider)
if not oauth_provider:
# Fallback: no OAuth configured, create admin session
from app.db import get_conn
with get_conn() as conn:
user = conn.execute("SELECT * FROM users WHERE login='admin'").fetchone()
if not user:
conn.execute(
"INSERT INTO users (login, full_name, email, avatar_url, is_active) "
"VALUES ('admin', 'Admin', 'admin@localhost', '', 1)"
# OAuth provider not configured — show error instead of auto-creating admin
return HTMLResponse(
f"""<!DOCTYPE html><html><head><title>FlowDeck</title><style>
body{{background:#191919;color:#fff;font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;text-align:center;}}
.box{{background:#222;border:1px solid rgba(255,255,255,.08);border-radius:12px;padding:40px;max-width:420px;}}
h1{{font-size:20px;margin-bottom:12px;}}p{{color:rgba(255,255,255,.5);font-size:14px;margin-bottom:16px;}}
a{{color:#2383E2;}}
</style></head><body><div class="box">
<h1>⚠️ {provider.title()} OAuth not configured</h1>
<p>The {provider} integration has not been set up by the server administrator.</p>
<p><a href="/auth/login?provider=local">↩ Use local login</a></p>
</div></body></html>""",
status_code=200,
)
conn.commit()
user = conn.execute("SELECT * FROM users WHERE login='admin'").fetchone()
user_data = dict(user)
session = SessionManager.create_session(user_data)
response = RedirectResponse(url="/workspaces", status_code=302)
response.set_cookie("flowdeck_session", session, httponly=True, max_age=86400 * 7, samesite="lax", path="/")
return response
state = secrets.token_hex(32)
request.session["oauth_state"] = state
request.session["oauth_provider"] = provider
auth_url = oauth_provider.get_authorize_url(state)
# Link mode: connect OAuth to current local account instead of creating new user
mode = request.query_params.get("mode", "")
# Encode auth mode in state to survive session loss during OAuth redirect
signed_state = f"{state}:{mode}" if mode else state
request.session["oauth_mode"] = mode
# Dynamic redirect URI based on incoming Host header
host = request.headers.get("host", "localhost:8080")
dynamic_redirect_uri = f"http://{host}/auth/callback"
auth_url = oauth_provider.get_authorize_url(signed_state, redirect_uri=dynamic_redirect_uri, force_login=(mode == "link"))
return RedirectResponse(url=auth_url, status_code=302)
@@ -136,13 +177,20 @@ async def register(request: Request):
if existing:
from fastapi.responses import JSONResponse
return JSONResponse({"error": "Account already exists"}, status_code=409)
# First real user (excluding default admin with no password) is admin
real_user_count = conn.execute(
"SELECT COUNT(*) FROM users WHERE password_hash IS NOT NULL AND password_hash != ''"
).fetchone()[0]
is_admin = 1 if real_user_count == 0 else 0
conn.execute(
"INSERT INTO users (login, full_name, email, password_hash) VALUES (?, ?, ?, ?)",
(email, name, email, hash_password(password)),
"INSERT INTO users (login, full_name, email, password_hash, is_admin) VALUES (?, ?, ?, ?, ?)",
(email, name, email, hash_password(password), is_admin),
)
conn.commit()
user = conn.execute("SELECT * FROM users WHERE login=?", (email,)).fetchone()
user_data = dict(user)
# Log login
_log_login(user_data["id"], request)
session = SessionManager.create_session(user_data)
from fastapi.responses import JSONResponse
response = JSONResponse({"status": "ok", "user": {"login": email, "name": name}})
@@ -199,6 +247,7 @@ async def local_login(request: Request):
)
conn.commit()
session = SessionManager.create_session(ud)
_log_login(ud["id"], request)
response = JSONResponse({"status": "ok", "user": {"login": ud["login"], "name": ud["full_name"]}})
response.set_cookie("flowdeck_session", session, httponly=True, max_age=86400 * 7, samesite="lax", path="/")
return response
@@ -211,19 +260,32 @@ async def callback(
state: str = Query(...),
):
"""Handle OAuth2 callback from Gitea."""
# Validate state
# Recover mode from state suffix (state:mode format), then validate
expected_state = request.session.get("oauth_state", "")
provider_name = request.session.get("oauth_provider", "gitea")
if not expected_state or state != expected_state:
auth_mode = ""
raw_state = state
if ":" in state:
raw_state, auth_mode = state.rsplit(":", 1)
if auth_mode:
request.session["oauth_mode"] = auth_mode
# Validate: state token must match session, unless session lost and mode present
if expected_state and raw_state != expected_state:
return HTMLResponse("<h1>Invalid state</h1>", status_code=400)
if not expected_state and not auth_mode:
return HTMLResponse("<h1>Session expired — please try connecting again</h1>", status_code=400)
from app.auth.providers import get_provider
oauth_provider = get_provider(provider_name)
if not oauth_provider:
return HTMLResponse(f"<h1>Unknown provider: {provider_name}</h1>", status_code=400)
# Exchange code for token
token_data = await oauth_provider.exchange_code(code)
# Exchange code for token — use dynamic redirect URI matching the authorize step
host = request.headers.get("host", "localhost:8080")
dynamic_redirect_uri = f"http://{host}/auth/callback"
token_data = await oauth_provider.exchange_code(code, redirect_uri=dynamic_redirect_uri)
if not token_data:
return HTMLResponse("<h1>Token exchange failed</h1>", status_code=400)
@@ -236,16 +298,34 @@ async def callback(
if not oauth_user:
return HTMLResponse("<h1>Failed to get user</h1>", status_code=400)
# Link mode: connect OAuth to current session user (for Settings → Integrations)
oauth_mode = request.session.pop("oauth_mode", "")
if oauth_mode == "link":
from app.auth.session import get_current_user as gcu
current = await gcu(request)
if not current:
return HTMLResponse("<h1>Not logged in — please log in first</h1>", status_code=400)
from app.db import get_conn as _gc
with _gc() as conn:
conn.execute(
"""INSERT OR REPLACE INTO user_oauth_tokens
(user_id, provider, access_token, refresh_token, expires_at, updated_at)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)""",
(current["id"], provider_name, access_token, token_data.get("refresh_token"), token_data.get("expires_at")),
)
conn.commit()
return RedirectResponse(url="/settings#integrations", status_code=302)
# Store user in DB
from app.db import get_conn
login_id = f"{provider_name}_{oauth_user['login']}"
with get_conn() as conn:
conn.execute(
"""INSERT INTO users (login, full_name, email, avatar_url)
VALUES (?, ?, ?, ?)
"""INSERT INTO users (login, full_name, email, avatar_url, auth_method)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(login)
DO UPDATE SET full_name=excluded.full_name, email=excluded.email, avatar_url=excluded.avatar_url""",
(login_id, oauth_user.get("full_name", ""), oauth_user.get("email", ""), oauth_user.get("avatar_url", "")),
DO UPDATE SET full_name=excluded.full_name, email=excluded.email, avatar_url=excluded.avatar_url, auth_method=excluded.auth_method""",
(login_id, oauth_user.get("full_name", ""), oauth_user.get("email", ""), oauth_user.get("avatar_url", ""), provider_name),
)
conn.commit()
# Store OAuth token
@@ -265,6 +345,7 @@ async def callback(
# Create session
session = SessionManager.create_session(user_data)
_log_login(user_data["id"], request)
response = RedirectResponse(url="/workspaces", status_code=302)
response.set_cookie("flowdeck_session", session, httponly=True, max_age=86400 * 7, samesite="lax", path="/")
return response
@@ -286,3 +367,19 @@ async def current_user(request: Request):
if not user:
return {"authenticated": False}
return {"authenticated": True, "user": user}
# ── Helpers ──
def _log_login(user_id: int, request: Request):
"""Record login in history."""
try:
from app.db import get_conn
ip = request.client.host if request.client else ''
ua = request.headers.get('user-agent', '')[:500]
with get_conn() as conn:
conn.execute(
"INSERT INTO login_history (user_id, ip_address, user_agent) VALUES (?, ?, ?)",
(user_id, ip, ua),
)
conn.commit()
except Exception:
pass
+156 -234
View File
@@ -5,7 +5,7 @@ import json
import logging
from fastapi import APIRouter, Request, HTTPException, Query
from fastapi.responses import HTMLResponse
from fastapi.responses import HTMLResponse, JSONResponse
from app.db import get_conn
from app.services.gitea_client import gitea
@@ -172,7 +172,7 @@ def _load_workspace_pages(ws_cookie: str) -> list:
ws_id = int(ws_cookie)
with get_conn() as conn:
rows = conn.execute(
"SELECT id, title, parent_section, content_format FROM pages WHERE workspace_id=? AND parent_id IS NULL ORDER BY created_at DESC",
"SELECT id, title, parent_section, content_format FROM pages WHERE workspace_id=? AND parent_id IS NULL AND deleted_at IS NULL ORDER BY created_at DESC",
(ws_id,),
).fetchall()
items = []
@@ -197,7 +197,7 @@ def _load_children(parent_id: int) -> list:
"""Recursively load children of a page."""
with get_conn() as conn:
rows = conn.execute(
"SELECT id, title, parent_section, content_format FROM pages WHERE parent_id=? ORDER BY created_at",
"SELECT id, title, parent_section, content_format FROM pages WHERE parent_id=? AND deleted_at IS NULL ORDER BY created_at",
(parent_id,),
).fetchall()
children = []
@@ -225,14 +225,49 @@ def _sidebar_data(request: Request, owner: str = "", repo: str = "") -> dict:
from app.routers.dashboard import WORKSPACE_COOKIE
ws_cookie = request.cookies.get(WORKSPACE_COOKIE, "")
active_ws_name = "Workspace"
if ws_cookie:
workspace_pages = []
gitea_workspace = False
gitea_owner = ""
gitea_repo = ""
has_active_workspace = False
if ws_cookie and ws_cookie.startswith("gitea:"):
# Gitea workspace: preserve context across pages
parts = ws_cookie.split(":", 2)
if len(parts) >= 3:
gitea_owner = parts[1]
gitea_repo = parts[2]
active_ws_name = f"{gitea_owner}/{gitea_repo}"
gitea_workspace = True
has_active_workspace = True
workspace_pages = [] # loaded client-side
# Get local workspace ID for mirror
if user:
try:
with get_conn() as conn:
ws = conn.execute("SELECT name FROM workspaces WHERE id=?", (int(ws_cookie),)).fetchone()
if ws:
active_ws_name = ws["name"]
row = conn.execute(
"SELECT id FROM workspaces WHERE owner_id=? AND name=? AND settings_json LIKE ?",
(user["id"], f"{gitea_owner}/{gitea_repo}", "%gitea_repo%")
).fetchone()
if row:
local_ws_id = row["id"]
except Exception:
pass
elif ws_cookie and user:
try:
wsi = int(ws_cookie)
with get_conn() as conn:
row = conn.execute(
"SELECT id, name, owner_id FROM workspaces WHERE id=? AND owner_id=?",
(wsi, user["id"])
).fetchone()
if row:
active_ws_name = row["name"]
workspace_pages = _load_workspace_pages(ws_cookie)
has_active_workspace = True
except (ValueError, Exception):
pass
local_ws_id = 0
recent = []
if owner and repo:
view_map = {
@@ -289,8 +324,9 @@ def _sidebar_data(request: Request, owner: str = "", repo: str = "") -> dict:
"WHERE share_mode='anyone' OR published=1 ORDER BY updated_at DESC LIMIT 20"
).fetchall()
shared_pages = []
published_pages = []
for r in shared_rows:
shared_pages.append({
page_entry = {
"id": f"page/{r['id']}",
"db_id": r["id"],
"name": r["title"] or "New page",
@@ -301,15 +337,50 @@ def _sidebar_data(request: Request, owner: str = "", repo: str = "") -> dict:
"depth": 0,
"has_children": False,
"children": [],
})
}
if r["published"]:
published_pages.append(page_entry)
else:
shared_pages.append(page_entry)
# Auth method & OAuth badge data
auth_method = "local"
gitea_linked = False
github_linked = False
if user and user.get("id"):
try:
with get_conn() as conn:
am_row = conn.execute("SELECT auth_method FROM users WHERE id=?", (user["id"],)).fetchone()
if am_row and am_row["auth_method"]:
auth_method = am_row["auth_method"]
tokens = conn.execute(
"SELECT provider FROM user_oauth_tokens WHERE user_id=?", (user["id"],)
).fetchall()
for t in tokens:
if t["provider"] == "gitea":
gitea_linked = True
elif t["provider"] == "github":
github_linked = True
except Exception:
pass
return {"workspace_name": ws_name, "workspace_initial": ws_name[0].upper() if ws_name else "B",
"active_ws_name": active_ws_name,
"workspace_pages": _load_workspace_pages(ws_cookie),
"workspace_key": f"{gitea_owner}/{gitea_repo}" if gitea_workspace else ws_key,
"workspace_pages": workspace_pages,
"gitea_workspace": gitea_workspace,
"gitea_owner": gitea_owner,
"gitea_repo": gitea_repo,
"local_ws_id": local_ws_id,
"current_page": repo or "Dashboard", "last_edited": "now",
"recent_pages": recent, "private_pages": private_items,
"favorite_pages": favorites, "shared_pages": shared_pages,
"user": user, "workspace_key": ws_key}
"published_pages": published_pages,
"user": user,
"auth_method": auth_method,
"gitea_linked": gitea_linked,
"github_linked": github_linked,
"has_active_workspace": has_active_workspace}
def _extract_ai_keywords(owner: str, repo: str, labels: list[dict], body: str = ""):
@@ -724,6 +795,8 @@ async def create_page(request: Request, title: str = Query(default=""),
"""Create a new Markdown page, optionally as a sub-page."""
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
ws_key = project if project else (user.get("login", "Bruno") if user else "Bruno")
page_title = title.strip() if title else "Untitled"
try:
with get_conn() as conn:
# Compute next sort_order for this parent
next_order = 0
@@ -736,11 +809,15 @@ async def create_page(request: Request, title: str = Query(default=""),
next_order = row[0]
cur = conn.execute(
"INSERT INTO pages (workspace, title, parent_section, parent_id, sort_order) VALUES (?,?,?,?,?)",
(ws_key, title, section, parent_val, next_order),
(ws_key, page_title, section, parent_val, next_order),
)
conn.commit()
page_id = cur.lastrowid
return {"status": "ok", "id": page_id, "title": title, "workspace": ws_key, "parent_id": parent_id}
return {"status": "ok", "id": page_id, "title": page_title, "workspace": ws_key, "parent_id": parent_id}
except Exception as e:
logger.error("create_page failed: %s", e)
from fastapi.responses import JSONResponse
return JSONResponse({"error": "Failed to create page", "detail": str(e)}, status_code=500)
@router.get("/api/pages/{page_id}")
@@ -790,42 +867,49 @@ async def save_page_blocks(request: Request, page_id: int):
@router.put("/api/pages/{page_id}/move")
async def move_page(request: Request, page_id: int,
new_parent_id: int = Query(default=0),
new_order: int = Query(default=0)):
"""Move/reorder a page in the tree (drag & drop).
new_parent_id=0 means move to root level.
new_order=0 means append to end (or set explicit position)."""
async def move_page(request: Request, page_id: int):
"""Move a page to another workspace or reorder within tree.
Body (JSON): { workspace_id?: int, parent_id?: int, new_order?: int }
- workspace_id: move page to a different workspace
- parent_id: change parent (0 = root level)
- new_order: position among siblings (0 = append)
"""
try:
body = await request.json()
except Exception:
body = {}
new_ws_id = body.get("workspace_id")
new_parent_id = body.get("parent_id", 0)
new_order = body.get("new_order", 0)
with get_conn() as conn:
# Verify page exists
row = conn.execute("SELECT id, workspace FROM pages WHERE id=?", (page_id,)).fetchone()
row = conn.execute("SELECT id, workspace, workspace_id FROM pages WHERE id=?", (page_id,)).fetchone()
if not row:
raise HTTPException(404, "Page not found")
# Update parent (None for root level)
if new_ws_id:
# Move to a different workspace: get the workspace name
ws_row = conn.execute("SELECT name FROM workspaces WHERE id=?", (new_ws_id,)).fetchone()
if not ws_row:
return JSONResponse({"status": "error", "detail": "Workspace not found"}, status_code=404)
conn.execute(
"UPDATE pages SET workspace_id=?, workspace=?, parent_id=NULL, updated_at=CURRENT_TIMESTAMP WHERE id=?",
(new_ws_id, ws_row["name"], page_id),
)
else:
# Reorder within same workspace
conn.execute(
"UPDATE pages SET parent_id=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
(new_parent_id if new_parent_id > 0 else None, page_id),
)
# Update sort order
conn.execute(
"UPDATE pages SET sort_order=?, updated_at=CURRENT_TIMESTAMP WHERE id=?",
(new_order, page_id),
)
# Re-index siblings to ensure no gaps
siblings = conn.execute(
"SELECT id, sort_order FROM pages WHERE workspace=? AND parent_id IS ? AND id != ? ORDER BY sort_order ASC",
(row["workspace"], new_parent_id if new_parent_id > 0 else None, page_id),
).fetchall()
# Recompute sort_order for all siblings after the insertion point
insert_point = new_order
reorder = []
for sib in siblings:
if sib["sort_order"] >= insert_point:
reorder.append(sib["id"])
for i, sid in enumerate(sorted(reorder, key=lambda x: next(s["sort_order"] for s in siblings if s["id"] == x))):
conn.execute("UPDATE pages SET sort_order=? WHERE id=?", (insert_point + i + 1, sid))
conn.commit()
return {"status": "ok", "id": page_id, "parent_id": new_parent_id, "order": new_order}
return {"status": "ok", "id": page_id}
@router.delete("/api/pages/{page_id}")
@@ -852,10 +936,6 @@ async def view_page(request: Request, page_id: int):
return HTMLResponse("<h2>Page not found</h2>", status_code=404)
page = dict(row)
# ── File viewer for uploaded files ──
if page.get("content_format") == "file":
return _render_file_viewer(page, request)
ws = page.get("workspace", "")
parts = ws.split("/") if "/" in ws else ["", ""]
owner, repo = parts[0], parts[1] if len(parts) > 1 else ""
@@ -867,207 +947,49 @@ async def view_page(request: Request, page_id: int):
fav = conn.execute(
"SELECT id FROM favorites WHERE user_id=? AND page_id=?", (uid, page_id)
).fetchone()
# Build page_data, including file metadata for uploaded files
page_data = {"id": page_id, "title": page.get("title"), "content_format": page.get("content_format", "blocks"), "content": page.get("content", ""), "favorited": fav is not None, "share_mode": page.get("share_mode", "private"), "published": bool(page.get("published", 0))}
# For file pages, extract file metadata and add to page_data
if page.get("content_format") == "file":
import json as _json
try:
meta = _json.loads(page.get("content", "{}"))
except _json.JSONDecodeError:
meta = {}
file_path = meta.get("file_path", "").replace("\\", "/")
mime_type = meta.get("mime_type", "application/octet-stream")
file_size = meta.get("size", 0)
# Build workspace_id from file_path
fp_parts = file_path.split("/")
ws_id = ""
for p in fp_parts:
if p.startswith("workspace_"):
ws_id = p.replace("workspace_", "")
break
filename = fp_parts[-1] if fp_parts else page.get("title", "File")
file_url = f"/api/files/{ws_id}/{filename}" if ws_id else ""
page_data["file_url"] = file_url
page_data["file_mime"] = mime_type
page_data["file_size"] = file_size
page_data["file_name"] = filename
from app.routers.dashboard import _nav_breadcrumb
with get_conn() as conn:
nav_crumbs = _nav_breadcrumb(conn, page_id)
ctx = {**sidebar, "page": page, "page_favorited": fav is not None,
"page_share_mode": page.get("share_mode", "private"),
"page_published": bool(page.get("published", 0)),
"page_data": {"id": page_id, "title": page.get("title"), "content_format": page.get("content_format", "blocks"), "content": page.get("content", ""), "favorited": fav is not None, "share_mode": page.get("share_mode", "private"), "published": bool(page.get("published", 0))}}
"page_data": page_data,
"breadcrumb_items": nav_crumbs,
"nav_workspace_id": page.get("workspace_id") or 0,
"nav_page_id": page_id}
template = env.get_template("page_editor.html")
response = template.render(**ctx)
return HTMLResponse(content=response, headers={"Cache-Control": "no-store, max-age=0"})
def _render_file_viewer(page: dict, request: Request) -> HTMLResponse:
"""Render a file viewer for uploaded files (content_format='file')."""
import json
page_id = page["id"]
title = page.get("title", "File")
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
ws_name = user.get("login", "Bruno") if user else "Bruno"
initial = ws_name[0].upper() if ws_name else "B"
try:
meta = json.loads(page.get("content", "{}"))
except json.JSONDecodeError:
meta = {}
file_path = meta.get("file_path", "")
mime_type = meta.get("mime_type", "application/octet-stream")
size = meta.get("size", 0)
# Build workspace_id from file_path
parts = file_path.split("/")
ws_id = ""
for p in parts:
if p.startswith("workspace_"):
ws_id = p.replace("workspace_", "")
break
filename = parts[-1] if parts else title
file_url = f"/api/files/{ws_id}/{filename}" if ws_id else ""
# Determine viewer type
is_image = mime_type.startswith("image/")
is_pdf = mime_type == "application/pdf"
is_text = mime_type.startswith("text/") or mime_type in (
"application/json", "application/javascript", "application/xml",
"application/x-python", "application/x-sh"
)
is_code = any(ext in (filename or "").lower() for ext in (
".py", ".js", ".ts", ".jsx", ".tsx", ".html", ".htm", ".css",
".json", ".xml", ".yaml", ".yml", ".md", ".sql", ".sh", ".bash",
".ps1", ".bat", ".cmd", ".rb", ".go", ".rs", ".java", ".c", ".cpp",
".h", ".hpp", ".php", ".swift", ".kt", ".scala", ".r", ".toml",
".ini", ".cfg", ".conf", ".env", ".dockerfile", ".makefile"
))
if is_code:
is_text = True
# Determine language class for syntax highlighting
ext_map = {
".py": "python", ".js": "javascript", ".ts": "typescript",
".html": "html", ".css": "css", ".json": "json", ".md": "markdown",
".sql": "sql", ".sh": "bash", ".ps1": "powershell", ".rs": "rust",
".go": "go", ".java": "java", ".rb": "ruby", ".xml": "xml",
".yaml": "yaml", ".yml": "yaml", ".toml": "toml",
}
lang = "plaintext"
for ext, name in ext_map.items():
if (filename or "").lower().endswith(ext):
lang = name
break
size_str = f"{size:,} bytes" if size < 1024 else f"{size/1024:.1f} KB" if size < 1024*1024 else f"{size/1024/1024:.1f} MB"
html = f"""<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title} — FlowDeck</title>
<style>
:root{{--bg:#0d1117;--bg2:#161b22;--text:#c9d1d9;--text2:#8b949e;--accent:#58a6ff;--border:#30363d;--line-num:#484f58;}}
*{{margin:0;padding:0;box-sizing:border-box}}
body{{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;min-height:100vh;}}
.topbar{{display:flex;align-items:center;gap:10px;padding:8px 16px;background:var(--bg2);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:10;}}
.topbar a,.topbar button{{color:var(--text2);text-decoration:none;background:var(--bg);border:1px solid var(--border);cursor:pointer;font-size:12px;padding:5px 10px;border-radius:6px;display:inline-flex;align-items:center;gap:4px;transition:all 150ms;}}
.topbar a:hover,.topbar button:hover{{background:var(--border);color:var(--text);}}
.topbar .title{{font-weight:600;color:var(--text);font-size:14px;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}}
.topbar .lang-badge{{font-size:11px;padding:2px 8px;background:var(--accent);color:#fff;border-radius:10px;font-weight:500;border:none;}}
.meta{{font-size:11px;color:var(--text2);white-space:nowrap;}}
.btn-copy{{gap:4px;}}
.btn-copy.copied{{background:#238636;border-color:#238636;color:#fff;}}
.viewer{{max-width:100%;margin:0 auto;}}
.viewer img{{max-width:100%;max-height:85vh;display:block;margin:0 auto;}}
.viewer iframe{{width:100%;height:90vh;border:none;}}
.code-container{{display:flex;overflow:auto;max-height:90vh;font-family:'Fira Code','Cascadia Code','JetBrains Mono','SF Mono',monospace;font-size:12px;line-height:20px;}}
.line-numbers{{flex-shrink:0;padding:12px 10px;text-align:right;color:var(--line-num);background:var(--bg2);border-right:1px solid var(--border);user-select:none;min-width:48px;}}
.line-numbers span{{display:block;}}
.code-content{{flex:1;padding:12px 16px;overflow:auto;white-space:pre;color:var(--text);background:var(--bg);}}
.code-content span{{display:block;}}
.code-content .hl-kw{{color:#ff7b72;}}
.code-content .hl-str{{color:#a5d6ff;}}
.code-content .hl-cmt{{color:#8b949e;font-style:italic;}}
.code-content .hl-num{{color:#79c0ff;}}
.code-content .hl-fn{{color:#d2a8ff;}}
.unsupported{{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:80px 20px;text-align:center;}}
.unsupported .icon{{font-size:64px;margin-bottom:16px;}}
.unsupported h2{{font-size:20px;margin-bottom:8px;}}
.unsupported p{{color:var(--text2);margin-bottom:20px;}}
.unsupported a{{display:inline-block;padding:10px 24px;background:var(--accent);color:#fff;text-decoration:none;border-radius:8px;font-weight:500;}}
</style></head>
<body>
<div class="topbar">
<a href="/local-workspace">← Workspace</a>
<span class="title">{title}</span>
<span class="lang-badge">{lang}</span>
<span class="meta">{size_str}</span>
<button class="btn-copy" onclick="copyCode()" title="Copy to clipboard">📋 Copy</button>
<a href="{file_url}" download>⬇ Download</a>
</div>
<div class="viewer">"""
if is_image:
html += f'<img src="{file_url}" alt="{title}">'
elif is_pdf:
html += f'<iframe src="{file_url}"></iframe>'
elif is_text:
html += f'''<div class="code-container">
<div class="line-numbers" id="line-numbers"></div>
<div class="code-content" id="code-content">Loading...</div>
</div>
<script>
var codeEl=document.getElementById("code-content");
var lineEl=document.getElementById("line-numbers");
fetch("{file_url}").then(function(r){{return r.text()}}).then(function(t){{
var lines=t.split("\\n");
if(lines.length>1&&lines[lines.length-1]==="")lines.pop();
var numHtml="",codeHtml="";
for(var i=0;i<lines.length;i++){{
numHtml+="<span>"+(i+1)+"</span>";
codeHtml+="<span>"+highlightCode(lines[i])+"</span>";
}}
lineEl.innerHTML=numHtml;
codeEl.innerHTML=codeHtml;
}}).catch(function(e){{codeEl.textContent="Error loading file: "+e;}});
function escHtml(s){{return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");}}
function highlightCode(line){{
var s=escHtml(line);
var lang="{lang}";
// Comments
if(lang==="python"||lang==="bash"||lang==="yaml"||lang==="toml"||lang==="powershell"){{
s=s.replace(/^(\\s*#.*)$/gm,'<span class="hl-cmt">$1</span>');
}}else if(lang==="javascript"||lang==="typescript"||lang==="go"||lang==="rust"||lang==="java"||lang==="sql"){{
s=s.replace(/^(\\s*\\/\\/.*)$/gm,'<span class="hl-cmt">$1</span>');
s=s.replace(/(\\/\\*[\\s\\S]*?\\*\\/)/g,'<span class="hl-cmt">$1</span>');
}}else if(lang==="html"||lang==="xml"){{
s=s.replace(/(&lt;!--[\\s\\S]*?--&gt;)/g,'<span class="hl-cmt">$1</span>');
}}else if(lang==="css"){{
s=s.replace(/(\\/\\*[\\s\\S]*?\\*\\/)/g,'<span class="hl-cmt">$1</span>');
}}
// Strings
s=s.replace(/(&quot;(?:[^&]|&(?!quot;))*&quot;)/g,'<span class="hl-str">$1</span>');
s=s.replace(/(&#x27;(?:[^&]|&(?!#x27;))*&#x27;)/g,'<span class="hl-str">$1</span>');
s=s.replace(/(`[^`]*`)/g,'<span class="hl-str">$1</span>');
// Numbers
s=s.replace(/\\b(\\d+\\.?\\d*)\\b/g,'<span class="hl-num">$1</span>');
// Keywords
var kw=[];
if(lang==="python")kw=["def","class","import","from","return","if","elif","else","for","while","try","except","finally","with","as","yield","raise","pass","break","continue","and","or","not","in","is","None","True","False","lambda","async","await","self"];
else if(lang==="javascript"||lang==="typescript")kw=["function","const","let","var","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","class","extends","import","export","default","from","async","await","typeof","instanceof","this","super","null","undefined","true","false","of","in"];
else if(lang==="go")kw=["func","package","import","return","if","else","for","range","switch","case","break","continue","defer","go","chan","map","struct","interface","type","var","const","nil","true","false"];
else if(lang==="rust")kw=["fn","let","mut","const","struct","enum","impl","trait","pub","use","mod","match","if","else","for","while","loop","return","break","continue","self","super","where","as","in","ref","move","true","false","async","await"];
else if(lang==="java")kw=["public","private","protected","class","interface","extends","implements","static","final","void","int","long","double","boolean","char","String","new","return","if","else","for","while","switch","case","break","continue","try","catch","finally","throw","throws","import","package","this","super","null","true","false"];
else if(lang==="sql")kw=["SELECT","FROM","WHERE","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TABLE","INDEX","VIEW","INTO","VALUES","SET","JOIN","LEFT","RIGHT","INNER","OUTER","ON","AND","OR","NOT","NULL","AS","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","DISTINCT","COUNT","SUM","AVG","MAX","MIN","EXISTS","BETWEEN","LIKE","IN","CASE","WHEN","THEN","ELSE","END","PRIMARY","KEY","FOREIGN","REFERENCES","CONSTRAINT","DEFAULT","CHECK","UNIQUE","CASCADE"];
else if(lang==="bash")kw=["if","then","else","elif","fi","for","while","do","done","case","esac","function","return","exit","export","local","readonly","unset","echo","printf","source","exec","trap"];
else if(lang==="powershell")kw=["function","param","if","else","elseif","foreach","for","while","do","until","switch","case","break","continue","return","throw","try","catch","finally","trap","begin","process","end","param","Write-Host","Write-Output","Get-Content","Set-Content","Out-File"];
if(kw.length>0){{
var re=new RegExp("\\\\b("+kw.join("|")+")\\\\b","g");
s=s.replace(re,'<span class="hl-kw">$1</span>');
}}
// Decorators (Python) & function calls
if(lang==="python"){{
s=s.replace(/(@\\w+)/g,'<span class="hl-fn">$1</span>');
}}
return s;
}}
function copyCode(){{
var text=Array.from(codeEl.children).map(function(s){{return s.textContent}}).join("\\n");
navigator.clipboard.writeText(text).then(function(){{
var btn=document.querySelector(".btn-copy");
btn.textContent="✓ Copied!";
btn.classList.add("copied");
setTimeout(function(){{btn.textContent="📋 Copy";btn.classList.remove("copied");}},2000);
}});
}}
</script>'''
else:
html += f'''<div class="unsupported">
<div class="icon">📎</div>
<h2>{title}</h2>
<p>{size_str} · {mime_type}<br>This file type cannot be previewed.</p>
<a href="{file_url}" download>⬇ Download</a>
</div>'''
html += "</div></body></html>"
return HTMLResponse(content=html)
@router.post("/api/sync/{owner}/{repo}")
async def sync_project(owner: str, repo: str):
"""Full bidirectional sync: fetch Gitea issues → update local DB."""
+1004 -133
View File
File diff suppressed because it is too large Load Diff
+343
View File
@@ -0,0 +1,343 @@
"""FlowDeck — Gitea integration API routes."""
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse
router = APIRouter(tags=["gitea"], prefix="/api/gitea")
def _require_gitea(request: Request):
"""Return a per-user GiteaClient or raise 401.
Only returns a client if the user has personally connected their Gitea
account (OAuth token). No fallback to admin token — each user must link
their own Gitea account to see Gitea projects.
"""
from app.services.gitea_client import get_user_gitea_client
client = get_user_gitea_client(request)
if not client:
raise HTTPException(status_code=401, detail="Gitea account not linked. Go to Settings → Integrations to connect.")
return client
def _require_user_gitea(request: Request):
"""Return a per-user GiteaClient or raise 401 (required for write ops)."""
from app.services.gitea_client import get_user_gitea_client
client = get_user_gitea_client(request)
if not client:
raise HTTPException(status_code=401, detail="Gitea not connected. Go to Settings → Integrations or register with Gitea.")
return client
# ── Orgs ──
@router.get("/orgs")
async def list_orgs(request: Request):
"""List organizations the user belongs to."""
gitea = _require_gitea(request)
try:
orgs = await gitea.get_user_orgs()
return {"orgs": orgs}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Projects (repos) ──
@router.get("/projects")
async def list_projects(request: Request, org: str = ""):
"""List Gitea repos: user repos (org='') or org repos."""
gitea = _require_gitea(request)
try:
if org:
repos = await gitea.get_org_repos(org)
else:
repos = await gitea.get_user_repos(limit=100)
return {"projects": repos}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Repo tree ──
@router.get("/projects/{owner}/{repo}/tree")
async def repo_tree(request: Request, owner: str, repo: str, path: str = ""):
"""Get contents of a repo directory (one level)."""
gitea = _require_gitea(request)
try:
items = await gitea.get_repo_contents(owner, repo, path)
tree = []
for item in items:
tree.append({
"name": item.get("name"),
"path": item.get("path"),
"type": "folder" if item.get("type") == "dir" else "file",
"size": item.get("size", 0),
"sha": item.get("sha"),
})
return {"tree": tree}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── File content ──
@router.get("/projects/{owner}/{repo}/file")
async def get_file(request: Request, owner: str, repo: str, path: str):
"""Get file content (decoded)."""
gitea = _require_gitea(request)
try:
content = await gitea.get_file_content(owner, repo, path)
return {"content": content, "path": path}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Save file (create or update) ──
@router.put("/projects/{owner}/{repo}/file")
async def save_file(request: Request, owner: str, repo: str):
"""Create or update a file in the repo."""
import json
gitea = _require_gitea(request) # admin token can write too
try:
body = await request.json()
except Exception:
body = {}
path = body.get("path", "").strip("/")
content = body.get("content", "")
message = body.get("message", "Update via FlowDeck")
sha = body.get("sha")
if not path:
return JSONResponse({"error": "Path required"}, status_code=400)
try:
result = await gitea.create_or_update_file(owner, repo, path, content, message, sha)
return {"status": "ok", "commit": result.get("commit", {})}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Upload file (binary) ──
@router.post("/projects/{owner}/{repo}/upload")
async def upload_file(request: Request, owner: str, repo: str):
"""Upload a binary file to the repo."""
import base64
gitea = _require_gitea(request)
try:
form = await request.form()
except Exception:
return JSONResponse({"error": "Invalid form data"}, status_code=400)
file = form.get("file")
folder = form.get("folder", "")
message = form.get("message", "Upload via FlowDeck")
if not file:
return JSONResponse({"error": "No file provided"}, status_code=400)
try:
content = await file.read()
encoded = base64.b64encode(content).decode("utf-8")
path = f"{folder.strip('/')}/{file.filename}".strip("/") if folder.strip("/") else file.filename
result = await gitea.create_or_update_file(owner, repo, path, encoded, message, sha=None)
return {"status": "ok", "path": path, "commit": result.get("commit", {})}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Delete file ──
@router.delete("/projects/{owner}/{repo}/file")
async def delete_file(request: Request, owner: str, repo: str):
"""Delete a file from the repo."""
import json
gitea = _require_gitea(request) # admin token can write too
path = request.query_params.get("path", "")
sha = request.query_params.get("sha", "")
message = request.query_params.get("message", "Delete via FlowDeck")
if not path or not sha:
return JSONResponse({"error": "Path and SHA required"}, status_code=400)
try:
await gitea.delete_file(owner, repo, path, sha, message)
return {"status": "ok"}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Labels ──
@router.get("/projects/{owner}/{repo}/labels")
async def get_labels(request: Request, owner: str, repo: str):
"""Get labels for a repo (mapped to tags)."""
gitea = _require_gitea(request)
try:
labels = await gitea.get_labels(owner, repo)
return {"labels": [
{"id": l["id"], "name": l["name"], "color": l.get("color", "#787774")}
for l in labels
]}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Account linking ──
@router.get("/status")
async def gitea_status(request: Request):
"""Check if the current user has Gitea linked."""
from app.services.gitea_client import get_user_gitea_client
client = get_user_gitea_client(request)
return {"linked": client is not None}
@router.delete("/disconnect")
async def disconnect_gitea(request: Request):
"""Remove all Gitea OAuth tokens for the current user."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
with get_conn() as conn:
conn.execute("DELETE FROM user_oauth_tokens WHERE user_id=? AND provider='gitea'", (user["id"],))
conn.commit()
return {"status": "ok"}
# ── Private Pages (local FlowDeck pages linked to Gitea project) ──
@router.get("/projects/{owner}/{repo}/private-pages")
async def list_private_pages(owner: str, repo: str, request: Request):
"""List private pages for this Gitea project."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"pages": []})
with get_conn() as conn:
rows = conn.execute(
"SELECT id, title, updated_at FROM gitea_private_pages WHERE user_id=? AND gitea_owner=? AND gitea_repo=? ORDER BY updated_at DESC",
(user["id"], owner, repo),
).fetchall()
return {"pages": [{"id": r["id"], "title": r["title"], "updated_at": r["updated_at"]} for r in rows]}
@router.post("/projects/{owner}/{repo}/private-pages")
async def create_private_page(owner: str, repo: str, request: Request):
"""Create a new private page for this Gitea project."""
from app.auth.session import SessionManager
from app.db import get_conn
import json
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
try:
body = await request.json()
except Exception:
body = {}
title = body.get("title", "Untitled").strip() or "Untitled"
with get_conn() as conn:
cursor = conn.execute(
"INSERT INTO gitea_private_pages (user_id, gitea_owner, gitea_repo, title) VALUES (?,?,?,?)",
(user["id"], owner, repo, title),
)
conn.commit()
return {"status": "ok", "page": {"id": cursor.lastrowid, "title": title}}
@router.get("/projects/{owner}/{repo}/private-pages/{page_id}")
async def get_private_page(owner: str, repo: str, page_id: int, request: Request):
"""Get a single private page."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
with get_conn() as conn:
row = conn.execute(
"SELECT * FROM gitea_private_pages WHERE id=? AND user_id=? AND gitea_owner=? AND gitea_repo=?",
(page_id, user["id"], owner, repo),
).fetchone()
if not row:
return JSONResponse({"error": "Not found"}, status_code=404)
return {"page": {"id": row["id"], "title": row["title"], "content": row["content"], "updated_at": row["updated_at"]}}
@router.put("/projects/{owner}/{repo}/private-pages/{page_id}")
async def update_private_page(owner: str, repo: str, page_id: int, request: Request):
"""Update a private page."""
from app.auth.session import SessionManager
from app.db import get_conn
import json
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
try:
body = await request.json()
except Exception:
body = {}
title = body.get("title", "").strip()
content = body.get("content", "")
with get_conn() as conn:
if title:
conn.execute(
"UPDATE gitea_private_pages SET title=?, updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=? AND gitea_owner=? AND gitea_repo=?",
(title, page_id, user["id"], owner, repo),
)
conn.execute(
"UPDATE gitea_private_pages SET content=?, updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=? AND gitea_owner=? AND gitea_repo=?",
(content, page_id, user["id"], owner, repo),
)
conn.commit()
return {"status": "ok"}
@router.delete("/projects/{owner}/{repo}/private-pages/{page_id}")
async def delete_private_page(owner: str, repo: str, page_id: int, request: Request):
"""Delete a private page."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
with get_conn() as conn:
conn.execute(
"DELETE FROM gitea_private_pages WHERE id=? AND user_id=? AND gitea_owner=? AND gitea_repo=?",
(page_id, user["id"], owner, repo),
)
conn.commit()
return {"status": "ok"}
# ── Commit history for a file ──
@router.get("/projects/{owner}/{repo}/commits")
async def file_commits(request: Request, owner: str, repo: str, path: str = ""):
"""Get recent commits for a specific file."""
gitea = _require_gitea(request)
try:
commits = await gitea.get_file_commits(owner, repo, path)
return {"commits": commits}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=502)
# ── Sync labels to tags ──
@router.post("/projects/{owner}/{repo}/sync-labels")
async def sync_labels(request: Request, owner: str, repo: str):
"""Sync Gitea labels to FlowDeck tags for the current user."""
from app.auth.session import get_current_user as gcu
from app.db import get_conn
user = await gcu(request)
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
gitea = _require_gitea(request)
try:
labels = await gitea.get_labels(owner, repo)
except Exception:
labels = []
imported = 0
with get_conn() as conn:
for label in labels:
name = label.get("name", "")
color = label.get("color", "#787774")
if not name: continue
existing = conn.execute(
"SELECT id FROM tags WHERE name=? AND user_id=?", (name, user["id"])
).fetchone()
if not existing:
conn.execute(
"INSERT INTO tags (name, color, user_id) VALUES (?, ?, ?)",
(name, f"#{color}", user["id"]),
)
imported += 1
conn.commit()
return {"status": "ok", "imported": imported, "total": len(labels)}
+35
View File
@@ -0,0 +1,35 @@
"""GitHub OAuth — status and disconnect routes."""
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
router = APIRouter(tags=["github"], prefix="/api/github")
@router.get("/status")
async def github_status(request: Request):
"""Check if the current user has GitHub linked."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return {"linked": False}
with get_conn() as conn:
row = conn.execute(
"SELECT access_token FROM user_oauth_tokens WHERE user_id=? AND provider='github' AND access_token IS NOT NULL AND access_token != ''",
(user["id"],)
).fetchone()
return {"linked": row is not None}
@router.delete("/disconnect")
async def disconnect_github(request: Request):
"""Remove all GitHub OAuth tokens for the current user."""
from app.auth.session import SessionManager
from app.db import get_conn
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return JSONResponse({"error": "Not authenticated"}, status_code=401)
with get_conn() as conn:
conn.execute("DELETE FROM user_oauth_tokens WHERE user_id=? AND provider='github'", (user["id"],))
conn.commit()
return {"status": "ok"}
+478
View File
@@ -0,0 +1,478 @@
"""FlowDeck — Library API: recents, favorites, shared, published, private, workspace."""
from __future__ import annotations
import logging
from fastapi import APIRouter, Request, Query
from fastapi.responses import JSONResponse
from app.db import get_conn
from app.auth.session import SessionManager
logger = logging.getLogger(__name__)
router = APIRouter(tags=["library"], prefix="/api/library")
SOURCE_TYPES = {"all", "local", "gitea", "github"}
def _get_user_id(request: Request) -> int:
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
return user["id"] if user and user.get("id") else 1
def _detect_source_type(workspace: str) -> str:
ws = (workspace or "").strip()
if not ws:
return "local"
if ws.startswith("github:"):
return "github"
if "/" in ws:
return "gitea"
return "local"
def _source_label(source_type: str, workspace: str) -> str:
if source_type == "gitea":
return workspace
elif source_type == "github":
return workspace.replace("github:", "", 1)
return workspace or "Private"
def _build_item(db_row: dict, uid: int = 1) -> dict:
workspace = db_row.get("workspace", "") or ""
source_type = _detect_source_type(workspace)
page_id = db_row["id"]
title = db_row.get("title") or "Untitled"
# URL
if source_type in ("gitea", "github"):
ws = workspace.replace("github:", "", 1) if source_type == "github" else workspace
parts = ws.split("/", 1)
url = f"/gitea-workspace?owner={parts[0]}&repo={parts[1] if len(parts) > 1 else ''}"
else:
url = f"/pages/{page_id}"
# Icon
content_format = db_row.get("content_format", "blocks")
if db_row.get("is_folder"):
icon = "📁"
elif content_format == "file":
icon = "📄"
fn = title.lower()
if fn.endswith(".pdf"): icon = "📕"
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
else:
icon = "📝"
return {
"id": page_id,
"title": title,
"icon": icon,
"is_folder": bool(db_row.get("is_folder", 0)),
"source_type": source_type,
"source_label": _source_label(source_type, workspace),
"workspace": workspace,
"workspace_name": _source_label(source_type, workspace),
"author": db_row.get("author") or "",
"author_initial": (db_row.get("author") or "?")[0].upper(),
"updated_at": db_row.get("updated_at", ""),
"visited_at": db_row.get("visited_at") or "",
"has_children": False,
"children": [],
"url": url,
"content_format": content_format,
"favorited": bool(db_row.get("favorited", 0)),
}
def _apply_source_filter(query: str, params: list, source_type: str) -> tuple[str, list]:
if source_type == "local":
query += " AND (p.workspace = '' OR (p.workspace NOT LIKE '%/%' AND p.workspace NOT LIKE 'github:%'))"
elif source_type == "gitea":
query += " AND p.workspace LIKE '%/%' AND p.workspace NOT LIKE 'github:%'"
elif source_type == "github":
query += " AND p.workspace LIKE 'github:%'"
return query, params
def _rows_to_items(rows, uid: int = 1) -> list:
return [_build_item(dict(r), uid) for r in rows]
def _enrich_children(items: list) -> list:
"""Add has_children info to items in a single batch query."""
if not items:
return items
ids = [it["id"] for it in items]
placeholders = ",".join(["?" for _ in ids])
with get_conn() as conn:
child_rows = conn.execute(
f"SELECT parent_id, COUNT(*) as cnt FROM pages "
f"WHERE parent_id IN ({placeholders}) AND deleted_at IS NULL "
f"GROUP BY parent_id",
ids,
).fetchall()
child_counts = {r["parent_id"]: r["cnt"] for r in child_rows}
for it in items:
it["has_children"] = bool(child_counts.get(it["id"], 0))
return items
# ═══════════ Tab endpoints ═══════════
BASE_SELECT = (
"SELECT p.id, p.title, p.workspace, p.updated_at, p.content_format, "
"p.parent_id, p.share_mode, p.parent_section"
)
@router.get("/recents")
async def library_recents(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
workspace_id: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = f"{BASE_SELECT} FROM pages p WHERE p.parent_section != 'Trash' AND p.deleted_at IS NULL"
params: list = []
# Hierarchical view: show only root-level pages at the top
if tree:
query += " AND p.parent_id IS NULL"
# Filter by active workspace
if workspace_id:
query += " AND p.workspace_id = ?"
params.append(workspace_id)
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY p.updated_at DESC LIMIT 50"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/favorites")
async def library_favorites(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = (
f"SELECT p.id, p.title, p.workspace, p.updated_at, p.content_format, "
f"p.parent_id, p.share_mode, p.parent_section, 1 as favorited "
f"FROM favorites f JOIN pages p ON p.id = f.page_id "
f"WHERE f.user_id = ? AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
)
params: list = [uid]
if tree:
query += " AND p.parent_id IS NULL"
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY f.position"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/shared")
async def library_shared(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = f"{BASE_SELECT} FROM pages p WHERE p.share_mode != 'private' AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
params: list = []
if tree:
query += " AND p.parent_id IS NULL"
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY p.updated_at DESC LIMIT 50"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/published")
async def library_published(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = f"{BASE_SELECT} FROM pages p WHERE p.published = 1 AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
params: list = []
if tree:
query += " AND p.parent_id IS NULL"
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY p.updated_at DESC LIMIT 50"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/private")
async def library_private(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = f"{BASE_SELECT} FROM pages p WHERE p.parent_section = 'Private' AND p.deleted_at IS NULL"
params: list = []
if tree:
query += " AND p.parent_id IS NULL"
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY p.updated_at DESC LIMIT 50"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/local-workspace-children/{item_id:int}")
async def library_local_workspace_children(item_id: int, request: Request):
"""Return children of a local workspace item for tree expansion."""
uid = _get_user_id(request)
with get_conn() as conn:
# Get the item to find its workspace
item = conn.execute(
"SELECT workspace_id FROM local_workspace_items WHERE id=? AND deleted_at IS NULL",
[item_id],
).fetchone()
if not item:
return {"items": []}
rows = conn.execute(
"SELECT id, name, is_folder, parent_id, content_format, size, "
"COALESCE(updated_at, created_at) as updated_at "
"FROM local_workspace_items "
"WHERE parent_id = ? AND deleted_at IS NULL "
"ORDER BY is_folder DESC, name COLLATE NOCASE",
[item_id],
).fetchall()
items = []
for r in rows:
name = r["name"] or "Untitled"
is_folder = bool(r["is_folder"])
icon = "📁" if is_folder else "📄"
fn = name.lower()
if not is_folder:
if fn.endswith(".pdf"): icon = "📕"
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
with get_conn() as conn:
child_count = conn.execute(
"SELECT COUNT(*) FROM local_workspace_items WHERE parent_id=? AND deleted_at IS NULL",
[r["id"]],
).fetchone()[0]
items.append({
"id": r["id"],
"title": name,
"icon": icon,
"is_folder": is_folder,
"source_type": "local-ws",
"source_label": "",
"workspace": "",
"workspace_name": "",
"author": "",
"author_initial": "?",
"updated_at": r["updated_at"] or "",
"visited_at": "",
"has_children": child_count > 0,
"children": [],
"url": f"/local-workspace?folder={r['id']}" if is_folder else f"/pages/{r['id']}",
"content_format": r["content_format"] or "file",
"favorited": False,
"size_display": _format_size(r["size"]) if r["size"] else "",
})
return {"items": items}
@router.get("/children/{page_id:int}")
async def library_children(page_id: int, request: Request):
"""Return child pages for a given parent page (for tree expansion in Library)."""
uid = _get_user_id(request)
with get_conn() as conn:
rows = conn.execute(
f"{BASE_SELECT}, (SELECT COUNT(*) FROM pages c WHERE c.parent_id = p.id AND c.deleted_at IS NULL) as child_count "
f"FROM pages p WHERE p.parent_id = ? AND p.deleted_at IS NULL "
f"ORDER BY p.title COLLATE NOCASE",
[page_id],
).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/repository")
async def library_repository(
request: Request,
gitea_owner: str = Query(default=""),
gitea_repo: str = Query(default=""),
):
"""Return Gitea repository pages/files for the Library Repository tab."""
if not gitea_owner or not gitea_repo:
return {"items": []}
uid = _get_user_id(request)
ws_key = f"{gitea_owner}/{gitea_repo}"
query = f"{BASE_SELECT} FROM pages p WHERE p.workspace = ? AND p.deleted_at IS NULL"
params = [ws_key]
query += " ORDER BY p.updated_at DESC LIMIT 100"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
@router.get("/local-workspace")
async def library_local_workspace(
request: Request,
workspace_id: int = Query(default=0),
):
"""Return local workspace items (files/folders) formatted for Library display."""
from app.routers.dashboard import _get_active_workspace
uid = _get_user_id(request)
# Get the active workspace
ws = _get_active_workspace(request, user_id=uid)
if not ws:
return {"items": []}
ws_id = workspace_id or ws["id"]
# Query local workspace tree
with get_conn() as conn:
rows = conn.execute(
"SELECT id, name, is_folder, parent_id, content_format, size, "
"COALESCE(updated_at, created_at) as updated_at "
"FROM local_workspace_items "
"WHERE workspace_id = ? AND deleted_at IS NULL "
"ORDER BY is_folder DESC, name COLLATE NOCASE",
[ws_id],
).fetchall()
items = []
for r in rows:
name = r["name"] or "Untitled"
is_folder = bool(r["is_folder"])
icon = "📁" if is_folder else "📄"
fn = name.lower()
if not is_folder:
if fn.endswith(".pdf"): icon = "📕"
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
# Check for children
child_count = conn.execute(
"SELECT COUNT(*) FROM local_workspace_items WHERE parent_id=? AND deleted_at IS NULL",
[r["id"]],
).fetchone()[0]
items.append({
"id": r["id"],
"title": name,
"icon": icon,
"is_folder": is_folder,
"source_type": "local-ws",
"source_label": ws.get("name", "Workspace"),
"workspace": ws.get("name", ""),
"workspace_name": ws.get("name", ""),
"author": "",
"author_initial": "?",
"updated_at": r["updated_at"] or "",
"visited_at": "",
"has_children": child_count > 0,
"children": [],
"url": f"/local-workspace?folder={r['id']}" if is_folder else f"/pages/{r['id']}",
"content_format": r["content_format"] or "file",
"favorited": False,
"size_display": _format_size(r["size"]) if r["size"] else "",
})
return {"items": items}
def _format_size(size_bytes):
if not size_bytes: return ""
if size_bytes < 1024: return f"{size_bytes} B"
if size_bytes < 1048576: return f"{size_bytes/1024:.1f} KB"
if size_bytes < 1073741824: return f"{size_bytes/1048576:.1f} MB"
return f"{size_bytes/1073741824:.1f} GB"
@router.get("/workspace")
async def library_workspace(
request: Request,
source_type: str = Query(default="all"),
tree: int = Query(default=0),
workspace_id: int = Query(default=0),
):
if source_type not in SOURCE_TYPES:
source_type = "all"
uid = _get_user_id(request)
query = f"{BASE_SELECT} FROM pages p WHERE (p.workspace != '' OR p.workspace_id IS NOT NULL) AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
params: list = []
if tree:
query += " AND p.parent_id IS NULL"
if workspace_id:
query += " AND p.workspace_id = ?"
params.append(workspace_id)
query, params = _apply_source_filter(query, params, source_type)
query += " ORDER BY p.updated_at DESC LIMIT 50"
with get_conn() as conn:
rows = conn.execute(query, params).fetchall()
items = _rows_to_items(rows, uid)
_enrich_children(items)
return {"items": items}
+60 -91
View File
@@ -6,6 +6,7 @@ import logging
from fastapi import APIRouter, Request, HTTPException, Query
from fastapi.responses import HTMLResponse
from jinja2 import Environment, FileSystemLoader
from app.db import get_conn
from app.auth.session import SessionManager
@@ -38,114 +39,82 @@ async def my_tasks_dashboard(request: Request, view: str = "all", days: int = 7)
collection_tasks = []
for p in pages:
props = json.loads(p["property_values_json"])
# Check if assigned to current user
assigned = False
for v in props.values():
if isinstance(v, list):
for item in v:
if isinstance(item, dict) and item.get("login") == user_login:
assigned = True
break
elif isinstance(v, str) and user_login.lower() in v.lower():
assigned = True
if assigned:
break
if not assigned and user_login == "admin":
assigned = True # admin sees all
if not assigned:
props = {}
try:
props = json.loads(p["property_values_json"] or "{}")
except (json.JSONDecodeError, TypeError):
pass
due_date = props.get("due_date", "")
status = props.get("status", "—")
assignee = props.get("assignee", "")
if view != "all" and assignee and assignee != user_login:
continue
# Extract status and due date
status = None
due_date = None
for v in props.values():
if isinstance(v, str) and v in ("Todo", "In Progress", "Done", "Complete"):
status = v
elif isinstance(v, str) and v.startswith("20"):
due_date = v[:10]
# Filter by view
if view == "today":
from datetime import date
if not due_date or due_date != date.today().isoformat():
continue
elif view == "overdue":
from datetime import date
if not due_date or due_date >= date.today().isoformat():
continue
elif view == "upcoming":
from datetime import date, timedelta
if not due_date:
continue
today = date.today()
limit = today + timedelta(days=days)
d = date.fromisoformat(due_date)
if d < today or d > limit:
continue
collection_tasks.append({
"id": p["id"], "title": p["title"], "icon": p.get("icon", "📄"),
"status": status, "due_date": due_date, "props": props,
"id": p["id"],
"title": p["title"] or "Untitled",
"icon": p["icon"] or "📋",
"status": status,
"due_date": due_date,
})
if collection_tasks:
grouped[col["name"]] = collection_tasks
total = sum(len(t) for t in grouped.values())
# Render
# Build content HTML
sections = ""
for col_name, tasks in grouped.items():
items = ""
for t in tasks:
due_badge = f"<span class='mt-due'>{t['due_date']}</span>" if t.get("due_date") else ""
status_badge = f"<span class='mt-status mt-{t['status'].lower().replace(' ','-') if t.get('status') else 'none'}'>{t.get('status','—')}</span>"
items += f"""<div class='mt-item'>
<span class='mt-icon'>{t['icon']}</span>
<span class='mt-title'>{t['title']}</span>
{status_badge}{due_badge}
</div>"""
status_cls = t['status'].lower().replace(' ', '-') if t.get('status') else 'none'
status_badge = f"<span class='mt-status mt-{status_cls}'>{t.get('status', '—')}</span>"
items += f"<div class='mt-item'><span class='mt-icon'>{t['icon']}</span><span class='mt-title'>{t['title']}</span>{status_badge}{due_badge}</div>"
sections += f"""<div class='mt-section'>
<div class='mt-section-header'>{col_name} <span class='mt-count'>{len(tasks)}</span></div>
{items}
</div>"""
sections += f"<div class='mt-section'><div class='mt-section-header'>{col_name} <span class='mt-count'>{len(tasks)}</span></div>{items}</div>"
return HTMLResponse(f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>My Tasks — FlowDeck</title>
<style>
body{{font-family:system-ui,sans-serif;background:#191919;color:#fff;margin:0;padding:20px}}
h1{{font-size:24px;margin:0 0 16px}}
.view-tabs{{display:flex;gap:4px;margin-bottom:20px;border-bottom:1px solid #333;padding-bottom:8px}}
.tab{{padding:6px 14px;border-radius:6px;cursor:pointer;color:#A0A0A0;font-size:13px;background:none;border:none;text-decoration:none}}
.tab:hover,.tab.active{{background:#333;color:#fff}}
.mt-section{{margin-bottom:24px}}
.mt-section-header{{font-size:14px;font-weight:600;color:#A0A0A0;margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px}}
.mt-count{{color:#6B6B6B;font-weight:400}}
.mt-item{{display:flex;align-items:center;gap:10px;padding:8px 12px;background:#1a1a1a;border-radius:6px;margin-bottom:3px;border:1px solid #222}}
.mt-item:hover{{border-color:#444}}
.mt-icon{{font-size:16px}}
.mt-title{{flex:1;font-size:14px}}
.mt-status{{font-size:11px;padding:2px 8px;border-radius:4px}}
.mt-due{{font-size:11px;color:#A0A0A0}}
.mt-todo{{background:#333;color:#A0A0A0}}
.mt-in-progress{{background:#1a2744;color:#3366CC}}
.mt-done,.mt-complete{{background:#1a332a;color:#00CC66}}
.p_desc{{color:#A0A0A0;margin-top:8px}}
</style></head><body>
<h1>📋 My Tasks</h1>
<div class="view-tabs">
<a class="tab{' active' if view=='all' else ''}" href="?view=all">All</a>
<a class="tab{' active' if view=='today' else ''}" href="?view=today">Today</a>
<a class="tab{' active' if view=='overdue' else ''}" href="?view=overdue">Overdue</a>
<a class="tab{' active' if view=='upcoming' else ''}" href="?view=upcoming&days=7">Next 7 days</a>
content_html = f"""<div style="max-width:800px;margin:0 auto;padding:40px 24px;">
<h1 style="font-size:24px;margin:0 0 8px;">📋 My Tasks</h1>
<p style="color:var(--text-dim);font-size:14px;margin-bottom:24px;">{total} tasks across {len(grouped)} collections</p>
<div class="view-tabs" style="display:flex;gap:4px;margin-bottom:24px;border-bottom:1px solid var(--border);padding-bottom:12px;">
<a class="tab{' active' if view=='all' else ''}" href="/my-tasks?view=all" style="padding:6px 14px;border-radius:6px;cursor:pointer;color:var(--text-dim);font-size:13px;text-decoration:none;">All</a>
<a class="tab{' active' if view=='today' else ''}" href="/my-tasks?view=today" style="padding:6px 14px;border-radius:6px;cursor:pointer;color:var(--text-dim);font-size:13px;text-decoration:none;">Today</a>
<a class="tab{' active' if view=='overdue' else ''}" href="/my-tasks?view=overdue" style="padding:6px 14px;border-radius:6px;cursor:pointer;color:var(--text-dim);font-size:13px;text-decoration:none;">Overdue</a>
<a class="tab{' active' if view=='upcoming' else ''}" href="/my-tasks?view=upcoming&days=7" style="padding:6px 14px;border-radius:6px;cursor:pointer;color:var(--text-dim);font-size:13px;text-decoration:none;">Next 7 days</a>
</div>
<style>
.tab.active{{background:var(--accent);color:#fff!important;}}
.tab:hover{{background:var(--bg-hover);color:var(--text);}}
.mt-section{{margin-bottom:24px;}}
.mt-section-header{{font-size:13px;font-weight:600;color:var(--text-dim);margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px;}}
.mt-count{{color:var(--text-dim);font-weight:400;opacity:.5;}}
.mt-item{{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--bg-card);border-radius:8px;margin-bottom:3px;border:1px solid var(--border);}}
.mt-item:hover{{border-color:var(--accent);}}
.mt-icon{{font-size:16px;}}
.mt-title{{flex:1;font-size:14px;}}
.mt-status{{font-size:11px;padding:2px 8px;border-radius:4px;}}
.mt-due{{font-size:11px;color:var(--text-dim);}}
.mt-todo,.mt-none{{background:rgba(255,255,255,.05);color:var(--text-dim);}}
.mt-in-progress{{background:rgba(35,131,226,.15);color:#2C8CEB;}}
.mt-done,.mt-completed,.mt-complete{{background:rgba(0,200,100,.15);color:#00CC66;}}
</style>
{sections}
<p class="p_desc">{total} tasks across {len(grouped)} collections</p>
</body></html>""")
</div>"""
from app.routers.dashboard import _sidebar_data
env = Environment(loader=FileSystemLoader("app/templates"))
sidebar = _sidebar_data(request, [])
block_tpl = env.from_string(
'{% extends "base.html" %}{% block content %}{{ content_html|safe }}{% endblock %}'
)
return block_tpl.render(
**sidebar,
request=request,
content_html=content_html,
page_title="My Tasks",
title_prefix="My Tasks",
page_icon="📋",
)
@router.get("/api")
+245
View File
@@ -0,0 +1,245 @@
"""FlowDeck — Sharing, Publishing & Recents API (v4.0)."""
from __future__ import annotations
import logging
import re
import unicodedata
from datetime import datetime
from fastapi import APIRouter, Request, HTTPException
from app.db import get_conn
from app.auth.session import SessionManager
logger = logging.getLogger(__name__)
router = APIRouter(tags=["sharing"], prefix="/api")
def _require_auth(request: Request) -> dict:
"""Require an authenticated session. Returns user dict or raises 401."""
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
raise HTTPException(status_code=401, detail="Authentication required")
return user
def _slugify(title: str) -> str:
"""Generate a URL-safe slug from a page title."""
slug = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode("ascii")
slug = re.sub(r"[^\w\s-]", "", slug.lower())
slug = re.sub(r"[-\s]+", "-", slug).strip("-")
return slug or "untitled"
# ── Page Sharing ──
@router.post("/pages/{page_id}/share")
async def share_page(page_id: int, request: Request):
"""Invite a user or email to a page."""
user = _require_auth(request)
body = await request.json() if request.headers.get("content-type") else {}
target_user_id = body.get("user_id")
email = body.get("email", "")
permission = body.get("permission", "view")
if permission not in ("view", "comment", "edit"):
raise HTTPException(400, "Invalid permission. Use view, comment, or edit.")
if not target_user_id and not email:
raise HTTPException(400, "Provide user_id or email to share with.")
with get_conn() as conn:
# Verify page exists
page = conn.execute("SELECT id, title FROM pages WHERE id=?", (page_id,)).fetchone()
if not page:
raise HTTPException(404, "Page not found")
# Verify target user exists if user_id given
if target_user_id:
target = conn.execute("SELECT id FROM users WHERE id=?", (target_user_id,)).fetchone()
if not target:
raise HTTPException(404, "Target user not found")
cur = conn.execute(
"""INSERT INTO page_shares (page_id, shared_with_user_id, shared_with_email, permission, created_by)
VALUES (?, ?, ?, ?, ?)""",
(page_id, target_user_id, email, permission, user["id"]),
)
conn.execute("UPDATE pages SET is_shared=1 WHERE id=?", (page_id,))
conn.commit()
return {
"id": cur.lastrowid,
"page_id": page_id,
"shared_with_user_id": target_user_id,
"shared_with_email": email,
"permission": permission,
"status": "shared",
}
@router.delete("/pages/{page_id}/share/{share_id}")
async def remove_share(page_id: int, share_id: int, request: Request):
"""Remove a share invitation."""
_require_auth(request)
with get_conn() as conn:
row = conn.execute(
"SELECT id FROM page_shares WHERE id=? AND page_id=?",
(share_id, page_id),
).fetchone()
if not row:
raise HTTPException(404, "Share entry not found")
conn.execute("DELETE FROM page_shares WHERE id=?", (share_id,))
# If no more shares, unset is_shared
remaining = conn.execute(
"SELECT COUNT(*) AS c FROM page_shares WHERE page_id=?", (page_id,)
).fetchone()["c"]
if remaining == 0:
conn.execute("UPDATE pages SET is_shared=0 WHERE id=?", (page_id,))
conn.commit()
return {"status": "removed", "share_id": share_id}
@router.get("/pages/{page_id}/shares")
async def list_shares(page_id: int, request: Request):
"""Get all shares for a page."""
_require_auth(request)
with get_conn() as conn:
page = conn.execute("SELECT id FROM pages WHERE id=?", (page_id,)).fetchone()
if not page:
raise HTTPException(404, "Page not found")
rows = conn.execute(
"""SELECT s.*, u.login, u.full_name, u.avatar_url
FROM page_shares s
LEFT JOIN users u ON s.shared_with_user_id = u.id
WHERE s.page_id=?
ORDER BY s.created_at DESC""",
(page_id,),
).fetchall()
return {
"page_id": page_id,
"shares": [
{
"id": r["id"],
"shared_with_user_id": r["shared_with_user_id"],
"shared_with_email": r["shared_with_email"],
"permission": r["permission"],
"created_at": r["created_at"],
"created_by": r["created_by"],
"user_login": r["login"],
"user_full_name": r["full_name"],
"user_avatar_url": r["avatar_url"],
}
for r in rows
],
}
# ── Page Publishing ──
@router.post("/pages/{page_id}/publish")
async def publish_page(page_id: int, request: Request):
"""Publish a page (is_published=1) with a URL slug."""
user = _require_auth(request)
with get_conn() as conn:
page = conn.execute(
"SELECT id, title, is_published FROM pages WHERE id=?", (page_id,)
).fetchone()
if not page:
raise HTTPException(404, "Page not found")
slug = _slugify(page["title"])
# Ensure uniqueness by appending suffix if needed
base_slug = slug
counter = 1
while conn.execute(
"SELECT id FROM pages WHERE publish_slug=? AND id!=?", (slug, page_id)
).fetchone():
slug = f"{base_slug}-{counter}"
counter += 1
conn.execute(
"UPDATE pages SET is_published=1, publish_slug=? WHERE id=?",
(slug, page_id),
)
conn.commit()
return {
"page_id": page_id,
"is_published": True,
"publish_slug": slug,
"status": "published",
}
@router.delete("/pages/{page_id}/publish")
async def unpublish_page(page_id: int, request: Request):
"""Unpublish a page."""
_require_auth(request)
with get_conn() as conn:
page = conn.execute(
"SELECT id, is_published FROM pages WHERE id=?", (page_id,)
).fetchone()
if not page:
raise HTTPException(404, "Page not found")
conn.execute(
"UPDATE pages SET is_published=0, publish_slug='' WHERE id=?",
(page_id,),
)
conn.commit()
return {
"page_id": page_id,
"is_published": False,
"status": "unpublished",
}
# ── Recents ──
@router.post("/recents/track")
async def track_recent(request: Request):
"""Record a page access in recents."""
user = _require_auth(request)
body = await request.json() if request.headers.get("content-type") else {}
page_id = body.get("page_id")
workspace = body.get("workspace", "")
source_type = body.get("source_type", "local")
if not page_id:
raise HTTPException(400, "page_id is required")
with get_conn() as conn:
page = conn.execute("SELECT id FROM pages WHERE id=?", (page_id,)).fetchone()
if not page:
raise HTTPException(404, "Page not found")
conn.execute(
"""INSERT INTO recents (user_id, page_id, workspace, source_type, accessed_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id, page_id)
DO UPDATE SET workspace=excluded.workspace,
source_type=excluded.source_type,
accessed_at=excluded.accessed_at""",
(user["id"], page_id, workspace, source_type, datetime.utcnow().isoformat()),
)
conn.commit()
return {
"status": "tracked",
"user_id": user["id"],
"page_id": page_id,
"accessed_at": datetime.utcnow().isoformat(),
}
+131 -3
View File
@@ -13,11 +13,16 @@ logger = logging.getLogger(__name__)
class GiteaClient:
"""Async Gitea API v1 client with simple TTL cache."""
"""Async Gitea API v1 client with simple TTL cache.
def __init__(self) -> None:
Can be instantiated with a per-user token (OAuth) or falls back
to the server-wide admin token.
"""
def __init__(self, user_token: str | None = None) -> None:
self._base = f"{settings.gitea_url}/api/v1"
self._headers = {"Authorization": f"token {settings.gitea_token}"}
token = user_token or settings.gitea_token
self._headers = {"Authorization": f"token {token}"}
self._cache: dict[str, tuple[datetime, Any]] = {}
self._ttl = timedelta(seconds=settings.gitea_cache_ttl)
@@ -295,6 +300,129 @@ class GiteaClient:
return data
# ── repo contents ──
async def get_repo_contents(self, owner, repo, path=""):
"""Get contents of a repo directory (lazy: one level)."""
url = f"{self._base}/repos/{owner}/{repo}/contents"
if path:
url += f"/{path}"
cache_key = f"contents:{owner}:{repo}:{path}"
cached = self._cached(cache_key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(url, headers=self._headers)
resp.raise_for_status()
data = resp.json()
if isinstance(data, dict):
data = [data]
self._set_cache(cache_key, data)
return data
async def get_file_content(self, owner, repo, path):
"""Get raw file content (decoded from base64)."""
import base64
cache_key = f"file:{owner}:{repo}:{path}"
cached = self._cached(cache_key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"{self._base}/repos/{owner}/{repo}/contents/{path}",
headers=self._headers,
)
resp.raise_for_status()
item = resp.json()
content = ""
if item.get("encoding") == "base64" and item.get("content"):
try:
content = base64.b64decode(item["content"]).decode("utf-8")
except Exception:
content = "[binary file]"
self._set_cache(cache_key, content)
return content
async def create_or_update_file(self, owner, repo, path, content, message, sha=None):
"""Create or update a file. Requires `sha` for updates."""
import base64
body = {
"content": base64.b64encode(content.encode("utf-8")).decode("utf-8"),
"message": message,
}
if sha:
body["sha"] = sha
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.put(
f"{self._base}/repos/{owner}/{repo}/contents/{path}",
headers=self._headers,
json=body,
)
resp.raise_for_status()
data = resp.json()
parent = "/".join(path.split("/")[:-1])
for p in (parent, path.rsplit("/", 1)[0] if "/" in path else ""):
self._cache.pop(f"contents:{owner}:{repo}:{p}", None)
self._cache.pop(f"file:{owner}:{repo}:{path}", None)
return data
async def delete_file(self, owner, repo, path, sha, message):
"""Delete a file from the repo."""
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.delete(
f"{self._base}/repos/{owner}/{repo}/contents/{path}",
headers=self._headers,
json={"message": message, "sha": sha},
)
resp.raise_for_status()
parent = "/".join(path.split("/")[:-1])
for p in (parent, path.rsplit("/", 1)[0] if "/" in path else ""):
self._cache.pop(f"contents:{owner}:{repo}:{p}", None)
self._cache.pop(f"file:{owner}:{repo}:{path}", None)
return {}
def _invalidate_tree_cache(self, owner, repo):
keys = [k for k in self._cache if k.startswith(f"contents:{owner}:{repo}:") or k.startswith(f"file:{owner}:{repo}:")]
for k in keys:
del self._cache[k]
async def get_file_commits(self, owner: str, repo: str, path: str) -> list[dict]:
"""Get recent commits affecting a specific file (cached 5 min)."""
key = f"commits:{owner}:{repo}:{path}"
cached = self._cached(key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"{self._base}/repos/{owner}/{repo}/commits",
headers=self._headers,
params={"path": path, "limit": 20},
)
if resp.status_code == 200:
data = resp.json()
self._set_cache(key, data)
return data
return []
# ── singleton ──
gitea = GiteaClient()
# ── Helper: get per-user GiteaClient ──
def get_user_gitea_client(request):
"""Return a GiteaClient authenticated with the user's OAuth token, or None."""
from app.auth.session import SessionManager
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
if not user:
return None
from app.db import get_conn
with get_conn() as conn:
row = conn.execute(
"SELECT access_token FROM user_oauth_tokens WHERE user_id=? AND provider='gitea' ORDER BY updated_at DESC LIMIT 1",
(user["id"],),
).fetchone()
if not row:
return None
return GiteaClient(user_token=row["access_token"])
+158
View File
@@ -0,0 +1,158 @@
"""FlowDeck — GitHub API adapter with caching."""
from __future__ import annotations
import base64
import logging
from datetime import datetime, timedelta
from typing import Any
import httpx
logger = logging.getLogger(__name__)
DEFAULT_TTL = 30 # seconds
class GitHubAdapter:
"""Async GitHub API client (v3 REST) with simple TTL cache.
Authenticated via OAuth2 Bearer token.
"""
def __init__(self, access_token: str, ttl: int = DEFAULT_TTL) -> None:
self._base = "https://api.github.com"
self._headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/vnd.github+json",
}
self._cache: dict[str, tuple[datetime, Any]] = {}
self._ttl = timedelta(seconds=ttl)
# ── cache helpers ──
def _cached(self, key: str) -> Any | None:
entry = self._cache.get(key)
if entry and entry[0] > datetime.now():
return entry[1]
return None
def _set_cache(self, key: str, value: Any) -> None:
self._cache[key] = (datetime.now() + self._ttl, value)
# ── repos ──
async def list_repos(self, page: int = 1, per_page: int = 50) -> list[dict]:
"""List repositories for the authenticated user (paginated)."""
cache_key = f"repos:{page}:{per_page}"
cached = self._cached(cache_key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"{self._base}/user/repos",
headers=self._headers,
params={"page": page, "per_page": per_page, "sort": "updated"},
)
resp.raise_for_status()
data = resp.json()
self._set_cache(cache_key, data)
return data
async def list_all_repos(self) -> list[dict]:
"""Fetch all user repos across pages (up to 5 pages / 250 repos)."""
all_repos: list[dict] = []
for page in range(1, 6):
repos = await self.list_repos(page=page)
if not repos:
break
all_repos.extend(repos)
return all_repos
# ── repo tree ──
async def get_repo_tree(
self, owner: str, repo: str, sha: str | None = None, recursive: bool = True
) -> list[dict]:
"""Get the git tree for a repo. If ``sha`` is omitted, resolves the
default branch first."""
cache_key = f"tree:{owner}:{repo}:{sha or 'default'}:{recursive}"
cached = self._cached(cache_key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
# Resolve default branch commit SHA if not provided
if sha is None:
repo_info = await client.get(
f"{self._base}/repos/{owner}/{repo}",
headers=self._headers,
)
repo_info.raise_for_status()
sha = repo_info.json()["default_branch"]
# Now get the commit to find tree SHA
branch_resp = await client.get(
f"{self._base}/repos/{owner}/{repo}/branches/{sha}",
headers=self._headers,
)
branch_resp.raise_for_status()
sha = branch_resp.json()["commit"]["commit"]["tree"]["sha"]
params: dict[str, Any] = {}
if recursive:
params["recursive"] = "1"
resp = await client.get(
f"{self._base}/repos/{owner}/{repo}/git/trees/{sha}",
headers=self._headers,
params=params,
)
resp.raise_for_status()
data = resp.json()
items = data.get("tree", [])
# Truncated responses — fetch remaining pages if needed
while data.get("truncated", False):
logger.warning("GitHub tree truncated for %s/%s — results incomplete", owner, repo)
break
self._set_cache(cache_key, items)
return items
# ── file content ──
async def get_file_content(self, owner: str, repo: str, path: str) -> str:
"""Get decoded file content from a repo."""
cache_key = f"file:{owner}:{repo}:{path}"
cached = self._cached(cache_key)
if cached:
return cached
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"{self._base}/repos/{owner}/{repo}/contents/{path}",
headers=self._headers,
)
resp.raise_for_status()
item = resp.json()
content = ""
if item.get("encoding") == "base64" and item.get("content"):
try:
content = base64.b64decode(item["content"]).decode("utf-8")
except Exception:
content = "[binary file]"
self._set_cache(cache_key, content)
return content
# ── token validation ──
async def validate_token(self) -> bool:
"""Check whether the access token is still valid."""
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get(
f"{self._base}/user",
headers=self._headers,
)
return resp.status_code == 200
+253
View File
@@ -0,0 +1,253 @@
{# ── Unified Header (Notion-inspired breadcrumb navigation) ──
Parameters available in calling context:
breadcrumb_items: list of {label, url, id, icon, menu} — last item = current page
page_icon: str — emoji icon
page_title: str — fallback current-page label when no breadcrumb_items
right_actions: str — raw HTML for right-side action buttons
hamburger_click: str — Alpine expression for hamburger button
hide_hamburger: bool — if truthy, hides the hamburger button
hide_home: bool — if truthy, do not prepend the "Home" crumb
nav_workspace_id: int — workspace id used to fetch the navigation menu
nav_page_id: int — current page id (enables the sibling nav menu)
#}
{% set ns = namespace(items=[]) %}
{% if not hide_home %}
{% set ns.items = ns.items + [{"label": "Home", "url": "/workspaces", "id": none, "icon": "🏠", "menu": false, "home": true}] %}
{% endif %}
{% if breadcrumb_items %}
{% for item in breadcrumb_items %}
{% set ns.items = ns.items + [{
"label": item.get('label') or item.get('name') or 'Untitled',
"url": item.get('url'),
"id": item.get('id'),
"icon": item.get('icon'),
"menu": (item.get('id') is not none)
}] %}
{% endfor %}
{% elif page_title %}
{% set ns.items = ns.items + [{
"label": page_title,
"url": none,
"id": nav_page_id if nav_page_id is defined else none,
"icon": page_icon if page_icon is defined else none,
"menu": (nav_page_id is defined and nav_page_id)
}] %}
{% endif %}
<header class="topbar unified-header">
{% if not hide_hamburger %}
<button class="hamburger-btn"
@click="{{ hamburger_click|default('sidebarCollapsed ? (sidebarCollapsed = false) : (mobileSidebarOpen = true, sidebarCollapsed = false)') }}"
title="Toggle sidebar">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="3" y1="6" x2="21" y2="6"/>
<line x1="3" y1="12" x2="21" y2="12"/>
<line x1="3" y1="18" x2="21" y2="18"/>
</svg>
</button>
{% endif %}
<script type="application/json" id="fd-breadcrumb-data">{{ {"workspace_id": nav_workspace_id|default(0), "crumbs": ns.items}|tojson }}</script>
<div class="topbar-left header-breadcrumb" x-data="fdBreadcrumb()" x-init="init()"
@mouseleave="dragCloseTimer()">
{% if page_icon %}
<span class="header-page-icon">{{ page_icon }}</span>
{% endif %}
<template x-for="(crumb, di) in display" :key="di">
<span class="crumb-cell">
{# ── Collapsed "…" segment ── #}
<template x-if="crumb.ellipsis">
<span class="crumb-anchor"
@mouseenter="cancelCloseTimer(); ellipsisOpen = true"
@mouseleave="dragCloseTimer()">
<button type="button" class="breadcrumb-link crumb-ellipsis">&hellip;</button>
<div class="fd-nav-menu" x-show="ellipsisOpen" x-cloak x-transition.opacity
@mouseenter="cancelCloseTimer()"
@mouseleave="dragCloseTimer()">
<template x-for="h in crumb.hidden" :key="h.id">
<div class="fd-nav-item" @click.stop="go(h.url); closeAll()">
<span class="fd-nav-ico" x-text="h.icon || '📄'"></span>
<span class="fd-nav-label" x-text="h.label"></span>
</div>
</template>
</div>
</span>
</template>
{# ── Plain link crumb (Home / non-menu with url) ── #}
<template x-if="!crumb.ellipsis && !crumb.menu && crumb.url">
<a class="breadcrumb-link" :href="crumb.url" x-text="crumb.label"
@mouseenter="closeAll()"></a>
</template>
{# ── Plain current crumb (no menu, no url) ── #}
<template x-if="!crumb.ellipsis && !crumb.menu && !crumb.url">
<span class="breadcrumb-current" x-text="crumb.label"
@mouseenter="closeAll()"></span>
</template>
{# ── Interactive crumb with navigation dropdown (Notion-style hover) ── #}
<template x-if="!crumb.ellipsis && crumb.menu">
<span class="crumb-anchor"
@mouseenter="cancelCloseTimer(); openMenu(crumb.origIndex)"
@mouseleave="dragCloseTimer()">
<button type="button" class="breadcrumb-link"
:class="{ 'breadcrumb-current': crumb.origIndex === crumbs.length - 1 }"
x-text="crumb.label"></button>
<div class="fd-nav-menu"
x-show="openIdx === crumb.origIndex" x-cloak x-transition.opacity
@mouseenter="cancelCloseTimer()"
@mouseleave="dragCloseTimer()">
<div class="fd-nav-section" x-text="crumb.home ? 'Workspaces' : 'Private'"></div>
<template x-if="loading">
<div class="fd-nav-empty">Loading&hellip;</div>
</template>
<template x-if="!loading && activeItems.length === 0">
<div class="fd-nav-empty">No pages</div>
</template>
<template x-for="item in activeItems" :key="item.id">
<div class="fd-nav-item"
@mouseenter="openSub(item)"
@click.stop="go(item.url); closeAll()">
<span class="fd-nav-ico" x-text="item.icon || '📄'"></span>
<span class="fd-nav-label" x-text="item.name"></span>
<span class="fd-nav-arrow" x-show="item.has_children">&rsaquo;</span>
<div class="fd-nav-menu fd-nav-submenu" x-show="subOpenId === item.id" x-cloak
@mouseenter="cancelCloseTimer()"
@mouseleave="dragCloseTimer()">
<template x-for="s in subItems" :key="s.id">
<div class="fd-nav-item" @click.stop="go(s.url); closeAll()">
<span class="fd-nav-ico" x-text="s.icon || '📄'"></span>
<span class="fd-nav-label" x-text="s.name"></span>
<span class="fd-nav-arrow" x-show="s.has_children">&rsaquo;</span>
</div>
</template>
</div>
</div>
</template>
</div>
</span>
</template>
<span class="breadcrumb-sep" x-show="di < display.length - 1">/</span>
</span>
</template>
</div>
<div class="topbar-right header-actions">
{{ right_actions|safe if right_actions else '' }}
</div>
</header>
<script>
document.addEventListener('alpine:init', function () {
if (window.Alpine && window.Alpine.__fdBreadcrumbRegistered) return;
if (window.Alpine) window.Alpine.__fdBreadcrumbRegistered = true;
Alpine.data('fdBreadcrumb', function () {
return {
crumbs: [],
wsId: 0,
openIdx: null,
ellipsisOpen: false,
loading: false,
cache: {},
activeItems: [],
subOpenId: null,
subItems: [],
closeTimer: null,
init: function () {
var el = document.getElementById('fd-breadcrumb-data');
if (el) {
try {
var d = JSON.parse(el.textContent);
this.crumbs = (d.crumbs || []).map(function (c, i) { c.origIndex = i; return c; });
this.wsId = d.workspace_id || 0;
} catch (e) { this.crumbs = []; }
}
},
get display() {
var c = this.crumbs;
if (c.length <= 4) return c;
var head = [c[0], c[1]];
var hidden = c.slice(2, c.length - 2);
var tail = [c[c.length - 2], c[c.length - 1]];
return head.concat([{ ellipsis: true, hidden: hidden }], tail);
},
parentIdFor: function (origIndex) {
if (origIndex <= 0) return null;
var prev = this.crumbs[origIndex - 1];
return prev && prev.id ? prev.id : null;
},
fetchMenu: function (parentId) {
var key = parentId == null ? 'root' : String(parentId);
var self = this;
if (this.cache[key]) return Promise.resolve(this.cache[key]);
var url = '/api/nav/menu?';
if (this.wsId) url += 'workspace_id=' + this.wsId + '&';
if (parentId != null) url += 'parent_id=' + parentId;
return fetch(url, { credentials: 'same-origin' })
.then(function (r) { return r.json(); })
.then(function (d) { self.cache[key] = d.items || []; return self.cache[key]; })
.catch(function () { return []; });
},
openMenu: function (origIndex) {
if (this.openIdx === origIndex) return; // already open
var self = this;
// Close sub first
this.subOpenId = null;
this.subItems = [];
this.openIdx = origIndex;
this.loading = true;
this.fetchMenu(this.parentIdFor(origIndex)).then(function (items) {
if (self.openIdx === origIndex) { self.activeItems = items; }
self.loading = false;
});
},
openSub: function (item) {
var self = this;
if (!item.has_children) { this.subOpenId = null; this.subItems = []; return; }
if (this.subOpenId === item.id) return;
this.subOpenId = item.id;
this.subItems = [];
this.fetchMenu(item.id).then(function (items) {
if (self.subOpenId === item.id) { self.subItems = items; }
});
},
// ── Hover close timer ──
dragCloseTimer: function () {
var self = this;
this.cancelCloseTimer();
this.closeTimer = setTimeout(function () {
self.closeAll();
}, 200);
},
cancelCloseTimer: function () {
if (this.closeTimer) {
clearTimeout(this.closeTimer);
this.closeTimer = null;
}
},
closeAll: function () {
this.cancelCloseTimer();
this.openIdx = null;
this.ellipsisOpen = false;
this.subOpenId = null;
this.subItems = [];
this.activeItems = [];
},
go: function (url) { if (url) window.location.href = url; }
};
});
});
</script>
+46
View File
@@ -0,0 +1,46 @@
{% macro render_workspace_tree(pages, depth=0) %}
{% for page in pages %}
{% set safe_name = page.name | replace("'", "\\'") %}
<li class="sidebar-item ws-tree-item"
data-id="{{ page.db_id }}"
data-is-folder="{{ 'true' if page.is_folder else 'false' }}"
data-depth="{{ depth }}"
data-name="{{ safe_name }}"
:class="{ active: activeNodeId === {{ page.db_id }} }"
draggable="true"
@dragstart="dragStart($event, {{ page.db_id }})"
@dragover.prevent="dragOver($event, {{ page.db_id }}, {{ 'true' if page.is_folder else 'false' }})"
@dragleave="dragLeave($event)"
@drop.prevent="drop($event, {{ page.db_id }})"
style="padding-left:{{ 4 + depth * 12 }}px;"
@contextmenu.prevent="showWsContext($event, {{ page.db_id }}, '{{ safe_name }}', {{ 'true' if page.is_folder else 'false' }})"
@touchstart="wsTouchStart($event)"
@touchend="wsTouchEnd($event, {{ page.db_id }}, '{{ safe_name }}', {{ 'true' if page.is_folder else 'false' }})"
@touchmove="wsTouchMove($event)">
{% if page.is_folder %}
<button class="tree-chevron"
@click.stop="toggleTreeFolder({{ page.db_id }})"
:class="{ open: expandedFolders[{{ page.db_id }}] }"
title="Toggle folder">▶</button>
{% else %}
<span style="width:12px;flex-shrink:0;"></span>
{% endif %}
<span class="page-icon">{{ page.icon }}</span>
{% if page.is_folder %}
<span class="page-name tree-folder-link"
@click.stop="navigateToFolder({{ page.db_id }})"
draggable="false"
title="Open folder">{{ page.name }}{% if page.child_count %} <span class="child-count">({{ page.child_count }})</span>{% endif %}</span>
{% else %}
<a href="/pages/{{ page.db_id }}" class="page-name" draggable="false">{{ page.name }}</a>
{% endif %}
</li>
{% if page.children %}
<li x-show="expandedFolders[{{ page.db_id }}]" x-transition style="list-style:none;margin:0;padding:0;">
<ul style="list-style:none;margin:0;padding:0;">
{{ render_workspace_tree(page.children, depth + 1) }}
</ul>
</li>
{% endif %}
{% endfor %}
{% endmacro %}
+1
View File
@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% block page_icon %}👤{% endblock %}
{% block page_title %}Accounts{% endblock %}
{% block title_prefix %}Accounts{% endblock %}
{% block content %}
<div class="page-title-area">
+723 -189
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% block page_icon %}📁{% endblock %}
{% block page_title %}Kanban board new{% endblock %}
{% block title_prefix %}Kanban board new{% endblock %}
{% block content %}
<!-- Cover image -->
+1
View File
@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% block page_icon %}🏠{% endblock %}
{% block page_title %}Home{% endblock %}
{% block title_prefix %}Home{% endblock %}
{% block content %}
<div class="page-title-area" style="padding-top: 24px;">
+819
View File
@@ -0,0 +1,819 @@
{% extends "base.html" %}
{% block page_title %}{{ workspace_name }}{% endblock %}
{% block title_prefix %}{{ workspace_name }}{% endblock %}
{% block page_icon %}🔗{% endblock %}
{% block topbar %}
{% set breadcrumb_items = [{"label": owner ~ "/" ~ repo, "url": None}] %}
{% set page_icon = "🔗" %}
{% set right_actions = '<button class="page-action-btn" @click="showNewFile=!showNewFile" title="New file">📄+</button><button class="page-action-btn" @click="triggerUpload()" title="Upload file">📤</button><input type="file" id="gitea-upload-input" style="display:none" @change="doUpload($event)" multiple><button class="page-action-btn" @click="refreshTree()" title="Refresh">🔄</button><a href="/accounts/settings" class="topbar-btn" title="Settings">⚙</a>' %}
{% include '_header.html' %}
{% endblock %}
{% block content %}
<!-- Prism.js syntax highlighting -->
<link rel="stylesheet" href="/static/css/prism.css">
<script src="/static/js/prism.min.js"></script>
<style>
.gw-main{display:flex;flex-direction:column;height:calc(100vh - 48px);overflow:hidden;}
.gw-content{padding:24px;overflow-y:auto;flex:1;}
.gw-content h3{font-size:16px;margin-bottom:12px;color:var(--text-dim);}
.gw-content pre{background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;padding:16px;overflow-x:auto;font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word;max-height:70vh;overflow-y:auto;}
.gw-content pre[class*="language-"]{background:transparent;border:none;padding:0;margin:0;white-space:pre;word-break:normal;}
.gw-content code[class*="language-"]{font-size:13px;line-height:1.5;tab-size:4;}
.gw-content .empty-state{text-align:center;padding:60px 20px;color:var(--text-dim);}
.gw-content .empty-state h2{font-size:18px;margin-bottom:8px;color:var(--text);}
.gw-content textarea{width:100%;min-height:50vh;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:13px;padding:12px;font-family:monospace;resize:vertical;outline:none;}
.gw-content textarea:focus{border-color:var(--accent);}
.gw-file-toolbar{display:flex;align-items:center;gap:8px;padding:8px 24px;background:var(--bg-secondary);border-bottom:1px solid var(--border);font-size:13px;color:var(--text-dim);}
.gw-file-toolbar strong{color:var(--text);margin-right:12px;}
.gw-commit-bar{display:flex;align-items:center;gap:8px;padding:12px 24px;background:var(--bg-secondary);border-top:1px solid var(--border);flex-wrap:wrap;}
.gw-commit-bar input{flex:1;min-width:180px;padding:8px 12px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:13px;outline:none;}
.gw-commit-bar input:focus{border-color:var(--accent);}
/* Prism theme tweaks for dark UI */
.gw-content pre[class*="language-"]{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;border-radius:8px!important;padding:16px!important;}
</style>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('giteaWorkspace', () => {
const params = new URLSearchParams(window.location.search);
const owner = params.get('owner') || '';
const repo = params.get('repo') || '';
return {
owner, repo,
showFile: false,
showEditor: false,
showPrivate: false,
privatePages: [],
editingPrivate: null,
editingPrivateTitle: '',
editingPrivateContent: '',
filePath: '',
fileContent: '',
fileSize: 0,
fileSha: '',
fileLoading: false,
fileLanguage: 'text',
editContent: '',
commitMessage: 'Update via FlowDeck',
commitHistory: JSON.parse(localStorage.getItem('fd_commit_msgs') || '[]'),
// File tree browser
treeItems: [],
sortedTreeItems: [],
treeLoading: false,
folderStack: [],
currentPath: '',
// Context menu
gwCtx: { visible: false, x: 0, y: 0, item: null },
_sortTree() {
this.sortedTreeItems = [...this.treeItems].sort(function(a, b) {
if (a.type === b.type) return a.name.localeCompare(b.name);
return a.type === 'folder' ? -1 : 1;
});
},
init() {
// Expose globally for header to access
window._gwData = this;
// Set cookie for sidebar
document.cookie = 'flowdeck_workspace=gitea:' + this.owner + ':' + this.repo + ';path=/;SameSite=Lax';
// Load sidebar tree (into gitea section)
this.loadSidebarTree();
// Load main content tree
this.loadMainTree('');
// Listen for sidebar clicks on Gitea items
this.setupSidebarClicks();
},
async loadMainTree(path) {
this.treeLoading = true;
this.currentPath = path;
try {
var url = '/api/gitea/projects/' + this.owner + '/' + this.repo + '/tree';
if (path) url += '?path=' + encodeURIComponent(path);
var r = await fetch(url);
if (!r.ok) { this.treeItems = []; this.sortedTreeItems = []; return; }
var d = await r.json();
this.treeItems = d.tree || [];
this._sortTree();
} catch(e) { this.treeItems = []; this.sortedTreeItems = []; }
finally { this.treeLoading = false; }
},
drillDown(path) {
this.folderStack.push(path.split('/').pop());
this.loadMainTree(path);
},
navigateToFolder(idx) {
// Truncate stack and rebuild path
this.folderStack = this.folderStack.slice(0, idx + 1);
var path = this.folderStack.join('/');
this.loadMainTree(path);
},
navigateToRoot() {
this.folderStack = [];
this.loadMainTree('');
},
openGwContext(ev, item) {
this.gwCtx = { visible: true, x: ev.clientX, y: ev.clientY, item: item };
},
gwRename() {
this.gwCtx.visible = false;
var item = this.gwCtx.item;
if (!item) return;
var newName = prompt('Rename:', item.name);
if (!newName || !newName.trim() || newName.trim() === item.name) return;
var self = this;
var oldPath = item.path;
var newPath = oldPath.replace(/[^/]+$/, newName.trim());
fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: oldPath, new_path: newPath, message: 'Rename ' + oldPath + ' to ' + newPath })
}).then(function(r){ return r.json(); })
.then(function(d){
if (d.status === 'ok') { self.refreshTree(); }
else { window.showToast('Rename failed', 'error'); }
})
.catch(function(){ window.showToast('Rename failed', 'error'); });
},
gwDelete() {
this.gwCtx.visible = false;
var item = this.gwCtx.item;
if (!item) return;
if (!confirm('Delete ' + item.name + '?')) return;
var self = this;
fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file?path=' + encodeURIComponent(item.path) + '&sha=' + (item.sha || '') + '&message=Delete ' + item.path, {
method: 'DELETE'
}).then(function(r){
if (r.ok) { self.refreshTree(); }
else { window.showToast('Delete failed', 'error'); }
}).catch(function(){ window.showToast('Delete failed', 'error'); });
},
async loadSidebarTree() {
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/tree');
if (!r.ok) {
// If API fails (e.g. no Gitea token), set a message
var container = document.getElementById('sidebar-gitea-items');
if (container) container.innerHTML = '<li class="sidebar-item empty-hint"><span class="page-icon">🔗</span><span class="page-name text-dim">Connect Gitea to browse files</span></li>';
return;
}
var d = await r.json();
var items = d.tree || [];
var container = document.getElementById('sidebar-gitea-items');
if (!container) return;
// Ensure gitea section is visible
if (window.appState && window.appState.sectionsOpen && !window.appState.sectionsOpen.gitea) {
window.appState.sectionsOpen.gitea = true;
}
container.innerHTML = '';
// Build tree HTML as string and set once (more performant)
var html = '';
for (var i = 0; i < items.length; i++) {
var item = items[i];
var icon = item.type === 'folder' ? '📁' : '📄';
html += '<li class="sidebar-item" data-gitea-path="' + item.path + '" data-gitea-type="' + (item.type === 'folder' ? 'folder' : 'file') + '" data-gitea-sha="' + (item.sha || '') + '" style="padding-left:12px;cursor:pointer;display:flex;align-items:center;gap:4px;">';
html += '<span class="page-icon">' + icon + '</span>';
html += '<span class="page-name">' + item.name + '</span>';
html += '</li>';
}
// Add Private Pages link
html += '<li style="border-top:1px solid var(--border);margin:8px 0;"></li>';
html += '<li class="sidebar-item" id="gitea-private-link" style="padding-left:12px;cursor:pointer;display:flex;align-items:center;gap:4px;">';
html += '<span class="page-icon">🔒</span><span class="page-name">Private Pages</span></li>';
container.innerHTML = html;
// Re-attach event listeners
this.setupSidebarClicks();
} catch(e) {
console.error('Gitea sidebar tree load failed:', e);
}
},
setupSidebarClicks() {
var self = this;
document.addEventListener('click', function(e) {
var el = e.target.closest('.sidebar-item[data-gitea-path]');
if (!el) return;
var path = el.getAttribute('data-gitea-path');
var type = el.getAttribute('data-gitea-type');
// If clicking the checkbox, let its own handler deal with selection
if (e.target.classList.contains('gitea-checkbox')) return;
// If clicking the inline rename input, don't navigate
if (e.target.classList.contains('inline-rename-input')) return;
// If Shift or Ctrl/Meta is pressed, use multi-selection
if (e.shiftKey || e.ctrlKey || e.metaKey) {
e.preventDefault();
e.stopPropagation();
self.selectItem(path, el, e);
return;
}
// Normal click: navigate (open file/folder)
e.preventDefault();
e.stopPropagation();
// Update visual "active" state
document.querySelectorAll('.sidebar-item.active').forEach(function(si) {
si.classList.remove('active');
});
el.classList.add('active');
if (type === 'folder') {
self.loadSubdir(path, el);
} else {
self.openFile(path, el.getAttribute('data-gitea-sha'));
}
});
// Listen for custom delete event on gitea sidebar items
document.addEventListener('gitea-delete', function(e) {
var el = e.target;
var path = el.getAttribute('data-gitea-path');
if (!path) return;
if (!confirm('Delete ' + path + ' from ' + self.owner + '/' + self.repo + '?')) return;
var sha = el.getAttribute('data-gitea-sha') || '';
fetch('/api/gitea/projects/' + self.owner + '/' + self.repo + '/file?path=' + encodeURIComponent(path) + '&sha=' + encodeURIComponent(sha) + '&message=' + encodeURIComponent('Delete via FlowDeck'), {
method: 'DELETE',
}).then(function(r) {
if (r.ok) self.refreshTree();
}).catch(function() {});
});
},
async loadSubdir(path, el) {
var self = this;
// Check if already loaded
var ul = el.querySelector('ul');
if (ul) {
ul.style.display = ul.style.display === 'none' ? '' : 'none';
return;
}
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/tree?path=' + encodeURIComponent(path));
if (!r.ok) return;
var d = await r.json();
var children = d.tree || [];
ul = document.createElement('ul');
ul.className = 'sidebar-items';
ul.style.paddingLeft = '20px';
children.forEach(function(child) {
var icon = child.type === 'folder' ? '📁' : '📄';
var li = document.createElement('li');
li.className = 'sidebar-item';
li.setAttribute('data-gitea-path', child.path);
li.setAttribute('data-gitea-type', child.type === 'folder' ? 'folder' : 'file');
li.setAttribute('data-gitea-sha', child.sha || '');
li.style.cssText = 'cursor:pointer;display:flex;align-items:center;gap:4px;';
// Checkbox
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'gitea-checkbox';
cb.style.cssText = 'flex-shrink:0;margin:0;display:none;';
cb.addEventListener('click', function(ev) {
ev.stopPropagation();
self.selectItem(child.path, li, ev);
});
li.appendChild(cb);
// Icon
var iconSpan = document.createElement('span');
iconSpan.className = 'sidebar-icon';
iconSpan.textContent = icon;
li.appendChild(iconSpan);
// Name
var nameSpan = document.createElement('span');
nameSpan.textContent = child.name;
nameSpan.addEventListener('dblclick', function(ev) {
ev.preventDefault();
ev.stopPropagation();
self.startInlineRename(nameSpan, child.path, li);
});
li.appendChild(nameSpan);
ul.appendChild(li);
});
el.appendChild(ul);
} catch(e) {}
},
async openFile(path, sha) {
this.filePath = path;
this.fileSha = sha || '';
this.showEditor = false;
this.showFile = true;
this.fileLoading = true;
this.fileLanguage = this.getLanguage(path);
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file?path=' + encodeURIComponent(path));
if (r.ok) {
var d = await r.json();
this.fileContent = d.content || '';
this.fileSize = d.content ? d.content.length : 0;
} else {
this.fileContent = '[Error loading file]';
}
} catch(e) {
this.fileContent = '[Error loading file]';
}
this.fileLoading = false;
// Highlight after Alpine renders
var self = this;
this.$nextTick(function() {
var block = self.$refs.codeBlock;
if (block && block.textContent && typeof Prism !== 'undefined') {
Prism.highlightElement(block);
}
});
},
getLanguage(path) {
var ext = (path || '').split('.').pop().toLowerCase();
var map = {
js:'javascript', jsx:'javascript', ts:'typescript', tsx:'typescript',
py:'python', rb:'ruby', rs:'rust', go:'go', java:'java', kt:'kotlin',
c:'c', cpp:'c', h:'c', hpp:'c', cs:'csharp',
html:'markup', htm:'markup', xml:'markup', svg:'markup', css:'css', scss:'css',
json:'json', yaml:'yaml', yml:'yaml', toml:'toml', ini:'ini',
md:'markdown', sql:'sql', sh:'bash', bash:'bash', zsh:'bash',
php:'php', swift:'swift', r:'r', lua:'lua', dart:'dart',
dockerfile:'docker', makefile:'makefile', cmake:'cmake',
};
return map[ext] || 'text';
},
openEditor() {
this.editContent = this.fileContent;
this.showEditor = true;
},
async saveFile() {
if (!this.filePath) return;
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file', {
method: 'PUT',
headers: {'Content-Type': 'application/json', 'X-CSRF-Token': this.getCsrfToken()},
body: JSON.stringify({
path: this.filePath, content: this.editContent,
message: this.commitMessage, sha: this.fileSha,
})
});
if (r.ok) {
this.fileContent = this.editContent;
this.showEditor = false;
if (!this.commitHistory.includes(this.commitMessage)) {
this.commitHistory.unshift(this.commitMessage);
if (this.commitHistory.length > 10) this.commitHistory.pop();
localStorage.setItem('fd_commit_msgs', JSON.stringify(this.commitHistory));
}
} else {
var d = await r.json();
window.showToast('Failed to save: ' + (d.error || 'Unknown error'), 'error');
}
} catch(e) { window.showToast('Network error', 'error'); }
},
async deleteCurrentFile() {
if (!this.filePath) return;
if (!confirm('Delete ' + this.filePath + ' from ' + this.owner + '/' + this.repo + '?')) return;
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file?path=' + encodeURIComponent(this.filePath) + '&sha=' + encodeURIComponent(this.fileSha) + '&message=' + encodeURIComponent('Delete via FlowDeck'), {
method: 'DELETE',
});
if (r.ok) {
this.showFile = false;
this.filePath = '';
await this.refreshTree();
}
} catch(e) {}
},
async refreshTree() {
// Reload main tree and sidebar tree without full page reload
this.loadMainTree(this.currentPath);
this.loadSidebarTree();
},
formatSize(bytes) {
if (!bytes) return '';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1048576) return (bytes/1024).toFixed(1) + ' KB';
return (bytes/1048576).toFixed(1) + ' MB';
},
// ── Private Pages ──
async loadPrivatePages() {
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/private-pages');
if (r.ok) { var d = await r.json(); this.privatePages = d.pages || []; }
} catch(e) {}
},
newPrivate() {
this.editingPrivate = 'new';
this.editingPrivateTitle = '';
this.editingPrivateContent = '';
},
async openPrivate(id) {
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/private-pages/' + id);
if (r.ok) {
var d = await r.json();
this.editingPrivate = id;
this.editingPrivateTitle = d.page.title;
this.editingPrivateContent = d.page.content;
}
} catch(e) {}
},
async savePrivate() {
var url = '/api/gitea/projects/' + this.owner + '/' + this.repo + '/private-pages';
var method = 'POST';
if (this.editingPrivate !== 'new') {
url += '/' + this.editingPrivate;
method = 'PUT';
}
try {
var r = await fetch(url, {
method, headers: {'Content-Type':'application/json','X-CSRF-Token': this.getCsrfToken ? this.getCsrfToken() : ''},
body: JSON.stringify({title: this.editingPrivateTitle, content: this.editingPrivateContent})
});
if (r.ok) {
this.editingPrivate = null;
this.editingPrivateTitle = '';
this.editingPrivateContent = '';
await this.loadPrivatePages();
}
} catch(e) {}
},
// Create new file
showNewFile: false,
newFilePath: '',
newFileContent: '',
newFileMsg: 'Create via FlowDeck',
async createNewFile() {
if (!this.newFilePath.trim()) return;
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/file', {
method: 'PUT',
headers: {'Content-Type':'application/json', 'X-CSRF-Token': this.getCsrfToken()},
body: JSON.stringify({path: this.newFilePath.trim(), content: this.newFileContent, message: this.newFileMsg || 'Create via FlowDeck'})
});
if (r.ok) {
this.showNewFile = false;
this.newFilePath = '';
this.newFileContent = '';
this.newFileMsg = 'Create via FlowDeck';
await this.loadSidebarTree();
} else {
var d = await r.json();
window.showToast('Failed: ' + (d.error || d.detail || 'Unknown error'), 'error');
}
} catch(e) { window.showToast('Error: ' + e.message, 'error'); }
},
// Upload files
triggerUpload() { document.getElementById('gitea-upload-input').click(); },
async doUpload(ev) {
var files = ev.target.files;
if (!files.length) return;
for (var i = 0; i < files.length; i++) {
var form = new FormData();
form.append('file', files[i]);
form.append('message', 'Upload ' + files[i].name + ' via FlowDeck');
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/upload', {
method: 'POST',
headers: {'X-CSRF-Token': this.getCsrfToken()},
body: form
});
if (!r.ok) { var d = await r.json(); console.error('Upload failed:', d.error); }
} catch(e) { console.error('Upload error:', e); }
}
await this.loadSidebarTree();
ev.target.value = '';
},
async deletePrivate(id) {
if (!confirm('Delete this private page?')) return;
try {
var r = await fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/private-pages/' + id, {
method: 'DELETE', headers: {'X-CSRF-Token': this.getCsrfToken ? this.getCsrfToken() : ''}
});
if (r.ok) await this.loadPrivatePages();
} catch(e) {}
},
getCsrfToken() {
return document.cookie.split('; ').find(function(c) { return c.startsWith('csrf_token='); })?.split('=')[1] || '';
},
// ── Multi-selection ──
multiSelect: false,
selectedPaths: [],
lastClickedPath: null,
toggleMultiSelect() {
this.multiSelect = !this.multiSelect;
var cbs = document.querySelectorAll('.gitea-checkbox');
var self = this;
cbs.forEach(function(cb) { cb.style.display = self.multiSelect ? '' : 'none'; });
if (!this.multiSelect) {
// Clear selection when leaving multi-select mode
cbs.forEach(function(cb) { cb.checked = false; });
this.selectedPaths = [];
this.lastClickedPath = null;
// Remove selected class
document.querySelectorAll('.sidebar-item.gitea-selected').forEach(function(el) {
el.classList.remove('gitea-selected');
});
}
},
selectItem(path, li, ev) {
if (ev.shiftKey && this.lastClickedPath) {
// Range select
var all = Array.from(document.querySelectorAll('.sidebar-item[data-gitea-path]'));
var startIdx = all.findIndex(function(el) { return el.getAttribute('data-gitea-path') === this.lastClickedPath; }.bind(this));
var endIdx = all.findIndex(function(el) { return el.getAttribute('data-gitea-path') === path; }.bind(this));
if (startIdx >= 0 && endIdx >= 0) {
var lo = Math.min(startIdx, endIdx);
var hi = Math.max(startIdx, endIdx);
this.selectedPaths = [];
for (var i = lo; i <= hi; i++) {
this.selectedPaths.push(all[i].getAttribute('data-gitea-path'));
all[i].classList.add('gitea-selected');
var cb = all[i].querySelector('.gitea-checkbox');
if (cb) cb.checked = true;
}
}
this.multiSelect = true;
this.toggleMultiSelect(); // ensure checkboxes are visible
} else if (ev.ctrlKey || ev.metaKey) {
// Toggle single
var idx = this.selectedPaths.indexOf(path);
if (idx >= 0) {
this.selectedPaths.splice(idx, 1);
li.classList.remove('gitea-selected');
var cb = li.querySelector('.gitea-checkbox');
if (cb) cb.checked = false;
} else {
this.selectedPaths.push(path);
li.classList.add('gitea-selected');
var cb = li.querySelector('.gitea-checkbox');
if (cb) cb.checked = true;
}
this.multiSelect = this.selectedPaths.length > 0;
this.toggleMultiSelect();
} else {
// Normal select — clear multi-selection
this.selectedPaths = [path];
this.lastClickedPath = path;
document.querySelectorAll('.sidebar-item.gitea-selected').forEach(function(el) {
el.classList.remove('gitea-selected');
});
li.classList.add('gitea-selected', 'active');
var cb = li.querySelector('.gitea-checkbox');
if (cb) cb.checked = true;
}
},
isSelected(path) {
return this.selectedPaths.indexOf(path) >= 0;
},
// ── Inline rename ──
startInlineRename(nameSpan, path, li) {
var originalName = nameSpan.textContent;
var input = document.createElement('input');
input.type = 'text';
input.value = originalName;
input.className = 'inline-rename-input';
input.style.cssText = 'flex:1;min-width:0;padding:2px 6px;background:var(--bg-tertiary);border:1px solid var(--accent);border-radius:4px;color:var(--text);font-size:13px;outline:none;';
nameSpan.replaceWith(input);
input.focus();
input.select();
var self = this;
var finish = function() { self.finishInlineRename(input, originalName, path, li); };
var cancel = function() {
var span = document.createElement('span');
span.className = 'page-name';
span.textContent = originalName;
input.replaceWith(span);
};
input.addEventListener('blur', finish);
input.addEventListener('keydown', function(e) {
if (e.key === 'Enter') finish();
if (e.key === 'Escape') { e.stopPropagation(); cancel(); }
});
},
finishInlineRename(input, originalName, path, li) {
if (input._renaming) return; // guard against double-fire
input._renaming = true;
var newName = input.value.trim();
if (!newName || newName === originalName) {
var span = document.createElement('span');
span.className = 'page-name';
span.textContent = originalName;
input.replaceWith(span);
return;
}
var self = this;
// Construct new path by replacing the last segment
var parts = path.split('/');
parts.pop();
var newPath = (parts.length > 0 ? parts.join('/') + '/' : '') + newName;
fetch('/api/gitea/projects/' + this.owner + '/' + this.repo + '/rename', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-CSRF-Token': this.getCsrfToken()},
body: JSON.stringify({old_path: path, new_path: newPath, new_name: newName})
}).then(function(r) {
if (r.ok) {
self.refreshTree();
} else {
var span = document.createElement('span');
span.className = 'page-name';
span.textContent = originalName;
input.replaceWith(span);
window.showToast('Rename failed', 'error');
}
}).catch(function() {
var span = document.createElement('span');
span.className = 'page-name';
span.textContent = originalName;
input.replaceWith(span);
});
},
};
});
});
</script>
<div class="gw-main" x-data="giteaWorkspace">
<!-- File view -->
<div x-show="showFile && !showEditor" x-transition>
<div class="gw-file-toolbar">
<strong x-text="filePath || ''"></strong>
<span x-text="formatSize(fileSize)"></span>
<span style="flex:1;"></span>
<button class="btn" @click="openEditor()">✏️ Edit</button>
<button class="btn btn-danger" @click="deleteCurrentFile()">🗑 Delete</button>
</div>
<div class="gw-content">
<!-- Skeleton loading -->
<div x-show="fileLoading" class="skeleton-file">
<div class="skeleton" style="height:15px;width:60%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:80%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:40%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:75%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:55%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:90%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:35%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:65%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:45%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:70%;margin-bottom:12px;"></div>
<div class="skeleton" style="height:15px;width:50%;"></div>
</div>
<!-- Syntax-highlighted code -->
<pre x-show="!fileLoading"><code :class="'language-'+fileLanguage" x-ref="codeBlock" x-text="fileContent"></code></pre>
</div>
</div>
<!-- Editor view -->
<template x-if="showEditor">
<div>
<div class="gw-file-toolbar">
<strong>Editing: <span x-text="filePath || 'new file'"></span></strong>
<span style="flex:1;"></span>
<button class="btn" @click="showEditor=false">Cancel</button>
</div>
<div class="gw-content">
<textarea x-model="editContent"></textarea>
</div>
<div class="gw-commit-bar">
<input type="text" x-model="commitMessage" placeholder="Commit message" list="commit-history">
<datalist id="commit-history">
<template x-for="msg in commitHistory" :key="msg">
<option :value="msg">
</template>
</datalist>
<button class="btn-primary" @click="saveFile()">💾 Commit</button>
</div>
</div>
</template>
<!-- File tree browser (like local-workspace) -->
<template x-if="!showFile && !showEditor && !showPrivate">
<div class="gw-content">
<!-- Breadcrumb -->
<div class="gw-breadcrumb" style="display:flex;align-items:center;gap:4px;margin-bottom:16px;font-size:14px;color:var(--text-secondary);">
<a href="#" @click.prevent="navigateToRoot()" style="color:var(--text-secondary);text-decoration:none;" x-text="owner + '/' + repo"></a>
<template x-for="(b, i) in folderStack" :key="i">
<span style="display:contents;">
<span style="color:var(--text-tertiary);">/</span>
<a href="#" @click.prevent="navigateToFolder(i)" style="color:var(--text-secondary);text-decoration:none;" x-text="b"></a>
</span>
</template>
<span x-show="treeLoading" style="color:var(--text-tertiary);">Loading...</span>
</div>
<!-- Tree items -->
<div x-show="!treeLoading">
<template x-if="treeItems.length === 0">
<div class="empty-state">
<h2>📁 Empty</h2>
<p>No files in this folder</p>
<button class="btn btn-primary" @click="showNewFile=!showNewFile">📄+ New file</button>
</div>
</template>
<div class="ws-tree">
<template x-for="item in sortedTreeItems" :key="item.path">
<div class="ws-tree-item"
@click="item.type==='folder' ? drillDown(item.path) : openFile(item.path, item.sha)"
@contextmenu.prevent="openGwContext($event, item)"
style="display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:6px;cursor:pointer;">
<span x-text="item.type==='folder' ? '📁' : '📄'" style="font-size:16px;"></span>
<span x-text="item.name" style="flex:1;font-size:14px;" :style="{ fontWeight: item.type==='folder' ? '500' : '400' }"></span>
<span x-text="item.type==='folder' ? '' : formatSize(item.size)" style="font-size:12px;color:var(--text-tertiary);"></span>
</div>
</template>
</div>
<!-- Context menu -->
<div class="gw-context-menu"
x-show="gwCtx.visible"
:style="'left:' + gwCtx.x + 'px; top:' + gwCtx.y + 'px'"
@click.outside="gwCtx.visible = false"
style="display:none;position:fixed;background:var(--bg-modal);border:1px solid var(--border);border-radius:var(--radius-md);box-shadow:var(--shadow-popover);z-index:1100;min-width:160px;padding:4px;">
<div class="ctx-item" @click="gwRename()">✏️ Rename</div>
<div class="ctx-item ctx-danger" @click="gwDelete()">🗑 Delete</div>
</div>
</div>
<!-- New file form -->
<div x-show="showNewFile" style="margin-top:16px;max-width:400px;">
<input type="text" x-model="newFilePath" placeholder="path/to/file.md" class="settings-input" style="margin-bottom:8px;">
<textarea x-model="newFileContent" placeholder="File content..." class="settings-input" style="height:120px;margin-bottom:8px;"></textarea>
<input type="text" x-model="newFileMsg" placeholder="Commit message" class="settings-input" style="margin-bottom:8px;">
<button class="btn btn-primary" @click="createNewFile()">💾 Create file</button>
</div>
</div>
</template>
<!-- Private pages view -->
<template x-if="showPrivate && !editingPrivate">
<div class="gw-content">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
<h3>🔒 Private Pages</h3>
<button class="btn btn-primary" onclick="window.FlowDeck.createPage()">+ New Page</button>
</div>
<template x-if="privatePages.length === 0">
<div class="empty-state" style="padding:40px 20px;">
<p>No private pages yet. Create one to store notes linked to this project.</p>
</div>
</template>
<template x-for="pp in privatePages" :key="pp.id">
<div style="background:var(--bg-secondary);border:1px solid var(--border);border-radius:8px;padding:16px;margin-bottom:8px;cursor:pointer;display:flex;align-items:center;justify-content:space-between;"
@click="openPrivate(pp.id)">
<div>
<div style="font-weight:500;" x-text="pp.title"></div>
<div style="font-size:12px;color:var(--text-dim);" x-text="pp.updated_at ? new Date(pp.updated_at+'Z').toLocaleString() : ''"></div>
</div>
<button class="btn btn-danger" style="padding:4px 8px;font-size:11px;" @click.stop="deletePrivate(pp.id)">🗑</button>
</div>
</template>
</div>
</template>
<!-- Private page editor -->
<template x-if="editingPrivate">
<div>
<div class="gw-file-toolbar">
<strong>Editing: <span x-text="editingPrivateTitle || 'Untitled'"></span></strong>
<span style="flex:1;"></span>
<button class="btn" @click="savePrivate()">💾 Save</button>
<button class="btn" @click="editingPrivate=null;editingPrivateTitle='';editingPrivateContent='';">Cancel</button>
</div>
<div class="gw-content">
<input x-model="editingPrivateTitle" placeholder="Page title" style="width:100%;padding:10px 12px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:16px;margin-bottom:12px;outline:none;">
<textarea x-model="editingPrivateContent" placeholder="Start writing…" style="min-height:60vh;"></textarea>
</div>
</div>
</template>
</div>
{% endblock %}
+204
View File
@@ -0,0 +1,204 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FlowDeck — All-in-one workspace</title>
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
<style>
:root {
--bg: #191919;
--bg-card: #1e1e1e;
--text: #e0e0e0;
--text-dim: #999;
--accent: #2383E2;
--accent-hover: #2C8CEB;
--border: rgba(255,255,255,.06);
--radius: 12px;
}
*{margin:0;padding:0;box-sizing:border-box;}
body{
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;
background:var(--bg);
color:var(--text);
min-height:100vh;
display:flex;
flex-direction:column;
}
/* Nav */
.landing-nav{
display:flex;
align-items:center;
justify-content:space-between;
padding:16px 32px;
border-bottom:1px solid var(--border);
}
.landing-logo{
font-size:20px;
font-weight:700;
display:flex;
align-items:center;
gap:8px;
text-decoration:none;
color:var(--text);
}
.landing-nav-actions{
display:flex;
gap:12px;
align-items:center;
}
.btn{
padding:10px 20px;
border-radius:8px;
font-size:14px;
font-weight:500;
cursor:pointer;
text-decoration:none;
border:none;
transition:all .15s;
}
.btn-primary{
background:var(--accent);
color:#fff;
}
.btn-primary:hover{background:var(--accent-hover);}
.btn-secondary{
background:transparent;
color:var(--text);
border:1px solid var(--border);
}
.btn-secondary:hover{background:rgba(255,255,255,.05);}
/* Hero */
.hero{
text-align:center;
padding:80px 32px 60px;
max-width:720px;
margin:0 auto;
}
.hero h1{
font-size:clamp(2rem,5vw,3.2rem);
font-weight:800;
letter-spacing:-.5px;
margin-bottom:16px;
line-height:1.2;
}
.hero .gradient-text{
background:linear-gradient(135deg,#2383E2,#6C5CE7);
-webkit-background-clip:text;
-webkit-text-fill-color:transparent;
background-clip:text;
}
.hero p{
font-size:18px;
color:var(--text-dim);
line-height:1.6;
margin-bottom:32px;
}
.hero-actions{
display:flex;
gap:12px;
justify-content:center;
flex-wrap:wrap;
}
.hero-actions .btn{
font-size:15px;
padding:12px 28px;
}
/* Features grid */
.features{
display:grid;
grid-template-columns:repeat(auto-fit,minmax(260px,1fr));
gap:16px;
max-width:1000px;
margin:0 auto;
padding:0 32px 60px;
}
.feature-card{
background:var(--bg-card);
border:1px solid var(--border);
border-radius:var(--radius);
padding:28px 24px;
transition:border-color .15s;
}
.feature-card:hover{border-color:rgba(255,255,255,.12);}
.feature-icon{font-size:28px;margin-bottom:12px;}
.feature-card h3{font-size:16px;font-weight:600;margin-bottom:8px;}
.feature-card p{font-size:14px;color:var(--text-dim);line-height:1.5;}
/* Footer */
.landing-footer{
margin-top:auto;
text-align:center;
padding:32px;
border-top:1px solid var(--border);
font-size:13px;
color:var(--text-dim);
}
</style>
</head>
<body>
<nav class="landing-nav">
<a href="/" class="landing-logo">
<span>📚</span> FlowDeck
</a>
<div class="landing-nav-actions">
<a href="/auth/login?provider=local" class="btn btn-secondary">Log in</a>
<a href="/auth/register" class="btn btn-primary">Get started free</a>
</div>
</nav>
<section class="hero">
<h1>Your <span class="gradient-text">Notion-style</span> workspace,<br>self-hosted & integrated</h1>
<p>
Write, organize, and collaborate — with block-based editing,
Kanban boards, databases, and deep Gitea/GitHub integration.
All on your own server.
</p>
<div class="hero-actions">
<a href="/auth/register" class="btn btn-primary">🚀 Get started — it's free</a>
<a href="/auth/login?provider=local" class="btn btn-secondary">I already have an account</a>
</div>
</section>
<div class="features">
<div class="feature-card">
<div class="feature-icon">📝</div>
<h3>Block Editor</h3>
<p>Notion-style editor with slash commands, markdown shortcuts, headings, code blocks, to-dos, and more.</p>
</div>
<div class="feature-card">
<div class="feature-icon">📊</div>
<h3>Kanban & Tables</h3>
<p>Visual project management with drag-drop boards, table views, and database collections.</p>
</div>
<div class="feature-card">
<div class="feature-icon">🦎</div>
<h3>Gitea & GitHub</h3>
<p>Browse repos, edit files, commit changes — all from your workspace sidebar.</p>
</div>
<div class="feature-card">
<div class="feature-icon">🌐</div>
<h3>Publish to Web</h3>
<p>One-click publish any page to a public URL. Share with anyone, no account needed.</p>
</div>
<div class="feature-card">
<div class="feature-icon">🔒</div>
<h3>Self-Hosted</h3>
<p>Your data stays on your server. No vendor lock-in, full control, Docker single-container deploy.</p>
</div>
<div class="feature-card">
<div class="feature-icon">⚡</div>
<h3>Fast & Light</h3>
<p>Alpine.js + FastAPI + SQLite. No React bloat, no Node.js needed. Sub-100ms page loads.</p>
</div>
</div>
<footer class="landing-footer">
FlowDeck v4.0.1 — Open source · Self-hosted · Notion-compatible
</footer>
</body>
</html>
+1258 -104
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+251 -56
View File
@@ -1,47 +1,18 @@
{% extends "base.html" %} {% block page_icon %}📄{% endblock %} {% block
{% extends "base.html" %} {% block page_icon %}{% if page.content_format == 'file' %}📎{% else %}📄{% endif %}{% endblock %} {% block
page_title %}{{ page.title }}{% endblock %} {% block topbar %}
<header class="topbar" style="background:var(--bg-primary);">
<button class="hamburger-btn" @click="mobileSidebarOpen = true; sidebarCollapsed = false;" title="Menu">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="topbar-left">
<span class="breadcrumb" style="color:rgba(255,255,255,.5);font-size:13px">{{ page.title }}</span>
</div>
</header>
{% set page_icon = "📄" if page.content_format != 'file' else "📎" %}
{% set page_title = page.title %}
{% set right_actions = '<span class="topbar-edited" style="cursor:pointer;" @click="window.E && window.E.toggleActivityOpen()">Edited <span x-text="window.E && window.E.timeAgo || \'\'"></span> ▾</span><button class="topbar-btn share-btn" @click="window.E && window.E.toggleShareOpen()">🔒 Share ▾</button><button class="topbar-btn" @click="window.E && window.E.copyPageLink()" title="Copy link">🔗</button><button class="topbar-btn star-btn" @click="window.E && window.E.toggleFavorite()" x-text="(window.E && window.E.favorited) ? \'⭐\' : \'☆\'"></button><button class="topbar-btn relative" @click="window.E && window.E.toggleMoreOpen()">⋯</button>' %}
{% include '_header.html' %}
{% endblock %} {% block content %}
<div class="page-editor-wrapper" x-data="editorState()">
<!-- ═══════════ Top Action Bar ═══════════ -->
<div class="page-topbar">
<div class="page-topbar-right" style="position: relative">
<span class="topbar-edited">Edited just now</span>
<button
class="page-action-btn share-btn"
@click="shareOpen = !shareOpen"
>
🔒 Share <span class="chevron-down">▾</span>
</button>
<button
class="page-action-btn"
@click="copyPageLink"
title="Copy link"
>
🔗
</button>
<button class="page-action-btn star-btn" @click="toggleFavorite">
<span
x-text="favorited ? '⭐' : '☆'"
:class="{ starred: favorited }"
></span>
</button>
<button class="page-action-btn" @click="moreOpen = !moreOpen">
⋮
</button>
<!-- Share/More dialogs (in content area, triggered by header buttons) -->
<!-- ═══════════ Share / Publish Dialog ═══════════ -->
<div
class="share-dialog"
x-show="shareOpen"
@click.away="shareOpen = false"
@click.outside="!_justOpened && (shareOpen = false)"
x-transition.opacity.scale.origin.top.right
>
<!-- Header with tabs -->
@@ -75,9 +46,9 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
class="sd-input"
placeholder="Add people, groups or emails..."
x-model="inviteEmail"
@keydown.enter="invitePerson"
@keydown.enter="shareInvite()"
/>
<button class="sd-btn-primary" @click="invitePerson">
<button class="sd-btn-primary" @click="shareInvite()">
Invite
</button>
</div>
@@ -121,7 +92,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
<div
class="sd-perm-menu"
x-show="a.permOpen"
@click.away="a.permOpen = false"
@click.outside="a.permOpen = false"
>
<div
class="sd-perm-option"
@@ -184,7 +155,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
<div
class="sd-access-menu"
x-show="accessMenuOpen"
@click.away="accessMenuOpen = false"
@click.outside="accessMenuOpen = false"
x-transition
>
<div
@@ -268,7 +239,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
</p>
<button
class="sd-btn-primary sd-btn-full"
@click="pagePublished = true"
@click="publishPage()"
>
Publish
</button>
@@ -354,7 +325,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
<button
class="sd-danger-btn"
@click="pagePublished = false"
@click="unpublishPage()"
>
Unpublish
</button>
@@ -362,11 +333,23 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
</div>
</div>
<!-- ═══════════ Activity Popover ═══════════ -->
<div class="activity-popover"
x-show="activityOpen"
@click.outside="!_justOpened && (activityOpen = false)"
x-transition.opacity.scale.origin.top.right
style="position:absolute;top:100%;right:0;margin-top:4px;background:var(--bg-modal);border:1px solid var(--border);border-radius:var(--radius-lg);box-shadow:var(--shadow-modal);z-index:1000;width:280px;padding:12px;">
<div style="font-size:12px;color:var(--text-secondary);margin-bottom:4px;">Edited <span x-text="timeAgo"></span></div>
<template x-if="pageCreated">
<div style="font-size:12px;color:var(--text-tertiary);">Created <span x-text="formatDate(pageCreated)"></span></div>
</template>
</div>
<!-- More menu dropdown -->
<div
class="more-menu"
x-show="moreOpen"
@click.away="moreOpen = false"
@click.outside="!_justOpened && (moreOpen = false)"
x-transition
>
<div class="more-menu-item" @click="exportPage">↗ Export</div>
@@ -379,13 +362,35 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
🗑️ Move to Trash
</div>
</div>
<!-- ═══════════ Move to Dialog ═══════════ -->
<div class="move-dialog"
x-show="moveOpen"
@click.outside="moveOpen = false"
x-transition.opacity.scale
style="position:absolute;top:100%;right:0;margin-top:4px;background:var(--bg-modal);border:1px solid var(--border);border-radius:var(--radius-lg);box-shadow:var(--shadow-modal);z-index:1000;width:320px;padding:16px;">
<h3 style="font-size:14px;margin-bottom:12px;">Move to workspace</h3>
<div x-show="moveLoading" style="color:var(--text-tertiary);text-align:center;padding:20px;">Loading...</div>
<div x-show="!moveLoading" style="max-height:240px;overflow-y:auto;">
<template x-for="ws in moveWorkspaces" :key="ws.id">
<div class="move-ws-item"
@click="doMove(ws.id)"
style="display:flex;align-items:center;gap:8px;padding:8px 10px;border-radius:6px;cursor:pointer;font-size:13px;">
<span>📁</span>
<span x-text="ws.name" style="flex:1;"></span>
<span style="font-size:11px;color:var(--text-tertiary);" x-text="ws.page_count + ' pages'"></span>
</div>
</template>
<div x-show="moveWorkspaces.length === 0" style="color:var(--text-tertiary);text-align:center;padding:12px;">
No workspaces available
</div>
</div>
</div>
<!-- ═══════════ Page Content ═══════════ -->
<div class="page-cover-area">
<div class="page-title-block">
<span class="page-icon-emoji">📄</span>
<span class="page-icon-emoji">{% if page.content_format == 'file' %}📎{% else %}📄{% endif %}</span>
<div
class="page-title-input"
contenteditable="true"
@@ -475,7 +480,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
<div
class="gs-more-dropdown"
x-show="gsMoreOpen"
@click.away="gsMoreOpen = false"
@click.outside="gsMoreOpen = false"
x-transition
>
<div class="gs-more-item" @click="gsMoreOpen=false">
@@ -518,6 +523,7 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
{{ page_data | tojson }}
</script>
<script>
/* eslint-disable */
const CMDS=[{name:'BASIC',items:[
{id:'paragraph',name:'Text',icon:'¶'},{id:'heading_1',name:'Heading 1',icon:'H1'},{id:'heading_2',name:'Heading 2',icon:'H2'},
{id:'heading_3',name:'Heading 3',icon:'H3'},{id:'heading_4',name:'Heading 4',icon:'H4'},{id:'bulleted_list',name:'Bulleted list',icon:'•'},{id:'numbered_list',name:'Numbered list',icon:'1.'},
@@ -567,6 +573,14 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
function renderBlock(b,idx){
if(b.type==='divider')return `<div class="block-wrapper"><hr class="block-divider"></div>`;
if(b.type==='image')return `<div class="block-wrapper"><div class="block-content block-image" style="text-align:center;padding:12px 0;"><img src="${b.src||''}" alt="${esc(b.alt||'')}" style="max-width:100%;max-height:70vh;border-radius:8px;display:block;margin:0 auto;" onerror="this.style.display='none';this.parentElement.innerHTML='<div style=\\'padding:40px;color:var(--text-tertiary)\\'>Image not found</div>'"></div></div>`;
if(b.type==='embed'){
if(b.embed_type==='pdf')return `<div class="block-wrapper"><div class="block-content block-embed" style="padding:0;"><iframe src="${b.src||''}" style="width:100%;height:80vh;border:none;border-radius:8px;"></iframe></div></div>`;
if(b.embed_type==='download'){
var sz=b.file_size||0;var szStr=sz<1024?sz+' B':sz<1048576?(sz/1024).toFixed(1)+' KB':(sz/1048576).toFixed(1)+' MB';
return `<div class="block-wrapper"><div class="block-content block-embed" style="text-align:center;padding:60px 20px;"><div style="font-size:48px;margin-bottom:12px;">📎</div><div style="font-size:16px;font-weight:500;color:var(--text-primary);margin-bottom:4px;">${esc(b.file_name||'File')}</div><div style="font-size:12px;color:var(--text-tertiary);margin-bottom:16px;">${szStr} · ${esc(b.file_mime||'')}</div><a href="${b.src||''}" download style="display:inline-block;padding:8px 20px;background:var(--accent);color:#fff;text-decoration:none;border-radius:8px;font-size:13px;font-weight:500;">⬇ Download</a></div></div>`;
}
}
const ph=b.type==='heading_1'?'Heading 1':b.type==='heading_2'?'Heading 2':b.type==='heading_3'?'Heading 3':b.type==='heading_4'?'Heading 4':b.type==='bulleted_list'?'List':b.type==='numbered_list'?'List':b.type==='to_do'?'To-do':b.type==='toggle'?'Toggle list':b.type==='quote'?'Empty quote':b.type==='code'?'Type code...':b.type==='callout'?'Type something...':'Press \'/\' for commands...';
let inner='';
if(b.type==='to_do')inner=`<input type="checkbox" class="todo-checkbox" ${b.checked?'checked':''} onchange="E._doToggle('${b.id}',this.checked)"><div data-bid="${b.id}" contenteditable="true" data-placeholder="${ph}" spellcheck="false">${esc(b.content)}</div>`;
@@ -588,8 +602,11 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
function editorState(){
return {
pid:null,pageTitle:'',blocks:[],dirty:false,saving:false,lastSaved:'',st:null,
updatedAt:'{{ page.get("updated_at", "") }}',
fmt:{open:false,top:0,left:0,idx:-1},
shareOpen:false,moreOpen:false,gsMoreOpen:false,accessMenuOpen:false,
moveOpen:false,moveWorkspaces:[],moveLoading:false,
activityOpen:false,pageCreated:'{{ page.get("created_at", "") }}',
shareTab:'share',favorited:false,
pagePublished:{{ page_published | tojson }},
generalAccess:'{{ page_share_mode }}',publicPerm:'viewer',
@@ -597,11 +614,26 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
pageUrl:window.location.href,publishedUrl:'',
inviteEmail:'',invitePermission:'editor',accessList:[],
toastVisible:false,toastMsg:'',
get timeAgo() {
if (!this.updatedAt) return 'just now';
var diff = Math.floor((Date.now() - new Date(this.updatedAt + 'Z').getTime()) / 1000);
if (diff < 60) return 'just now';
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
return Math.floor(diff / 86400) + 'd ago';
},
formatDate(d) {
if (!d) return '';
var dt = new Date(d + 'Z');
return dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) +
' at ' + dt.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
},
init(){
_bid=Math.floor(Math.random()*10000);
const dataEl=document.getElementById('page-data');
if(dataEl){try{const data=JSON.parse(dataEl.textContent);this.pid=data.id;this.pageTitle=data.title||'';this.favorited=data.favorited||false;const fmt=data.content_format||'blocks';const raw=data.content||'';
if(fmt==='blocks'&&raw){try{this.blocks=JSON.parse(raw);this.blocks.forEach(b=>{if(!b.id)b.id=genId()});}catch(e){this.blocks=[];}}
if(fmt==='file'){this.fileData=data;this.loadFileContent(data);}
else if(fmt==='blocks'&&raw){try{this.blocks=JSON.parse(raw);this.blocks.forEach(b=>{if(!b.id)b.id=genId()});}catch(e){this.blocks=[];}}
else if(raw&&raw.trim())this.blocks=this.md2b(raw);}catch(e){}}
if(!this.blocks.length)this.blocks=[this.mkB('paragraph','')];
window.E=this;SM.init();this.render();
@@ -611,13 +643,36 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
if(typeof Sortable!=='undefined')Sortable.create(ct,{draggable:'.block-wrapper',handle:'.block-handle',animation:150,ghostClass:'sortable-ghost',dragClass:'sortable-drag',onEnd:evt=>{if(evt.oldIndex===evt.newIndex)return;const[item]=this.blocks.splice(evt.oldIndex,1);this.blocks.splice(evt.newIndex,0,item);this.dirty=true;this.autoSave();this.render();}});
},100);
},
fileData:null,
async loadFileContent(data){
const url=data.file_url||'';const mime=data.file_mime||'';const name=data.file_name||'';const self=this;
if(!url){this.blocks=[this.mkB('paragraph','File not available')];this.render();return;}
const ext=name.toLowerCase().split('.').pop();
if(mime.startsWith('image/')||['png','jpg','jpeg','gif','webp','svg','bmp','ico'].includes(ext)){
this.blocks=[this.mkB('image','',{src:url,alt:name})];this.render();return;
}
if(mime==='application/pdf'||ext==='pdf'){
this.blocks=[this.mkB('embed','',{src:url,embed_type:'pdf'})];this.render();return;
}
const codeExts=['py','js','ts','jsx','tsx','html','htm','css','json','xml','yaml','yml','md','markdown','sql','sh','bash','ps1','bat','cmd','rb','go','rs','java','c','cpp','h','hpp','php','swift','kt','scala','r','toml','ini','cfg','conf','env','txt','log'];
const langMap={'py':'python','js':'javascript','ts':'typescript','jsx':'javascript','tsx':'typescript','html':'html','htm':'html','css':'css','json':'json','xml':'xml','yaml':'yaml','yml':'yaml','md':'markdown','markdown':'markdown','sql':'sql','sh':'bash','bash':'bash','ps1':'powershell','bat':'plaintext','cmd':'plaintext','rb':'ruby','go':'go','rs':'rust','java':'java','c':'c','cpp':'cpp','h':'c','hpp':'cpp','php':'php','swift':'swift','kt':'kotlin','scala':'scala','r':'r','toml':'toml','ini':'ini','cfg':'ini','conf':'ini','env':'ini','txt':'plaintext','log':'plaintext'};
if(mime.startsWith('text/')||codeExts.includes(ext)){
try{const r=await fetch(url);const text=await r.text();
if(ext==='md'||ext==='markdown'){this.blocks=this.md2b(text);}
else{this.blocks=[this.mkB('code',text,{language:langMap[ext]||'Plain Text'})];}
this.render();
}catch(e){this.blocks=[this.mkB('paragraph','Error loading file: '+e.message)];this.render();}
return;
}
this.blocks=[this.mkB('embed','',{src:url,embed_type:'download',file_name:name,file_size:data.file_size||0,file_mime:mime})];this.render();
},
mkB(type,content,extras){const b={id:genId(),type,content:content||'',...(extras||{})};if(type==='toggle')b.expanded=true;if(type==='to_do')b.checked=false;return b;},
getEl(bid){const ct=document.getElementById('_blocksCt');return ct?ct.querySelector(`[data-bid="${bid}"]`):null;},
getIdx(bid){return this.blocks.findIndex(b=>b.id===bid);},
getActiveBlock(){const el=document.activeElement;if(!el||!el.hasAttribute('data-bid'))return null;return{el,bid:el.dataset.bid,idx:this.getIdx(el.dataset.bid)};},
focusBlock(){const b=this.blocks[0];if(!b)return;const el=this.getEl(b.id);if(el){el.focus();ce(el);}},
onCtClick(e){if(e.target===document.getElementById('_blocksCt')||e.target?.classList?.contains('blocks-empty')){if(!this.blocks.length)this.addAt(0);else{const b=this.blocks[this.blocks.length-1];const el=b&&this.getEl(b.id);if(el){el.focus();ce(el);}}}},
sync(){const ct=document.getElementById('_blocksCt');if(!ct)return;for(const b of this.blocks){if(b.type==='divider')continue;const el=ct.querySelector(`[data-bid="${b.id}"]`);if(el)b.content=el.textContent||'';}},
sync(){const ct=document.getElementById('_blocksCt');if(!ct)return;for(const b of this.blocks){if(b.type==='divider'||b.type==='image'||b.type==='embed')continue;const el=ct.querySelector(`[data-bid="${b.id}"]`);if(el)b.content=el.textContent||'';}},
render(){const ct=document.getElementById('_blocksCt');if(!ct)return;let html='';for(let i=0;i<this.blocks.length;i++)html+=renderBlock(this.blocks[i],i);ct.innerHTML=html;
ct.querySelectorAll('.block-wrapper').forEach(w=>{w.onmouseenter=()=>{w.querySelector('.block-handle')?.classList.add('visible');w.querySelector('.block-actions')?.classList.add('visible');};w.onmouseleave=()=>{w.querySelector('.block-handle')?.classList.remove('visible');w.querySelector('.block-actions')?.classList.remove('visible');};});
ct.querySelectorAll('[data-placeholder]').forEach(el=>{el.innerHTML=el.innerHTML.replace(/<br[^>]*>/gi,'').trim()!==''?el.innerHTML:'';el.classList.toggle('empty',!el.textContent.trim());});
@@ -631,14 +686,30 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
const csrf=document.cookie.match(/csrf_token=([^;]+)/);
const m=this.favorited?'DELETE':'POST';
fetch(`/board/api/favorites/${this.pid}`,{method:m,headers:{'X-CSRF-Token':csrf?csrf[1]:''}})
.then(r=>r.json()).then(()=>{this.favorited=!this.favorited;}).catch(()=>{});
.then(r=>r.json()).then(()=>{this.favorited=!this.favorited;this.showToast(this.favorited?'Added to favorites':'Removed from favorites');
if(window.appState&&window.appState.refreshFavorites)window.appState.refreshFavorites();
}).catch(()=>{this.showToast('Failed to toggle favorite');});
},
toggleActivityOpen(){
if(!this.activityOpen){this.activityOpen=true;this._justOpened=true;setTimeout(()=>this._justOpened=false,200);}
else{this.activityOpen=false;}
},
toggleShareOpen(){
if(!this.shareOpen){this.shareOpen=true;this._justOpened=true;setTimeout(()=>this._justOpened=false,200);}
else{this.shareOpen=false;}
},
toggleMoreOpen(){
if(!this.moreOpen){this.moreOpen=true;this._justOpened=true;setTimeout(()=>this._justOpened=false,200);}
else{this.moreOpen=false;}
},
_justOpened:false,
togglePublish(){this.pagePublished=!this.pagePublished;this.saveShare();},
saveShare(){
const csrf=document.cookie.match(/csrf_token=([^;]+)/);
fetch(`/board/api/share/${this.pid}`,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':csrf?csrf[1]:''},body:JSON.stringify({mode:this.generalAccess,published:this.pagePublished})}).catch(()=>{});
},
copyPageLink(){
async copyPageLink(){
console.log('copyPageLink invoked');
const url = this.pageUrl;
const fallback = () => {
const ta = document.createElement('textarea');
@@ -647,9 +718,8 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
document.execCommand('copy'); document.body.removeChild(ta);
};
try {
navigator.clipboard.writeText(url).then(() => {
await navigator.clipboard.writeText(url);
this.showToast('Link copied to clipboard');
}).catch(() => { fallback(); this.showToast('Link copied to clipboard'); });
} catch(e) { fallback(); this.showToast('Link copied to clipboard'); }
},
showToast(msg){
@@ -657,12 +727,119 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
clearTimeout(this._toastTimer);
this._toastTimer = setTimeout(() => { this.toastVisible = false; }, 2500);
},
publishPage() {
var self = this;
var csrf = document.cookie.match(/csrf_token=([^;]+)/);
fetch('/api/pages/' + this.pid + '/publish', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf ? csrf[1] : '' }
}).then(function(r){ return r.json(); }).then(function(d){
if (d.is_published) {
self.pagePublished = true;
self.publishedUrl = window.location.origin + '/p/' + d.publish_slug;
self.showToast('Published to web — ' + self.publishedUrl);
} else {
self.showToast(d.detail || 'Publish failed');
}
}).catch(function(){ self.showToast('Publish failed'); });
},
unpublishPage() {
var self = this;
var csrf = document.cookie.match(/csrf_token=([^;]+)/);
fetch('/api/pages/' + this.pid + '/publish', {
method: 'DELETE',
headers: { 'X-CSRF-Token': csrf ? csrf[1] : '' }
}).then(function(r){ return r.json(); }).then(function(d){
if (!d.is_published) {
self.pagePublished = false;
self.publishedUrl = '';
self.showToast('Unpublished');
} else {
self.showToast(d.detail || 'Unpublish failed');
}
}).catch(function(){ self.showToast('Unpublish failed'); });
},
shareInvite() {
var self = this;
if (!this.inviteEmail.trim()) return;
var csrf = document.cookie.match(/csrf_token=([^;]+)/);
fetch('/api/pages/' + this.pid + '/share', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf ? csrf[1] : '' },
body: JSON.stringify({ email: this.inviteEmail.trim(), permission: this.invitePermission })
}).then(function(r){ return r.json(); }).then(function(d){
if (d.status === 'shared') { self.inviteEmail = ''; self.showToast('Invitation sent'); self.loadShares(); }
else { self.showToast(d.detail || 'Share failed'); }
}).catch(function(){ self.showToast('Share failed'); });
},
loadShares() {
var self = this;
fetch('/api/pages/' + this.pid + '/shares').then(function(r){ return r.json(); }).then(function(d){
self.accessList = d.shares || [];
}).catch(function(){ self.accessList = []; });
},
removeShare(sid) {
var self = this;
var csrf = document.cookie.match(/csrf_token=([^;]+)/);
fetch('/api/pages/' + this.pid + '/share/' + sid, {
method: 'DELETE',
headers: { 'X-CSRF-Token': csrf ? csrf[1] : '' }
}).then(function(r){ return r.json(); }).then(function(d){
if (d.status === 'removed') { self.showToast('Share removed'); self.loadShares(); }
else { self.showToast(d.detail || 'Remove failed'); }
}).catch(function(){ self.showToast('Remove failed'); });
},
invitePerson(){if(!this.inviteEmail.trim())return;this.accessList.push({email:this.inviteEmail,permission:this.invitePermission,permOpen:false});this.inviteEmail='';},
removeAccess(email){this.accessList=this.accessList.filter(a=>a.email!==email);},
exportPage(){this.moreOpen=false;},
duplicatePage(){this.moreOpen=false;const csrf=document.cookie.match(/csrf_token=([^;]+)/);fetch(`/board/api/pages?title=${encodeURIComponent(this.pageTitle+' copy')}&section=Private&project=${encodeURIComponent('{{ workspace_key }}')}`,{method:'POST',headers:{'X-CSRF-Token':csrf?csrf[1]:''}}).then(r=>r.json()).then(d=>{window.location.href=`/pages/${d.id}`;}).catch(()=>{alert('Duplicate failed');});},
movePage(){this.moreOpen=false;},
deletePage(){this.moreOpen=false;if(!confirm('Move to Trash?'))return;const csrf=document.cookie.match(/csrf_token=([^;]+)/);fetch(`/board/api/pages/${this.pid}/trash`,{method:'POST',headers:{'X-CSRF-Token':csrf?csrf[1]:''}}).then(()=>{window.location.href='/';}).catch(()=>{alert('Failed');});},
exportPage(){
this.moreOpen=false;
// Export blocks as Markdown
var md = '# ' + (this.pageTitle || 'Untitled') + '\n\n';
for (var i = 0; i < this.blocks.length; i++) {
var b = this.blocks[i];
md += blocksToMarkdown(b) + '\n\n';
}
var blob = new Blob([md], {type: 'text/markdown'});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url; a.download = (this.pageTitle || 'export') + '.md';
a.click(); URL.revokeObjectURL(url);
this.showToast('Exported as Markdown');
},
duplicatePage(){this.moreOpen=false;const csrf=document.cookie.match(/csrf_token=([^;]+)/);fetch(`/board/api/pages?title=${encodeURIComponent(this.pageTitle+' copy')}&section=Private&project=${encodeURIComponent('{{ workspace_key }}')}`,{method:'POST',headers:{'X-CSRF-Token':csrf?csrf[1]:''}}).then(r=>r.json()).then(d=>{window.location.href=`/pages/${d.id}`;}).catch(()=>{window.showToast('Duplicate failed','error');});},
movePage(){
this.moreOpen=false;
this.moveOpen = true;
this.moveLoading = true;
var self = this;
fetch('/api/workspaces')
.then(function(r){ return r.json(); })
.then(function(d){
self.moveWorkspaces = d.workspaces || [];
self.moveLoading = false;
})
.catch(function(){ self.moveLoading = false; });
},
doMove(wsId) {
this.moveOpen = false;
var csrf = document.cookie.match(/csrf_token=([^;]+)/);
var self = this;
fetch('/api/pages/' + this.pid + '/move', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf ? csrf[1] : '' },
body: JSON.stringify({ workspace_id: wsId })
}).then(function(r){ return r.json(); })
.then(function(d){
if (d.status === 'ok') {
self.showToast('Moved to workspace');
setTimeout(function(){ window.location.href = '/local-workspace'; }, 800);
} else {
self.showToast(d.detail || 'Move failed');
}
})
.catch(function(){ self.showToast('Move failed'); });
},
deletePage(){this.moreOpen=false;if(!confirm('Move to Trash?'))return;const csrf=document.cookie.match(/csrf_token=([^;]+)/);fetch(`/board/api/pages/${this.pid}/trash`,{method:'POST',headers:{'X-CSRF-Token':csrf?csrf[1]:''}}).then(()=>{window.location.href='/';}).catch(()=>{window.showToast('Failed','error');});},
onKd(e){
const ab=this.getActiveBlock();if(!ab)return;
@@ -720,8 +897,9 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
fmtApply(f){this.fmt.open=false;if(!this._sel)return;const s=window.getSelection();s.removeAllRanges();s.addRange(this._sel.range);document.execCommand(f==='strikeThrough'?'strikeThrough':f);this._sel=null;this.dirty=true;this.autoSave();},
fmtLink(){this.fmt.open=false;const u=prompt('URL:');if(u){document.execCommand('createLink',false,u);this.dirty=true;this.autoSave();}},
pastePlain(e){e.preventDefault();document.execCommand('insertText',false,(e.clipboardData||window.clipboardData).getData('text/plain'));this.dirty=true;this.autoSave();},
autoSave(){clearTimeout(this.st);this.st=setTimeout(()=>this.save(),1500);},
autoSave(){if(this.fileData)return;clearTimeout(this.st);this.st=setTimeout(()=>this.save(),1500);},
save(){
if(this.fileData)return;
if(this.saving)return;
this.sync();
const t=document.getElementById('_titleEl');if(t)this.pageTitle=t.textContent?.trim()||'New page';
@@ -736,5 +914,22 @@ page_title %}{{ page.title }}{% endblock %} {% block topbar %}
};
}
document.addEventListener('mouseup',()=>{setTimeout(()=>{const s=window.getSelection();if(!s||s.isCollapsed)return;const ed=document.querySelector('.page-editor-wrapper');if(!ed?.__x)return;const d=ed.__x.$data;const ct=document.getElementById('_blocksCt');if(!ct?.contains(s.anchorNode))return;const bel=s.anchorNode.parentElement?.closest('[data-bid]');if(bel){const idx=d.getIdx(bel.dataset.bid);if(idx>=0)d.showFmt(idx);}},80);});
function blocksToMarkdown(b) {
var c = b.content || '';
switch(b.type) {
case 'heading_1': return '# ' + c;
case 'heading_2': return '## ' + c;
case 'heading_3': return '### ' + c;
case 'heading_4': return '#### ' + c;
case 'bulleted_list': return '- ' + c;
case 'numbered_list': return '1. ' + c;
case 'to_do': return (b.checked ? '- [x] ' : '- [ ] ') + c;
case 'quote': return '> ' + c;
case 'divider': return '---';
case 'code': return '```' + (b.language || '') + '\n' + c + '\n```';
case 'toggle': return '## ' + c;
default: return c;
}
}
</script>
{% endblock %}
+153
View File
@@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }} — FlowDeck</title>
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
<style>
:root {
--bg: #191919;
--bg-card: #1e1e1e;
--text: #e0e0e0;
--text-dim: #999;
--accent: #4c9aff;
--radius: 12px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
background: var(--bg);
color: var(--text);
line-height: 1.7;
min-height: 100vh;
}
.pub-header {
border-bottom: 1px solid rgba(255,255,255,.06);
padding: 14px 24px;
display: flex;
align-items: center;
justify-content: space-between;
background: rgba(255,255,255,.01);
backdrop-filter: blur(10px);
position: sticky;
top: 0;
z-index: 10;
}
.pub-brand {
font-size: 14px;
font-weight: 600;
color: var(--text);
text-decoration: none;
display: flex;
align-items: center;
gap: 8px;
}
.pub-brand span { font-size: 18px; }
.pub-badge {
font-size: 11px;
padding: 3px 10px;
background: rgba(76,154,255,.12);
color: var(--accent);
border-radius: 20px;
font-weight: 500;
}
.pub-container {
max-width: 800px;
margin: 0 auto;
padding: 40px 24px 80px;
}
.pub-title {
font-size: 2.5rem;
font-weight: 800;
margin-bottom: 8px;
letter-spacing: -.5px;
}
.pub-meta {
font-size: 13px;
color: var(--text-dim);
margin-bottom: 32px;
}
.pub-content {
font-size: 16px;
color: var(--text);
}
.pub-content p {
margin: 4px 0;
line-height: 1.7;
}
.pub-content h1, .pub-content h2, .pub-content h3, .pub-content h4 {
color: var(--text);
margin-bottom: 6px;
}
.pub-content pre {
background: rgba(255,255,255,.05);
padding: 16px 20px;
border-radius: 8px;
overflow-x: auto;
margin: 12px 0;
}
.pub-content code {
font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
font-size: 14px;
}
.pub-content blockquote {
border-left: 3px solid var(--accent);
margin: 12px 0;
padding: 4px 16px;
opacity: .85;
}
.pub-content img {
max-width: 100%;
border-radius: 8px;
}
.pub-content hr {
border: none;
border-top: 1px solid rgba(255,255,255,.08);
margin: 16px 0;
}
.pub-content details {
margin: 8px 0;
}
.pub-content summary {
cursor: pointer;
font-weight: 500;
}
.pub-footer {
text-align: center;
padding: 24px;
border-top: 1px solid rgba(255,255,255,.06);
font-size: 12px;
color: var(--text-dim);
}
.pub-footer a {
color: var(--accent);
text-decoration: none;
}
</style>
</head>
<body>
<header class="pub-header">
<a href="/" class="pub-brand">
<span>📚</span> FlowDeck
</a>
<span class="pub-badge">🌐 Published</span>
</header>
<main class="pub-container">
<h1 class="pub-title">{{ title }}</h1>
{% if updated_at %}
<div class="pub-meta">Last updated: {{ updated_at[:10] }}</div>
{% endif %}
<div class="pub-content">
{{ content_html | safe }}
</div>
</main>
<footer class="pub-footer">
Made with <a href="/">FlowDeck</a> — a Notion-style workspace
</footer>
</body>
</html>
+764 -153
View File
@@ -1,192 +1,803 @@
{% extends "base.html" %}
{% block page_title %}Account Settings{% endblock %}
{% block page_title %}Settings{% endblock %}
{% block title_prefix %}Settings{% endblock %}
{% block page_icon %}⚙️{% endblock %}
{% block topbar %}
<header class="topbar">
<button class="hamburger-btn" @click="mobileSidebarOpen = true; sidebarCollapsed = false;" title="Menu">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="topbar-left">
<span class="breadcrumb" style="color:rgba(255,255,255,.5)">
Settings
</span>
<span class="page-title-topbar">Account Settings</span>
</div>
<div class="topbar-right"></div>
</header>
{% set page_icon = "⚙" %}
{% set page_title = "Settings" %}
{% include '_header.html' %}
{% endblock %}
{% block content %}
<style>
.settings-layout{max-width:700px;margin:0 auto;padding:40px 24px;}
.settings-section{margin-bottom:32px;}
.settings-section h2{font-size:14px;color:rgba(255,255,255,.5);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;font-weight:500;}
.settings-card{background:#222;border:1px solid rgba(255,255,255,.08);border-radius:12px;overflow:hidden;}
.settings-row{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid rgba(255,255,255,.06);}
.settings-row:last-child{border-bottom:none;}
.settings-row-left{flex:1;}
.settings-row-label{font-size:14px;color:#fff;}
.settings-row-desc{font-size:12px;color:rgba(255,255,255,.45);margin-top:2px;}
.settings-row-value{font-size:13px;color:rgba(255,255,255,.5);margin-right:12px;}
.settings-input{background:#2A2A2A;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:8px 12px;color:#fff;font-size:13px;width:220px;outline:none;}
.settings-input:focus{border-color:#2383E2;}
.settings-btn{padding:8px 16px;border-radius:8px;font-size:13px;cursor:pointer;border:none;font-weight:500;}
.settings-btn-primary{background:#2383E2;color:#fff;}
.settings-btn-primary:hover{background:#2C8CEB;}
.settings-btn-danger{background:rgba(255,80,80,.15);color:#ff5050;}
.settings-btn-danger:hover{background:rgba(255,80,80,.25);}
.settings-btn-secondary{background:#333;color:#fff;}
.settings-btn-secondary:hover{background:#444;}
.inline-form{display:flex;align-items:center;gap:8px;}
.forge-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;background:#2A2A2A;border-radius:6px;font-size:12px;}
.connected{color:#50ff50;}
.disconnected{color:rgba(255,255,255,.3);}
.settings-overlay{position:fixed;inset:0;z-index:500;display:flex;background:rgba(0,0,0,.4);backdrop-filter:blur(2px);}
.settings-panel{display:flex;width:1050px;max-width:98vw;height:85vh;margin:auto;background:var(--bg-primary);border:1px solid var(--border-strong);border-radius:14px;box-shadow:var(--shadow-modal);overflow:hidden;}
.settings-nav{width:200px;min-width:200px;background:var(--bg-sidebar);border-right:1px solid var(--border);padding:8px 0;overflow-y:auto;}
.settings-nav-header{padding:12px 16px;font-size:13px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:.5px;}
.settings-nav-item{display:flex;align-items:center;gap:8px;padding:6px 16px;font-size:13px;color:var(--text-secondary);cursor:pointer;transition:background 100ms;border-radius:0;}
.settings-nav-item:hover{background:var(--bg-hover);}
.settings-nav-item.active{background:rgba(35,131,226,.12);color:var(--text);font-weight:500;}
.settings-content{flex:1;overflow-y:auto;padding:24px 32px;}
.settings-content h2{font-size:18px;font-weight:600;margin-bottom:4px;}
.settings-content .section-desc{font-size:12px;color:var(--text-dim);margin-bottom:24px;}
.setting-group{margin-bottom:28px;}
.setting-group h3{font-size:12px;text-transform:uppercase;letter-spacing:.5px;color:var(--text-dim);margin-bottom:8px;padding-bottom:4px;border-bottom:1px solid var(--border);}
.setting-row{display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border);}
.setting-row:last-child{border-bottom:none;}
.setting-label{font-size:14px;color:var(--text);}
.setting-desc{font-size:12px;color:var(--text-dim);margin-top:2px;}
.setting-control{flex-shrink:0;margin-left:16px;}
/* Avatar */
.avatar-section{display:flex;align-items:center;gap:16px;padding:12px 0;}
.avatar-preview{width:64px;height:64px;border-radius:50%;background:var(--bg-tertiary);display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:700;color:var(--text);overflow:hidden;flex-shrink:0;}
.avatar-preview img{width:100%;height:100%;object-fit:cover;}
.avatar-upload-label{cursor:pointer;font-size:13px;color:var(--accent);padding:6px 12px;border:1px solid var(--accent);border-radius:6px;transition:all 150ms;}
.avatar-upload-label:hover{background:rgba(35,131,226,.1);}
.avatar-upload-input{display:none;}
/* Avatar color swatches */
.avatar-color-swatch{width:40px;height:40px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;color:var(--text-primary);cursor:pointer;border:2px solid transparent;transition:all 120ms;}
.avatar-color-swatch:hover{transform:scale(1.1);}
.avatar-color-swatch.selected{border-color:var(--accent);box-shadow:0 0 0 2px rgba(35,131,226,.4);}
/* Tags */
.tag-mgmt-item{display:flex;align-items:center;gap:10px;padding:8px 10px;background:var(--bg-tertiary);border-radius:8px;margin-bottom:4px;}
.tag-mgmt-item .tag-color-dot{width:14px;height:14px;border-radius:50%;flex-shrink:0;}
.tag-name{flex:1;font-size:13px;color:var(--text);}
.tag-count{font-size:12px;color:var(--text-dim);}
.new-tag-form{display:flex;align-items:center;gap:10px;margin-top:8px;padding:8px 10px;background:var(--bg-tertiary);border:1px dashed var(--border);border-radius:8px;}
.new-tag-form input{flex:1;background:none;border:none;color:var(--text);font-size:13px;outline:none;}
.color-swatch{width:22px;height:22px;border-radius:6px;cursor:pointer;border:2px solid transparent;transition:all 120ms;}
.color-swatch:hover{transform:scale(1.15);}
.color-swatch.selected{border-color:var(--text);box-shadow:0 0 0 2px var(--accent);}
/* Admin tables */
.table-wrap{overflow-x:auto;border-radius:8px;border:1px solid var(--border);}
.admin-table{width:100%;border-collapse:collapse;font-size:13px;}
.admin-table th{background:var(--bg-tertiary);color:var(--text-dim);font-weight:500;padding:8px 12px;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.5px;white-space:nowrap;}
.admin-table td{padding:8px 12px;border-top:1px solid var(--border);color:var(--text);}
.admin-table tr:hover td{background:var(--bg-secondary);}
.stat-card{background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;padding:14px;text-align:center;}
.stat-value{font-size:22px;font-weight:700;color:var(--accent);}
.stat-label{font-size:11px;color:var(--text-dim);margin-top:2px;text-transform:uppercase;letter-spacing:.5px;}
.role-badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:500;}
.role-admin{background:rgba(35,131,226,.2);color:var(--accent);}
.role-user{background:rgba(120,119,116,.2);color:var(--text-dim);}
.status-dot{display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:5px;vertical-align:middle;}
.status-dot.active{background:var(--toast-success-bg);}
.status-dot.inactive{background:var(--danger);}
/* Close button */
.settings-close{position:absolute;top:12px;right:12px;width:32px;height:32px;background:none;border:none;color:var(--text-dim);font-size:20px;cursor:pointer;border-radius:6px;display:flex;align-items:center;justify-content:center;}
.settings-close:hover{background:var(--bg-hover);color:var(--text);}
</style>
<div class="settings-layout" x-data="settingsPage()">
<div class="settings-overlay" x-data="settingsInit()" @keydown.escape="window.history.back()">
<div class="settings-panel" style="position:relative;">
<button class="settings-close" @click="closeSettings()" title="Close">×</button>
<!-- Profile -->
<div class="settings-section">
<h2>Profile</h2>
<div class="settings-card">
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">Email</div>
<div class="settings-row-desc">Used for login and notifications</div>
</div>
<div class="settings-row-value">{{ user.email or user.login or '' }}</div>
</div>
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">Name</div>
<div class="settings-row-desc">Display name</div>
</div>
<div class="inline-form">
<input class="settings-input" x-model="name" :value="name" placeholder="Your name">
<button class="settings-btn settings-btn-primary" @click="saveName">Save</button>
</div>
</div>
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">Password</div>
<div class="settings-row-desc">Change your password</div>
</div>
<div class="inline-form">
<input class="settings-input" type="password" x-model="newPassword" placeholder="New password">
<button class="settings-btn settings-btn-primary" @click="savePassword">Update</button>
</div>
</div>
<!-- Left navigation -->
<div class="settings-nav">
<div class="settings-nav-header">Account</div>
<div class="settings-nav-item" :class="{ active: activeSection==='account' }" @click="activeSection='account'">👤 My account</div>
<div class="settings-nav-item" :class="{ active: activeSection==='notifications' }" @click="activeSection='notifications'">🔔 Notifications</div>
<div class="settings-nav-header">Workspace</div>
<div class="settings-nav-item" :class="{ active: activeSection==='workspace' }" @click="activeSection='workspace'">📋 General</div>
<div class="settings-nav-item" :class="{ active: activeSection==='tags' }" @click="activeSection='tags'">🏷️ Tags</div>
<div class="settings-nav-header">Features</div>
<div class="settings-nav-item" :class="{ active: activeSection==='features' }" @click="activeSection='features'">🧩 Integrations</div>
<!-- Admin nav: only visible to admins -->
<template x-if="userIsAdmin">
<div>
<div class="settings-nav-header">Admin</div>
<div class="settings-nav-item" :class="{ active: activeSection==='admin-users' }" @click="activeSection='admin-users'; loadAdminUsers()">👥 Users &amp; Roles</div>
<div class="settings-nav-item" :class="{ active: activeSection==='admin-audit' }" @click="activeSection='admin-audit'; loadAdminAudit()">📋 Audit Log</div>
</div>
</template>
</div>
<!-- Connected Forges -->
<div class="settings-section">
<h2>Connected Forges</h2>
<div class="settings-card">
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">🔗 Gitea</div>
<div class="settings-row-desc">Connect to your Gitea instance</div>
</div>
{% if gitea_connected %}
<span class="forge-badge connected">✅ Connected</span>
<button class="settings-btn settings-btn-danger" @click="disconnect('gitea')">Disconnect</button>
{% else %}
<button class="settings-btn settings-btn-primary" onclick="window.location='/auth/login?provider=gitea'">Connect</button>
{% endif %}
</div>
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">🐙 GitHub</div>
<div class="settings-row-desc">Connect to GitHub</div>
</div>
{% if github_connected %}
<span class="forge-badge connected">✅ Connected</span>
<button class="settings-btn settings-btn-danger" @click="disconnect('github')">Disconnect</button>
{% else %}
<button class="settings-btn settings-btn-secondary">
Coming soon
</button>
{% endif %}
</div>
</div>
</div>
<!-- Right content -->
<div class="settings-content">
<!-- API Tokens -->
<div class="settings-section">
<h2>API Tokens</h2>
<div class="settings-card">
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">Generate API Token</div>
<div class="settings-row-desc">For programmatic access to FlowDeck API</div>
<!-- Account -->
<div x-show="activeSection==='account'">
<h2>My account</h2>
<p class="section-desc">Manage your profile and preferences.</p>
<div class="setting-group">
<h3>Profile</h3>
<div class="avatar-section">
<div class="avatar-preview" :style="{background: avatarColor || '#3A3A3A'}">
<img x-show="avatarUrl" :src="avatarUrl" alt="Avatar">
<span x-show="!avatarUrl">{{ user.get('full_name', user.get('login',''))[:1].upper() }}</span>
</div>
<button class="settings-btn settings-btn-primary" @click="generateToken">Generate</button>
<div>
<label class="avatar-upload-label">
Upload photo
<input type="file" class="avatar-upload-input" accept="image/*" @change="uploadAvatar($event)">
</label>
<div style="font-size:11px;color:var(--text-dim);margin-top:4px;">JPG, PNG or GIF — max 2MB</div>
</div>
<template x-if="token">
<div class="settings-row" style="background:#1a2a1a">
<div class="settings-row-left">
<div class="settings-row-label" style="font-family:monospace;font-size:12px;word-break:break-all" x-text="token"></div>
<div class="settings-row-desc" style="color:#50ff50">Copy this token now — it won't be shown again</div>
</div>
<button class="settings-btn settings-btn-primary" @click="copyToken">Copy</button>
<div style="margin-top:8px;">
<div style="font-size:12px;color:var(--text-dim);margin-bottom:6px;">Or pick a color:</div>
<div style="display:flex;gap:6px;flex-wrap:wrap;">
<template x-for="c in avatarColors" :key="c">
<div class="avatar-color-swatch" :style="{background: c}"
:class="{ selected: avatarColor === c }"
@click="selectAvatarColor(c)">
<span>{{ user.get('full_name', user.get('login',''))[:1].upper() }}</span>
</div>
</template>
</div>
</div>
<!-- Active Sessions -->
<div class="settings-section">
<h2>Active Sessions</h2>
<div class="settings-card">
<div class="settings-row">
<div class="settings-row-left">
<div class="settings-row-label">Current session</div>
<div class="settings-row-desc">You are logged in</div>
</div>
<button class="settings-btn settings-btn-danger" onclick="window.location='/auth/logout'">Log out</button>
<!-- Editable fields -->
<div class="setting-group">
<h3>Account details</h3>
<div class="setting-row" style="flex-direction:column;align-items:stretch;gap:4px;">
<div class="setting-label">Username</div>
<input type="text" class="settings-input" x-model="accountForm.login" style="max-width:300px;">
</div>
<div class="setting-row" style="flex-direction:column;align-items:stretch;gap:4px;">
<div class="setting-label">Full name</div>
<input type="text" class="settings-input" x-model="accountForm.full_name" style="max-width:300px;">
</div>
<div class="setting-row" style="flex-direction:column;align-items:stretch;gap:4px;">
<div class="setting-label">Email</div>
<input type="email" class="settings-input" x-model="accountForm.email" style="max-width:300px;">
</div>
<div style="margin-top:12px;">
<button class="btn btn-primary" @click="saveAccount()" :disabled="accountSaving" style="width:auto;padding:8px 20px;font-size:13px;">
<span x-show="!accountSaving">💾 Save changes</span>
<span x-show="accountSaving">Saving…</span>
</button>
<span x-show="accountMsg" x-text="accountMsg" style="margin-left:12px;font-size:13px;color:var(--toast-success-bg);"></span>
</div>
</div>
<!-- Password change -->
<div class="setting-group">
<h3>Change password</h3>
<div class="setting-row" style="flex-direction:column;align-items:stretch;gap:4px;">
<div class="setting-label">New password</div>
<div class="pw-wrapper" style="max-width:300px;">
<input :type="pwVisible ? 'text' : 'password'" class="settings-input" x-model="accountForm.password" placeholder="Leave blank to keep current" style="padding-right:36px;">
<button type="button" class="pw-toggle" @click="pwVisible=!pwVisible" x-text="pwVisible ? '🙈' : '👁'" style="top:50%;"></button>
</div>
</div>
<div style="margin-top:12px;">
<button class="btn btn-primary" @click="saveAccount()" :disabled="accountSaving || !accountForm.password" style="width:auto;padding:8px 20px;font-size:13px;">
<span x-show="!accountSaving">🔒 Update password</span>
<span x-show="accountSaving">Saving…</span>
</button>
</div>
</div>
<!-- Preferences -->
<div class="setting-group">
<h3>Preferences</h3>
<div class="setting-row">
<div>
<div class="setting-label">Theme</div>
<div class="setting-desc">Choose between light and dark appearance</div>
</div>
<div class="setting-control">
<select x-model="theme" @change="applyTheme()" style="background:var(--bg-tertiary);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;padding:6px 10px;outline:none;">
<option value="dark">🌙 Dark</option>
<option value="light">☀️ Light</option>
</select>
</div>
</div>
<div class="setting-row">
<div>
<div class="setting-label">Default view</div>
<div class="setting-desc">Workspace view mode when opening a workspace</div>
</div>
<div class="setting-control">
<select x-model="defaultView" @change="saveDefaultView()" style="background:var(--bg-tertiary);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;padding:6px 10px;outline:none;">
<option value="tree">🌳 Tree</option>
<option value="list">📋 List</option>
<option value="details">📊 Details</option>
<option value="title">🏷️ Title</option>
<option value="content">📝 Content</option>
</select>
</div>
</div>
</div>
</div>
<!-- Notifications -->
<div x-show="activeSection==='notifications'">
<h2>Notifications</h2>
<p class="section-desc">Choose when and how you want to be notified.</p>
<div class="setting-group">
<h3>Email notifications</h3>
<div class="setting-row">
<div>
<div class="setting-label">Comments</div>
<div class="setting-desc">When someone comments on your pages</div>
</div>
<div class="setting-control"><span style="font-size:12px;color:var(--text-dim);">Coming soon</span></div>
</div>
<div class="setting-row">
<div>
<div class="setting-label">Mentions</div>
<div class="setting-desc">When someone @mentions you</div>
</div>
<div class="setting-control"><span style="font-size:12px;color:var(--text-dim);">Coming soon</span></div>
</div>
</div>
</div>
<!-- Workspace -->
<div x-show="activeSection==='workspace'">
<h2>Workspace</h2>
<p class="section-desc">General workspace settings.</p>
<div class="setting-group">
<h3>General</h3>
<div class="setting-row">
<div>
<div class="setting-label">Workspace name</div>
<div class="setting-desc">{{ workspace_name }}</div>
</div>
</div>
</div>
</div>
<!-- Tags -->
<div x-show="activeSection==='tags'">
<h2>Tags</h2>
<p class="section-desc">Manage all tags across your workspace.</p>
<div class="setting-group">
<h3>All tags</h3>
<template x-for="tag in allTags" :key="tag.id">
<div class="tag-mgmt-item">
<div class="tag-color-dot" :style="{background: tag.color}"></div>
<span class="tag-name"
x-text="tag.name"
@dblclick="renameTag(tag)"
title="Double-click to rename"
style="cursor:pointer;"></span>
<span class="tag-count" x-text="tag.count + ' items'"></span>
<input type="color" :value="tag.color" @input="updateTagColor(tag.id, $event.target.value)" style="width:24px;height:24px;border:none;cursor:pointer;background:none;padding:0;" title="Change color">
<button class="tag-chip rm-btn" @click="deletingTag=tag" title="Delete">×</button>
</div>
</template>
<div class="new-tag-form">
<template x-for="c in presetColors" :key="c">
<div class="color-swatch" :class="{ selected: newTagColor === c }" :style="{background: c}" @click="newTagColor=c"></div>
</template>
<input type="text" placeholder="New tag..." x-model="newTagName" @keydown.enter="createTag()">
<button class="btn btn-primary" @click="createTag()" :disabled="!newTagName.trim()" style="padding:4px 12px;font-size:12px;">Add</button>
</div>
</div>
<!-- Delete confirmation modal -->
<div class="modal-overlay" x-show="deletingTag" @click.self="deletingTag=null" @keydown.escape="deletingTag=null" style="z-index:1000;">
<div class="modal-box" style="max-width:360px;">
<h3 style="margin:0 0 8px;">Delete tag</h3>
<p style="color:var(--text-dim);margin:0 0 16px;">
Are you sure you want to delete the tag "<strong x-text="deletingTag?.name"></strong>"?
<span x-show="deletingTag?.count > 0" style="color:var(--danger);display:block;margin-top:4px;">
⚠️ This tag is used on <span x-text="deletingTag?.count"></span> item(s).
</span>
</p>
<div style="display:flex;gap:8px;justify-content:flex-end;">
<button class="btn" @click="deletingTag=null">Cancel</button>
<button class="btn btn-danger" @click="confirmDeleteTag()">Delete</button>
</div>
</div>
</div>
<!-- Rename modal -->
<div class="modal-overlay" x-show="renamingTag" @click.self="renamingTag=null" @keydown.escape="renamingTag=null" style="z-index:1000;">
<div class="modal-box" style="max-width:360px;">
<h3 style="margin:0 0 12px;">Rename tag</h3>
<div style="display:flex;gap:8px;align-items:center;">
<div class="tag-color-dot" :style="{background: renamingTag?.color}" style="width:16px;height:16px;"></div>
<input type="text" class="settings-input" x-model="renameValue"
@keydown.enter="confirmRenameTag()" @keydown.escape="renamingTag=null"
style="flex:1;" autofocus>
</div>
<div style="display:flex;gap:8px;justify-content:flex-end;margin-top:16px;">
<button class="btn" @click="renamingTag=null">Cancel</button>
<button class="btn btn-primary" @click="confirmRenameTag()" :disabled="!renameValue.trim()">Rename</button>
</div>
</div>
</div>
</div>
<!-- Features -->
<div x-show="activeSection==='features'">
<h2>Features</h2>
<p class="section-desc">Integrations and feature toggles.</p>
<div class="setting-group">
<h3>Integrations</h3>
<!-- Gitea -->
<div class="setting-row">
<div>
<div class="setting-label">🦎 Gitea <span x-show="authMethod==='gitea'" style="font-size:10px;background:var(--accent);color:#fff;padding:1px 6px;border-radius:3px;margin-left:6px;">Primary</span></div>
<div class="setting-desc">
<span x-show="giteaLinked">Connected to git.dracodev.net</span>
<span x-show="!giteaLinked">Connect your Gitea account to access projects</span>
</div>
</div>
<div class="setting-control">
<span x-show="giteaLinked" style="font-size:12px;color:var(--toast-success-bg);">✅ Active</span>
<button x-show="giteaLinked && authMethod!=='gitea'" class="btn-sm" style="color:var(--danger);" @click="disconnectGitea()">Disconnect</button>
<a x-show="!giteaLinked" class="btn-sm" href="/auth/login?provider=gitea&mode=link" style="text-decoration:none;color:var(--accent);">🔗 Connect</a>
</div>
</div>
<!-- GitHub -->
<div class="setting-row">
<div>
<div class="setting-label">🐙 GitHub <span x-show="authMethod==='github'" style="font-size:10px;background:var(--accent);color:#fff;padding:1px 6px;border-radius:3px;margin-left:6px;">Primary</span></div>
<div class="setting-desc">
<span x-show="githubLinked">Connected to github.com</span>
<span x-show="!githubLinked">Connect your GitHub account to access repositories</span>
</div>
</div>
<div class="setting-control">
<span x-show="githubLinked" style="font-size:12px;color:var(--toast-success-bg);">✅ Active</span>
<button x-show="githubLinked && authMethod!=='github'" class="btn-sm" style="color:var(--danger);" @click="disconnectGithub()">Disconnect</button>
<a x-show="!githubLinked" class="btn-sm" href="/auth/login?provider=github&mode=link" style="text-decoration:none;color:var(--accent);">🔗 Connect</a>
</div>
</div>
</div>
</div>
<!-- Admin: Users & Roles -->
<div x-show="activeSection==='admin-users'">
<h2>Users &amp; Roles</h2>
<p class="section-desc">Manage user accounts, roles, and permissions.</p>
<!-- Quick Stats -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;">
<div class="stat-card">
<div class="stat-value" x-text="adminStats.total_users">—</div>
<div class="stat-label">Total Users</div>
</div>
<div class="stat-card">
<div class="stat-value" x-text="adminStats.total_workspaces">—</div>
<div class="stat-label">Workspaces</div>
</div>
<div class="stat-card">
<div class="stat-value" x-text="adminStats.total_files">—</div>
<div class="stat-label">Files</div>
</div>
<div class="stat-card">
<div class="stat-value" x-text="adminStats.total_mb + ' MB'">— MB</div>
<div class="stat-label">Storage</div>
</div>
</div>
<!-- Create User Button -->
<div style="margin-bottom:16px;">
<button class="btn btn-primary" @click="showCreateUser=!showCreateUser" style="font-size:13px;">+ New User</button>
</div>
<!-- Create User Form -->
<div x-show="showCreateUser" class="new-tag-form" style="margin-bottom:16px;">
<input type="text" placeholder="Login" x-model="newUser.login" style="width:120px;">
<input type="text" placeholder="Full name" x-model="newUser.name" style="width:140px;">
<input type="email" placeholder="Email" x-model="newUser.email" style="width:160px;">
<input type="password" placeholder="Password" x-model="newUser.password" style="width:130px;">
<label style="font-size:11px;color:var(--text-dim);white-space:nowrap;">
<input type="checkbox" x-model="newUser.is_admin"> Admin
</label>
<button class="btn btn-primary" @click="adminCreateUser()" :disabled="!newUser.login || !newUser.password" style="padding:4px 12px;font-size:12px;">Create</button>
</div>
<!-- Users Table -->
<div class="table-wrap">
<table class="admin-table">
<thead>
<tr>
<th>User</th>
<th>Role</th>
<th>Status</th>
<th>Workspaces</th>
<th>Files</th>
<th>Folders</th>
<th>Storage</th>
<th>Last Login</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<template x-for="u in adminUsers" :key="u.id">
<tr>
<td>
<div style="font-weight:500;" x-text="u.full_name || u.login"></div>
<div style="font-size:11px;color:var(--text-dim);" x-text="u.login"></div>
</td>
<td>
<span class="role-badge" :class="u.is_admin ? 'role-admin' : 'role-user'" x-text="u.is_admin ? 'Admin' : 'User'"></span>
</td>
<td>
<span class="status-dot" :class="u.is_active ? 'active' : 'inactive'"></span>
<span x-text="u.is_active ? 'Active' : 'Inactive'" style="font-size:12px;color:var(--text-dim);"></span>
</td>
<td x-text="u.ws_count" style="text-align:center;"></td>
<td x-text="u.file_count" style="text-align:center;"></td>
<td x-text="u.folder_count" style="text-align:center;"></td>
<td x-text="u.total_mb + ' MB'" style="text-align:right;"></td>
<td>
<span style="font-size:11px;color:var(--text-dim);" x-text="u.last_login ? new Date(u.last_login*1000).toLocaleDateString() : 'Never'"></span>
</td>
<td>
<div style="display:flex;gap:4px;">
<button class="btn-sm" @click="editingUser=u; editUserForm={login:u.login,name:u.full_name,email:u.email,is_admin:u.is_admin,is_active:u.is_active}" title="Edit">✏️</button>
<button class="btn-sm btn-sm-danger" @click="adminDeleteUser(u.id)" title="Delete" x-show="adminUsers.length > 1">🗑</button>
</div>
</td>
</tr>
</template>
</tbody>
</table>
</div>
<!-- Edit User Modal -->
<div class="modal-overlay" x-show="editingUser" @click.self="editingUser=null" @keydown.escape="editingUser=null" style="z-index:1001;">
<div class="modal-box" style="max-width:400px;">
<h3 style="margin:0 0 12px;">Edit User: <span x-text="editUserForm.login"></span></h3>
<div style="display:flex;flex-direction:column;gap:10px;">
<input type="text" class="settings-input" placeholder="Full name" x-model="editUserForm.name">
<input type="email" class="settings-input" placeholder="Email" x-model="editUserForm.email">
<input type="password" class="settings-input" placeholder="New password (leave blank to keep)" x-model="editUserForm.password">
<label style="font-size:13px;color:var(--text);display:flex;align-items:center;gap:8px;">
<input type="checkbox" x-model="editUserForm.is_admin"> Admin role
</label>
<label style="font-size:13px;color:var(--text);display:flex;align-items:center;gap:8px;">
<input type="checkbox" x-model="editUserForm.is_active"> Active account
</label>
</div>
<div style="display:flex;gap:8px;justify-content:flex-end;margin-top:16px;">
<button class="btn" @click="editingUser=null">Cancel</button>
<button class="btn btn-primary" @click="adminUpdateUser()">Save</button>
</div>
</div>
</div>
</div>
<!-- Admin: Audit Log -->
<div x-show="activeSection==='admin-audit'">
<h2>Audit Log</h2>
<p class="section-desc">Login history and security events.</p>
<div class="table-wrap">
<table class="admin-table">
<thead>
<tr>
<th>Date</th>
<th>User</th>
<th>IP Address</th>
<th>User Agent</th>
</tr>
</thead>
<tbody>
<template x-for="e in auditEntries" :key="e.id">
<tr>
<td><span style="font-size:12px;" x-text="new Date(e.logged_at+'Z').toLocaleString()"></span></td>
<td>
<span style="font-weight:500;" x-text="e.full_name || e.login"></span>
<span style="font-size:11px;color:var(--text-dim);display:block;" x-text="e.login"></span>
</td>
<td><code style="font-size:11px;" x-text="e.ip_address || '—'"></code></td>
<td><span style="font-size:11px;color:var(--text-dim);max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block;" x-text="e.user_agent || '—'"></span></td>
</tr>
</template>
<tr x-show="auditEntries.length === 0">
<td colspan="4" style="text-align:center;color:var(--text-dim);padding:20px;">No login events yet</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
function settingsPage() {
document.addEventListener('alpine:init', function() {
Alpine.data('settingsInit', function() {
return {
name: '{{ user.full_name or '' }}',
newPassword: '',
token: '',
async saveName() {
await fetch('/api/user/profile', {method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({full_name:this.name})});
alert('Name saved');
activeSection: 'account',
allTags: [],
newTagName: '',
newTagColor: '#787774',
deletingTag: null,
renamingTag: null,
renameValue: '',
presetColors: ['#787774','#E03E3E','#D9730D','#DFAB01','#0F7B6C','#0B6E99','#6940A5','#AD1A72','#E16259','#D4A72C','#448361','#337EA9','#9065B0','#C94D8B'],
avatarUrl: '{{ avatar_url or "" }}',
avatarColor: '{{ avatar_color or "#3A3A3A" }}',
avatarColors: ['#E03E3E','#D9730D','#DFAB01','#0F7B6C','#0B6E99','#6940A5','#AD1A72','#E16259','#448361','#337EA9','#9065B0','#C94D8B','#787774','#3A3A3A'],
defaultView: localStorage.getItem('fd_default_view') || 'tree',
userInfo: {full_name: '{{ user.full_name or "" }}', login: '{{ user.login or "" }}', email: '{{ user.email or "" }}'},
userIsAdmin: {{ 'true' if user.get('is_admin') else 'false' }},
// Auth & Integrations
authMethod: '{{ auth_method }}',
giteaLinked: false,
githubLinked: false,
// Theme
theme: localStorage.getItem('fd_theme') || 'light',
// Account form
accountForm: {login:'{{ user.login or "" }}', full_name:'{{ user.full_name or "" }}', email:'{{ user.email or "" }}', password:''},
accountSaving: false,
accountMsg: '',
pwVisible: false,
// Admin data
adminUsers: [],
adminStats: {},
auditEntries: [],
showCreateUser: false,
newUser: {login:'',name:'',email:'',password:'',is_admin:false},
editingUser: null,
editUserForm: {login:'',name:'',email:'',password:'',is_admin:false,is_active:true},
async init() {
await this.loadTags();
await this.loadGiteaStatus();
await this.loadGithubStatus();
},
async savePassword() {
if (!this.newPassword || this.newPassword.length < 6) { alert('Password must be at least 6 characters'); return; }
await fetch('/api/user/password', {method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:this.newPassword})});
this.newPassword = '';
alert('Password updated');
async loadTags() {
try {
var r = await fetch('/api/settings/tags/all');
var d = await r.json();
this.allTags = d.tags || [];
} catch(e) { this.allTags = []; }
},
async generateToken() {
const r = await fetch('/api/user/token', {method:'POST'});
const d = await r.json();
this.token = d.token;
async createTag() {
var n = this.newTagName.trim();
if (!n) return;
var r = await fetch('/api/settings/tags', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({name: n, color: this.newTagColor})
});
if (r.ok) { this.newTagName = ''; this.newTagColor = '#787774'; await this.loadTags(); }
},
copyToken() {
navigator.clipboard?.writeText(this.token);
const ta = document.createElement('textarea');
ta.value = this.token; ta.style.position='fixed'; ta.style.opacity='0';
document.body.appendChild(ta); ta.select(); document.execCommand('copy');
document.body.removeChild(ta);
alert('Token copied to clipboard');
async updateTagColor(id, color) {
await fetch('/api/settings/tags/' + id, {
method: 'PUT', headers: {'Content-Type':'application/json'},
body: JSON.stringify({color: color})
});
await this.loadTags();
},
async disconnect(provider) {
if (!confirm('Disconnect ' + provider + '?')) return;
await fetch('/api/user/forge/' + provider, {method:'DELETE'});
window.location.reload();
async deleteTag(id) {
if (!confirm('Delete this tag?')) return;
await fetch('/api/settings/tags/' + id, { method: 'DELETE' });
await this.loadTags();
},
async renameTag(tag) {
this.renamingTag = tag;
this.renameValue = tag.name;
// Focus the input after Alpine renders the modal
var self = this;
this.$nextTick(function() {
var input = document.querySelector('.modal-box input[type=text]');
if (input) { input.focus(); input.select(); }
});
},
async confirmRenameTag() {
var tag = this.renamingTag;
var newName = this.renameValue.trim();
if (!tag || !newName || newName.toLowerCase() === tag.name.toLowerCase()) {
this.renamingTag = null; return;
}
await fetch('/api/settings/tags/' + tag.id, {
method: 'PUT', headers: {'Content-Type':'application/json'},
body: JSON.stringify({name: newName})
});
this.renamingTag = null;
await this.loadTags();
},
async confirmDeleteTag() {
var tag = this.deletingTag;
if (!tag) return;
await fetch('/api/settings/tags/' + tag.id, { method: 'DELETE' });
this.deletingTag = null;
await this.loadTags();
},
// ── Admin ──
getCsrfToken() {
return document.cookie.split('; ').find(r => r.startsWith('csrf_token='))?.split('=')[1] || '';
},
async adminFetch(url, opts) {
opts = opts || {};
opts.headers = opts.headers || {};
opts.headers['X-CSRF-Token'] = this.getCsrfToken();
return await fetch(url, opts);
},
async loadAdminUsers() {
try {
var r = await this.adminFetch('/api/admin/users');
var d = await r.json();
this.adminUsers = d.users || [];
} catch(e) { this.adminUsers = []; }
await this.loadAdminStats();
},
async loadAdminStats() {
try {
var r = await this.adminFetch('/api/admin/stats');
this.adminStats = await r.json();
} catch(e) { this.adminStats = {}; }
},
async loadAdminAudit() {
try {
var r = await this.adminFetch('/api/admin/audit?limit=200');
var d = await r.json();
this.auditEntries = d.entries || [];
} catch(e) { this.auditEntries = []; }
},
async adminCreateUser() {
var u = this.newUser;
if (!u.login || !u.password) return;
try {
var r = await this.adminFetch('/api/admin/users', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({login:u.login, name:u.name, email:u.email, password:u.password, is_admin:u.is_admin?1:0})
});
if (r.ok) {
this.newUser = {login:'',name:'',email:'',password:'',is_admin:false};
this.showCreateUser = false;
await this.loadAdminUsers();
} else {
var d = await r.json();
window.showToast(d.error || 'Failed to create user', 'error');
}
} catch(e) { window.showToast('Network error', 'error'); }
},
async adminUpdateUser() {
var f = this.editUserForm;
if (!f.login) return;
var body = {name: f.name, email: f.email, is_admin: f.is_admin?1:0, is_active: f.is_active?1:0};
if (f.password) body.password = f.password;
try {
var r = await this.adminFetch('/api/admin/users/' + this.editingUser.id, {
method: 'PUT', headers: {'Content-Type':'application/json'},
body: JSON.stringify(body)
});
if (r.ok) {
this.editingUser = null;
await this.loadAdminUsers();
}
} catch(e) {}
},
async adminDeleteUser(id) {
if (!confirm('Permanently delete this user and all their data?')) return;
try {
await this.adminFetch('/api/admin/users/' + id, { method: 'DELETE' });
await this.loadAdminUsers();
} catch(e) {}
},
async saveAccount() {
this.accountSaving = true;
this.accountMsg = '';
var body = {};
var f = this.accountForm;
if (f.full_name !== this.userInfo.full_name) body.full_name = f.full_name;
if (f.login !== this.userInfo.login) body.login = f.login;
if (f.email !== this.userInfo.email) body.email = f.email;
if (f.password) body.password = f.password;
if (Object.keys(body).length === 0) { this.accountSaving = false; return; }
try {
var r = await fetch('/api/settings/account', {
method: 'PUT', headers: {'Content-Type':'application/json', 'X-CSRF-Token': this.getCsrfToken()},
body: JSON.stringify(body)
});
var d = await r.json();
if (r.ok) {
this.userInfo = {login: d.user.login, full_name: d.user.full_name, email: d.user.email};
this.accountForm.password = '';
this.accountMsg = '✓ Saved!';
setTimeout(() => { this.accountMsg = ''; }, 3000);
} else {
this.accountMsg = '✗ ' + (d.error || 'Error');
}
} catch(e) { this.accountMsg = '✗ Network error'; }
this.accountSaving = false;
},
async uploadAvatar(ev) {
var file = ev.target.files[0];
if (!file) return;
var form = new FormData();
form.append('file', file);
var r = await fetch('/api/settings/avatar', { method: 'POST', body: form });
if (r.ok) {
var d = await r.json();
this.avatarUrl = d.avatar_url + '?t=' + Date.now();
this.avatarColor = '';
}
},
async selectAvatarColor(color) {
this.avatarColor = color;
var r = await fetch('/api/settings/avatar-color', {
method: 'POST', headers: {'Content-Type':'application/json'},
body: JSON.stringify({color: color})
});
if (r.ok) { this.avatarUrl = ''; }
},
applyTheme() {
localStorage.setItem('fd_theme', this.theme);
document.documentElement.setAttribute('data-theme', this.theme);
},
saveDefaultView() {
localStorage.setItem('fd_default_view', this.defaultView);
},
async loadGiteaStatus() {
try {
var r = await fetch('/api/gitea/status');
var d = await r.json();
this.giteaLinked = d.linked || false;
} catch(e) { this.giteaLinked = false; }
},
async disconnectGitea() {
if (!confirm('Disconnect Gitea? You can reconnect anytime.')) return;
try {
var r = await fetch('/api/gitea/disconnect', { method: 'DELETE', headers: {'X-CSRF-Token': this.getCsrfToken()} });
if (r.ok) { this.giteaLinked = false; }
} catch(e) {}
},
async loadGithubStatus() {
try {
var r = await fetch('/api/github/status');
var d = await r.json();
this.githubLinked = d.linked || false;
} catch(e) { this.githubLinked = false; }
},
async disconnectGithub() {
if (!confirm('Disconnect GitHub? You can reconnect anytime.')) return;
try {
var r = await fetch('/api/github/disconnect', { method: 'DELETE', headers: {'X-CSRF-Token': this.getCsrfToken()} });
if (r.ok) { this.githubLinked = false; }
} catch(e) {}
},
closeSettings() {
// Refresh parent page after settings changes, then navigate back
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
window.close();
return;
}
// If navigated directly to settings, redirect to workspaces (forces refresh)
if (!document.referrer || document.referrer === window.location.href) {
window.location.href = '/workspaces?ts=' + Date.now();
return;
}
// Go back and force refresh
var prev = document.referrer;
if (prev && prev.includes('/settings')) {
// Came from another settings tab — go back two steps then refresh
history.go(-2);
setTimeout(function() { window.location.reload(); }, 100);
} else {
history.back();
setTimeout(function() { window.location.reload(); }, 100);
}
},
};
}
});
});
</script>
{% endblock %}
+2 -1
View File
@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% block page_icon %}🗑️{% endblock %}
{% block page_title %}Trash{% endblock %}
{% block title_prefix %}Trash{% endblock %}
{% block content %}
<div class="page-title-area">
@@ -21,7 +22,7 @@
<!-- Filters -->
<div style="display:flex; gap:8px; margin-bottom:16px;">
<button class="trash-filter active">
<span style="color:#5b9bd5;">👤</span> Last edited by ▾
<span style="color:var(--accent);">👤</span> Last edited by ▾
</button>
<button class="trash-filter">
<span>📁</span> In ▾
+27 -35
View File
@@ -1,58 +1,50 @@
{% extends "base.html" %}
{% block page_title %}Workspace{% endblock %}
{% block title_prefix %}Workspace{% endblock %}
{% block page_icon %}🏠{% endblock %}
{% block topbar %}
<header class="topbar">
<button class="hamburger-btn" @click="mobileSidebarOpen = true; sidebarCollapsed = false;" title="Menu">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="topbar-left">
<span class="breadcrumb" style="color:rgba(255,255,255,.5)">Workspace</span>
<span class="page-title-topbar">Projects</span>
</div>
<div class="topbar-right">
<button class="page-action-btn" onclick="window.location='/auth/login?provider=local'" title="Login">🔑</button>
<button class="page-action-btn" onclick="window.location='/accounts/settings'" title="Settings">⚙</button>
</div>
</header>
{% set page_icon = "🏠" %}
{% set page_title = "Workspace — Projects" %}
{% set right_actions = '<a href="/auth/login?provider=local" class="topbar-btn" title="Login">🔑</a><a href="/accounts/settings" class="topbar-btn" title="Settings">⚙</a>' %}
{% include '_header.html' %}
{% endblock %}
{% block content %}
<style>
.workspace-layout{max-width:900px;margin:0 auto;padding:32px 24px;}
.workspace-header{margin-bottom:24px;}
.workspace-header h1{font-size:28px;font-weight:600;margin-bottom:8px;}
.workspace-header p{color:rgba(255,255,255,.5);font-size:14px;}
.workspace-header h1{font-size:28px;font-weight:600;margin-bottom:8px;color:var(--text-primary);}
.workspace-header p{color:var(--text-secondary);font-size:14px;}
.forge-section{margin-bottom:32px;}
.forge-section h2{font-size:14px;color:rgba(255,255,255,.45);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;font-weight:500;display:flex;align-items:center;gap:8px;}
.forge-section h2{font-size:14px;color:var(--text-dim);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;font-weight:500;display:flex;align-items:center;gap:8px;}
.forge-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:500;}
.forge-badge.gitea{background:rgba(96,155,80,.15);color:#609b50;}
.forge-badge.github{background:rgba(110,84,148,.15);color:#6e5494;}
.forge-badge.builtin{background:rgba(35,131,226,.15);color:#2383E2;}
.forge-badge.gitea{background:rgba(96,155,80,.15);color:var(--green);}
.forge-badge.github{background:rgba(110,84,148,.15);color:var(--purple);}
.forge-badge.builtin{background:rgba(35,131,226,.15);color:var(--accent);}
.project-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;}
.project-card{background:#222;border:1px solid rgba(255,255,255,.06);border-radius:12px;padding:16px;cursor:pointer;transition:background 150ms ease;}
.project-card:hover{background:#2A2A2A;border-color:rgba(255,255,255,.12);}
.project-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px;cursor:pointer;transition:background var(--transition);}
.project-card:hover{background:var(--bg-hover);border-color:var(--border-strong);}
.project-card-top{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:8px;}
.project-card-icon{font-size:20px;}
.project-card-name{font-size:14px;font-weight:500;color:#fff;margin-bottom:4px;}
.project-card-desc{font-size:12px;color:rgba(255,255,255,.4);margin-bottom:8px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}
.project-card-meta{display:flex;align-items:center;gap:8px;font-size:11px;color:rgba(255,255,255,.3);}
.project-card-name{font-size:14px;font-weight:500;color:var(--text-primary);margin-bottom:4px;}
.project-card-desc{font-size:12px;color:var(--text-secondary);margin-bottom:8px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}
.project-card-meta{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--text-dim);}
.empty-state{text-align:center;padding:40px;color:rgba(255,255,255,.3);font-size:14px;}
.empty-state .btn{margin-top:12px;display:inline-block;padding:8px 16px;background:#2383E2;color:#fff;border-radius:8px;text-decoration:none;font-size:13px;}
.empty-state{text-align:center;padding:40px;color:var(--text-dim);font-size:14px;}
.empty-state .btn{margin-top:12px;display:inline-block;padding:8px 16px;background:var(--accent);color:#fff;border-radius:var(--radius-md);text-decoration:none;font-size:13px;}
.new-project-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;background:rgba(35,131,226,.15);color:#2383E2;border:1px solid rgba(35,131,226,.3);border-radius:8px;cursor:pointer;font-size:13px;}
.new-project-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;background:rgba(35,131,226,.15);color:var(--accent);border:1px solid rgba(35,131,226,.3);border-radius:var(--radius-md);cursor:pointer;font-size:13px;}
.new-project-btn:hover{background:rgba(35,131,226,.25);}
/* Modal */
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:500;}
.modal-box{background:#1F1F1F;border:1px solid rgba(255,255,255,.08);border-radius:18px;padding:32px;width:400px;max-width:90vw;}
.modal-box h3{font-size:16px;margin-bottom:16px;}
.modal-input{width:100%;padding:10px 12px;background:#2A2A2A;border:1px solid rgba(255,255,255,.1);border-radius:8px;color:#fff;font-size:14px;margin-bottom:12px;outline:none;}
.modal-input:focus{border-color:#2383E2;}
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.4);display:flex;align-items:center;justify-content:center;z-index:500;}
.modal-box{background:var(--bg-modal);border:1px solid var(--border);border-radius:var(--radius-lg);padding:32px;width:400px;max-width:90vw;box-shadow:var(--shadow-modal);}
.modal-box h3{font-size:16px;margin-bottom:16px;color:var(--text-primary);}
.modal-input{width:100%;padding:10px 12px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-primary);font-size:14px;margin-bottom:12px;outline:none;}
.modal-input:focus{border-color:var(--accent);}
.modal-actions{display:flex;gap:8px;justify-content:flex-end;}
</style>
@@ -80,8 +72,8 @@
</div>
</div>
</template>
<div class="project-card" style="border:1px dashed rgba(255,255,255,.1);display:flex;align-items:center;justify-content:center;min-height:100px" @click="showCreateModal = true">
<span style="color:rgba(255,255,255,.3);font-size:24px">+</span>
<div class="project-card" style="border:1px dashed var(--border-strong);display:flex;align-items:center;justify-content:center;min-height:100px" @click="showCreateModal = true">
<span style="color:var(--text-dim);font-size:24px">+</span>
</div>
</div>
</div>
@@ -135,7 +127,7 @@
</div>
<!-- Create Modal -->
<div class="modal-overlay" x-show="showCreateModal" @click.away="showCreateModal=false" @keydown.escape="showCreateModal=false">
<div class="modal-overlay" x-show="showCreateModal" @click.outside="showCreateModal=false" @keydown.escape="showCreateModal=false">
<div class="modal-box">
<h3>Create New Project</h3>
<input class="modal-input" x-model="newProjectName" placeholder="Project name" @keydown.enter="createProject">
+219 -42
View File
@@ -1,69 +1,70 @@
{% extends "base.html" %}
{% block page_title %}Workspaces{% endblock %}
{% block title_prefix %}Workspaces{% endblock %}
{% block page_icon %}🏠{% endblock %}
{% block topbar %}
<header class="topbar">
<button class="hamburger-btn" @click="mobileSidebarOpen = true; sidebarCollapsed = false;" title="Menu">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="topbar-left">
<span class="breadcrumb" style="color:rgba(255,255,255,.5)">Home</span>
<span class="page-title-topbar">Workspaces</span>
</div>
<div class="topbar-right">
<button class="page-action-btn" onclick="window.location='/accounts/settings'" title="Settings">⚙</button>
</div>
</header>
{% set breadcrumb_items = [{"label": "Workspaces", "url": None}] %}
{% set page_icon = "🏠" %}
{% set right_actions = '<a href="/auth/login?provider=local" class="topbar-btn" title="Login">🔑</a><a href="/accounts/settings" class="topbar-btn" title="Settings">⚙</a>' %}
{% include '_header.html' %}
{% endblock %}
{% block content %}
<style>
.ws-page{max-width:800px;margin:0 auto;padding:40px 24px;}
.ws-page{max-width:1000px;margin:0 auto;padding:40px 24px;}
.ws-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;}
.ws-header h1{font-size:24px;}
.ws-section{margin-bottom:40px;}
.ws-section-title{font-size:14px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;display:flex;align-items:center;gap:8px;}
.ws-section-title .badge{font-size:11px;background:var(--bg-tertiary);color:var(--text-dim);padding:1px 8px;border-radius:10px;}
.ws-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;}
.ws-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius);padding:20px;cursor:pointer;transition:background 150ms;}
.ws-card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius);padding:20px;cursor:pointer;transition:background 150ms, border-color 150ms;}
.ws-card:hover{background:var(--bg-tertiary);border-color:var(--border-strong);}
.ws-card.active{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent);}
.ws-card-name{font-size:16px;font-weight:500;margin-bottom:4px;}
.ws-card-count{font-size:12px;color:var(--text-tertiary);}
.ws-card-name{font-size:15px;font-weight:500;margin-bottom:2px;}
.ws-card-sub{font-size:12px;color:var(--text-dim);margin-bottom:4px;}
.ws-card-count{font-size:12px;color:var(--text-dim);}
.ws-card-actions{display:flex;gap:4px;margin-top:8px;opacity:0;transition:opacity 150ms;}
.ws-card:hover .ws-card-actions{opacity:1;}
.dialog-overlay{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:500;}
.dialog-box{background:#1F1F1F;border:1px solid var(--border);border-radius:18px;padding:24px;width:400px;max-width:90vw;}
.dialog-box h3{margin-bottom:16px;}
.dialog-input{width:100%;padding:10px 12px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:14px;margin-bottom:12px;outline:none;}
.dialog-input:focus{border-color:var(--accent);}
.dialog-actions{display:flex;gap:8px;justify-content:flex-end;}
.btn{padding:8px 16px;border-radius:8px;font-size:13px;cursor:pointer;border:none;font-weight:500;}
.btn-primary{background:var(--accent);color:#fff;}
.btn-primary:hover{background:var(--accent-hover);}
.btn-secondary{background:var(--bg-tertiary);color:var(--text);}
.btn-secondary:hover{background:var(--bg-hover);}
.btn-danger{background:rgba(255,80,80,.15);color:var(--danger);}
.btn-danger:hover{background:rgba(255,80,80,.25);}
.btn-new{border:1px dashed var(--border-strong);background:transparent;color:var(--text-secondary);display:flex;align-items:center;justify-content:center;min-height:120px;}
.btn-new:hover{background:var(--bg-tertiary);color:var(--text);}
/* Gitea org grouping */
.gitea-org{margin-bottom:16px;}
.gitea-org-header{font-size:14px;font-weight:600;color:var(--text);display:flex;align-items:center;gap:8px;margin-bottom:8px;}
.gitea-org-header img{border-radius:4px;}
.gitea-org-avatar{width:24px;height:24px;border-radius:4px;background:var(--bg-tertiary);display:flex;align-items:center;justify-content:center;font-size:14px;}
.gitea-empty{padding:24px;text-align:center;color:var(--text-dim);font-size:14px;border:1px dashed var(--border);border-radius:var(--radius);}
.gitea-connect{display:inline-block;margin-top:8px;color:var(--accent);cursor:pointer;font-size:13px;}
.gitea-connect:hover{text-decoration:underline;}
.gitea-loading{color:var(--text-dim);font-size:13px;padding:12px 0;}
/* Org tabs */
.org-tab{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:6px;font-size:13px;color:var(--text-dim);background:transparent;border:1px solid var(--border);cursor:pointer;white-space:nowrap;transition:all 100ms;}
.org-tab:hover{background:var(--bg-tertiary);color:var(--text);}
.org-tab.active{background:var(--accent);color:#fff;border-color:var(--accent);}
.org-tab-badge{font-size:10px;padding:0 5px;border-radius:8px;background:rgba(255,255,255,.15);}
[data-theme="light"] .org-tab-badge{background:rgba(0,0,0,.08);}
.search-input:focus{border-color:var(--accent);}
</style>
<div class="ws-page" x-data="workspacesPage()">
<div class="ws-header">
<h1>🏠 Workspaces</h1>
<button class="btn btn-primary" @click="showCreate=true">+ New Workspace</button>
</div>
<!-- ── Local Workspaces ── -->
<div class="ws-section">
<div class="ws-section-title">📁 My Workspaces <span class="badge" x-text="workspaces.length"></span></div>
<div class="ws-grid">
<template x-for="ws in workspaces" :key="ws.id">
<div class="ws-card" :class="{active:ws.id===activeId}" @click="select(ws)">
<template x-for="ws in workspaces" :key="'local-'+ws.id">
<div class="ws-card" :class="{active:ws.id===activeId}" @click="selectLocal(ws)">
<div class="ws-card-name" x-text="ws.name"></div>
<div class="ws-card-count" x-text="ws.page_count+' page(s)'"></div>
<div class="ws-card-actions" @click.stop>
<button class="btn btn-secondary" style="padding:4px 8px;font-size:11px" @click="renameWs(ws)">✏️</button>
<button class="btn btn-danger" style="padding:4px 8px;font-size:11px" @click="deleteWs(ws)">🗑</button>
<button class="btn-sm" @click="renameWs(ws)">✏️</button>
<button class="btn-sm" style="color:var(--danger);border-color:rgba(255,80,80,.3)" @click="deleteWs(ws)">🗑</button>
</div>
</div>
</template>
@@ -71,9 +72,94 @@
<span style="font-size:32px">+</span>
</div>
</div>
</div>
<!-- ── Gitea Projects ── -->
<div class="ws-section">
<div class="ws-section-title">🔗 Gitea Projects <span class="badge" x-text="giteaTotal"></span></div>
<!-- Not linked -->
<div class="gitea-empty" x-show="giteaStatus==='not_linked'">
<div>Connect your Gitea account to see your projects.</div>
<a class="gitea-connect" href="/auth/login?provider=gitea&mode=link">🔗 Connect Gitea</a>
<span style="margin:0 8px;color:var(--text-dim);">or</span>
<a class="gitea-connect" href="/auth/login?provider=gitea">📝 Register with Gitea</a>
</div>
<!-- Loading skeletons -->
<div x-show="giteaStatus==='loading'" class="ws-grid">
<template x-for="i in 6" :key="i">
<div class="ws-card" style="pointer-events:none;">
<div class="skeleton" style="height:16px;width:65%;margin-bottom:8px;"></div>
<div class="skeleton" style="height:12px;width:45%;margin-bottom:6px;"></div>
<div class="skeleton" style="height:12px;width:80%;"></div>
</div>
</template>
</div>
<!-- Error -->
<div class="gitea-empty" x-show="giteaStatus==='error'">
<div>⚠ Could not load Gitea projects.</div>
<button class="gitea-connect" @click="loadGitea()">Retry</button>
</div>
<!-- Projects (tabs by org + search) -->
<div x-show="giteaStatus==='ok' && giteaGroups.length > 0">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;flex-wrap:wrap;">
<!-- Org tabs -->
<div style="display:flex;gap:4px;overflow-x:auto;flex:1;min-width:0;">
<button class="org-tab" :class="{active:activeOrg==='all'}" @click="activeOrg='all'">
All <span class="org-tab-badge" x-text="giteaTotal"></span>
</button>
<template x-for="g in giteaGroups" :key="g.org">
<button class="org-tab" :class="{active:activeOrg===g.org}" @click="activeOrg=g.org">
<span x-text="g.org"></span>
<span class="org-tab-badge" x-text="g.projects.length"></span>
</button>
</template>
</div>
<!-- Search -->
<input type="text" class="search-input" x-model="giteaSearch" placeholder="🔍 Filter projects…" style="width:200px;padding:6px 10px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:13px;outline:none;">
</div>
<!-- Project cards (filtered) -->
<template x-for="group in filteredGroups" :key="group.org">
<div class="gitea-org">
<div class="gitea-org-header">
<span class="gitea-org-avatar" x-text="group.org.charAt(0).toUpperCase()"></span>
<span x-text="group.org"></span>
</div>
<div class="ws-grid">
<template x-for="proj in group.projects" :key="proj.id">
<div class="ws-card" @click="openGitea(proj)">
<div class="ws-card-name" x-text="proj.name"></div>
<div class="ws-card-sub">
<span x-text="group.org"></span>
<span style="margin:0 4px">/</span>
<span x-text="proj.name"></span>
</div>
<div class="ws-card-count">
<span x-show="proj.private" style="margin-right:6px">🔒</span>
<span x-text="proj.description || proj.language || ''" style="display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:220px;"></span>
</div>
</div>
</template>
</div>
</div>
</template>
<div class="gitea-empty" x-show="filteredGroups.length===0" style="margin-top:12px;">
No projects match your search.
</div>
</div>
<!-- No projects at all -->
<div class="gitea-empty" x-show="giteaStatus==='ok' && giteaTotal==0 && giteaGroups.length===0">
No Gitea projects found.
</div>
</div>
<!-- Create/Rename dialog -->
<div class="dialog-overlay" x-show="showCreate||showRename" @click.away="showCreate=false;showRename=false">
<div class="dialog-overlay" x-show="showCreate||showRename" @click.outside="showCreate=false;showRename=false">
<div class="dialog-box">
<h3 x-text="showRename?'Rename Workspace':'New Workspace'"></h3>
<input class="dialog-input" x-model="wsName" placeholder="Workspace name" @keydown.enter="showRename?doRename():doCreate()">
@@ -96,23 +182,42 @@ function workspacesPage() {
wsName: '',
renameTarget: null,
// Gitea
giteaStatus: 'loading', // loading|ok|not_linked|error
giteaGroups: [],
giteaTotal: 0,
activeOrg: 'all',
giteaSearch: '',
get filteredGroups() {
var self = this;
var q = (this.giteaSearch || '').toLowerCase();
var groups = this.activeOrg === 'all' ? this.giteaGroups : this.giteaGroups.filter(function(g) { return g.org === self.activeOrg; });
if (!q) return groups;
return groups.map(function(g) {
return {org: g.org, avatar: g.avatar, projects: g.projects.filter(function(p) {
return p.name.toLowerCase().includes(q) || (p.description||'').toLowerCase().includes(q);
})};
}).filter(function(g) { return g.projects.length > 0; });
},
async init() {
await this.load();
await this.loadGitea();
},
async load() {
const r = await fetch('/api/workspaces');
const d = await r.json();
this.workspaces = d.workspaces || [];
this.activeId = d.active_id;
},
async select(ws) {
async selectLocal(ws) {
await fetch(`/api/workspaces/${ws.id}/select`, {method:'POST'});
if (ws.page_count > 0) {
window.location = '/local-workspace';
} else {
window.location = '/local-workspace';
}
},
async doCreate() {
if (!this.wsName.trim()) return;
await fetch('/api/workspaces', {
@@ -124,11 +229,13 @@ function workspacesPage() {
this.showCreate = false;
await this.load();
},
renameWs(ws) {
this.renameTarget = ws;
this.wsName = ws.name;
this.showRename = true;
},
async doRename() {
if (!this.wsName.trim()||!this.renameTarget) return;
await fetch(`/api/workspaces/${this.renameTarget.id}`, {
@@ -141,10 +248,80 @@ function workspacesPage() {
this.renameTarget = null;
await this.load();
},
async deleteWs(ws) {
if (!confirm(`Delete workspace "${ws.name}" and all its pages?`)) return;
await fetch(`/api/workspaces/${ws.id}`, {method:'DELETE'});
await this.load();
},
// ── Gitea ──
async loadGitea() {
this.giteaStatus = 'loading';
try {
// Get orgs
const orgsRes = await fetch('/api/gitea/orgs');
if (orgsRes.status === 401) { this.giteaStatus = 'not_linked'; return; }
if (!orgsRes.ok) { this.giteaStatus = 'error'; return; }
const orgsData = await orgsRes.json();
const orgs = orgsData.orgs || [];
// Fetch repos: user repos + org repos
const groups = [];
// Get username for the "personal" tab
let myLogin = 'Me';
try {
const meRes = await fetch('/auth/user');
if (meRes.ok) {
const meData = await meRes.json();
myLogin = meData.user?.login || 'Me';
if (myLogin.includes('_')) myLogin = myLogin.split('_').pop(); // strip gitea_ prefix if present
}
} catch(e) {}
// User repos (no org filter)
try {
const userRes = await fetch('/api/gitea/projects');
if (userRes.ok) {
const d = await userRes.json();
const repos = d.projects || [];
if (repos.length) {
groups.push({org: myLogin, avatar: '', projects: repos.map(r => ({...r, owner: r.owner || {login: myLogin}}))});
}
}
} catch(e) {}
// Org repos
for (const org of orgs) {
try {
const res = await fetch('/api/gitea/projects?org=' + encodeURIComponent(org.username || org.login || org.name));
if (res.ok) {
const d = await res.json();
if (d.projects && d.projects.length) {
groups.push({org: org.username || org.login || org.name, avatar: org.avatar_url || '', projects: d.projects});
}
}
} catch(e) {}
}
this.giteaGroups = groups;
this.giteaTotal = groups.reduce((sum, g) => sum + g.projects.length, 0);
this.giteaStatus = 'ok';
} catch(e) {
this.giteaStatus = 'error';
}
},
openGitea(proj) {
const owner = proj.owner?.login || proj.owner?.username || proj.full_name?.split('/')[0] || '';
const repo = proj.name;
if (owner && repo) {
// Set workspace cookie so sidebar shows tree
document.cookie = 'flowdeck_workspace=gitea:' + owner + ':' + repo + ';path=/;SameSite=Lax';
window.location = `/gitea-workspace?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`;
}
}
};
}
+52 -52
View File
@@ -29,87 +29,87 @@
## Phase 1 — Authentification Multi-Mode
### 1.1 Comptes locaux avec mot de passe
- [ ] **DB**: Ajouter `password_hash` (bcrypt) à la table `users`
- [ ] **DB**: Ajouter `is_active`, `is_admin`, `last_login`, `login_attempts`, `locked_until`
- [ ] **API**: `POST /auth/register` — création de compte local (email + password)
- [ ] **API**: `POST /auth/login` — login local (email + password → session)
- [ ] **Page**: `/login` — formulaire login/register
- [ ] **Sécurité**: Rate limiting (5 tentatives → lock 15 min), bcrypt cost=12
- [ ] **Sécurité**: CSRF sur toutes les routes auth
- [ ] **Session**: Détachée de Gitea — session valide sans OAuth
- [x] **DB**: Ajouter `password_hash` (hash) à la table `users`
- [x] **DB**: Ajouter `is_active`, `is_admin`, `last_login`, `login_attempts`, `locked_until`
- [x] **API**: `POST /auth/register` — création de compte local (email + password)
- [x] **API**: `POST /auth/login` — login local (email + password → session)
- [x] **Page**: `/login` — formulaire login/register
- [x] **Sécurité**: Rate limiting (5 tentatives → lock 15 min)
- [x] **Sécurité**: CSRF sur toutes les routes auth
- [x] **Session**: Détachée de Gitea — session valide sans OAuth
### 1.2 Page de configuration du compte
- [ ] **Page**: `/accounts/settings` — config du profil
- [ ] **Section**: Profil (nom, email, avatar, mot de passe)
- [ ] **Section**: Connexions forges (Gitea, GitHub) — lier/délier
- [ ] **Section**: Préférences (langue, thème, notifs)
- [x] **Page**: `/accounts/settings` — config du profil
- [x] **Section**: Profil (nom, email, avatar, mot de passe)
- [x] **Section**: Connexions forges (Gitea, GitHub) — lier/délier
- [x] **Section**: Préférences (langue, thème, notifs)
- [ ] **Section**: Tokens API (générer/révoquer des clés API)
- [ ] **Section**: Sessions actives (voir et révoquer)
### 1.3 OAuth multi-forge
- [ ] **Refactor**: `GiteaOAuth` → `OAuthProvider` (classe abstraite)
- [x] **Refactor**: `GiteaOAuth` → `OAuthProvider` (classe abstraite)
- [ ] **Implement**: `GitHubOAuthProvider` (OAuth2 GitHub)
- [ ] **Implement**: `GiteaOAuthProvider` (existant, refactoré)
- [ ] **DB**: Table `user_oauth_tokens` (user_id, provider, access_token, refresh_token, expires_at)
- [ ] **API**: `GET /auth/{provider}/login` — redirige vers OAuth
- [ ] **API**: `GET /auth/{provider}/callback` — callback OAuth
- [ ] **Page**: `/accounts/settings` → boutons "Connect GitHub" / "Connect Gitea"
- [ ] **Fallback**: L'utilisateur peut utiliser FlowDeck SANS lier aucune forge
- [x] **Implement**: `GiteaOAuthProvider` (existant, refactoré)
- [x] **DB**: Table `user_oauth_tokens` (user_id, provider, access_token, refresh_token, expires_at)
- [x] **API**: `GET /auth/{provider}/login` — redirige vers OAuth
- [x] **API**: `GET /auth/{provider}/callback` — callback OAuth
- [x] **Page**: `/accounts/settings` → boutons "Connect GitHub" / "Connect Gitea"
- [x] **Fallback**: L'utilisateur peut utiliser FlowDeck SANS lier aucune forge
---
## Phase 2 — Abstraction Multi-Forge
### 2.1 Adapter pattern pour les forges
- [ ] **Interface**: `ForgeAdapter` (classe abstraite)
- [x] **Interface**: `ForgeAdapter` (classe abstraite)
- `list_repos(token) → List[Repo]`
- `get_repo(token, owner, repo) → RepoDetail`
- `list_issues(token, owner, repo) → List[Issue]`
- `get_file_tree(token, owner, repo, path) → TreeNode`
- `get_file_content(token, owner, repo, path) → str`
- `create_webhook(token, owner, repo, url) → Webhook`
- [ ] **Implement**: `GiteaAdapter` (API Gitea existante → interface unifiée)
- [x] **Implement**: `GiteaAdapter` (API Gitea existante → interface unifiée)
- [ ] **Implement**: `GitHubAdapter` (API GitHub v3 → interface unifiée)
- [ ] **DB**: Table `forge_connections` (user_id, provider, token_id, instance_url)
- [ ] **Config**: Support GitHub Enterprise (custom URL) et Gitea self-hosted
- [x] **DB**: Table `forge_connections` (user_id, provider, token_id, instance_url)
- [x] **Config**: Support GitHub Enterprise (custom URL) et Gitea self-hosted
### 2.2 Synchronisation des projets
- [ ] **Service**: `ProjectSyncService` — sync projets depuis les forges liées
- [x] **Service**: `ProjectSyncService` — sync projets depuis les forges liées
- [ ] **DB**: Table `projects` avec type (`builtin`, `gitea`, `github`)
- [ ] **DB**: `projects.forge_id` — référence externe (repo ID)
- [ ] **DB**: `projects.clone_url`, `projects.default_branch`, `projects.language`
- [ ] **Cron**: Sync périodique des projets (configurable, défaut: chaque heure)
- [ ] **Page**: `/workspace` — liste TOUS les projets (built-in + Gitea + GitHub)
- [x] **Page**: `/workspace` — liste TOUS les projets (built-in + Gitea + GitHub)
---
## Phase 3 — Workspace & Navigation
### 3.1 Nouvelle page Workspace
- [ ] **Page**: `/workspace` — dashboard central
- [x] **Page**: `/workspace` — dashboard central
- Section "My Projects" (built-in)
- Section "Gitea Projects" (si connecté)
- Section "GitHub Projects" (si connecté)
- Bouton "Create Project" (built-in)
- Bouton "Import from Gitea/GitHub"
- [ ] **Filtres**: Par forge, par statut, recherche
- [ ] **Carte projet**: Nom, description, forge badge, dernière activité, nombre de pages
- [x] **Filtres**: Par forge, par statut, recherche
- [x] **Carte projet**: Nom, description, forge badge, dernière activité, nombre de pages
### 3.2 Barre de navigation projet
- [ ] **Topbar**: Section entre "Meetings" et la sidebar
- [x] **Topbar**: Section entre "Meetings" et la sidebar
- Nom du projet actif (dropdown pour switcher)
- Badge forge (icône Gitea/GitHub/built-in)
- [ ] **Arborescence**: Sous le projet dans la sidebar gauche
- [x] **Arborescence**: Sous le projet dans la sidebar gauche
- Dossiers et fichiers du repo Git (lecture seule si forge externe)
- Pages FlowDeck liées au projet
- Bouton "+" pour créer nouvelle page dans le projet
- [ ] **Service**: `FileTreeService` — construit l'arborescence depuis l'API forge
- [ ] **Cache**: Arborescence en cache (TTL 5 min) pour éviter les appels API à chaque page
- [x] **Service**: `FileTreeService` — construit l'arborescence depuis l'API forge
- [x] **Cache**: Arborescence en cache (TTL 5 min) pour éviter les appels API à chaque page
### 3.3 Navigation projet
- [ ] **Sidebar**: Les projets apparaissent sous une section dédiée
- [ ] **Breadcrumb**: Workspace > Projet > Dossier > Page
- [ ] **Contexte projet**: Toute nouvelle page créée depuis un projet y est liée
- [x] **Sidebar**: Les projets apparaissent sous une section dédiée
- [x] **Breadcrumb**: Workspace > Projet > Dossier > Page
- [x] **Contexte projet**: Toute nouvelle page créée depuis un projet y est liée
- [ ] **Quick switch**: Ctrl+K → chercher et switcher de projet
---
@@ -117,32 +117,32 @@
## Phase 4 — Fonctionnement sans forge
### 4.1 Mode standalone
- [ ] **Config**: `FLOWDECK_STANDALONE=true` — démarre sans aucune forge
- [ ] **UI**: Pas de sections Gitea/GitHub si non configuré
- [ ] **Workspace**: Uniquement projets built-in
- [ ] **Auth**: Login local uniquement (pas de boutons OAuth)
- [ ] **Pages**: Création/édition 100% locale, pas de synchro externe
- [x] **Config**: `FLOWDECK_STANDALONE=true` — démarre sans aucune forge
- [x] **UI**: Pas de sections Gitea/GitHub si non configuré
- [x] **Workspace**: Uniquement projets built-in
- [x] **Auth**: Login local uniquement (pas de boutons OAuth)
- [x] **Pages**: Création/édition 100% locale, pas de synchro externe
### 4.2 Mode hybride
- [ ] Un utilisateur peut avoir Gitea lié, un autre GitHub, un troisième rien
- [ ] Chaque utilisateur voit SES projets de forge dans SA workspace
- [ ] Les projets built-in sont partagés selon les permissions workspace
- [x] Un utilisateur peut avoir Gitea lié, un autre GitHub, un troisième rien
- [x] Chaque utilisateur voit SES projets de forge dans SA workspace
- [x] Les projets built-in sont partagés selon les permissions workspace
---
## Phase 5 — Permissions & Collaboratif
### 5.1 Rôles workspace
- [ ] **DB**: Table `workspace_members` avec rôles: owner, admin, editor, viewer
- [ ] **API**: `POST /workspace/{id}/members` — inviter un utilisateur
- [ ] **API**: `DELETE /workspace/{id}/members/{user_id}` — retirer
- [ ] **API**: `PUT /workspace/{id}/members/{user_id}` — changer rôle
- [ ] **Middleware**: `PermissionMiddleware` — vérifie les droits avant chaque action
- [x] **DB**: Table `workspace_members` avec rôles: owner, admin, editor, viewer
- [x] **API**: `POST /workspace/{id}/members` — inviter un utilisateur
- [x] **API**: `DELETE /workspace/{id}/members/{user_id}` — retirer
- [x] **API**: `PUT /workspace/{id}/members/{user_id}` — changer rôle
- [x] **Middleware**: `PermissionMiddleware` — vérifie les droits avant chaque action
### 5.2 Partage de pages
- [ ] Étendre le système Share existant pour supporter les permissions workspace
- [ ] Une page dans un workspace est visible par tous les membres
- [ ] "Anyone with the link" crée un lien public indépendant du workspace
- [x] Étendre le système Share existant pour supporter les permissions workspace
- [x] Une page dans un workspace est visible par tous les membres
- [x] "Anyone with the link" crée un lien public indépendant du workspace
---
@@ -207,4 +207,4 @@
---
*Dernière mise à jour: 2026-07-10 — créé avec Bruno*
*Dernière mise à jour: 2026-07-13 — phases 1-5 majoritairement complétées*
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Before

Width:  |  Height:  |  Size: 205 KiB

After

Width:  |  Height:  |  Size: 205 KiB

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 170 KiB

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Before

Width:  |  Height:  |  Size: 209 KiB

After

Width:  |  Height:  |  Size: 209 KiB

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 68 KiB

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 93 KiB

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 126 KiB

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 91 KiB

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 52 KiB

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.9 KiB

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Some files were not shown because too many files have changed in this diff Show More