diff --git a/map4.js b/map4.js index 714760c..fc91698 100644 --- a/map4.js +++ b/map4.js @@ -241,14 +241,12 @@ ${crown}${member.user_name} `; - list.appendChild(li); - }); -} // =================================== -// ホスト自動交代 +// ホスト自動交代(完全改良版) // =================================== async function checkHostAuto() { + // 最新のグループ情報を取得 const { data: group } = await supa .from("groups") .select("*") @@ -259,30 +257,37 @@ currentHostName = group.host_name; - const hostExists = Object.values(latestByDevice).some( - (r) => r.user_name === currentHostName - ); + // 現在オンラインのメンバーを抽出(6秒以内更新) + const onlineUsers = Object.values(latestByDevice).filter((r) => { + return (Date.now() - new Date(r.updated_at)) / 1000 < 6; + }); - if (hostExists) { + // 現ホストがオンラインか確認 + const hostOnline = onlineUsers.some((u) => u.user_name === currentHostName); + + if (hostOnline) { + // 自分がホストなら反映 isHost = currentUser === currentHostName; return; } - // ホスト不在 → 最新更新ユーザーに交代 - const users = Object.values(latestByDevice); - if (users.length === 0) return; + // ★ ホストがいない場合 → 新しいホストに自動交代 ★ + if (onlineUsers.length === 0) return; - const newest = users.sort( + // 最も最近更新されたオンラインユーザーを新ホストにする + const newHost = onlineUsers.sort( (a, b) => new Date(b.updated_at) - new Date(a.updated_at) )[0]; - currentHostName = newest.user_name; - + // Supabase に保存 await supa .from("groups") - .update({ host_name: currentHostName }) + .update({ host_name: newHost.user_name }) .eq("group_name", currentGroup); + currentHostName = newHost.user_name; + + // 自分が新ホストになったか? isHost = currentUser === currentHostName; }