Compare commits

...
2 changed files with 125 additions and 35 deletions

No files matched your search

+110 -35
View File
@@ -1,8 +1,9 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { cached, call, readStored, storageKey, writeStored, type Me } from "./api";
import { clearPendingLogin, isCloudLoginUrl, loginStaysOnPage, loginWaitOver, pollStatus, readPendingLogin, writePendingLogin } from "./login-wait";
import { Browse, type Tab } from "./Browse";
import { Gallery } from "./Gallery";
import { Icon } from "./parts";
@@ -218,42 +219,112 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [keep, setKeep] = useState(true);
const openRef = useRef<HTMLAnchorElement>(null);
const popupRef = useRef<Window | null>(null);
// A phone often reloads this page while the person is on the cloud. The same attempt is still valid.
useEffect(() => {
const saved = readPendingLogin(info.id);
if (!saved) return;
setKeep(saved.remember);
setLoginUrl(saved.loginUrl);
setState(saved.state);
}, [info.id]);
const stop = useCallback(() => {
popupRef.current?.close();
popupRef.current = null;
clearPendingLogin(info.id);
setState(null);
setLoginUrl(null);
}, [info.id]);
useEffect(() => {
if (!state) return;
let live = true;
const timer = setInterval(() => {
let timer = 0;
let inflight = false;
const poll = () => {
if (!live || inflight || document.visibilityState === "hidden") return;
inflight = true;
call<{ pending?: boolean; token?: string; viewer?: { name: string } }>("/v1/archive/login/poll", null, { method: "POST", body: JSON.stringify({ state, remember: keep }) }).then(
({ status, body }) => {
if (!live || status === 202 || !body.token) return;
clearInterval(timer);
window.clearInterval(timer);
popupRef.current?.close();
popupRef.current = null;
clearPendingLogin(info.id);
onDone(body.token, body.viewer?.name ?? "", keep);
},
() => {
if (!live) return;
clearInterval(timer);
setState(null);
(err: unknown) => {
if (!live || !loginWaitOver(pollStatus(err))) return;
window.clearInterval(timer);
stop();
setError("A autorização expirou ou falhou. Tenta outra vez.");
},
);
}, 2000);
).finally(() => {
inflight = false;
});
};
const arm = () => {
window.clearInterval(timer);
if (document.visibilityState === "hidden") return;
poll();
timer = window.setInterval(poll, 3000);
};
arm();
document.addEventListener("visibilitychange", arm);
window.addEventListener("pageshow", arm);
window.addEventListener("focus", arm);
return () => {
live = false;
clearInterval(timer);
window.clearInterval(timer);
document.removeEventListener("visibilitychange", arm);
window.removeEventListener("pageshow", arm);
window.removeEventListener("focus", arm);
};
}, [state, onDone, keep]);
}, [state, onDone, keep, info.id, stop]);
useEffect(() => {
if (!state) return;
openRef.current?.focus();
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") stop();
};
window.addEventListener("keydown", onKey);
return () => {
document.body.style.overflow = prev;
window.removeEventListener("keydown", onKey);
};
}, [state, stop]);
const start = () => {
setBusy(true);
setError(null);
// The window opens on the click (browsers block it later); the address follows.
const win = window.open("about:blank", "_blank");
// On a phone a popup replaces this page and the wait dies. The dialog stays; the cloud opens from it.
let win: Window | null = null;
if (!loginStaysOnPage()) {
try {
win = window.open("about:blank", "_blank");
} catch {
win = null;
}
}
popupRef.current = win;
call<{ loginUrl: string; state: string }>(`/v1/archive/${info.id}/login`, null, { method: "POST" })
.then(
({ body }) => {
if (!isCloudLoginUrl(body.loginUrl)) {
win?.close();
setError("O serviço de entrada não está a responder. Tenta daqui a pouco.");
return;
}
writePendingLogin(info.id, { state: body.state, loginUrl: body.loginUrl, remember: keep, at: Date.now() });
setLoginUrl(body.loginUrl);
setState(body.state);
if (win) win.location.href = body.loginUrl;
if (win && !win.closed) win.location.href = body.loginUrl;
},
() => {
win?.close();
@@ -275,27 +346,14 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
Entra com a tua conta {owner}: vês as galerias a que tens acesso, procuras por jogo, equipa ou pessoa, e descarregas as fotos.
</p>
</div>
{state ? (
<p className="arq-notice">
A aguardar que autorizes a entrada na outra janela…{" "}
{loginUrl && (
<a href={loginUrl} target="_blank" rel="noreferrer">
Abrir a página de autorização
</a>
)}
</p>
) : (
<>
<button type="button" className="arq-btn accent" disabled={busy} onClick={start}>
Entrar
<Icon name="next" size={18} />
</button>
<label className="arq-keep">
<input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} />
<span>Manter sessão iniciada neste dispositivo</span>
</label>
</>
)}
<button type="button" className="arq-btn accent" disabled={busy || !!state} onClick={start}>
Entrar
<Icon name="next" size={18} />
</button>
<label className="arq-keep">
<input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} />
<span>Manter sessão iniciada neste dispositivo</span>
</label>
{error && <p className="arq-error">{error}</p>}
<p style={{ fontSize: 14 }}>
A tua palavra-passe só é escrita na página de entrada, nunca aqui.{" "}
@@ -314,6 +372,23 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
<span />
<span />
</div>
{state && loginUrl && (
<div className="arq-scrim arq-signin-wait">
<div className="arq-dialog" role="dialog" aria-modal="true" aria-labelledby="arq-login-title" aria-describedby="arq-login-desc">
<h2 id="arq-login-title">Entrar na conta</h2>
<p id="arq-login-desc">
A página da tua conta {owner} abre por cima desta. Esta fica aberta e conclui a entrada quando voltares.
</p>
<a ref={openRef} className="arq-btn accent" href={loginUrl} target="_blank" rel="noopener noreferrer">
Abrir a página da conta
<Icon name="next" size={18} />
</a>
<button type="button" className="arq-btn ghost" onClick={stop}>
Cancelar
</button>
</div>
</div>
)}
</section>
);
}
@@ -1354,6 +1354,21 @@
.arq-signin .arq-error {
color: #ffb4a8;
}
.arq-signin-wait .arq-dialog p {
margin: 0;
color: var(--muted);
}
.arq-signin-wait .arq-btn {
width: 100%;
min-height: 52px;
white-space: normal;
text-align: center;
}
@media (max-width: 639px) {
.arq-signin-wait .arq-dialog {
padding-bottom: calc(24px + env(safe-area-inset-bottom));
}
}
.arq-mosaic {
flex: 1 1 420px;
min-height: 360px;