Corrige les bugs trouvés par l'audit (synchro, notifications, fiche, thème…)
deploy / deploy (push) Successful in 34s

- Fiche : un geste fait pendant l'ajout d'un titre (note, coup de cœur…)
  était perdu ; il est mis en attente puis appliqué.
- Fiche : l'ouvrir changeait sa date de modification (note du public,
  image, saisons mises à jour via update) et faisait bouger la bannière
  « Je regarde » ; ces mises à jour passent par patchMany.
- Réglages → Mon compte : état de la synchro visible (synchronisé il y a…,
  hors ligne, échec + raison, modifications en attente) et bouton
  « Synchroniser » (18 langues).
- Notifications : elles étaient marquées lues avant d'être chargées, le
  point « non lu » ne s'affichait jamais.
- Retour / Échap : le menu ⋯, la confirmation et l'aperçu de partage se
  ferment seuls (au lieu de la fiche) ; Échap ferme aussi la roulette, le
  calendrier, le Top 5 et la fenêtre d'installation. Entrée d'historique
  orpheline nettoyée après un rechargement.
- Thème : script bloquant public/theme-boot.js (compatible CSP) qui pose
  les couleurs avant le premier affichage ; meta color-scheme suit le thème.
- Import « Fusionner » : une sauvegarde plus ancienne n'écrase plus une
  fiche modifiée depuis ; « Remplacer » date les fiches importées.
- Avis et notifications : réponses du serveur validées (avatar, textes).
- Épisodes : une série/un anime annoncé mais pas encore diffusé n'a plus
  tous ses épisodes comptés comme sortis.
- Divers : is_admin vérifié une fois par connexion, revisionnages du plus
  récent au plus ancien, erreur affichée si l'enregistrement des infos échoue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-10-08 20:16:35 +00:00
1 parent 8fafb6799f
commit 618fd66e09
36 files changed
+385 -24

No files matched your search

+2
View File
@@ -15,6 +15,8 @@
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" /> <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
<link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" />
<title>AzuuCine</title> <title>AzuuCine</title>
<!-- Thème choisi appliqué avant le premier affichage (fichier local : compatible avec la CSP) -->
<script src="/theme-boot.js"></script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+26
View File
@@ -0,0 +1,26 @@
/*
* AzuuCine — thème posé avant le premier affichage (script bloquant, chargé dans <head>).
* Reprend les couleurs calculées au dernier lancement (voir applyTheme dans src/lib/theme.ts),
* pour ne jamais voir le thème par défaut le temps que l'app démarre.
*/
;(function () {
try {
var raw = localStorage.getItem('azuucine:theme-css')
if (!raw) return
var v = JSON.parse(raw)
var hex = /^#[0-9a-f]{6}$/i
var modes = { light: 1, dark: 1, night: 1, starfield: 1 }
if (!v || !modes[v.theme] || !hex.test(v.accent) || !hex.test(v.fill) || !hex.test(v.on) || !hex.test(v.canvas)) return
var root = document.documentElement
root.setAttribute('data-theme', v.theme)
root.style.setProperty('--color-accent', v.accent)
root.style.setProperty('--color-accent-fill', v.fill)
root.style.setProperty('--color-on-accent', v.on)
var meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.setAttribute('content', v.canvas)
var scheme = document.querySelector('meta[name="color-scheme"]')
if (scheme) scheme.setAttribute('content', v.theme === 'light' ? 'light' : 'dark')
} catch (e) {
/* stockage indisponible : thème par défaut */
}
})()
+43 -1
View File
@@ -1,12 +1,14 @@
import Avatar from './social/Avatar' import Avatar from './social/Avatar'
import { useSocial } from './social/SocialProvider' import { useSocial } from './social/SocialProvider'
import { t } from '../i18n' import { t } from '../i18n'
import { KeyRound, Loader2, LogOut, UserRound } from 'lucide-react' import { AlertTriangle, Check, CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth' import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth'
import { timeAgo } from '../lib/timeAgo'
import type { AccountApi } from '../store' import type { AccountApi } from '../store'
import ConfirmDialog from './ConfirmDialog' import ConfirmDialog from './ConfirmDialog'
import { SectionTitle } from './ui' import { SectionTitle } from './ui'
import { cx } from '../lib/utils'
/** Réglages → Mon compte : mot de passe, déconnexion. La synchro tourne en arrière-plan. */ /** Réglages → Mon compte : mot de passe, déconnexion. La synchro tourne en arrière-plan. */
export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) { export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) {
@@ -67,6 +69,46 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
</span> </span>
</div> </div>
{/* État de la synchronisation : visible, surtout quand quelque chose bloque */}
<div className="flex items-center gap-3.5 px-4 py-3.5" role="status">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-full bg-surface-2', sync.state === 'error' ? 'text-accent' : 'text-ink-2')}>
{sync.state === 'syncing' ? (
<RefreshCw size={18} className="animate-spin" />
) : sync.state === 'offline' ? (
<CloudOff size={18} />
) : sync.state === 'error' ? (
<AlertTriangle size={18} />
) : (
<Check size={18} />
)}
</span>
<span className="min-w-0 flex-1">
<span className={cx('block text-sm font-medium', sync.state === 'error' && 'text-accent')}>
{sync.state === 'syncing'
? t('sync.syncing')
: sync.state === 'offline'
? t('sync.offline')
: sync.state === 'error'
? t('sync.error')
: sync.lastSyncAt
? t('sync.synced', { when: timeAgo(sync.lastSyncAt) })
: t('sync.never')}
</span>
{(sync.pending > 0 || (sync.state === 'error' && sync.error)) && (
<span className="mt-0.5 block truncate text-xs text-ink-3">
{[sync.pending > 0 ? t('sync.pending', { count: sync.pending }) : '', sync.state === 'error' ? sync.error : ''].filter(Boolean).join(' · ')}
</span>
)}
</span>
<button
onClick={() => void account.syncNow().catch(() => {})}
disabled={sync.state === 'syncing' || sync.state === 'offline'}
className="btn btn-ghost shrink-0 px-3 py-1.5 text-xs"
>
{t('sync.now')}
</button>
</div>
<button <button
onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())} onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())}
className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2" className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2"
+2
View File
@@ -9,6 +9,7 @@ import { remotePosterToLocal } from '../lib/image'
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases' import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
import { readStorage } from '../lib/security' import { readStorage } from '../lib/security'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape'
import { useScrollLock } from '../lib/scrollLock' import { useScrollLock } from '../lib/scrollLock'
import { cx, normalizeText, todayISO } from '../lib/utils' import { cx, normalizeText, todayISO } from '../lib/utils'
import { useMedia } from '../store' import { useMedia } from '../store'
@@ -111,6 +112,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
const request = useRef(0) const request = useRef(0)
useScrollLock() useScrollLock()
useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
useEffect(() => { useEffect(() => {
+2
View File
@@ -1,4 +1,5 @@
import { t } from '../i18n' import { t } from '../i18n'
import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape' import { useEscape } from '../lib/escape'
interface Props { interface Props {
@@ -13,6 +14,7 @@ interface Props {
/** Fenêtre « Êtes-vous sûr ? » intégrée à l'app (plus fiable que window.confirm sur mobile). */ /** Fenêtre « Êtes-vous sûr ? » intégrée à l'app (plus fiable que window.confirm sur mobile). */
export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) { export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) {
useEscape(onCancel, open) useEscape(onCancel, open)
useBackToClose(onCancel, open)
if (!open) return null if (!open) return null
return ( return (
+2
View File
@@ -22,6 +22,7 @@ import { TypeBadge } from './Badges'
import Poster from './Poster' import Poster from './Poster'
import { RatingBadge } from './Rating' import { RatingBadge } from './Rating'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape'
import { useScrollLock } from '../lib/scrollLock' import { useScrollLock } from '../lib/scrollLock'
const CARD = 112 // largeur d'une affiche dans le rouleau (w-28) const CARD = 112 // largeur d'une affiche dans le rouleau (w-28)
@@ -74,6 +75,7 @@ export default function Roulette({ onClose, onOpen }: Props) {
// Bloque le défilement derrière + mémorise les filtres // Bloque le défilement derrière + mémorise les filtres
useScrollLock() useScrollLock()
useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
useEffect(() => saveFilters(filters), [filters]) useEffect(() => saveFilters(filters), [filters])
+2
View File
@@ -2,6 +2,7 @@ import { t } from '../i18n'
import { Download, Share2, X } from 'lucide-react' import { Download, Share2, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { shareImage } from '../lib/shareCard' import { shareImage } from '../lib/shareCard'
import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape' import { useEscape } from '../lib/escape'
interface Props { interface Props {
@@ -30,6 +31,7 @@ export default function SharePreview({ blob, filename, title, onClose }: Props)
return () => URL.revokeObjectURL(u) return () => URL.revokeObjectURL(u)
}, [blob]) }, [blob])
useEscape(onClose) useEscape(onClose)
useBackToClose(onClose)
const go = async () => { const go = async () => {
setBusy(true) setBusy(true)
+2
View File
@@ -8,6 +8,7 @@ import type { TopCategory } from '../types'
import { TypeBadge } from './Badges' import { TypeBadge } from './Badges'
import Poster from './Poster' import Poster from './Poster'
import { useBackToClose } from '../lib/backNav' import { useBackToClose } from '../lib/backNav'
import { useEscape } from '../lib/escape'
import { useScrollLock } from '../lib/scrollLock' import { useScrollLock } from '../lib/scrollLock'
interface Props { interface Props {
@@ -32,6 +33,7 @@ export default function TopFiveEditor({ category: initialCategory, onClose }: Pr
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items]) const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items])
useScrollLock() useScrollLock()
useEscape(onClose)
useBackToClose(onClose) useBackToClose(onClose)
/** Changer de catégorie enregistre d'abord celle en cours. */ /** Changer de catégorie enregistre d'abord celle en cours. */
+2 -2
View File
@@ -1,6 +1,6 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react' import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { getFollowRequests, getMyProfile, type Profile, type ProfileCard } from '../../lib/cloud/social' import { getFollowRequests, getMyProfile, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { markNotificationsRead, unreadCount } from '../../lib/cloud/notifications' import { unreadCount } from '../../lib/cloud/notifications'
import { useMedia } from '../../store' import { useMedia } from '../../store'
import type { MediaItem } from '../../types' import type { MediaItem } from '../../types'
import EditProfile from './EditProfile' import EditProfile from './EditProfile'
@@ -143,8 +143,8 @@ export function SocialProvider({ children, onOpenOwnItem }: { children: ReactNod
openFollowList: (profile, list) => push({ kind: 'follows', profile, list }), openFollowList: (profile, list) => push({ kind: 'follows', profile, list }),
openReviews: (externalId, title) => push({ kind: 'reviews', externalId, title }), openReviews: (externalId, title) => push({ kind: 'reviews', externalId, title }),
openNotifications: () => { openNotifications: () => {
// La liste se marque lue elle-même, après chargement (sinon les « non lu » n'étaient jamais visibles)
setUnread(0) setUnread(0)
void markNotificationsRead().catch(() => {})
push({ kind: 'notifications' }) push({ kind: 'notifications' })
}, },
unread, unread,
+5
View File
@@ -61,6 +61,7 @@ export default function EditDetails({
overview: item?.overview, overview: item?.overview,
})) }))
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [saveError, setSaveError] = useState<string>()
const [posterError, setPosterError] = useState<string>() const [posterError, setPosterError] = useState<string>()
const fileRef = useRef<HTMLInputElement>(null) const fileRef = useRef<HTMLInputElement>(null)
const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft((d) => ({ ...d, [k]: v })) const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft((d) => ({ ...d, [k]: v }))
@@ -80,6 +81,7 @@ export default function EditDetails({
const submit = async () => { const submit = async () => {
if (!draft.title.trim() || saving) return if (!draft.title.trim() || saving) return
setSaving(true) setSaving(true)
setSaveError(undefined)
const clean: Draft = { const clean: Draft = {
...draft, ...draft,
title: draft.title.trim(), title: draft.title.trim(),
@@ -98,6 +100,8 @@ export default function EditDetails({
const created = await add({ ...clean, status: 'a_voir', criteria: {}, episodesWatched: 0 }) const created = await add({ ...clean, status: 'a_voir', criteria: {}, episodesWatched: 0 })
onCreated?.(created) onCreated?.(created)
} }
} catch (e) {
setSaveError((e as Error).message)
} finally { } finally {
setSaving(false) setSaving(false)
} }
@@ -124,6 +128,7 @@ export default function EditDetails({
void submit() void submit()
}} }}
> >
{saveError && <p role="alert" className="mx-auto mt-4 max-w-2xl rounded-xl border border-accent px-3 py-2.5 text-sm">{saveError}</p>}
<div className="mx-auto max-w-2xl space-y-7 px-4 pt-6 pb-[calc(10rem+env(safe-area-inset-bottom))]"> <div className="mx-auto max-w-2xl space-y-7 px-4 pt-6 pb-[calc(10rem+env(safe-area-inset-bottom))]">
<div className="flex gap-4"> <div className="flex gap-4">
<div className="w-28 shrink-0"> <div className="w-28 shrink-0">
+35 -10
View File
@@ -1,6 +1,6 @@
import { locale, t } from '../../i18n' import { locale, t } from '../../i18n'
import { Bookmark, Check, ChevronDown, Eye, Heart, Loader2, MessagesSquare, Minus, MoreHorizontal, Pencil, Play, Plus, Share2, Trash2, X } from 'lucide-react' import { Bookmark, Check, ChevronDown, Eye, Heart, Loader2, MessagesSquare, Minus, MoreHorizontal, Pencil, Play, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useState, type ReactNode } from 'react' import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type SearchResult, type TitleExtras } from '../../lib/catalogApi' import { getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type SearchResult, type TitleExtras } from '../../lib/catalogApi'
import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants' import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants'
import { genreLabel } from '../../lib/genres' import { genreLabel } from '../../lib/genres'
@@ -43,7 +43,7 @@ interface Props {
* Vu / En cours / À voir, note, coup de cœur, avis, épisodes, casting et note moyenne du public. * Vu / En cours / À voir, note, coup de cœur, avis, épisodes, casting et note moyenne du public.
*/ */
export default function TitleSheet({ item: initial, seed, onClose, onGoToSettings }: Props) { export default function TitleSheet({ item: initial, seed, onClose, onGoToSettings }: Props) {
const { items, settings, add, update, remove, lists } = useMedia() const { items, settings, add, update, remove, lists, patchMany } = useMedia()
const social = useSocial() const social = useSocial()
useScrollLock() useScrollLock()
useEscape(onClose) useEscape(onClose)
@@ -104,7 +104,8 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
patch.seasons = seasons patch.seasons = seasons
if ((total ?? 0) > (item.episodesTotal ?? 0)) patch.episodesTotal = total if ((total ?? 0) > (item.episodesTotal ?? 0)) patch.episodesTotal = total
} }
if (Object.keys(patch).length) void update(item.id, patch) // Mise à jour d'arrière-plan : ne change pas la date de modification de la fiche (ni l'ordre « récent »)
if (Object.keys(patch).length) void patchMany([{ id: item.id, patch }])
}) })
.catch(() => {}) .catch(() => {})
return () => { return () => {
@@ -115,11 +116,13 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
// Garde la note du public de la fiche à jour (utilisée par les stats « Moi vs le public ») // Garde la note du public de la fiche à jour (utilisée par les stats « Moi vs le public »)
useEffect(() => { useEffect(() => {
if (item && extras?.average != null && Math.abs((item.publicRating ?? 0) - extras.average) >= 0.1) void update(item.id, { publicRating: extras.average }) if (item && extras?.average != null && Math.abs((item.publicRating ?? 0) - extras.average) >= 0.1) void patchMany([{ id: item.id, patch: { publicRating: extras.average } }])
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [extras?.average, item?.id]) }, [extras?.average, item?.id])
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const addingRef = useRef(false)
const pendingRef = useRef<Partial<MediaInput>>({})
const [toast, setToast] = useState<string>() const [toast, setToast] = useState<string>()
useEffect(() => { useEffect(() => {
if (!toast) return if (!toast) return
@@ -130,7 +133,13 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
/** Applique un changement ; ajoute d'abord le titre à la bibliothèque s'il n'y est pas encore. */ /** Applique un changement ; ajoute d'abord le titre à la bibliothèque s'il n'y est pas encore. */
const save = async (patch: Partial<MediaInput>) => { const save = async (patch: Partial<MediaInput>) => {
if (item) return update(item.id, patch) if (item) return update(item.id, patch)
if (busy || !seed) return if (!seed) return
// Ajout déjà en cours (affiche qui se télécharge…) : le geste est gardé et appliqué juste après
if (addingRef.current) {
Object.assign(pendingRef.current, patch)
return
}
addingRef.current = true
setBusy(true) setBusy(true)
try { try {
const base: Partial<MediaInput> = { ...(seed.source === 'tmdb' ? meta : seed.prefill) } const base: Partial<MediaInput> = { ...(seed.source === 'tmdb' ? meta : seed.prefill) }
@@ -149,9 +158,13 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
} as MediaInput) } as MediaInput)
setItemId(created.id) setItemId(created.id)
setToast(t('title.added')) setToast(t('title.added'))
const pending = pendingRef.current
pendingRef.current = {}
if (Object.keys(pending).length) await update(created.id, pending)
} catch (e) { } catch (e) {
setToast((e as Error).message) setToast((e as Error).message)
} finally { } finally {
addingRef.current = false
setBusy(false) setBusy(false)
} }
} }
@@ -492,8 +505,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
)} )}
{moreOpen && item && ( {moreOpen && item && (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center" onClick={() => setMoreOpen(false)}> <MoreMenu onClose={() => setMoreOpen(false)}>
<div className="safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>
<MenuButton icon={<Pencil size={18} />} onClick={() => (setMoreOpen(false), setEditing(true))}> <MenuButton icon={<Pencil size={18} />} onClick={() => (setMoreOpen(false), setEditing(true))}>
{t('hero.edit')} {t('hero.edit')}
</MenuButton> </MenuButton>
@@ -503,8 +515,7 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
<MenuButton icon={<Trash2 size={18} />} onClick={() => (setMoreOpen(false), setConfirmDelete(true))} danger> <MenuButton icon={<Trash2 size={18} />} onClick={() => (setMoreOpen(false), setConfirmDelete(true))} danger>
{t('form.delete')} {t('form.delete')}
</MenuButton> </MenuButton>
</div> </MoreMenu>
</div>
)} )}
{reviewing && ( {reviewing && (
@@ -550,6 +561,19 @@ function StatusButton({ icon, label, on, onClick, disabled }: { icon: ReactNode;
) )
} }
/** Menu « ⋯ » : se ferme avec Échap ou le geste retour, sans fermer la fiche derrière. */
function MoreMenu({ onClose, children }: { onClose: () => void; children: ReactNode }) {
useEscape(onClose)
useBackToClose(onClose)
return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center" onClick={onClose}>
<div role="menu" className="safe-bottom w-full max-w-md rounded-t-3xl border border-line-strong bg-surface p-3 sm:rounded-3xl" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>
)
}
function MenuButton({ icon, children, onClick, danger }: { icon: ReactNode; children: ReactNode; onClick: () => void; danger?: boolean }) { function MenuButton({ icon, children, onClick, danger }: { icon: ReactNode; children: ReactNode; onClick: () => void; danger?: boolean }) {
return ( return (
<button onClick={onClick} className={cx('flex w-full items-center gap-3 rounded-xl px-3 py-3.5 text-left text-[15px] active:bg-surface-2', danger ? 'text-accent' : 'text-ink')}> <button onClick={onClick} className={cx('flex w-full items-center gap-3 rounded-xl px-3 py-3.5 text-left text-[15px] active:bg-surface-2', danger ? 'text-accent' : 'text-ink')}>
@@ -663,7 +687,8 @@ function Synopsis({ text }: { text: string }) {
/** Dates, plateforme, listes et revisionnages : enregistrés dès qu'on les change. */ /** Dates, plateforme, listes et revisionnages : enregistrés dès qu'on les change. */
function Tracking({ item, lists, onChange }: { item: MediaItem; lists: { id: string; name: string }[]; onChange: (p: Partial<MediaInput>) => void }) { function Tracking({ item, lists, onChange }: { item: MediaItem; lists: { id: string; name: string }[]; onChange: (p: Partial<MediaInput>) => void }) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const rewatches = item.rewatchDates ?? [] // Plus récent en premier (la sauvegarde les range dans l'autre sens)
const rewatches = [...(item.rewatchDates ?? [])].sort().reverse()
const summary = [ const summary = [
item.startDate && `${t('form.startShort')} ${formatDate(item.startDate)}`, item.startDate && `${t('form.startShort')} ${formatDate(item.startDate)}`,
item.endDate && `${t('form.endShort')} ${formatDate(item.endDate)}`, item.endDate && `${t('form.endShort')} ${formatDate(item.endDate)}`,
+11
View File
@@ -1014,6 +1014,17 @@ const dict: Translations = {
'title.rewatchCount_two': "أُعيدت مشاهدته مرتين", 'title.rewatchCount_two': "أُعيدت مشاهدته مرتين",
'title.rewatchCount_few': "أُعيدت مشاهدته {count} مرات", 'title.rewatchCount_few': "أُعيدت مشاهدته {count} مرات",
'title.rewatchCount_many': "أُعيدت مشاهدته {count} مرة", 'title.rewatchCount_many': "أُعيدت مشاهدته {count} مرة",
'sync.syncing': "جارٍ المزامنة…",
'sync.offline': "غير متصل",
'sync.error': "فشلت المزامنة",
'sync.synced': "تمت المزامنة · {when}",
'sync.never': "لم تتم المزامنة بعد",
'sync.pending_one': "تعديل واحد في الانتظار",
'sync.pending_other': "{count} تعديل في الانتظار",
'sync.now': "مزامنة الآن",
'sync.pending_two': "تعديلان في الانتظار",
'sync.pending_few': "{count} تعديلات في الانتظار",
'sync.pending_many': "{count} تعديلًا في الانتظار",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Einmal erneut gesehen", 'title.rewatchCount_one': "Einmal erneut gesehen",
'title.rewatchCount_other': "{count}-mal erneut gesehen", 'title.rewatchCount_other': "{count}-mal erneut gesehen",
'title.rewatchedToday': "Heute erneut gesehen", 'title.rewatchedToday': "Heute erneut gesehen",
'sync.syncing': "Wird synchronisiert…",
'sync.offline': "Offline",
'sync.error': "Synchronisierung fehlgeschlagen",
'sync.synced': "Synchronisiert · {when}",
'sync.never': "Noch nicht synchronisiert",
'sync.pending_one': "{count} Änderung ausstehend",
'sync.pending_other': "{count} Änderungen ausstehend",
'sync.now': "Jetzt synchronisieren",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Rewatched once", 'title.rewatchCount_one': "Rewatched once",
'title.rewatchCount_other': "Rewatched {count} times", 'title.rewatchCount_other': "Rewatched {count} times",
'title.rewatchedToday': "Rewatched today", 'title.rewatchedToday': "Rewatched today",
'sync.syncing': "Syncing…",
'sync.offline': "Offline",
'sync.error': "Sync failed",
'sync.synced': "Synced · {when}",
'sync.never': "Not synced yet",
'sync.pending_one': "{count} change waiting",
'sync.pending_other': "{count} changes waiting",
'sync.now': "Sync now",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Vuelto a ver una vez", 'title.rewatchCount_one': "Vuelto a ver una vez",
'title.rewatchCount_other': "Vuelto a ver {count} veces", 'title.rewatchCount_other': "Vuelto a ver {count} veces",
'title.rewatchedToday': "Vuelto a ver hoy", 'title.rewatchedToday': "Vuelto a ver hoy",
'sync.syncing': "Sincronizando…",
'sync.offline': "Sin conexión",
'sync.error': "La sincronización falló",
'sync.synced': "Sincronizado · {when}",
'sync.never': "Aún no sincronizado",
'sync.pending_one': "{count} cambio pendiente",
'sync.pending_other': "{count} cambios pendientes",
'sync.now': "Sincronizar",
} }
export default dict export default dict
+8
View File
@@ -881,6 +881,14 @@ const dict = {
'title.rewatchCount_one': "Revu {count} fois", 'title.rewatchCount_one': "Revu {count} fois",
'title.rewatchCount_other': "Revu {count} fois", 'title.rewatchCount_other': "Revu {count} fois",
'title.rewatchedToday': "Revu aujourd’hui", 'title.rewatchedToday': "Revu aujourd’hui",
'sync.syncing': "Synchronisation…",
'sync.offline': "Hors ligne",
'sync.error': "La synchronisation a échoué",
'sync.synced': "Synchronisé · {when}",
'sync.never': "Pas encore synchronisé",
'sync.pending_one': "{count} modification en attente",
'sync.pending_other': "{count} modifications en attente",
'sync.now': "Synchroniser",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "{count} बार दोबारा देखा", 'title.rewatchCount_one': "{count} बार दोबारा देखा",
'title.rewatchCount_other': "{count} बार दोबारा देखा", 'title.rewatchCount_other': "{count} बार दोबारा देखा",
'title.rewatchedToday': "आज दोबारा देखा", 'title.rewatchedToday': "आज दोबारा देखा",
'sync.syncing': "सिंक हो रहा है…",
'sync.offline': "ऑफ़लाइन",
'sync.error': "सिंक विफल रहा",
'sync.synced': "सिंक हुआ · {when}",
'sync.never': "अभी तक सिंक नहीं हुआ",
'sync.pending_one': "{count} बदलाव बाकी",
'sync.pending_other': "{count} बदलाव बाकी",
'sync.now': "अभी सिंक करें",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Ditonton ulang {count} kali", 'title.rewatchCount_one': "Ditonton ulang {count} kali",
'title.rewatchCount_other': "Ditonton ulang {count} kali", 'title.rewatchCount_other': "Ditonton ulang {count} kali",
'title.rewatchedToday': "Ditonton ulang hari ini", 'title.rewatchedToday': "Ditonton ulang hari ini",
'sync.syncing': "Menyinkronkan…",
'sync.offline': "Offline",
'sync.error': "Sinkronisasi gagal",
'sync.synced': "Tersinkron · {when}",
'sync.never': "Belum disinkronkan",
'sync.pending_one': "{count} perubahan menunggu",
'sync.pending_other': "{count} perubahan menunggu",
'sync.now': "Sinkronkan",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Rivisto una volta", 'title.rewatchCount_one': "Rivisto una volta",
'title.rewatchCount_other': "Rivisto {count} volte", 'title.rewatchCount_other': "Rivisto {count} volte",
'title.rewatchedToday': "Rivisto oggi", 'title.rewatchedToday': "Rivisto oggi",
'sync.syncing': "Sincronizzazione…",
'sync.offline': "Offline",
'sync.error': "Sincronizzazione non riuscita",
'sync.synced': "Sincronizzato · {when}",
'sync.never': "Non ancora sincronizzato",
'sync.pending_one': "{count} modifica in attesa",
'sync.pending_other': "{count} modifiche in attesa",
'sync.now': "Sincronizza",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "{count} 回再視聴", 'title.rewatchCount_one': "{count} 回再視聴",
'title.rewatchCount_other': "{count} 回再視聴", 'title.rewatchCount_other': "{count} 回再視聴",
'title.rewatchedToday': "今日再視聴", 'title.rewatchedToday': "今日再視聴",
'sync.syncing': "同期中…",
'sync.offline': "オフライン",
'sync.error': "同期に失敗しました",
'sync.synced': "同期済み · {when}",
'sync.never': "まだ同期されていません",
'sync.pending_one': "{count} 件の変更が保留中",
'sync.pending_other': "{count} 件の変更が保留中",
'sync.now': "今すぐ同期",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "{count}번 다시 봄", 'title.rewatchCount_one': "{count}번 다시 봄",
'title.rewatchCount_other': "{count}번 다시 봄", 'title.rewatchCount_other': "{count}번 다시 봄",
'title.rewatchedToday': "오늘 다시 봄", 'title.rewatchedToday': "오늘 다시 봄",
'sync.syncing': "동기화 중…",
'sync.offline': "오프라인",
'sync.error': "동기화 실패",
'sync.synced': "동기화됨 · {when}",
'sync.never': "아직 동기화되지 않음",
'sync.pending_one': "변경 {count}개 대기 중",
'sync.pending_other': "변경 {count}개 대기 중",
'sync.now': "지금 동기화",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Eén keer opnieuw bekeken", 'title.rewatchCount_one': "Eén keer opnieuw bekeken",
'title.rewatchCount_other': "{count} keer opnieuw bekeken", 'title.rewatchCount_other': "{count} keer opnieuw bekeken",
'title.rewatchedToday': "Vandaag opnieuw bekeken", 'title.rewatchedToday': "Vandaag opnieuw bekeken",
'sync.syncing': "Synchroniseren…",
'sync.offline': "Offline",
'sync.error': "Synchronisatie mislukt",
'sync.synced': "Gesynchroniseerd · {when}",
'sync.never': "Nog niet gesynchroniseerd",
'sync.pending_one': "{count} wijziging in wachtrij",
'sync.pending_other': "{count} wijzigingen in wachtrij",
'sync.now': "Nu synchroniseren",
} }
export default dict export default dict
+10
View File
@@ -969,6 +969,16 @@ const dict: Translations = {
'title.seasons_many': "{count} sezonów", 'title.seasons_many': "{count} sezonów",
'title.rewatchCount_few': "Obejrzane ponownie {count} razy", 'title.rewatchCount_few': "Obejrzane ponownie {count} razy",
'title.rewatchCount_many': "Obejrzane ponownie {count} razy", 'title.rewatchCount_many': "Obejrzane ponownie {count} razy",
'sync.syncing': "Synchronizacja…",
'sync.offline': "Offline",
'sync.error': "Synchronizacja nie powiodła się",
'sync.synced': "Zsynchronizowano · {when}",
'sync.never': "Jeszcze nie zsynchronizowano",
'sync.pending_one': "{count} zmiana oczekuje",
'sync.pending_other': "{count} zmiany oczekuje",
'sync.now': "Synchronizuj",
'sync.pending_few': "{count} zmiany oczekują",
'sync.pending_many': "{count} zmian oczekuje",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Revisto uma vez", 'title.rewatchCount_one': "Revisto uma vez",
'title.rewatchCount_other': "Revisto {count} vezes", 'title.rewatchCount_other': "Revisto {count} vezes",
'title.rewatchedToday': "Revisto hoje", 'title.rewatchedToday': "Revisto hoje",
'sync.syncing': "Sincronizando…",
'sync.offline': "Offline",
'sync.error': "A sincronização falhou",
'sync.synced': "Sincronizado · {when}",
'sync.never': "Ainda não sincronizado",
'sync.pending_one': "{count} alteração pendente",
'sync.pending_other': "{count} alterações pendentes",
'sync.now': "Sincronizar",
} }
export default dict export default dict
+10
View File
@@ -969,6 +969,16 @@ const dict: Translations = {
'title.seasons_many': "{count} сезонов", 'title.seasons_many': "{count} сезонов",
'title.rewatchCount_few': "Пересмотрено {count} раза", 'title.rewatchCount_few': "Пересмотрено {count} раза",
'title.rewatchCount_many': "Пересмотрено {count} раз", 'title.rewatchCount_many': "Пересмотрено {count} раз",
'sync.syncing': "Синхронизация…",
'sync.offline': "Нет сети",
'sync.error': "Ошибка синхронизации",
'sync.synced': "Синхронизировано · {when}",
'sync.never': "Ещё не синхронизировано",
'sync.pending_one': "{count} изменение ожидает",
'sync.pending_other': "{count} изменения ожидают",
'sync.now': "Синхронизировать",
'sync.pending_few': "{count} изменения ожидают",
'sync.pending_many': "{count} изменений ожидают",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "ดูซ้ำ {count} ครั้ง", 'title.rewatchCount_one': "ดูซ้ำ {count} ครั้ง",
'title.rewatchCount_other': "ดูซ้ำ {count} ครั้ง", 'title.rewatchCount_other': "ดูซ้ำ {count} ครั้ง",
'title.rewatchedToday': "ดูซ้ำวันนี้", 'title.rewatchedToday': "ดูซ้ำวันนี้",
'sync.syncing': "กำลังซิงค์…",
'sync.offline': "ออฟไลน์",
'sync.error': "ซิงค์ไม่สำเร็จ",
'sync.synced': "ซิงค์แล้ว · {when}",
'sync.never': "ยังไม่ได้ซิงค์",
'sync.pending_one': "รอซิงค์ {count} รายการ",
'sync.pending_other': "รอซิงค์ {count} รายการ",
'sync.now': "ซิงค์ตอนนี้",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "{count} kez tekrar izlendi", 'title.rewatchCount_one': "{count} kez tekrar izlendi",
'title.rewatchCount_other': "{count} kez tekrar izlendi", 'title.rewatchCount_other': "{count} kez tekrar izlendi",
'title.rewatchedToday': "Bugün tekrar izlendi", 'title.rewatchedToday': "Bugün tekrar izlendi",
'sync.syncing': "Eşitleniyor…",
'sync.offline': "Çevrimdışı",
'sync.error': "Eşitleme başarısız",
'sync.synced': "Eşitlendi · {when}",
'sync.never': "Henüz eşitlenmedi",
'sync.pending_one': "{count} değişiklik bekliyor",
'sync.pending_other': "{count} değişiklik bekliyor",
'sync.now': "Şimdi eşitle",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "Đã xem lại {count} lần", 'title.rewatchCount_one': "Đã xem lại {count} lần",
'title.rewatchCount_other': "Đã xem lại {count} lần", 'title.rewatchCount_other': "Đã xem lại {count} lần",
'title.rewatchedToday': "Đã xem lại hôm nay", 'title.rewatchedToday': "Đã xem lại hôm nay",
'sync.syncing': "Đang đồng bộ…",
'sync.offline': "Ngoại tuyến",
'sync.error': "Đồng bộ thất bại",
'sync.synced': "Đã đồng bộ · {when}",
'sync.never': "Chưa đồng bộ",
'sync.pending_one': "{count} thay đổi đang chờ",
'sync.pending_other': "{count} thay đổi đang chờ",
'sync.now': "Đồng bộ ngay",
} }
export default dict export default dict
+8
View File
@@ -879,6 +879,14 @@ const dict: Translations = {
'title.rewatchCount_one': "重看 {count} 次", 'title.rewatchCount_one': "重看 {count} 次",
'title.rewatchCount_other': "重看 {count} 次", 'title.rewatchCount_other': "重看 {count} 次",
'title.rewatchedToday': "今天重看了", 'title.rewatchedToday': "今天重看了",
'sync.syncing': "正在同步…",
'sync.offline': "离线",
'sync.error': "同步失败",
'sync.synced': "已同步 · {when}",
'sync.never': "尚未同步",
'sync.pending_one': "{count} 项更改待上传",
'sync.pending_other': "{count} 项更改待上传",
'sync.now': "立即同步",
} }
export default dict export default dict
+5 -2
View File
@@ -115,7 +115,8 @@ const followed = (item: AiringItem) =>
*/ */
export function airedCount(item: AiringItem, cache: AiringCache = loadAiring()): number | undefined { export function airedCount(item: AiringItem, cache: AiringCache = loadAiring()): number | undefined {
const info = cache[item.id] const info = cache[item.id]
if (!info || !info.aired || !followed(item)) return undefined // 0 épisode sorti n'est une info sûre que si une date de sortie est annoncée
if (!info || !followed(item) || (!info.aired && !info.next)) return undefined
return info.next && info.next.date <= localDay() ? info.aired + 1 : info.aired return info.next && info.next.date <= localDay() ? info.aired + 1 : info.aired
} }
@@ -194,6 +195,8 @@ async function checkTmdb(tvId: string, key: string): Promise<Omit<AiringInfo, 'c
} }
const nx = d.next_episode_to_air const nx = d.next_episode_to_air
const nextDate = safeDay(nx?.air_date) const nextDate = safeDay(nx?.air_date)
// Rien encore diffusé (série annoncée) : les épisodes prévus ne sont pas « sortis »
if (!last && (nx || d.status === 'Planned' || d.status === 'In Production')) aired = 0
return { return {
aired, aired,
seasons: n0(d.number_of_seasons) || undefined, seasons: n0(d.number_of_seasons) || undefined,
@@ -235,7 +238,7 @@ async function checkAniList(ids: number[]): Promise<Map<number, Omit<AiringInfo,
const nx = m.nextAiringEpisode const nx = m.nextAiringEpisode
const ts = n0(nx?.airingAt, 4102444800) // borne : an 2100 const ts = n0(nx?.airingAt, 4102444800) // borne : an 2100
out.set(m.id, { out.set(m.id, {
aired: nx ? Math.max(0, n0(nx.episode) - 1) : n0(m.episodes), aired: nx ? Math.max(0, n0(nx.episode) - 1) : m.status === 'NOT_YET_RELEASED' ? 0 : n0(m.episodes),
ended: m.status === 'FINISHED' || m.status === 'CANCELLED', ended: m.status === 'FINISHED' || m.status === 'CANCELLED',
next: nx && ts ? { episode: n0(nx.episode), date: localDay(new Date(ts * 1000)) } : undefined, next: nx && ts ? { episode: n0(nx.episode), date: localDay(new Date(ts * 1000)) } : undefined,
}) })
+9 -2
View File
@@ -16,6 +16,12 @@ let ignorePops = 0
let syncTimer = 0 let syncTimer = 0
let listening = false let listening = false
// Page rechargée avec une fenêtre ouverte : l'entrée d'historique n'a plus de fenêtre derrière elle
if (typeof history !== 'undefined' && history.state && typeof history.state === 'object' && 'azuuDepth' in history.state) {
const { azuuDepth: _old, ...rest } = history.state as Record<string, unknown>
history.replaceState(rest, '')
}
const depthOf = (state: unknown) => { const depthOf = (state: unknown) => {
const d = (state as { azuuDepth?: unknown } | null)?.azuuDepth const d = (state as { azuuDepth?: unknown } | null)?.azuuDepth
return typeof d === 'number' ? d : 0 return typeof d === 'number' ? d : 0
@@ -47,13 +53,14 @@ function onPop(e: PopStateEvent) {
} }
/** Ferme la fenêtre avec le geste / bouton retour du téléphone. */ /** Ferme la fenêtre avec le geste / bouton retour du téléphone. */
export function useBackToClose(onClose: CloseFn) { export function useBackToClose(onClose: CloseFn, active = true) {
const closeRef = useRef(onClose) const closeRef = useRef(onClose)
useEffect(() => { useEffect(() => {
closeRef.current = onClose closeRef.current = onClose
}) })
useEffect(() => { useEffect(() => {
if (!active) return
if (!listening) { if (!listening) {
window.addEventListener('popstate', onPop) window.addEventListener('popstate', onPop)
listening = true listening = true
@@ -70,5 +77,5 @@ export function useBackToClose(onClose: CloseFn) {
if (i >= 0) stack.splice(i, 1) if (i >= 0) stack.splice(i, 1)
scheduleSync() scheduleSync()
} }
}, []) }, [active])
} }
+30 -1
View File
@@ -1,5 +1,7 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import { cleanText, isPlainObject, safeIso } from '../security'
import { cloudFetch } from './api' import { cloudFetch } from './api'
import { safeMediaUrl } from './social'
/** Notifications (cloche) : abonnements, demandes acceptées, réactions reçues. */ /** Notifications (cloche) : abonnements, demandes acceptées, réactions reçues. */
@@ -52,7 +54,34 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
return res.json() as Promise<T> return res.json() as Promise<T>
} }
export const listNotifications = (offset = 0) => rpc<AppNotification[]>('get_notifications', { p_offset: offset }) const KINDS: NotificationKind[] = ['follow_request', 'follow_accepted', 'new_follower', 'reaction', 'new_episode', 'new_season']
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
/** Réponse du serveur relue champ par champ (adresses d'images comprises), comme pour les profils. */
function toNotification(v: unknown): AppNotification | null {
if (!isPlainObject(v) || typeof v.id !== 'number' || !KINDS.includes(v.kind as NotificationKind)) return null
const created = safeIso(v.created_at)
if (!created) return null
const a = isPlainObject(v.actor) ? v.actor : null
const username = a && typeof a.username === 'string' && /^[a-z0-9_]{3,20}$/.test(a.username) ? a.username : null
return {
id: v.id,
kind: v.kind as NotificationKind,
created_at: created,
read_at: safeIso(v.read_at) ?? null,
emoji: cleanText(v.emoji, 8) ?? null,
item_id: cleanText(v.item_id, 64) ?? null,
episode: num(v.episode),
ep_count: num(v.ep_count),
actor: username ? { username, display_name: cleanText(a!.display_name, 40) ?? username, avatar_url: safeMediaUrl(a!.avatar_url) ?? null } : null,
title: cleanText(v.title, 300) ?? null,
}
}
export const listNotifications = async (offset = 0): Promise<AppNotification[]> => {
const raw = await rpc<unknown>('get_notifications', { p_offset: offset })
return (Array.isArray(raw) ? raw : []).map(toNotification).filter((n): n is AppNotification => n !== null)
}
export async function unreadCount(): Promise<number> { export async function unreadCount(): Promise<number> {
try { try {
+44 -2
View File
@@ -1,5 +1,7 @@
import { t } from '../../i18n' import { t } from '../../i18n'
import { cleanText, isPlainObject, safeIso } from '../security'
import { cloudFetch } from './api' import { cloudFetch } from './api'
import { safeMediaUrl } from './social'
/** Avis des autres membres sur un même titre, et réactions (emoji). */ /** Avis des autres membres sur un même titre, et réactions (emoji). */
@@ -44,9 +46,49 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
return res.json() as Promise<T> return res.json() as Promise<T>
} }
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
/** Avis relu champ par champ : une réponse inattendue n'est ni affichée telle quelle ni source de plantage. */
function toReview(v: unknown): TitleReview | null {
if (!isPlainObject(v) || !isPlainObject(v.user) || typeof v.user_id !== 'string' || !UUID.test(v.user_id)) return null
const u = v.user
const username = typeof u.username === 'string' && /^[a-z0-9_]{3,20}$/.test(u.username) ? u.username : null
const notes = cleanText(v.notes, 20000)
if (!username || !notes) return null
const reactions: Record<string, number> = {}
if (isPlainObject(v.reactions)) {
for (const e of REACTION_EMOJIS) {
const n = v.reactions[e]
if (typeof n === 'number' && n > 0) reactions[e] = Math.floor(n)
}
}
return {
user: {
id: typeof u.id === 'string' ? u.id : v.user_id,
username,
display_name: cleanText(u.display_name, 40) ?? username,
avatar_url: safeMediaUrl(u.avatar_url) ?? null,
is_private: u.is_private === true,
relation: typeof u.relation === 'string' ? u.relation : 'none',
},
user_id: v.user_id,
item_id: cleanText(v.item_id, 64) ?? '',
updated_at: safeIso(v.updated_at) ?? new Date(0).toISOString(),
rating: typeof v.rating === 'number' && v.rating > 0 && v.rating <= 10 ? v.rating : null,
notes,
reactions,
total: Object.values(reactions).reduce((a, b) => a + b, 0),
mine: (REACTION_EMOJIS as readonly string[]).includes(v.mine as string) ? (v.mine as string) : null,
}
}
const toReviews = (v: unknown) => (Array.isArray(v) ? v : []).map(toReview).filter((r): r is TitleReview => r !== null)
/** Tous les avis publics sur un titre (séparés : amis / autres). */ /** Tous les avis publics sur un titre (séparés : amis / autres). */
export const titleReviews = (externalId: string, offset = 0) => export async function titleReviews(externalId: string, offset = 0): Promise<TitleReviews> {
rpc<TitleReviews>('title_reviews', { p_external_id: externalId, p_offset: offset }) const raw = await rpc<unknown>('title_reviews', { p_external_id: externalId, p_offset: offset })
return isPlainObject(raw) ? { friends: toReviews(raw.friends), others: toReviews(raw.others) } : { friends: [], others: [] }
}
export async function reactToReview(author: string, item: string, emoji: ReactionEmoji): Promise<void> { export async function reactToReview(author: string, item: string, emoji: ReactionEmoji): Promise<void> {
await rpc('react_to_review', { p_author: author, p_item: item, p_emoji: emoji }) await rpc('react_to_review', { p_author: author, p_item: item, p_emoji: emoji })
+4
View File
@@ -113,9 +113,13 @@ export function applyTheme(accentColor: string, mode: ThemeMode) {
root.setProperty('--color-on-accent', c.onAccent) root.setProperty('--color-on-accent', c.onAccent)
// Couleur de la barre du navigateur / de l'app installée // Couleur de la barre du navigateur / de l'app installée
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', CANVAS[resolved]) document.querySelector('meta[name="theme-color"]')?.setAttribute('content', CANVAS[resolved])
// Contrôles natifs (dates, listes, barres de défilement) clairs ou sombres comme le thème
document.querySelector('meta[name="color-scheme"]')?.setAttribute('content', resolved === 'light' ? 'light' : 'dark')
// Retenu pour le prochain lancement : appliqué avant même le premier affichage (voir applySavedTheme) // Retenu pour le prochain lancement : appliqué avant même le premier affichage (voir applySavedTheme)
try { try {
localStorage.setItem(BOOT_KEY, JSON.stringify({ color: accentColor, mode })) localStorage.setItem(BOOT_KEY, JSON.stringify({ color: accentColor, mode }))
// Couleurs déjà calculées, lues par public/theme-boot.js avant même que l'app ne charge
localStorage.setItem('azuucine:theme-css', JSON.stringify({ theme: resolved, accent: c.accent, fill: c.accentFill, on: c.onAccent, canvas: CANVAS[resolved] }))
} catch { } catch {
/* stockage indisponible : on garde le thème par défaut au lancement */ /* stockage indisponible : on garde le thème par défaut au lancement */
} }
+8 -2
View File
@@ -14,6 +14,8 @@ import { detectPlatform, useInstallPrompt } from '../lib/pwa'
import { isAdmin } from '../lib/cloud/admin' import { isAdmin } from '../lib/cloud/admin'
import type { NotifPrefs } from '../types' import type { NotifPrefs } from '../types'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useEscape } from '../lib/escape'
import { useBackToClose } from '../lib/backNav'
import { useMedia } from '../store' import { useMedia } from '../store'
type Message = { kind: 'ok' | 'error'; text: string } type Message = { kind: 'ok' | 'error'; text: string }
@@ -42,10 +44,12 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account } = useMedia() const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account } = useMedia()
const { canInstall, installed, install } = useInstallPrompt() const { canInstall, installed, install } = useInstallPrompt()
const [admin, setAdmin] = useState(false) const [admin, setAdmin] = useState(false)
// Une seule vérification par connexion (et pas à chaque changement d'état de la synchro)
const signedIn = !!account
useEffect(() => { useEffect(() => {
if (account) void isAdmin().then(setAdmin) if (signedIn) void isAdmin().then(setAdmin)
else setAdmin(false) else setAdmin(false)
}, [account]) }, [signedIn])
const fileRef = useRef<HTMLInputElement>(null) const fileRef = useRef<HTMLInputElement>(null)
const [pending, setPending] = useState<ParsedBackup>() const [pending, setPending] = useState<ParsedBackup>()
const [message, setMessage] = useState<Message>() const [message, setMessage] = useState<Message>()
@@ -148,6 +152,8 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
} }
const [showInstall, setShowInstall] = useState(false) const [showInstall, setShowInstall] = useState(false)
useEscape(() => setShowInstall(false), showInstall)
useBackToClose(() => setShowInstall(false), showInstall)
const platform = detectPlatform() const platform = detectPlatform()
const doNativeInstall = async () => { const doNativeInstall = async () => {
+11 -2
View File
@@ -277,8 +277,17 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
) )
const importItems = useCallback(async (incoming: MediaItem[], mode: 'merge' | 'replace') => { const importItems = useCallback(async (incoming: MediaItem[], mode: 'merge' | 'replace') => {
if (mode === 'replace') await mediaDB.clear() if (mode === 'replace') {
await mediaDB.putMany(incoming) await mediaDB.clear()
// Remplacement voulu : les fiches importées deviennent la version la plus récente
// (sinon le serveur garderait ses versions plus récentes et les appareils divergeraient)
const now = new Date().toISOString()
await mediaDB.putMany(incoming.map((i) => ({ ...i, updatedAt: now })))
} else {
// Fusion : une sauvegarde plus ancienne n'écrase pas une fiche modifiée depuis
const current = new Map((await mediaDB.getAll()).map((i) => [i.id, i]))
await mediaDB.putMany(incoming.filter((i) => !current.has(i.id) || current.get(i.id)!.updatedAt < i.updatedAt))
}
const all = await mediaDB.getAll() const all = await mediaDB.getAll()
setItems(all.sort(byUpdatedDesc)) setItems(all.sort(byUpdatedDesc))
}, []) }, [])