diff --git a/backend/app/activity.py b/backend/app/activity.py index 032b945..a063384 100644 --- a/backend/app/activity.py +++ b/backend/app/activity.py @@ -22,6 +22,11 @@ "connect_decline", "connect_withdraw", "question", + "group_propose", + "group_join", + "group_vote", + "group_fix", + "board_post", ) DETAIL_CHARS = 60 diff --git a/backend/app/config.py b/backend/app/config.py index 96dd9cb..f319d1d 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -26,6 +26,7 @@ class Settings(BaseSettings): idx_agenda: str = "confox-agenda" idx_transcripts: str = "confox-transcripts" idx_activity: str = "confox-activity" + idx_groups: str = "confox-groups" # The demo runs on Emma's Monday morning. Leave DEMO_NOW empty to use the real clock in Salt Lake City. demo_now: str = "2026-11-09T08:40:00" diff --git a/backend/app/data/groups.py b/backend/app/data/groups.py new file mode 100644 index 0000000..28205f7 --- /dev/null +++ b/backend/app/data/groups.py @@ -0,0 +1,145 @@ +"""Sample meetup groups for the demo, all marked sample=True. + +Hosts and members are generated sample attendees who really share the group's value (the Bangladesh meetup is the +exception: no generated attendee is from Bangladesh, so its two members are simply interested). Emma is in none of +them, so she can join, vote and propose her own during the demo. Slots are real food and coffee breaks. +Four hallway board posts by sample attendees, tagged with their own interests, run until late Monday morning. +""" + +from datetime import datetime, timedelta + +from ..groups_store import new_group, new_post + +DEMO_MORNING = "2026-11-09T08:" # seeded created_at minutes are appended + + +def _break(sessions: list[dict], day: str, word: str, nth: int = 0) -> dict: + found = [s for s in sessions if s.get("is_food") and s["day"] == day and word in s["title"].lower()] + return sorted(found, key=lambda s: s["starts_at"])[nth] + + +def _sharing(attendees: list[dict], field: str, value: str, n: int) -> list[dict]: + out = [] + for p in attendees: + if p["id"] in ("emma", "alice"): + continue + v = p.get(field) + if value == v or (isinstance(v, list) and value in v): + out.append(p) + return out[:n] + + +def _group(gid, host, members, basis, value, title, description, slots, votes, minute): + g = new_group(gid, host, basis, value, title, description, slots, at=None, sample=True) + for m in members: + g["members"].append(m["id"]) + g["member_names"].append(m["name"]) + for slot_index, voters in votes.items(): + g["votes"][g["proposed_slots"][slot_index]["session_id"]] = [p["id"] for p in voters] + return g | {"created_at": f"{DEMO_MORNING}{minute:02d}:00"} + + +def sample_groups(sessions: list[dict], attendees: list[dict]) -> list[dict]: + mon, tue, wed = "2026-11-09", "2026-11-10", "2026-11-11" + mon_lunch, mon_coffee_pm = _break(sessions, mon, "lunch"), _break(sessions, mon, "coffee", 1) + tue_coffee, tue_lunch, tue_coffee_pm = ( + _break(sessions, tue, "coffee"), + _break(sessions, tue, "lunch"), + _break(sessions, tue, "coffee", 1), + ) + wed_lunch = _break(sessions, wed, "lunch") + + utah = _sharing(attendees, "schools", "University of Utah", 5) + wicn = _sharing(attendees, "communities", "Women in Cloud Native", 4) + kubeflow = _sharing(attendees, "interests", "Kubeflow", 4) + brazil = _sharing(attendees, "country", "Brazil", 3) + others = [p for p in attendees if p["id"] not in ("emma", "alice")] + bangladesh = [others[-1], others[-2]] + + return [ + _group( + "sample-grp-utah", + utah[0], + utah[1:4], + "school", + "University of Utah", + "University of Utah alumni lunch", + "Utes at KubeCon in our home town. Grab lunch together and swap stories from campus.", + [mon_lunch, tue_lunch, wed_lunch], + {0: utah[:3], 1: utah[1:3]}, + 5, + ), + _group( + "sample-grp-bangladesh", + bangladesh[0], + bangladesh[1:], + "country", + "Bangladesh", + "Bangladesh meetup", + "From Bangladesh, or with family there? Say hello over coffee.", + [mon_coffee_pm, tue_coffee], + {1: bangladesh[:1]}, + 12, + ), + _group( + "sample-grp-wicn", + wicn[0], + wicn[1:4], + "community", + "Women in Cloud Native", + "Women in Cloud Native coffee", + "Informal coffee for members and allies. Newcomers to KubeCon very welcome.", + [mon_coffee_pm, tue_coffee, tue_coffee_pm], + {0: wicn[:2], 1: wicn[1:4]}, + 18, + ), + _group( + "sample-grp-kubeflow", + kubeflow[0], + kubeflow[1:3], + "interest", + "Kubeflow", + "Kubeflow users", + "Running Kubeflow in production? Compare pipelines, notebooks and serving setups.", + [tue_lunch, wed_lunch], + {0: kubeflow[:2]}, + 24, + ), + _group( + "sample-grp-brazil", + brazil[0], + brazil[1:3], + "country", + "Brazil", + "Brasileiros na KubeCon", + "Everyone from Brazil: lunch and a chat in Portuguese.", + [tue_lunch, wed_lunch], + {1: brazil[:3]}, + 31, + ), + ] + + +# (minutes after 08:00 on the demo Monday, lasting minutes, interest the author must have, text, place) +POSTS = [ + (5, 180, "Cilium", "At the Cilium booth till 11:00, come talk eBPF and network policy.", "Project Pavilion"), + (15, 180, "GPU scheduling", "Anyone else fighting GPU fragmentation? Saving seats near the front.", "Room 254"), + (25, 180, "OpenTelemetry", "Coffee and OpenTelemetry questions by the registration desk.", "Hall A foyer"), + (32, 180, "Kubeflow", "Kubeflow pipelines on spot nodes: happy to compare notes before lunch.", ""), +] + + +def sample_posts(attendees: list[dict]) -> list[dict]: + """Hallway board posts, each by the first sample attendee (not Emma or Alice) into the post's topic.""" + out = [] + for i, (minute, minutes, tag, text, place) in enumerate(POSTS): + author = next( + p + for p in attendees + if p["id"] not in ("emma", "alice") + and tag in p.get("interests", []) + and p["id"] not in {o["author_id"] for o in out} + ) + at = datetime.fromisoformat(f"{DEMO_MORNING}00:00") + timedelta(minutes=minute) + out.append(new_post(f"sample-post-{i + 1}", author, text, place, minutes, [tag], at=at, sample=True)) + return out diff --git a/backend/app/groups_store.py b/backend/app/groups_store.py new file mode 100644 index 0000000..5a7d5c5 --- /dev/null +++ b/backend/app/groups_store.py @@ -0,0 +1,457 @@ +"""Meetup groups: people who share a school, country, company, community or interest meet at a food break. + +One document per group in `confox-groups`: + + { title, basis: "school" | "country" | "company" | "community" | "interest", value ("University of Utah"), + description, host_id, host_name, members [ids, host first], member_names (same order), max_members, + proposed_slots [{session_id, title, starts_at, ends_at, room}] (1 to 3 food or coffee breaks), + votes {session_id: [user ids]}, fixed_slot (one of the proposed slots, or null), status: "open" | "fixed", + created_at, sample } + +Hallway board posts share the index with `type: "post"`: + + { type: "post", text (<= 140 chars), place, tags (from the author's interests), author_id, author_name, + created_at, expires_at (30 minutes, 1 hour or 3 hours later), sample } + +When the host fixes a time every member gets a confirmed agenda meeting "Meetup: " with the id +"{user_id}-g-{group_id}", so joining or leaving a fixed group adds or removes exactly that one item. + +The rules are pure functions, tested without Elasticsearch; they raise GroupError with the HTTP status to answer. +""" + +import secrets +from datetime import datetime, timedelta + +from elasticsearch import NotFoundError + +from .agenda_store import meeting_title, stamp +from .clock import now +from .config import settings +from .es import es + +BASES = ("school", "country", "company", "community", "interest") +# Ranking and suggestion order: alumni ties first (the demo's headline), then where people are from. +BASIS_ORDER = {b: i for i, b in enumerate(("school", "country", "community", "company", "interest"))} +MAX_SLOTS = 3 +DEFAULT_MAX_MEMBERS = 12 +MAX_MEMBERS_CAP = 50 +TITLE_CHARS = 80 +DESCRIPTION_CHARS = 280 +MAX_SUGGESTIONS = 6 + +# How each basis reads in a match reason and in a suggestion. +MATCH_LABEL = { + "school": "You studied at {v}", + "country": "You are from {v}", + "company": "You work or worked at {v}", + "community": "You are in {v}", + "interest": "You are into {v}", +} +SUGGEST_TITLE = { + "school": "{v} alumni meetup", + "country": "{v} meetup", + "company": "{v} folks meetup", + "community": "{v} meetup", + "interest": "{v} meetup", +} + + +class GroupError(Exception): + def __init__(self, status: int, detail: str): + super().__init__(detail) + self.status = status + self.detail = detail + + +# ---------- pure rules ---------- + + +def _list(v) -> list[str]: + if v is None or v == "": + return [] + return [x for x in v if x] if isinstance(v, list) else [v] + + +def profile_values(user: dict) -> dict[str, list[str]]: + """The user's own values per basis, in profile order. Company is the current one, then past ones.""" + return { + "school": _list(user.get("schools")), + "country": _list(user.get("country")), + "company": list(dict.fromkeys(_list(user.get("company")) + _list(user.get("past_companies")))), + "community": _list(user.get("communities")), + "interest": _list(user.get("interests")), + } + + +def group_id() -> str: + return f"grp-{secrets.token_hex(4)}" + + +def agenda_item_id(user_id: str, gid: str) -> str: + return f"{user_id}-g-{gid}" + + +def clean(text: str | None, limit: int) -> str: + return " ".join((text or "").split())[:limit] + + +def slot_of(session: dict) -> dict: + """A proposed slot from a food or coffee break session (with `id`).""" + return { + "session_id": session["id"], + "title": meeting_title(session.get("title", "")), + "starts_at": session["starts_at"], + "ends_at": session["ends_at"], + "room": session.get("room"), + } + + +def new_group( + gid: str, + host: dict, + basis: str, + value: str, + title: str, + description: str, + slots: list[dict], + max_members: int = DEFAULT_MAX_MEMBERS, + at: datetime | None = None, + sample: bool = False, +) -> dict: + """A new open group with the host as its first member. `host` needs `id` and `name`; `slots` are break sessions.""" + if basis not in BASES: + raise GroupError(422, f"basis must be one of {', '.join(BASES)}") + value = clean(value, TITLE_CHARS) + if not value: + raise GroupError(422, "value is required") + ids = [s["id"] for s in slots] + if not 1 <= len(ids) <= MAX_SLOTS or len(set(ids)) != len(ids): + raise GroupError(422, f"pick 1 to {MAX_SLOTS} different times") + proposed = sorted((slot_of(s) for s in slots), key=lambda s: (s["starts_at"], s["session_id"])) + return { + "id": gid, + "type": "group", + "title": clean(title, TITLE_CHARS) or SUGGEST_TITLE[basis].format(v=value), + "basis": basis, + "value": value, + "description": clean(description, DESCRIPTION_CHARS), + "host_id": host["id"], + "host_name": host.get("name") or host["id"], + "members": [host["id"]], + "member_names": [host.get("name") or host["id"]], + "max_members": max(2, min(int(max_members or DEFAULT_MAX_MEMBERS), MAX_MEMBERS_CAP)), + "proposed_slots": proposed, + "votes": {s["session_id"]: [] for s in proposed}, + "fixed_slot": None, + "status": "open", + "created_at": stamp(at), + "sample": sample, + } + + +def match_reason(group: dict, user: dict) -> dict | None: + """Why this group is relevant to the user: the group's value is one of theirs for the same basis.""" + basis, value = group.get("basis"), group.get("value") + if basis in BASIS_ORDER and value in profile_values(user)[basis]: + return {"basis": basis, "value": value, "label": MATCH_LABEL[basis].format(v=value)} + return None + + +def is_member(group: dict, user_id: str) -> bool: + return user_id in (group.get("members") or []) + + +def tally(group: dict, user_id: str = "") -> list[dict]: + """Proposed slots in time order, each with its vote count and whether `user_id` voted for it.""" + votes = group.get("votes") or {} + out = [] + for s in sorted(group.get("proposed_slots") or [], key=lambda s: (s["starts_at"], s["session_id"])): + voters = votes.get(s["session_id"]) or [] + out.append(s | {"votes": len(voters), "voted": user_id in voters}) + return out + + +def leading_slot(group: dict) -> str | None: + """The slot with most votes (earliest on a tie), or None when nobody has voted.""" + ranked = sorted(tally(group), key=lambda s: (-s["votes"], s["starts_at"])) + return ranked[0]["session_id"] if ranked and ranked[0]["votes"] else None + + +def view(group: dict, user_id: str, user: dict | None = None) -> dict: + """The group as the API returns it to one user.""" + members = group.get("members") or [] + return group | { + "member_count": len(members), + "spots_left": max(0, (group.get("max_members") or DEFAULT_MAX_MEMBERS) - len(members)), + "is_member": user_id in members, + "is_host": group.get("host_id") == user_id, + "match": match_reason(group, user) if user else None, + "tally": tally(group, user_id), + "leading": leading_slot(group), + } + + +def _rank_key(group: dict, user: dict) -> tuple: + reason = match_reason(group, user) + return ( + reason is None, # groups sharing one of the user's values first + BASIS_ORDER[reason["basis"]] if reason else 0, + group.get("status") != "open", # still deciding before already fixed + -len(group.get("members") or []), + group.get("created_at") or "", + group.get("id") or "", + ) + + +def rank(groups: list[dict], user_id: str, user: dict) -> dict: + """{"groups": others ranked for the user, "mine": groups they host or joined, earliest fixed time first}.""" + mine = [g for g in groups if is_member(g, user_id)] + others = [g for g in groups if not is_member(g, user_id)] + others.sort(key=lambda g: _rank_key(g, user)) + mine.sort(key=lambda g: ((g.get("fixed_slot") or {}).get("starts_at") or "9", g.get("created_at") or "")) + return {"groups": [view(g, user_id, user) for g in others], "mine": [view(g, user_id, user) for g in mine]} + + +def join(group: dict, user_id: str, name: str) -> dict: + """The group with the user added. Joining twice is a no-op; a full group refuses (409).""" + if is_member(group, user_id): + return group + members = group.get("members") or [] + if len(members) >= (group.get("max_members") or DEFAULT_MAX_MEMBERS): + raise GroupError(409, "this group is full") + return group | {"members": members + [user_id], "member_names": (group.get("member_names") or []) + [name]} + + +def leave(group: dict, user_id: str) -> dict: + """The group without the user, their votes removed too. The host cannot leave their own group (409).""" + if group.get("host_id") == user_id: + raise GroupError(409, "the host cannot leave their own group") + members = group.get("members") or [] + if user_id not in members: + return group + i = members.index(user_id) + names = list(group.get("member_names") or []) + votes = {sid: [u for u in voters if u != user_id] for sid, voters in (group.get("votes") or {}).items()} + return group | { + "members": members[:i] + members[i + 1 :], + "member_names": names[:i] + names[i + 1 :], + "votes": votes, + } + + +def proposed(group: dict, session_id: str) -> dict: + slot = next((s for s in group.get("proposed_slots") or [] if s["session_id"] == session_id), None) + if slot is None: + raise GroupError(422, f"{session_id} is not one of this group's proposed times") + return slot + + +def vote(group: dict, user_id: str, session_id: str, on: bool = True) -> dict: + """Mark (or unmark) one proposed time the member can make. Members may vote for several times.""" + if group.get("status") != "open": + raise GroupError(409, "the time is already fixed") + if not is_member(group, user_id): + raise GroupError(403, "join the group to vote") + proposed(group, session_id) + votes = {sid: list(voters) for sid, voters in (group.get("votes") or {}).items()} + voters = [u for u in votes.get(session_id, []) if u != user_id] + votes[session_id] = voters + [user_id] if on else voters + return group | {"votes": votes} + + +def fix(group: dict, user_id: str, session_id: str) -> dict: + """The host fixes one of the proposed times; the group becomes `fixed` (once).""" + if group.get("host_id") != user_id: + raise GroupError(403, "only the host can fix the time") + if group.get("status") != "open": + raise GroupError(409, "the time is already fixed") + return group | {"status": "fixed", "fixed_slot": proposed(group, session_id)} + + +def agenda_item(group: dict, user_id: str, at: datetime | None = None) -> dict: + """The confirmed agenda meeting a member gets once the time is fixed.""" + slot = group["fixed_slot"] + return { + "id": agenda_item_id(user_id, group["id"]), + "user_id": user_id, + "kind": "meeting", + "status": "confirmed", + "group_id": group["id"], + "with_id": group["id"], + "with_name": group["title"], + "session_id": slot["session_id"], + "title": f"Meetup: {group['title']}", + "starts_at": slot["starts_at"], + "ends_at": slot["ends_at"], + "room": slot.get("room"), + "sample": bool(group.get("sample")) and user_id != settings.demo_user, + "created_at": stamp(at), + } + + +def suggest_aggs(user_id: str, user: dict) -> dict: + """One filters aggregation per basis, a bucket per value of the user's; the user is excluded in the query.""" + fields = {"school": ["schools"], "country": ["country"], "community": ["communities"], "interest": ["interests"]} + fields["company"] = ["company", "past_companies"] + aggs = {} + for basis, values in profile_values(user).items(): + if not values: + continue + buckets = {} + for v in values: + clauses = [{"term": {f: v}} for f in fields[basis]] + buckets[v] = clauses[0] if len(clauses) == 1 else {"bool": {"should": clauses, "minimum_should_match": 1}} + aggs[basis] = {"filters": {"filters": buckets}} + return aggs + + +def suggestions(user: dict, aggs: dict, groups: list[dict], limit: int = MAX_SUGGESTIONS) -> list[dict]: + """Values the user shares with others, most telling basis first, then by how many people share them. + + Each says how many open groups already exist for it, so the page can point at them instead of a duplicate. + """ + out = [] + for basis, values in profile_values(user).items(): + buckets = aggs.get(basis, {}).get("buckets", {}) + for order, v in enumerate(values): + count = buckets.get(v, {}).get("doc_count", 0) + if not count: + continue + existing = [g["id"] for g in groups if g.get("basis") == basis and g.get("value") == v] + out.append( + { + "basis": basis, + "value": v, + "count": count, + "label": f"{v} · {count} {'person' if count == 1 else 'people'} here", + "title": SUGGEST_TITLE[basis].format(v=v), + "existing": existing, + "_order": (BASIS_ORDER[basis], -count, order), + } + ) + out.sort(key=lambda s: s.pop("_order")) + return out[:limit] + + +# ---------- hallway board ---------- + +POST_CHARS = 140 +PLACE_CHARS = 60 +POST_MINUTES = (30, 60, 180) +MAX_TAGS = 3 +BOARD_SIZE = 40 + + +def post_id() -> str: + return f"post-{secrets.token_hex(4)}" + + +def new_post( + pid: str, + author: dict, + text: str, + place: str = "", + minutes: int = 60, + tags: list[str] | None = None, + at: datetime | None = None, + sample: bool = False, +) -> dict: + """A board post. Tags are kept only when they are the author's own interests (at most three).""" + text = clean(text, POST_CHARS) + if not text: + raise GroupError(422, "write something to post") + if minutes not in POST_MINUTES: + raise GroupError(422, "a post lasts 30, 60 or 180 minutes") + start = (at or now()).replace(microsecond=0) + own = profile_values(author)["interest"] + return { + "id": pid, + "type": "post", + "text": text, + "place": clean(place, PLACE_CHARS), + "tags": [t for t in own if t in set(tags or [])][:MAX_TAGS], + "author_id": author["id"], + "author_name": author.get("name") or author["id"], + "created_at": stamp(start), + "expires_at": stamp(start + timedelta(minutes=minutes)), + "sample": sample, + } + + +def board(posts: list[dict], groups: list[dict], user_id: str, user: dict, at: datetime) -> list[dict]: + """The hallway feed, newest first: live posts (each says if it matches the viewer's interests and if it is + theirs) and meetup groups still to happen (open, or fixed and not yet over).""" + at_iso = stamp(at) + mine = {i.lower() for i in profile_values(user)["interest"]} + items = [] + for p in posts: + if (p.get("expires_at") or "") <= at_iso: + continue + matching = [t for t in p.get("tags") or [] if t.lower() in mine] + items.append( + p | {"kind": "post", "for_you": bool(matching), "matching": matching, "mine": p["author_id"] == user_id} + ) + for g in groups: + fixed = g.get("fixed_slot") or {} + if g.get("status") == "fixed" and (fixed.get("ends_at") or "") <= at_iso: + continue + reason = match_reason(g, user) + items.append( + { + "kind": "group", + "id": g["id"], + "title": g.get("title"), + "basis": g.get("basis"), + "value": g.get("value"), + "status": g.get("status"), + "fixed_slot": g.get("fixed_slot"), + "member_count": len(g.get("members") or []), + "author_name": g.get("host_name"), + "created_at": g.get("created_at"), + "for_you": reason is not None, + "is_member": is_member(g, user_id), + "sample": bool(g.get("sample")), + } + ) + items.sort(key=lambda i: (i.get("created_at") or "", i["id"]), reverse=True) + return items[:BOARD_SIZE] + + +def remove_check(post: dict, user_id: str) -> None: + if post.get("type") != "post": + raise GroupError(404, "no such post") + if post.get("author_id") != user_id: + raise GroupError(403, "only the author can remove a post") + + +# ---------- Elasticsearch ---------- + + +def get(gid: str, kind: str = "group") -> tuple[dict, dict]: + """The group (or, with kind "post", the board post) and its concurrency token ({if_seq_no, if_primary_term}); + 404 when missing or of the other kind.""" + try: + doc = es.get(index=settings.idx_groups, id=gid) + except NotFoundError as exc: + raise GroupError(404, f"no {kind} {gid}") from exc + if (doc["_source"].get("type") == "post") != (kind == "post"): + raise GroupError(404, f"no {kind} {gid}") + return doc["_source"] | {"id": doc["_id"]}, {"if_seq_no": doc["_seq_no"], "if_primary_term": doc["_primary_term"]} + + +def save(group: dict, token: dict | None = None) -> None: + """Write the group; with a token only if nobody changed it since it was read (ConflictError otherwise).""" + body = {k: v for k, v in group.items() if k != "id"} + es.index(index=settings.idx_groups, id=group["id"], document=body, refresh="wait_for", **(token or {})) + + +def all_posts(size: int = 200) -> list[dict]: + r = es.search(index=settings.idx_groups, query={"term": {"type": "post"}}, sort=[{"created_at": "desc"}], size=size) + return [h["_source"] | {"id": h["_id"]} for h in r["hits"]["hits"]] + + +def all_groups(size: int = 200) -> list[dict]: + """Every meetup group (hallway posts share the index and are left out).""" + query = {"bool": {"must_not": [{"term": {"type": "post"}}]}} + r = es.search(index=settings.idx_groups, query=query, sort=[{"created_at": "asc"}], size=size) + return [h["_source"] | {"id": h["_id"]} for h in r["hits"]["hits"]] diff --git a/backend/app/indices.py b/backend/app/indices.py index 82bea84..1c65ec3 100644 --- a/backend/app/indices.py +++ b/backend/app/indices.py @@ -85,6 +85,37 @@ "message": {"type": "text"}, "request_id": {"type": "keyword"}, "created_at": LOCAL_TIME, + # Groups: the meetup group a confirmed "Meetup: ..." item belongs to. + "group_id": {"type": "keyword"}, + } + }, + # Meetup groups (app/groups_store.py). Slots and votes are kept as stored objects, not indexed: they are only + # ever read back with their group, and break ids as field names would grow the mapping with every break. + settings.idx_groups: { + "properties": { + "type": {"type": "keyword"}, # "group", or "post" for a hallway board post + "title": TEXT_KW, + "basis": {"type": "keyword"}, + "value": {"type": "keyword"}, + "description": {"type": "text"}, + "host_id": {"type": "keyword"}, + "host_name": {"type": "keyword"}, + "members": {"type": "keyword"}, + "member_names": {"type": "keyword"}, + "max_members": {"type": "integer"}, + "proposed_slots": {"type": "object", "enabled": False}, + "votes": {"type": "object", "enabled": False}, + "fixed_slot": {"type": "object", "enabled": False}, + "status": {"type": "keyword"}, + "created_at": LOCAL_TIME, + "sample": {"type": "boolean"}, + # Hallway board posts (type "post"): short-lived lines like "At the Cilium booth till 15:00". + "text": {"type": "text"}, + "place": {"type": "keyword"}, + "tags": {"type": "keyword"}, + "expires_at": LOCAL_TIME, + "author_id": {"type": "keyword"}, + "author_name": {"type": "keyword"}, } }, # Sample keynote transcripts in ~200-word chunks (doc_type "chunk"), plus one cached Claude summary per talk diff --git a/backend/app/load.py b/backend/app/load.py index db46f79..45a8c98 100644 --- a/backend/app/load.py +++ b/backend/app/load.py @@ -1,4 +1,4 @@ -"""Load the schedule snapshot, speakers, sample attendees and Emma's Monday into Elasticsearch. +"""Load the schedule snapshot, speakers, sample attendees, Emma's Monday and sample meetup groups into Elasticsearch. uv run python -m app.load # everything uv run python -m app.load --only sessions # one index; the others are left alone @@ -15,6 +15,7 @@ from .config import RAW_SCHEDULE, settings from .data.demo import emma_monday +from .data.groups import sample_groups, sample_posts from .data.people import sample_attendees, speakers from .data.samples import attendee_agendas, sample_activity from .data.sessions import build_sessions @@ -66,8 +67,9 @@ def _index(index: str, docs: list[dict]) -> int: def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("--only", choices=["sessions", "people", "agenda", "activity"], action="append") - only = set(parser.parse_args().only or ["sessions", "people", "agenda", "activity"]) + indices = ["sessions", "people", "agenda", "activity", "groups"] + parser.add_argument("--only", choices=indices, action="append") + only = set(parser.parse_args().only or indices) setup_telemetry(service_name="confox-load") try: @@ -84,6 +86,9 @@ def main() -> None: if "activity" in only: # Rebuilding drops recorded real events too; that is the point of a reload before a demo. _index(settings.idx_activity, sample_activity(attendees, agendas)) + if "groups" in only: + # Sample meetup groups (and hallway posts); groups created during a demo are dropped. + _index(settings.idx_groups, sample_groups(sessions, attendees) + sample_posts(attendees)) finally: shutdown_telemetry() diff --git a/backend/app/routers/groups.py b/backend/app/routers/groups.py new file mode 100644 index 0000000..dea58ca --- /dev/null +++ b/backend/app/routers/groups.py @@ -0,0 +1,300 @@ +"""Groups: meetups for people who share a school, country, company, community or interest. + +Someone proposes a group with up to three food or coffee breaks they are free for, others join and vote for the +times they can make, and the host fixes one; every member then has a confirmed "Meetup: <title>" on their agenda. +The rules live in app/groups_store.py; this module reads and writes Elasticsearch around them. +""" + +from collections.abc import Callable + +from elasticsearch import ConflictError, NotFoundError +from fastapi import APIRouter, HTTPException, Query +from opentelemetry import metrics, trace +from pydantic import BaseModel, Field + +from .. import activity +from .. import agenda_store as agenda +from .. import groups_store as store +from ..clock import now +from ..config import settings +from ..es import es +from .connect import _food_sessions + +router = APIRouter(prefix="/api/groups", tags=["groups"]) +changes = metrics.get_meter("confox.groups").create_counter( + "confox.groups.changes", unit="{change}", description="Meetup groups proposed, joined, left, voted on and fixed" +) +PROPOSE_SLOTS = 6 # free breaks offered when proposing; the host picks up to store.MAX_SLOTS of them + + +def _user_id() -> str: + return Query(default_factory=lambda: settings.demo_user, min_length=1) + + +class Propose(BaseModel): + user_id: str = Field(default_factory=lambda: settings.demo_user, min_length=1) + basis: str + value: str = Field(min_length=1, max_length=200) + title: str = Field(default="", max_length=200) + description: str = Field(default="", max_length=1000) + session_ids: list[str] = Field(min_length=1, max_length=store.MAX_SLOTS) + max_members: int = store.DEFAULT_MAX_MEMBERS + + +class SlotChoice(BaseModel): + user_id: str = Field(default_factory=lambda: settings.demo_user, min_length=1) + session_id: str = Field(min_length=1) + vote: bool = True # false takes the vote back + + +def _http(exc: store.GroupError) -> HTTPException: + return HTTPException(status_code=exc.status, detail=exc.detail) + + +def _profile(user_id: str) -> dict: + try: + doc = es.get(index=settings.idx_people, id=user_id, source_excludes=["embedding", "bio"]) + except NotFoundError as exc: + raise HTTPException(status_code=404, detail=f"unknown user {user_id}") from exc + return doc["_source"] | {"id": doc["_id"]} + + +def _free_breaks(user_id: str, limit: int = PROPOSE_SLOTS) -> list[dict]: + """Food and coffee breaks the user is free for (today, then the next day with breaks), same rules as Meet.""" + items = agenda.user_items(user_id) + kinds = agenda.session_kinds([i.get("session_id") or "" for i in items]) + return agenda.free_slots(_food_sessions(), items, kinds, "", now(), limit=limit) + + +def _write_agenda(group: dict, user_ids: list[str]) -> None: + for uid in user_ids: + item = store.agenda_item(group, uid) + es.index(index=settings.idx_agenda, id=item.pop("id"), document=item) + agenda.refresh() + + +def _busy_at(user_id: str, slot: dict | None, group_id: str) -> dict | None: + """The user's confirmed item that overlaps the meetup slot (co-located days aside), other than this meetup.""" + if not slot: + return None + items = [i for i in agenda.user_items(user_id) if i.get("id") != store.agenda_item_id(user_id, group_id)] + kinds = agenda.session_kinds([i.get("session_id") or "" for i in items]) + return next( + ( + i + for i in agenda.blocking(items, kinds) + if agenda.overlaps(slot["starts_at"], slot["ends_at"], i["starts_at"], i["ends_at"]) + ), + None, + ) + + +def _drop_agenda(group_id: str, user_id: str) -> None: + try: + es.delete(index=settings.idx_agenda, id=store.agenda_item_id(user_id, group_id)) + except NotFoundError: + return + agenda.refresh() + + +def _change(group_id: str, user_id: str, action: str, rule: Callable[[dict], dict]) -> tuple[dict, dict]: + """Read the group, apply a pure rule, write it back only if nobody changed it meanwhile. Returns (before, after).""" + span = trace.get_current_span() + span.set_attribute("confox.groups.id", group_id) + span.set_attribute("confox.groups.action", action) + try: + before, token = store.get(group_id) + after = rule(before) + if after is not before: + store.save(after, token) + except store.GroupError as exc: + raise _http(exc) from exc + except ConflictError as exc: + # Two people joined or voted at the same moment; the page reloads and the user tries again. + span.record_exception(exc) + raise HTTPException(status_code=409, detail="the group just changed, try again") from exc + changes.add(1, {"action": action}) + return before, after + + +@router.get("") +def groups(user_id: str = _user_id()) -> dict: + """{"groups": groups the user is not in, ranked (sharing one of their values first, each with `match`), + "mine": groups they host or joined}. Every group carries member_count, spots_left, tally and leading.""" + user = _profile(user_id) + out = store.rank(store.all_groups(), user_id, user) + trace.get_current_span().set_attribute("confox.groups.count", len(out["groups"]) + len(out["mine"])) + return out + + +@router.get("/suggest") +def suggest(user_id: str = _user_id()) -> dict: + """Groups worth proposing: values the user shares with others and how many people share each, + e.g. {"basis": "school", "value": "University of Utah", "count": 8, "label": "University of Utah · 8 people here"}. + """ + user = _profile(user_id) + aggs = store.suggest_aggs(user_id, user) + if not aggs: + return {"suggestions": []} + r = es.search( + index=settings.idx_people, size=0, query={"bool": {"must_not": [{"ids": {"values": [user_id]}}]}}, aggs=aggs + ) + open_groups = [g for g in store.all_groups() if g.get("status") == "open"] + found = store.suggestions(user, r.get("aggregations", {}), open_groups) + trace.get_current_span().set_attribute("confox.groups.suggestions", len(found)) + return {"suggestions": found} + + +@router.get("/slots") +def slots(user_id: str = _user_id()) -> dict: + """Breaks the user is free for, to choose a group's candidate times from: {"slots": [...]}, at most 6.""" + found = _free_breaks(user_id) + trace.get_current_span().set_attribute("confox.groups.slots", len(found)) + return {"slots": found} + + +@router.post("") +def propose(body: Propose) -> dict: + """Create an open group hosted by the user. Every chosen time must be a break the host is free for (422).""" + host = _profile(body.user_id) + free = {s["session_id"] for s in _free_breaks(body.user_id, limit=50)} + if missing := [sid for sid in body.session_ids if sid not in free]: + raise HTTPException(status_code=422, detail=f"not a free break for you: {', '.join(missing)}") + sessions = [agenda.get_session(sid) for sid in dict.fromkeys(body.session_ids)] + try: + group = store.new_group( + store.group_id(), + host, + body.basis, + body.value, + body.title, + body.description, + [s for s in sessions if s], + body.max_members, + ) + except store.GroupError as exc: + raise _http(exc) from exc + store.save(group) + trace.get_current_span().set_attribute("confox.groups.id", group["id"]) + changes.add(1, {"action": "propose"}) + activity.record("group_propose", body.user_id, f"{group['basis']} {group['value']}") + return store.view(group, body.user_id, host) + + +@router.post("/{group_id}/join") +def join(group_id: str, user_id: str = _user_id()) -> dict: + """Join a group (idempotent). If its time is already fixed, the meetup goes straight onto the user's agenda.""" + user = _profile(user_id) + try: + current, _ = store.get(group_id) + except store.GroupError as exc: + raise _http(exc) from exc + if current.get("status") == "fixed": + busy = _busy_at(user_id, current.get("fixed_slot"), group_id) + if busy: # the meetup would be a second confirmed item at the same time + raise HTTPException(status_code=409, detail=f"you already have {busy.get('title') or 'something'} then") + before, after = _change(group_id, user_id, "join", lambda g: store.join(g, user_id, user.get("name") or user_id)) + if after is not before: + activity.record("group_join", user_id, group_id) + if after.get("status") == "fixed": + # Also for members skipped at fix time because they were busy: once free, joining again adds the meetup. + _write_agenda(after, [user_id]) + return store.view(after, user_id, user) + + +@router.post("/{group_id}/leave") +def leave(group_id: str, user_id: str = _user_id()) -> dict: + """Leave a group and take back the user's votes; a fixed meetup leaves their agenda. The host cannot leave.""" + user = _profile(user_id) + try: + store.get(group_id) + except store.GroupError as exc: + if exc.status != 404: + raise _http(exc) from exc + # The group is gone (for example after a reload of the groups seed): clear its meetup off the agenda. + _drop_agenda(group_id, user_id) + return {"id": group_id, "removed": True} + before, after = _change(group_id, user_id, "leave", lambda g: store.leave(g, user_id)) + if after is not before and after.get("status") == "fixed": + _drop_agenda(group_id, user_id) + return store.view(after, user_id, user) + + +@router.post("/{group_id}/vote") +def vote(group_id: str, body: SlotChoice) -> dict: + """Vote for (or, with vote false, un-vote) one proposed time. Voting on a group joins it first.""" + user = _profile(body.user_id) + name = user.get("name") or body.user_id + + def rule(g: dict) -> dict: + return store.vote(store.join(g, body.user_id, name), body.user_id, body.session_id, body.vote) + + before, after = _change(group_id, body.user_id, "vote", rule) + if not store.is_member(before, body.user_id): + activity.record("group_join", body.user_id, group_id) + if body.vote: + activity.record("group_vote", body.user_id, group_id) + return store.view(after, body.user_id, user) + + +@router.post("/{group_id}/fix") +def fix(group_id: str, body: SlotChoice) -> dict: + """The host fixes one proposed time: the group becomes `fixed` and each member gets a confirmed agenda meeting.""" + user = _profile(body.user_id) + _, after = _change(group_id, body.user_id, "fix", lambda g: store.fix(g, body.user_id, body.session_id)) + members = after.get("members") or [] + # Never double-book: members already busy at that time do not get the meetup on their agenda. + busy = [m for m in members if _busy_at(m, after.get("fixed_slot"), group_id)] + _write_agenda(after, [m for m in members if m not in busy]) + activity.record("group_fix", body.user_id, group_id) + names = dict(zip(members, after.get("member_names") or [], strict=False)) + return store.view(after, body.user_id, user) | {"busy_members": [names.get(m, m) for m in busy]} + + +# ---------- hallway board ---------- + + +class NewPost(BaseModel): + user_id: str = Field(default_factory=lambda: settings.demo_user, min_length=1) + text: str = Field(min_length=1, max_length=400) + place: str = Field(default="", max_length=200) + minutes: int = 60 + tags: list[str] = Field(default_factory=list, max_length=10) + + +@router.get("/board") +def board(user_id: str = _user_id()) -> dict: + """The hallway board: {"items": live posts and upcoming meetup groups, newest first, each with `for_you` + when it matches the viewer's interests (posts) or values (groups)}, plus the viewer's `interests` to tag with.""" + user = _profile(user_id) + items = store.board(store.all_posts(), store.all_groups(), user_id, user, now()) + trace.get_current_span().set_attribute("confox.board.items", len(items)) + return {"items": items, "interests": store.profile_values(user)["interest"], "minutes": store.POST_MINUTES} + + +@router.post("/board") +def post(body: NewPost) -> dict: + """Post a short line to the board for 30, 60 or 180 minutes. Tags not among the author's interests are dropped.""" + author = _profile(body.user_id) + try: + item = store.new_post(store.post_id(), author, body.text, body.place, body.minutes, body.tags) + except store.GroupError as exc: + raise _http(exc) from exc + store.save(item) + changes.add(1, {"action": "post"}) + activity.record("board_post", body.user_id, " ".join(item["tags"])) + return item | {"kind": "post", "for_you": bool(item["tags"]), "matching": item["tags"], "mine": True} + + +@router.delete("/board/{post_id}") +def remove(post_id: str, user_id: str = _user_id()) -> dict: + """The author takes their post down (403 for anyone else, 404 if it is not a post).""" + trace.get_current_span().set_attribute("confox.board.post_id", post_id) + try: + item, token = store.get(post_id, kind="post") + store.remove_check(item, user_id) + except store.GroupError as exc: + raise _http(exc) from exc + es.delete(index=settings.idx_groups, id=post_id, refresh="wait_for", **token) + changes.add(1, {"action": "unpost"}) + return {"id": post_id, "deleted": True} diff --git a/backend/tests/test_groups.py b/backend/tests/test_groups.py new file mode 100644 index 0000000..2e2dcca --- /dev/null +++ b/backend/tests/test_groups.py @@ -0,0 +1,389 @@ +"""Meetup group rules on hand-written documents: ranking, suggestions, votes, joining, fixing. No Elasticsearch.""" + +from datetime import datetime + +import pytest + +from app.data.groups import sample_groups, sample_posts +from app.groups_store import ( + GroupError, + agenda_item, + board, + fix, + join, + leading_slot, + leave, + match_reason, + new_group, + new_post, + rank, + remove_check, + suggest_aggs, + suggestions, + tally, + view, + vote, +) + +AT = datetime.fromisoformat("2026-11-09T08:40:00") +EMMA = { + "id": "emma", + "name": "Emma Carter", + "company": "Wasatch Cloud", + "past_companies": ["Copperleaf"], + "schools": ["University of Utah"], + "communities": ["Women in Cloud Native"], + "interests": ["AI inference", "Kubeflow"], + "country": "United States", +} +HOST = {"id": "att-002", "name": "Maya Okafor"} + + +def brk(sid, start, end, title="Coffee Break"): + return {"id": sid, "title": title, "starts_at": f"2026-11-09T{start}:00", "ends_at": f"2026-11-09T{end}:00"} + + +LUNCH = brk("lunch", "12:46", "13:30", "Lunch | On Own") | {"room": "Ballroom"} +COFFEE = brk("coffee-pm", "14:48", "15:03") +EARLY = brk("coffee-am", "10:48", "11:03") + + +def group(gid="g1", basis="school", value="University of Utah", slots=(LUNCH, COFFEE), **kw): + return new_group(gid, HOST, basis, value, "", "", list(slots), at=AT, **kw) + + +# ---------- creating ---------- + + +def test_new_group_sorts_slots_names_itself_and_starts_open_with_the_host(): + g = group(slots=(COFFEE, LUNCH)) + assert [s["session_id"] for s in g["proposed_slots"]] == ["lunch", "coffee-pm"] + assert g["proposed_slots"][0] == { + "session_id": "lunch", + "title": "Lunch", + "starts_at": "2026-11-09T12:46:00", + "ends_at": "2026-11-09T13:30:00", + "room": "Ballroom", + } + assert g["title"] == "University of Utah alumni meetup" + assert g["members"] == ["att-002"] and g["member_names"] == ["Maya Okafor"] + assert g["status"] == "open" and g["fixed_slot"] is None + assert g["votes"] == {"lunch": [], "coffee-pm": []} + assert g["created_at"] == "2026-11-09T08:40:00" + + +@pytest.mark.parametrize( + "kwargs", + [ + {"basis": "planet"}, + {"value": " "}, + {"slots": ()}, + {"slots": (LUNCH, LUNCH)}, + {"slots": (EARLY, LUNCH, COFFEE, brk("x", "16:00", "16:30"))}, + ], +) +def test_new_group_refuses_bad_input(kwargs): + with pytest.raises(GroupError) as err: + group(**kwargs) + assert err.value.status == 422 + + +def test_max_members_is_clamped(): + assert group(max_members=1)["max_members"] == 2 + assert group(max_members=999)["max_members"] == 50 + + +# ---------- ranking ---------- + + +def test_match_reason_needs_the_same_basis(): + assert match_reason(group(), EMMA) == { + "basis": "school", + "value": "University of Utah", + "label": "You studied at University of Utah", + } + assert match_reason(group(basis="company", value="Copperleaf"), EMMA)["label"] == "You work or worked at Copperleaf" + assert match_reason(group(basis="country", value="University of Utah"), EMMA) is None + assert match_reason(group(basis="country", value="Bangladesh"), EMMA) is None + + +def test_rank_puts_matching_groups_first_by_basis_then_size_and_splits_mine(): + bangladesh = group("bd", "country", "Bangladesh") + bangladesh = join(join(join(bangladesh, "a", "A"), "b", "B"), "c", "C") # biggest, but no match + kubeflow = group("kf", "interest", "Kubeflow") + wicn = group("wicn", "community", "Women in Cloud Native") + utah = group("utah") + mine = join(group("us", "country", "United States"), "emma", "Emma Carter") + out = rank([bangladesh, kubeflow, wicn, utah, mine], "emma", EMMA) + assert [g["id"] for g in out["groups"]] == ["utah", "wicn", "kf", "bd"] + assert [g["id"] for g in out["mine"]] == ["us"] + assert out["groups"][0]["match"]["label"] == "You studied at University of Utah" + assert out["groups"][-1]["match"] is None and out["groups"][-1]["member_count"] == 4 + assert out["mine"][0]["is_member"] and not out["mine"][0]["is_host"] + + +def test_suggestions_count_people_per_value_most_telling_basis_first(): + aggs = suggest_aggs("emma", EMMA) + assert set(aggs) == {"school", "country", "company", "community", "interest"} + assert aggs["company"]["filters"]["filters"]["Copperleaf"]["bool"]["should"][1] == { + "term": {"past_companies": "Copperleaf"} + } + counts = { + "school": {"University of Utah": 8}, + "country": {"United States": 40}, + "company": {"Wasatch Cloud": 12, "Copperleaf": 0}, + "community": {"Women in Cloud Native": 20}, + "interest": {"AI inference": 30, "Kubeflow": 15}, + } + result = {b: {"buckets": {v: {"doc_count": c} for v, c in vs.items()}} for b, vs in counts.items()} + existing = [group("utah")] + out = suggestions(EMMA, result, existing) + assert [s["value"] for s in out] == [ + "University of Utah", + "United States", + "Women in Cloud Native", + "Wasatch Cloud", + "AI inference", + "Kubeflow", + ] + assert out[0]["label"] == "University of Utah · 8 people here" + assert out[0]["existing"] == ["utah"] and out[1]["existing"] == [] + assert "_order" not in out[0] + assert len(suggestions(EMMA, result, [], limit=2)) == 2 + + +# ---------- votes ---------- + + +def test_vote_tally_and_leading_slot(): + g = join(join(group(), "emma", "Emma Carter"), "b", "B") + assert leading_slot(g) is None + g = vote(g, "emma", "coffee-pm") + g = vote(g, "b", "coffee-pm") + g = vote(g, "b", "lunch") + g = vote(g, "b", "lunch") # voting twice counts once + assert [(s["session_id"], s["votes"], s["voted"]) for s in tally(g, "emma")] == [ + ("lunch", 1, False), + ("coffee-pm", 2, True), + ] + assert leading_slot(g) == "coffee-pm" + g = vote(g, "emma", "coffee-pm", on=False) + assert leading_slot(g) == "lunch" # tie at one vote each: the earlier time leads + + +def test_vote_does_not_mutate_the_original(): + g = join(group(), "emma", "Emma Carter") + vote(g, "emma", "lunch") + assert g["votes"]["lunch"] == [] + + +@pytest.mark.parametrize( + ("user", "session", "status"), + [("stranger", "lunch", 403), ("emma", "nope", 422)], +) +def test_vote_rules(user, session, status): + g = join(group(), "emma", "Emma Carter") + with pytest.raises(GroupError) as err: + vote(g, user, session) + assert err.value.status == status + + +def test_no_votes_once_fixed(): + g = fix(join(group(), "emma", "Emma Carter"), "att-002", "lunch") + with pytest.raises(GroupError) as err: + vote(g, "emma", "coffee-pm") + assert err.value.status == 409 + + +# ---------- join and leave ---------- + + +def test_join_is_idempotent_and_respects_the_limit(): + g = group(max_members=2) + g = join(g, "emma", "Emma Carter") + assert join(g, "emma", "Emma Carter") is g + with pytest.raises(GroupError) as err: + join(g, "c", "C") + assert err.value.status == 409 + assert view(g, "emma")["spots_left"] == 0 + + +def test_leave_removes_member_name_and_votes_but_not_the_host(): + g = vote(join(group(), "emma", "Emma Carter"), "emma", "lunch") + g = leave(g, "emma") + assert g["members"] == ["att-002"] and g["member_names"] == ["Maya Okafor"] + assert g["votes"]["lunch"] == [] + assert leave(g, "emma") is g + with pytest.raises(GroupError) as err: + leave(g, "att-002") + assert err.value.status == 409 + + +# ---------- fixing ---------- + + +def test_only_the_host_fixes_once_and_only_a_proposed_time(): + g = join(group(), "emma", "Emma Carter") + for user, session, status in [("emma", "lunch", 403), ("att-002", "coffee-am", 422)]: + with pytest.raises(GroupError) as err: + fix(g, user, session) + assert err.value.status == status + fixed = fix(g, "att-002", "lunch") + assert fixed["status"] == "fixed" and fixed["fixed_slot"]["session_id"] == "lunch" + with pytest.raises(GroupError) as err: + fix(fixed, "att-002", "coffee-pm") + assert err.value.status == 409 + + +def test_fixed_group_gives_members_a_confirmed_agenda_meeting(): + g = fix(join(group(sample=True), "emma", "Emma Carter"), "att-002", "lunch") + item = agenda_item(g, "emma", at=AT) + assert item == { + "id": "emma-g-g1", + "user_id": "emma", + "kind": "meeting", + "status": "confirmed", + "group_id": "g1", + "with_id": "g1", + "with_name": "University of Utah alumni meetup", + "session_id": "lunch", + "title": "Meetup: University of Utah alumni meetup", + "starts_at": "2026-11-09T12:46:00", + "ends_at": "2026-11-09T13:30:00", + "room": "Ballroom", + "sample": False, # Emma's own item is real; sample members' items are sample + "created_at": "2026-11-09T08:40:00", + } + assert agenda_item(g, "att-002", at=AT)["sample"] is True + + +# ---------- seed ---------- + + +def _session(sid, day, start, end, title): + return {"id": sid, "day": day, "is_food": True, "title": title, "starts_at": f"{day}T{start}:00", + "ends_at": f"{day}T{end}:00", "room": "Hall"} # fmt: skip + + +def test_sample_groups_are_labelled_and_consistent(): + sessions = [] + for day in ("2026-11-09", "2026-11-10", "2026-11-11"): + sessions += [ + _session(f"{day}-c1", day, "10:30", "11:00", "Coffee Break"), + _session(f"{day}-l", day, "12:30", "13:30", "Lunch"), + _session(f"{day}-c2", day, "15:00", "15:30", "Coffee Break"), + ] + attendees = [{"id": "emma", "name": "Emma"}, {"id": "alice", "name": "Alice"}] + attendees += [ + { + "id": f"att-{i:03d}", + "name": f"Person {i}", + "schools": ["University of Utah"], + "communities": ["Women in Cloud Native"], + "interests": ["Kubeflow"], + "country": "Brazil", + } + for i in range(1, 7) + ] + groups = sample_groups(sessions, attendees) + assert [g["title"] for g in groups][:4] == [ + "University of Utah alumni lunch", + "Bangladesh meetup", + "Women in Cloud Native coffee", + "Kubeflow users", + ] + for g in groups: + assert g["sample"] is True and g["status"] == "open" + assert "emma" not in g["members"] and len(g["members"]) == len(g["member_names"]) + assert g["members"][0] == g["host_id"] + assert all(set(v) <= set(g["members"]) for v in g["votes"].values()) + assert set(g["votes"]) == {s["session_id"] for s in g["proposed_slots"]} + + +# ---------- hallway board ---------- + + +def test_new_post_trims_keeps_only_own_interests_and_expires(): + author = EMMA | {"interests": ["AI inference", "Kubeflow", "KServe", "vLLM", "GPU scheduling"]} + p = new_post("p1", author, " At the Kubeflow booth " + "x" * 200, "Hall B", 30, ["Kubeflow", "Cilium"], at=AT) + assert p["text"].startswith("At the Kubeflow booth x") and len(p["text"]) == 140 + assert p["tags"] == ["Kubeflow"] + assert (p["type"], p["author_id"], p["place"]) == ("post", "emma", "Hall B") + assert (p["created_at"], p["expires_at"]) == ("2026-11-09T08:40:00", "2026-11-09T09:10:00") + many = new_post("p2", author, "hi", tags=["vLLM", "KServe", "AI inference", "Kubeflow"], at=AT) + assert many["tags"] == ["AI inference", "Kubeflow", "KServe"] # profile order, at most three + + +@pytest.mark.parametrize(("text", "minutes"), [(" ", 60), ("hi", 45)]) +def test_new_post_refuses_empty_text_and_odd_lengths(text, minutes): + with pytest.raises(GroupError) as err: + new_post("p", EMMA, text, minutes=minutes, at=AT) + assert err.value.status == 422 + + +def test_board_highlights_matches_hides_expired_and_mixes_in_groups(): + later = datetime.fromisoformat("2026-11-09T08:50:00") + mine = new_post("p-mine", EMMA, "Here", minutes=30, tags=["Kubeflow"], at=AT) + other = new_post( + "p-other", HOST | {"interests": ["Cilium"]}, "Cilium booth", minutes=180, tags=["Cilium"], at=later + ) + gone = new_post("p-gone", HOST, "Old news", minutes=30, at=datetime.fromisoformat("2026-11-09T08:00:00")) + done = fix(group("done", slots=(EARLY,)), "att-002", "coffee-am") + feed = board( + [mine, other, gone], [group("utah"), done], "emma", EMMA, datetime.fromisoformat("2026-11-09T12:00:00") + ) + assert [i["id"] for i in feed] == ["utah"] # posts expired, fixed group over; the open group stays + feed = board([mine, other, gone], [group("utah"), done], "emma", EMMA, later) + assert [(i["id"], i["kind"], i["for_you"]) for i in feed] == [ + ("p-other", "post", False), # newest first; same-minute items by id + ("utah", "group", True), + ("p-mine", "post", True), + ("done", "group", True), + ] + assert feed[2]["mine"] and not feed[0]["mine"] and feed[2]["matching"] == ["Kubeflow"] + + +def test_only_the_author_removes_a_post(): + p = new_post("p", EMMA, "hi", at=AT) + remove_check(p, "emma") + with pytest.raises(GroupError) as err: + remove_check(p, "att-002") + assert err.value.status == 403 + with pytest.raises(GroupError) as err: + remove_check(group(), "att-002") + assert err.value.status == 404 + + +def test_sample_posts_are_tagged_with_their_authors_interests(): + attendees = [{"id": "emma", "name": "Emma", "interests": ["Kubeflow"]}] + attendees += [ + {"id": f"att-{i}", "name": f"P{i}", "interests": ["Cilium", "GPU scheduling", "OpenTelemetry", "Kubeflow"]} + for i in range(4) + ] + posts = sample_posts(attendees) + assert len(posts) == 4 and all(p["sample"] and p["type"] == "post" for p in posts) + assert len({p["author_id"] for p in posts}) == 4 and "emma" not in {p["author_id"] for p in posts} + assert all(p["tags"] and p["expires_at"] > "2026-11-09T08:40:00" for p in posts) + + +def test_busy_at_finds_a_confirmed_item_at_the_meetup_time(monkeypatch): + from app.routers import groups as router + + slot = {"starts_at": "2026-11-09T14:48:00", "ends_at": "2026-11-09T15:03:00"} + items = [ + {"id": "emma-g-g1", "status": "confirmed", "starts_at": slot["starts_at"], "ends_at": slot["ends_at"]}, + { + "id": "emma-colocated", + "status": "confirmed", + "session_id": "day", + "starts_at": "2026-11-09T09:00:00", + "ends_at": "2026-11-09T17:30:00", + }, # fmt: skip + ] + monkeypatch.setattr(router.agenda, "user_items", lambda uid: items) + monkeypatch.setattr(router.agenda, "session_kinds", lambda ids: {"day": "colocated"}) + # Its own meetup item and the co-located day do not count, so the user is free. + assert router._busy_at("emma", slot, "g1") is None + coffee = {"id": "emma-coffee", "status": "confirmed", "title": "Coffee", **slot} + monkeypatch.setattr(router.agenda, "user_items", lambda uid: [*items, coffee]) + assert router._busy_at("emma", slot, "g1")["title"] == "Coffee" diff --git a/docs/architecture.md b/docs/architecture.md index b1427f8..ba22657 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,19 +19,20 @@ flowchart LR |---|---|---| | Browser app | Pages, navigation, browser telemetry | Pull request 2b | | API | One service; every endpoint traced | Pull requests 0, 1 | -| Elasticsearch | Sessions, people, agendas, transcripts, connections | Pull requests 2, 3 | +| Elasticsearch | Sessions, people, agendas, transcripts, connections, meetup groups | Pull requests 2, 3 | | LLM | Ask and Catch up answers, grounded in retrieved documents | Pull requests 8, 9 | | Telemetry | OpenTelemetry to Dash0: traces, metrics, logs, RUM | Pull requests 1, 12 | ## Data (pull request 2) -`uv run python -m app.load` reads the snapshot in `data/raw/` and fills three indices. `--only sessions|people|agenda` rebuilds one index and leaves the others alone. +`uv run python -m app.load` reads the snapshot in `data/raw/` and fills three indices. `--only sessions|people|agenda|activity|groups` rebuilds one index and leaves the others alone. | Index | Holds | Count | |---|---|---| | `confox-sessions` | Every scheduled session: time (local, no offset), day, room, venue, track, level, CNCF projects, speakers, kind, `is_food` | 600 | | `confox-people` | 712 public speaker profiles from the schedule, plus 80 generated attendees marked `sample: true` (Emma and Alice first, then University of Utah alumni) | 792 | | `confox-agenda` | Emma's Monday: the co-located AI day, a confirmed coffee with Alice, a pending lunch request (all `sample: true`) | 3 | +| `confox-groups` | 5 sample meetup groups and 4 hallway board posts (`--only groups`), all `sample: true`; see Groups and connections | 9 | Session kinds come from the track and the cleaned title: `keynote`, `talk`, `lightning`, `tutorial`, `contribfest`, `poster`, `showcase`, `colocated`, `break`, `registration`. Titles are stripped of emoji first, so "☕ Coffee Break" inside the Project Lightning Talks track is a `break` with `is_food`. @@ -213,6 +214,41 @@ Ids: `{user}-s-{session_id}` for added sessions, `{user}-m-{8 hex}` for new requ - **Writes.** Every write refreshes the agenda index so the next read sees it. Counters: `confox.agenda.changes` (attribute `action`: add, remove) and `confox.connect.requests` (`action`: send, accept, decline); the request spans carry the session or person id. - **Schedule.** Each day-view row except breaks and registration has an "Agenda" / "Added" toggle; it writes, then reloads the day and the agenda ids, so For you, clashes and the count update together. Search results get the same toggle through the `SessionCard` aside, with state from `GET /api/agenda`. Outgoing requests show as "Request sent". - **People.** Every card has a primary "Meet" button that opens an inline panel: the free slots as a native radio group (first one chosen and focused), an optional line, "Send request". After sending, the card says "Request sent for 14:48 · Coffee" and the button becomes a disabled "Requested" (warn colours, since it is pending); people with a pending outgoing request show "Requested" on load, and a confirmed meeting shows as a green chip. Escape closes the panel and returns focus to the button. +## Groups and connections + +The People page has three tabs, kept in the address as `?tab=connections|groups` (Match is the default): **Match** (above), **Connections** and **Groups**. Groups live in `backend/app/routers/groups.py` with the pure rules in `backend/app/groups_store.py`; the UI is `src/components/groups/`, `src/components/connect/ConnectionsTab.tsx` and `src/styles/groups.css`. + +**Connections** reads `GET /api/connect`: requests to the user with Accept and Decline, requests they sent with Withdraw, and confirmed meetings (group meetups show as "Group meetup"). It adds no endpoint. + +**Groups.** A meetup for people who share a school, country, company, community or interest. Someone proposes it with up to three food or coffee breaks they are free for, others join and vote for the times they can make, and the host fixes one. One document per group in `confox-groups`: + +| Field | Meaning | +|---|---| +| `type` | `group` (board posts share the index as `post`) | +| `basis`, `value` | `school`, `country`, `company`, `community` or `interest`, and the shared value ("University of Utah") | +| `title`, `description` | At most 80 and 280 characters; the title defaults to "University of Utah alumni meetup" and so on | +| `host_id`, `host_name`, `members`, `member_names`, `max_members` | Host first; names kept in member order so cards need no join; 12 members by default | +| `proposed_slots`, `votes`, `fixed_slot` | 1 to 3 breaks `{session_id, title, starts_at, ends_at, room}`; `{session_id: [user ids]}`; the chosen slot or null. Stored but not indexed (`enabled: false`), so break ids never become mapping fields | +| `status`, `created_at`, `sample` | `open` or `fixed`; local time; `true` for seeded groups | + +| Endpoint | Returns | +|---|---| +| `GET /api/groups?user_id` | `{groups, mine}`: groups the user is not in, ranked, and groups they host or joined. Each adds `member_count`, `spots_left`, `is_member`, `is_host`, `match`, `tally` (slots with `votes` and `voted`) and `leading` | +| `GET /api/groups/suggest?user_id` | `{suggestions: [{basis, value, count, label, title, existing}]}`, at most 6: "University of Utah · 7 people here", with ids of open groups already formed around it | +| `GET /api/groups/slots?user_id` | Up to 6 breaks the user is free for (the Meet rules from `agenda_store.free_slots`, no other person) | +| `POST /api/groups {user_id, basis, value, title, description, session_ids}` | The new open group; 422 if a time is not a free break for the host or the input is invalid | +| `POST /api/groups/{id}/join?user_id`, `/leave?user_id` | The group. Join is idempotent, 409 when full; leaving drops the user's votes; the host cannot leave (409) | +| `POST /api/groups/{id}/vote {user_id, session_id, vote}` | The group. A member may vote for several times; `vote: false` takes one back; voting on a group joins it first; 422 for a time not proposed, 409 once fixed | +| `POST /api/groups/{id}/fix {user_id, session_id}` | The fixed group; host only (403), once (409), one of the proposed times (422) | + +- **Ranking.** Groups whose value is one of the user's own for the same basis come first, with a `match` reason ("You studied at University of Utah"); then by basis (school, country, community, company, interest), open before fixed, more members first. Suggestions use one `size: 0` search on `confox-people` with a `filters` aggregation per basis over the user's values (company matches current or past), excluding the user, in the same basis order and then by count. +- **Fixing.** Every member gets a confirmed agenda meeting `{user}-g-{group}` (`kind: meeting`, `group_id`, `with_id` the group, `title` "Meetup: <title>", the break's time and room), so it shows in Agenda, My brief and Connections and blocks that break for Meet. Joining a fixed group writes the joiner's item; leaving deletes it. +- **Concurrency.** Changes read the group, apply a pure rule and write back with `if_seq_no`/`if_primary_term`; a clash answers 409 and the page reloads. +- **UI.** "Suggested for you" cards open the Propose dialog (native `<dialog>`) with basis, value and title filled in; times are the free breaks as checkboxes in the shared `SlotList` (radio for Meet, checkboxes here), at most 3. Group cards show the basis chip, member initials and count, each proposed time with a vote bar and a Vote toggle (`aria-pressed`), Join or Leave, and for the host "Fix time" per slot; a fixed group shows its time and "on your agenda". A Match card offers "Propose a University of Utah meetup" from its first school, community, company or interest reason, which switches to Groups with the dialog open. +- **Hallway board.** Short-lived posts in the same index (`type: post`, `text` up to 140 characters, optional `place`, `tags` limited to the author's own interests, `expires_at` 30, 60 or 180 minutes after posting). `GET /api/groups/board?user_id` returns live posts (expired ones are hidden by `clock.now()`) and meetup groups still to happen, newest first, each with `for_you` (a tag matches the viewer's interests, or the group shares one of their values) and the viewer's `interests` for tagging; `POST /api/groups/board {user_id, text, place, minutes, tags}` posts; `DELETE /api/groups/board/{id}?user_id` lets only the author remove it (403 otherwise). Matching posts are highlighted. +- **Telemetry.** Counter `confox.groups.changes` (attribute `action`: propose, join, leave, vote, fix, post, unpost); request spans carry `confox.groups.id`, `confox.groups.action` and counts. Activity events `group_propose`, `group_join`, `group_vote`, `group_fix`, `board_post`. +- **Seed.** `uv run python -m app.load --only groups` rebuilds `confox-groups` alone: University of Utah alumni lunch, Bangladesh meetup, Women in Cloud Native coffee, Kubeflow users and Brasileiros na KubeCon, hosted and joined by sample attendees who share the value (none in Bangladesh, so that one is simply two sample attendees), with votes, plus four board posts until late Monday morning. Emma is in none of them. Everything seeded is labelled "Sample" in the UI. + ## My brief (pull request 10) One calm page for the signed-in attendee's day. `GET /api/brief?user_id=emma` (day of `clock.now()`) lives in `backend/app/routers/brief.py`; the page is `src/pages/Brief.tsx` with `src/components/brief/` and `src/styles/brief.css`. Nothing new is stored: the endpoint reads `confox-sessions`, `confox-people` and `confox-agenda` and reuses the other features' helpers (schedule `_day_sessions`, `annotate`, `_knn`; Match `build_match_query`, `why`; `next_food()`). diff --git a/frontend/src/components/connect/ConnectionsTab.tsx b/frontend/src/components/connect/ConnectionsTab.tsx new file mode 100644 index 0000000..951a1cc --- /dev/null +++ b/frontend/src/components/connect/ConnectionsTab.tsx @@ -0,0 +1,203 @@ +import { useCallback, useEffect, useState } from 'react' +import { CalendarCheck, Check, Clock, Inbox, LoaderCircle, MessageSquare, Send, Undo2, Users, X } from 'lucide-react' +import { getJSON, postJSON } from '../../api.ts' +import Avatar from '../people/Avatar.tsx' +import { dayLabel, hhmm, roomLabel } from '../schedule/time.ts' +import type { ConnectResponse, Meeting } from './types.ts' + +type Props = { userId: string; onChanged?: () => void } +type Load = { status: 'loading' } | { status: 'failed' } | { status: 'ready'; data: ConnectResponse } +type Action = 'accept' | 'decline' | 'withdraw' + +const DONE: Record<Action, string> = { accept: 'Accepted', decline: 'Declined', withdraw: 'Withdrew the request to' } + +function When({ m, label }: { m: Meeting; label?: string }) { + const room = roomLabel(m.room ?? '') + return ( + <p className="conn-when"> + <Clock size={13} aria-hidden="true" /> + <span> + {label ?? m.title} · {dayLabel(m.starts_at.slice(0, 10))} <time dateTime={m.starts_at}>{hhmm(m.starts_at)}</time> + {room && ` · ${room}`} + </span> + </p> + ) +} + +/** Meeting requests to and from the user, and confirmed meetings, from the existing /api/connect endpoints. */ +export default function ConnectionsTab({ userId, onChanged }: Props) { + const [load, setLoad] = useState<Load>({ status: 'loading' }) + const [busy, setBusy] = useState('') + const [said, setSaid] = useState('') + const [error, setError] = useState('') + + const reload = useCallback( + (signal?: AbortSignal) => + getJSON<ConnectResponse>('connect', { user_id: userId }, { signal }) + .then((data) => setLoad({ status: 'ready', data })) + .catch(() => !signal?.aborted && setLoad((l) => (l.status === 'ready' ? l : { status: 'failed' }))), + [userId], + ) + + useEffect(() => { + const ctrl = new AbortController() + reload(ctrl.signal) + return () => ctrl.abort() + }, [reload]) + + const act = async (m: Meeting, action: Action) => { + setBusy(`${m.id}:${action}`) + setError('') + try { + await postJSON(`connect/${encodeURIComponent(m.id)}/${action}?user_id=${encodeURIComponent(userId)}`, {}) + setSaid(`${DONE[action]} ${m.with_name}.`) + await reload() + onChanged?.() + } catch { + setError(`Could not ${action} the request from ${m.with_name}. Try again.`) + } finally { + setBusy('') + } + } + + if (load.status === 'loading') + return ( + <p className="people-status"> + <LoaderCircle size={18} className="spin" aria-hidden="true" /> + Loading your connections… + </p> + ) + if (load.status === 'failed') + return <p className="people-status">Could not load connections. Check that the API is running and try again.</p> + + const { incoming, outgoing, meetings } = load.data + const button = (m: Meeting, action: Action, label: string, primary = false) => { + const Icon = action === 'accept' ? Check : action === 'decline' ? X : Undo2 + const key = `${m.id}:${action}` + return ( + <button + type="button" + className={primary ? 'btn-primary' : 'group-btn'} + disabled={busy !== ''} + onClick={() => act(m, action)} + aria-label={`${label} ${action === 'withdraw' ? 'the request to' : 'the request from'} ${m.with_name}`} + > + <Icon size={14} aria-hidden="true" /> + {busy === key ? `${label}…` : label} + </button> + ) + } + + return ( + <div className="conn-tab"> + <p className="people-note">Sample people and their requests are generated demo data.</p> + <p className="people-sr-only" role="status" aria-live="polite"> + {said} + </p> + {error && ( + <p className="meet-error" role="alert"> + {error} + </p> + )} + + <section aria-labelledby="conn-incoming"> + <h2 id="conn-incoming" className="section-label group-section-label"> + <Inbox size={14} aria-hidden="true" /> Requests to you · {incoming.length} + </h2> + {incoming.length === 0 ? ( + <p className="group-empty">No requests waiting for you.</p> + ) : ( + <ul className="conn-list"> + {incoming.map((m) => ( + <li key={m.id}> + <article className="conn-card" aria-labelledby={`conn-${m.id}`}> + <Avatar name={m.with_name} /> + <div className="conn-body"> + <div className="conn-head"> + <h3 id={`conn-${m.id}`}>{m.with_name} wants to meet</h3> + {m.sample && <span className="chip chip-warn group-sample">Sample</span>} + </div> + <When m={m} /> + {m.message && ( + <p className="conn-message"> + <MessageSquare size={13} aria-hidden="true" /> + <span>{m.message}</span> + </p> + )} + <div className="group-actions"> + {button(m, 'accept', 'Accept', true)} + {button(m, 'decline', 'Decline')} + </div> + </div> + </article> + </li> + ))} + </ul> + )} + </section> + + <section aria-labelledby="conn-outgoing"> + <h2 id="conn-outgoing" className="section-label group-section-label"> + <Send size={14} aria-hidden="true" /> Requests you sent · {outgoing.length} + </h2> + {outgoing.length === 0 ? ( + <p className="group-empty">No requests waiting on others. Use Meet on a Match card to send one.</p> + ) : ( + <ul className="conn-list"> + {outgoing.map((m) => ( + <li key={m.id}> + <article className="conn-card" aria-labelledby={`conn-${m.id}`}> + <Avatar name={m.with_name} /> + <div className="conn-body"> + <div className="conn-head"> + <h3 id={`conn-${m.id}`}>{m.with_name}</h3> + <span className="chip chip-warn">Pending</span> + </div> + <When m={m} /> + <div className="group-actions">{button(m, 'withdraw', 'Withdraw')}</div> + </div> + </article> + </li> + ))} + </ul> + )} + </section> + + <section aria-labelledby="conn-meetings"> + <h2 id="conn-meetings" className="section-label group-section-label"> + <CalendarCheck size={14} aria-hidden="true" /> Confirmed meetings · {meetings.length} + </h2> + {meetings.length === 0 ? ( + <p className="group-empty">No confirmed meetings yet.</p> + ) : ( + <ul className="conn-list"> + {meetings.map((m) => { + const group = Boolean(m.group_id) + return ( + <li key={m.id}> + <article className="conn-card conn-card-ok" aria-labelledby={`conn-${m.id}`}> + {group ? ( + <span className="avatar people-avatar conn-group-avatar" aria-hidden="true"> + <Users size={18} /> + </span> + ) : ( + <Avatar name={m.with_name} /> + )} + <div className="conn-body"> + <div className="conn-head"> + <h3 id={`conn-${m.id}`}>{m.with_name}</h3> + <span className="chip group-status-fixed">{group ? 'Group meetup' : 'Confirmed'}</span> + {m.sample && <span className="chip chip-warn group-sample">Sample</span>} + </div> + <When m={m} label={group ? 'Meetup' : undefined} /> + </div> + </article> + </li> + ) + })} + </ul> + )} + </section> + </div> + ) +} diff --git a/frontend/src/components/connect/SlotList.tsx b/frontend/src/components/connect/SlotList.tsx index fb58214..1461d76 100644 --- a/frontend/src/components/connect/SlotList.tsx +++ b/frontend/src/components/connect/SlotList.tsx @@ -6,28 +6,44 @@ type Props = { name: string legend: string slots: Slot[] - selected: string + /** One session id: a radio group. A list: checkboxes, for choosing several times (Groups). */ + selected: string | string[] + /** Radio: the chosen slot. Checkboxes: the slot that was ticked or unticked. */ onSelect: (sessionId: string) => void - /** Gets the checked radio, so the panel can move focus into the group when it opens. */ + /** Checkboxes only: once this many are ticked, the others are disabled. */ + max?: number + /** Gets the checked radio (or first checkbox), so the panel can move focus into the group when it opens. */ checkedRef?: Ref<HTMLInputElement> + /** Optional hint under the legend, e.g. "Pick up to 3". */ + hint?: string } -/** Free breaks as one native radio group: arrow keys move between slots, Tab leaves the group. */ -export default function SlotList({ name, legend, slots, selected, onSelect, checkedRef }: Props) { +/** Free breaks as one native radio or checkbox group: arrow keys move between radios, Tab leaves the group. */ +export default function SlotList({ name, legend, slots, selected, onSelect, max, checkedRef, hint }: Props) { + const multiple = Array.isArray(selected) + const hintId = hint ? `${name}-hint` : undefined return ( - <fieldset className="slot-list"> + <fieldset className="slot-list" aria-describedby={hintId}> <legend className="slot-legend">{legend}</legend> - {slots.map((s) => { - const checked = s.session_id === selected + {hint && ( + <p id={hintId} className="slot-hint"> + {hint} + </p> + )} + {slots.map((s, i) => { + const checked = multiple ? selected.includes(s.session_id) : s.session_id === selected + const full = multiple && max !== undefined && !checked && selected.length >= max + const takesFocus = multiple ? i === 0 : checked const room = roomLabel(s.room ?? '') return ( - <label key={s.session_id} className={checked ? 'slot is-checked' : 'slot'}> + <label key={s.session_id} className={`slot${checked ? ' is-checked' : ''}${full ? ' is-disabled' : ''}`}> <input - type="radio" + type={multiple ? 'checkbox' : 'radio'} name={name} value={s.session_id} checked={checked} - ref={checked ? checkedRef : undefined} + disabled={full} + ref={takesFocus ? checkedRef : undefined} onChange={() => onSelect(s.session_id)} /> <time className="slot-time" dateTime={s.starts_at}> diff --git a/frontend/src/components/connect/types.ts b/frontend/src/components/connect/types.ts index b322273..5cc6608 100644 --- a/frontend/src/components/connect/types.ts +++ b/frontend/src/components/connect/types.ts @@ -27,6 +27,8 @@ export type Meeting = { session_id?: string message?: string sample?: boolean + /** Set on a confirmed group meetup (Groups); with_id is then the group id and with_name its title. */ + group_id?: string } /** GET /api/connect */ diff --git a/frontend/src/components/groups/GroupCard.tsx b/frontend/src/components/groups/GroupCard.tsx new file mode 100644 index 0000000..478d29d --- /dev/null +++ b/frontend/src/components/groups/GroupCard.tsx @@ -0,0 +1,201 @@ +import { useState } from 'react' +import { CalendarCheck, Check, Crown, LogOut, Pin, Sparkles, UserPlus, Vote } from 'lucide-react' +import { ApiError, postJSON } from '../../api.ts' +import { dayLabel, hhmm, roomLabel } from '../schedule/time.ts' +import { BASIS_ICON, BASIS_LABEL } from './fields.ts' +import type { Group, GroupSlot } from './types.ts' + +type Props = { + group: Group + userId: string + /** Called with the updated group after any change, and with a sentence for the live region. */ + onChanged: (group: Group, said: string) => void +} + +const SHOWN_MEMBERS = 5 + +function initials(name: string): string { + const parts = name.trim().split(/\s+/).filter(Boolean) + return ((parts[0]?.[0] ?? '') + (parts.length > 1 ? parts[parts.length - 1][0] : '')).toUpperCase() +} + +function when(s: GroupSlot): string { + const room = roomLabel(s.room ?? '') + return `${s.title} · ${dayLabel(s.starts_at.slice(0, 10))} ${hhmm(s.starts_at)}${room ? ` · ${room}` : ''}` +} + +export default function GroupCard({ group: g, userId, onChanged }: Props) { + const [busy, setBusy] = useState('') + const [error, setError] = useState('') + const Icon = BASIS_ICON[g.basis] + const headingId = `group-${g.id}` + const maxVotes = Math.max(1, ...g.tally.map((t) => t.votes)) + const others = g.member_names.length - SHOWN_MEMBERS + + const act = async (key: string, path: string, body: unknown, said: (next: Group) => string) => { + setBusy(key) + setError('') + try { + const next = await postJSON<Group>(`groups/${encodeURIComponent(g.id)}/${path}`, body) + onChanged(next, said(next)) + } catch (err) { + const status = err instanceof ApiError ? err.status : 0 + setError( + status === 409 ? 'This group just changed or is full. Reload and try again.' : 'Could not save. Try again.', + ) + } finally { + setBusy('') + } + } + + const q = `?user_id=${encodeURIComponent(userId)}` + const join = () => act('join', `join${q}`, {}, () => `You joined ${g.title}.`) + const leave = () => act('leave', `leave${q}`, {}, () => `You left ${g.title}.`) + const vote = (s: GroupSlot, on: boolean) => + act(`vote-${s.session_id}`, 'vote', { user_id: userId, session_id: s.session_id, vote: on }, () => + on ? `Voted for ${s.title} at ${hhmm(s.starts_at)}.` : `Vote for ${hhmm(s.starts_at)} taken back.`, + ) + const fix = (s: GroupSlot) => + act(`fix-${s.session_id}`, 'fix', { user_id: userId, session_id: s.session_id }, (next) => { + const left = next.busy_members ?? [] + const fixed = `Fixed ${g.title} for ${s.title} at ${hhmm(s.starts_at)}.` + return left.length + ? `${fixed} Not added for ${left.join(', ')}: busy then. They can join again once free.` + : `${fixed} It is on every member's agenda.` + }) + + return ( + <article className="group-card" aria-labelledby={headingId}> + <div className="group-head"> + <h3 id={headingId} className="group-title"> + {g.title} + </h3> + {g.sample && ( + <span className="chip chip-warn group-sample" title="Generated sample group"> + Sample + </span> + )} + </div> + + <ul className="chips group-meta" aria-label="About this group"> + <li className="chip group-basis" title={BASIS_LABEL[g.basis]}> + <Icon size={13} aria-hidden="true" /> + <span>{g.value}</span> + </li> + {g.status === 'fixed' ? ( + <li className="chip group-status-fixed">Time fixed</li> + ) : ( + <li className="chip group-status-open">Voting on a time</li> + )} + {g.is_host && ( + <li className="chip group-host-chip"> + <Crown size={13} aria-hidden="true" /> You host + </li> + )} + </ul> + + {g.match && !g.is_member && ( + <p className="group-match"> + <Sparkles size={13} aria-hidden="true" /> + {g.match.label} + </p> + )} + {g.description && <p className="group-desc">{g.description}</p>} + + <div className="group-members"> + <span className="group-avatars" aria-hidden="true"> + {g.member_names.slice(0, SHOWN_MEMBERS).map((n, i) => ( + <span key={`${g.members[i]}`} className="avatar group-avatar"> + {initials(n)} + </span> + ))} + {others > 0 && <span className="avatar group-avatar group-avatar-more">+{others}</span>} + </span> + <span className="group-count-text"> + {g.member_count} of {g.max_members} going · hosted by {g.is_host ? 'you' : g.host_name} + </span> + </div> + + {g.status === 'fixed' && g.fixed_slot ? ( + <p className="group-fixed"> + <CalendarCheck size={15} aria-hidden="true" /> + <span> + <time dateTime={g.fixed_slot.starts_at}>{when(g.fixed_slot)}</time> + {g.is_member && ' · on your agenda'} + </span> + </p> + ) : ( + <div className="group-times" role="group" aria-label={`Proposed times for ${g.title}`}> + {g.tally.map((t) => { + const leading = g.leading === t.session_id + return ( + <div key={t.session_id} className={leading ? 'group-time is-leading' : 'group-time'}> + <div className="group-time-main"> + <time dateTime={t.starts_at} className="group-time-label"> + {when(t)} + </time> + <span className="group-votes"> + <span className="group-vote-bar" aria-hidden="true"> + <span style={{ width: `${(t.votes / maxVotes) * 100}%` }} /> + </span> + <span> + {t.votes} {t.votes === 1 ? 'vote' : 'votes'} + {leading && ' · leading'} + </span> + </span> + </div> + <div className="group-time-actions"> + <button + type="button" + className={t.voted ? 'group-btn is-on' : 'group-btn'} + aria-pressed={t.voted} + disabled={busy !== ''} + onClick={() => vote(t, !t.voted)} + aria-label={`${t.voted ? 'Voted' : 'Vote'} for ${t.title} at ${hhmm(t.starts_at)}${g.is_member ? '' : ' (joins the group)'}`} + > + {t.voted ? <Check size={14} aria-hidden="true" /> : <Vote size={14} aria-hidden="true" />} + {t.voted ? 'Voted' : 'Vote'} + </button> + {g.is_host && ( + <button + type="button" + className="group-btn group-btn-fix" + disabled={busy !== ''} + onClick={() => fix(t)} + aria-label={`Fix ${g.title} for ${t.title} at ${hhmm(t.starts_at)}`} + > + <Pin size={14} aria-hidden="true" /> + Fix time + </button> + )} + </div> + </div> + ) + })} + {!g.is_member && <p className="group-hint">Voting for a time also joins the group.</p>} + </div> + )} + + {error && ( + <p className="meet-error" role="alert"> + {error} + </p> + )} + + <div className="group-actions"> + {!g.is_member && ( + <button type="button" className="btn-primary" disabled={busy !== '' || g.spots_left === 0} onClick={join}> + <UserPlus size={15} aria-hidden="true" /> + {g.spots_left === 0 ? 'Full' : busy === 'join' ? 'Joining' : 'Join'} + </button> + )} + {g.is_member && !g.is_host && ( + <button type="button" className="group-btn" disabled={busy !== ''} onClick={leave}> + <LogOut size={14} aria-hidden="true" /> + {busy === 'leave' ? 'Leaving' : 'Leave'} + </button> + )} + </div> + </article> + ) +} diff --git a/frontend/src/components/groups/GroupsTab.tsx b/frontend/src/components/groups/GroupsTab.tsx new file mode 100644 index 0000000..31fb48b --- /dev/null +++ b/frontend/src/components/groups/GroupsTab.tsx @@ -0,0 +1,173 @@ +import { useCallback, useEffect, useState } from 'react' +import { LoaderCircle, Plus, Users } from 'lucide-react' +import { getJSON } from '../../api.ts' +import { BASIS_ICON } from './fields.ts' +import GroupCard from './GroupCard.tsx' +import HallwayBoard from './HallwayBoard.tsx' +import ProposeDialog from './ProposeDialog.tsx' +import type { Group, GroupsResponse, ProposeSeed, SuggestResponse, Suggestion } from './types.ts' + +type Props = { + userId: string + /** A meetup to propose, handed over from a Match card: the dialog opens with it when the tab mounts. */ + seed: ProposeSeed | null +} + +type Load = { status: 'loading' } | { status: 'failed' } | { status: 'ready'; data: GroupsResponse } + +export default function GroupsTab({ userId, seed }: Props) { + const [load, setLoad] = useState<Load>({ status: 'loading' }) + const [suggested, setSuggested] = useState<Suggestion[]>([]) + const [dialog, setDialog] = useState<ProposeSeed | null>(seed) + const [said, setSaid] = useState('') + const [version, setVersion] = useState(0) + + const reload = useCallback( + (signal?: AbortSignal) => + Promise.all([ + getJSON<GroupsResponse>('groups', { user_id: userId }, { signal }), + getJSON<SuggestResponse>('groups/suggest', { user_id: userId }, { signal }), + ]) + .then(([data, s]) => { + setLoad({ status: 'ready', data }) + setSuggested(s.suggestions) + }) + .catch((err: unknown) => { + if (signal?.aborted) return + console.error('groups failed', err) + setLoad((l) => (l.status === 'ready' ? l : { status: 'failed' })) + }), + [userId], + ) + + useEffect(() => { + const ctrl = new AbortController() + reload(ctrl.signal) + return () => ctrl.abort() + }, [reload]) + + const changed = (_g: Group, sentence: string) => { + setSaid(sentence) + setVersion((v) => v + 1) + reload() + } + + const created = (g: Group) => { + setDialog(null) + setSaid(`Proposed ${g.title}. It is under Your groups; fix a time once people have voted.`) + setVersion((v) => v + 1) + reload() + } + + const titleOf = new Map( + load.status === 'ready' ? [...load.data.groups, ...load.data.mine].map((g) => [g.id, g.title]) : [], + ) + + return ( + <div className="groups-tab"> + <p className="people-note">Sample groups and their members are generated demo data; groups you create are real.</p> + <p className="people-sr-only" role="status" aria-live="polite"> + {said} + </p> + {said && ( + <p className="group-said" aria-hidden="true"> + {said} + </p> + )} + + <section aria-labelledby="groups-suggested"> + <div className="group-section-head"> + <h2 id="groups-suggested" className="section-label"> + Suggested for you + </h2> + <button type="button" className="group-btn" onClick={() => setDialog({ basis: 'interest', value: '' })}> + <Plus size={14} aria-hidden="true" /> + Propose meetup + </button> + </div> + {suggested.length === 0 && load.status === 'ready' && ( + <p className="group-empty">No shared schools, places or communities found yet.</p> + )} + <ul className="suggest-list"> + {suggested.map((s) => { + const Icon = BASIS_ICON[s.basis] + const open = s.existing.map((id) => titleOf.get(id)).filter(Boolean) + return ( + <li key={`${s.basis}:${s.value}`}> + <button + type="button" + className="suggest-card" + onClick={() => setDialog({ basis: s.basis, value: s.value, title: s.title })} + > + <Icon size={16} aria-hidden="true" className="suggest-icon" /> + <span className="suggest-body"> + <span className="suggest-title">Propose a meetup for {s.value}</span> + <span className="suggest-meta"> + {s.count} {s.count === 1 ? 'person' : 'people'} here + {open.length > 0 && ` · ${open.length} open group${open.length > 1 ? 's' : ''} below`} + </span> + </span> + <Plus size={16} aria-hidden="true" className="suggest-plus" /> + </button> + </li> + ) + })} + </ul> + </section> + + {load.status === 'loading' && ( + <p className="people-status"> + <LoaderCircle size={18} className="spin" aria-hidden="true" /> + Loading groups… + </p> + )} + {load.status === 'failed' && ( + <p className="people-status">Could not load groups. Check that the API is running and try again.</p> + )} + + {load.status === 'ready' && ( + <> + <section aria-labelledby="groups-join"> + <h2 id="groups-join" className="section-label group-section-label"> + Groups you can join + </h2> + {load.data.groups.length === 0 ? ( + <p className="group-empty">No other groups yet.</p> + ) : ( + <ul className="group-list"> + {load.data.groups.map((g) => ( + <li key={g.id}> + <GroupCard group={g} userId={userId} onChanged={changed} /> + </li> + ))} + </ul> + )} + </section> + <section aria-labelledby="groups-mine"> + <h2 id="groups-mine" className="section-label group-section-label"> + Your groups + </h2> + {load.data.mine.length === 0 ? ( + <p className="group-empty"> + <Users size={15} aria-hidden="true" /> You have not joined a group yet. Join one above or propose your own. + </p> + ) : ( + <ul className="group-list"> + {load.data.mine.map((g) => ( + <li key={g.id}> + <GroupCard group={g} userId={userId} onChanged={changed} /> + </li> + ))} + </ul> + )} + </section> + + </> + )} + + <HallwayBoard userId={userId} version={version} /> + + <ProposeDialog userId={userId} seed={dialog} onClose={() => setDialog(null)} onCreated={created} /> + </div> + ) +} diff --git a/frontend/src/components/groups/HallwayBoard.tsx b/frontend/src/components/groups/HallwayBoard.tsx new file mode 100644 index 0000000..c77453b --- /dev/null +++ b/frontend/src/components/groups/HallwayBoard.tsx @@ -0,0 +1,243 @@ +import { useCallback, useEffect, useState, type FormEvent } from 'react' +import { Clock, LoaderCircle, MapPin, Megaphone, Send, Sparkles, Trash2, Users } from 'lucide-react' +import { deleteJSON, getJSON, postJSON } from '../../api.ts' +import { dayLabel, hhmm } from '../schedule/time.ts' +import { BASIS_ICON } from './fields.ts' +import type { BoardGroup, BoardPost, BoardResponse } from './types.ts' + +const POST_CHARS = 140 +const LENGTH_LABEL: Record<number, string> = { 30: '30 minutes', 60: '1 hour', 180: '3 hours' } + +type Props = { + userId: string + /** Bumped by the Groups tab whenever groups change, so the feed shows them too. */ + version: number +} + +type Load = { status: 'loading' } | { status: 'failed' } | { status: 'ready'; data: BoardResponse } + +/** Short-lived posts ("At the Cilium booth till 15:00") and meetup groups, newest first. */ +export default function HallwayBoard({ userId, version }: Props) { + const [load, setLoad] = useState<Load>({ status: 'loading' }) + const [text, setText] = useState('') + const [place, setPlace] = useState('') + const [minutes, setMinutes] = useState(60) + const [tags, setTags] = useState<string[]>([]) + const [busy, setBusy] = useState('') + const [error, setError] = useState('') + const [said, setSaid] = useState('') + + const reload = useCallback( + (signal?: AbortSignal) => + getJSON<BoardResponse>('groups/board', { user_id: userId }, { signal }) + .then((data) => setLoad({ status: 'ready', data })) + .catch(() => !signal?.aborted && setLoad((l) => (l.status === 'ready' ? l : { status: 'failed' }))), + [userId], + ) + + useEffect(() => { + const ctrl = new AbortController() + reload(ctrl.signal) + return () => ctrl.abort() + }, [reload, version]) + + const submit = async (e: FormEvent) => { + e.preventDefault() + if (!text.trim() || busy) return + setBusy('post') + setError('') + try { + await postJSON<BoardPost>('groups/board', { user_id: userId, text: text.trim(), place: place.trim(), minutes, tags }) + setText('') + setPlace('') + setTags([]) + setSaid('Posted to the hallway board.') + await reload() + } catch { + setError('Could not post. Try again.') + } finally { + setBusy('') + } + } + + const remove = async (p: BoardPost) => { + setBusy(p.id) + setError('') + try { + await deleteJSON(`groups/board/${encodeURIComponent(p.id)}`, { user_id: userId }) + setSaid('Post removed.') + await reload() + } catch { + setError('Could not remove the post. Try again.') + } finally { + setBusy('') + } + } + + const interests = load.status === 'ready' ? load.data.interests : [] + const lengths = load.status === 'ready' ? load.data.minutes : [30, 60, 180] + const toggleTag = (t: string) => setTags((x) => (x.includes(t) ? x.filter((y) => y !== t) : [...x, t].slice(-3))) + + return ( + <section aria-labelledby="groups-board" className="board"> + <h2 id="groups-board" className="section-label group-section-label"> + <Megaphone size={14} aria-hidden="true" /> Hallway board + </h2> + <p className="people-sr-only" role="status" aria-live="polite"> + {said} + </p> + + <form className="board-form" onSubmit={submit}> + <label className="group-field"> + <span>Where are you, what do you want to talk about?</span> + <input + type="text" + value={text} + maxLength={POST_CHARS} + required + placeholder="At the Cilium booth till 15:00, come talk eBPF" + autoComplete="off" + aria-describedby="board-count" + onChange={(e) => setText(e.target.value)} + /> + </label> + <p id="board-count" className="board-count"> + {text.length} of {POST_CHARS} characters + </p> + <div className="group-field-row"> + <label className="group-field group-field-grow"> + <span>Place (optional)</span> + <input type="text" value={place} maxLength={60} autoComplete="off" onChange={(e) => setPlace(e.target.value)} /> + </label> + <label className="group-field"> + <span>Show it for</span> + <select value={minutes} onChange={(e) => setMinutes(Number(e.target.value))}> + {lengths.map((m) => ( + <option key={m} value={m}> + {LENGTH_LABEL[m] ?? `${m} minutes`} + </option> + ))} + </select> + </label> + </div> + {interests.length > 0 && ( + <fieldset className="board-tags"> + <legend>Tags from your interests (up to 3)</legend> + <div className="chips"> + {interests.map((t) => ( + <label key={t} className={tags.includes(t) ? 'board-tag is-on' : 'board-tag'}> + <input type="checkbox" checked={tags.includes(t)} onChange={() => toggleTag(t)} /> + {t} + </label> + ))} + </div> + </fieldset> + )} + {error && ( + <p className="meet-error" role="alert"> + {error} + </p> + )} + <div className="group-dialog-actions"> + <button type="submit" className="btn-primary" disabled={!text.trim() || busy !== ''}> + {busy === 'post' ? <LoaderCircle size={15} className="spin" aria-hidden="true" /> : <Send size={15} aria-hidden="true" />} + Post + </button> + </div> + </form> + + {load.status === 'loading' && ( + <p className="people-status"> + <LoaderCircle size={18} className="spin" aria-hidden="true" /> + Loading the board… + </p> + )} + {load.status === 'failed' && <p className="people-status">Could not load the hallway board.</p>} + {load.status === 'ready' && load.data.items.length === 0 && <p className="group-empty">Nothing on the board right now.</p>} + {load.status === 'ready' && load.data.items.length > 0 && ( + <ul className="board-list"> + {load.data.items.map((item) => ( + <li key={item.id}> + {item.kind === 'post' ? ( + <PostCard post={item} busy={busy === item.id} onRemove={() => remove(item)} /> + ) : ( + <GroupItem group={item} /> + )} + </li> + ))} + </ul> + )} + </section> + ) +} + +function PostCard({ post: p, busy, onRemove }: { post: BoardPost; busy: boolean; onRemove: () => void }) { + return ( + <article className={p.for_you ? 'board-item is-for-you' : 'board-item'} aria-label={`Post by ${p.author_name}`}> + <div className="board-item-head"> + <span className="board-author">{p.mine ? 'You' : p.author_name}</span> + {p.for_you && ( + <span className="chip board-for-you"> + <Sparkles size={12} aria-hidden="true" /> Matches your interests + </span> + )} + {p.sample && <span className="chip chip-warn group-sample">Sample</span>} + </div> + <p className="board-text">{p.text}</p> + <p className="board-meta"> + {p.place && ( + <span> + <MapPin size={12} aria-hidden="true" /> {p.place} + </span> + )} + <span> + <Clock size={12} aria-hidden="true" /> until <time dateTime={p.expires_at}>{hhmm(p.expires_at)}</time> + </span> + </p> + {p.tags.length > 0 && ( + <ul className="chips board-item-tags" aria-label="Tags"> + {p.tags.map((t) => ( + <li key={t} className={p.matching.includes(t) ? 'chip' : 'chip board-tag-plain'}> + {t} + </li> + ))} + </ul> + )} + {p.mine && ( + <div className="group-actions"> + <button type="button" className="group-btn" disabled={busy} onClick={onRemove}> + <Trash2 size={14} aria-hidden="true" /> {busy ? 'Removing' : 'Remove'} + </button> + </div> + )} + </article> + ) +} + +function GroupItem({ group: g }: { group: BoardGroup }) { + const Icon = BASIS_ICON[g.basis] + return ( + <article className={g.for_you ? 'board-item board-group is-for-you' : 'board-item board-group'} aria-label={`Meetup group ${g.title}`}> + <div className="board-item-head"> + <Users size={14} aria-hidden="true" className="board-group-icon" /> + <span className="board-author">Meetup group by {g.author_name}</span> + {g.sample && <span className="chip chip-warn group-sample">Sample</span>} + </div> + <p className="board-text"> + <a href={`#group-${g.id}`}>{g.title}</a> + </p> + <p className="board-meta"> + <span> + <Icon size={12} aria-hidden="true" /> {g.value} + </span> + <span>{g.member_count} going</span> + <span> + {g.status === 'fixed' && g.fixed_slot + ? `${g.fixed_slot.title} ${dayLabel(g.fixed_slot.starts_at.slice(0, 10))} ${hhmm(g.fixed_slot.starts_at)}` + : 'Voting on a time'} + </span> + {g.is_member && <span>You are in</span>} + </p> + </article> + ) +} diff --git a/frontend/src/components/groups/ProposeDialog.tsx b/frontend/src/components/groups/ProposeDialog.tsx new file mode 100644 index 0000000..0f7c4d5 --- /dev/null +++ b/frontend/src/components/groups/ProposeDialog.tsx @@ -0,0 +1,241 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react' +import { LoaderCircle, Plus, X } from 'lucide-react' +import { ApiError, getJSON, postJSON } from '../../api.ts' +import SlotList from '../connect/SlotList.tsx' +import type { Slot } from '../connect/types.ts' +import { BASES, BASIS_LABEL, defaultTitle } from './fields.ts' +import type { Basis, Group, ProposeSeed, SlotsResponse } from './types.ts' + +const MAX_TIMES = 3 +const TITLE_CHARS = 80 +const DESCRIPTION_CHARS = 280 + +type Props = { + userId: string + /** The open dialog's starting values; null keeps it closed. */ + seed: ProposeSeed | null + onClose: () => void + onCreated: (group: Group) => void +} + +type Load = { status: 'loading' } | { status: 'failed' } | { status: 'ready'; slots: Slot[] } + +/** Propose a meetup: who it is for, a title, an optional line, and up to three free breaks to vote on. */ +export default function ProposeDialog({ userId, seed, onClose, onCreated }: Props) { + const ref = useRef<HTMLDialogElement>(null) + + useEffect(() => { + const dialog = ref.current + if (!dialog) return + if (seed && !dialog.open) dialog.showModal() + if (!seed && dialog.open) dialog.close() + }, [seed]) + + return ( + <dialog + ref={ref} + className="group-dialog" + aria-labelledby="propose-title" + onClose={onClose} + onClick={(e) => { + if (e.target === e.currentTarget) ref.current?.close() // backdrop click + }} + > + {/* Remounting per seed resets the form each time the dialog opens. */} + {seed && ( + <ProposeForm + key={`${seed.basis}:${seed.value}`} + userId={userId} + seed={seed} + onCancel={() => ref.current?.close()} + onCreated={onCreated} + /> + )} + </dialog> + ) +} + +function ProposeForm({ + userId, + seed, + onCancel, + onCreated, +}: { + userId: string + seed: ProposeSeed + onCancel: () => void + onCreated: (group: Group) => void +}) { + const [basis, setBasis] = useState<Basis>(seed.basis) + const [value, setValue] = useState(seed.value) + const [title, setTitle] = useState(seed.title ?? (seed.value ? defaultTitle(seed.basis, seed.value) : '')) + const [titleEdited, setTitleEdited] = useState(Boolean(seed.title)) + const [description, setDescription] = useState('') + const [load, setLoad] = useState<Load>({ status: 'loading' }) + const [times, setTimes] = useState<string[]>([]) + const [saving, setSaving] = useState(false) + const [error, setError] = useState('') + const titleRef = useRef<HTMLInputElement>(null) + + useEffect(() => { + const ctrl = new AbortController() + getJSON<SlotsResponse>('groups/slots', { user_id: userId }, { signal: ctrl.signal }) + .then((r) => { + setTimes(r.slots.slice(0, 1).map((s) => s.session_id)) + setLoad({ status: 'ready', slots: r.slots }) + }) + .catch(() => !ctrl.signal.aborted && setLoad({ status: 'failed' })) + return () => ctrl.abort() + }, [userId]) + + useEffect(() => titleRef.current?.focus(), []) + + // The title follows basis and value until the user types their own. + const retitle = (b: Basis, v: string) => { + if (!titleEdited) setTitle(v.trim() ? defaultTitle(b, v.trim()) : '') + } + + const toggleTime = (id: string) => + setTimes((t) => (t.includes(id) ? t.filter((x) => x !== id) : t.length < MAX_TIMES ? [...t, id] : t)) + + const submit = async (e: FormEvent) => { + e.preventDefault() + if (saving || !value.trim() || times.length === 0) return + setSaving(true) + setError('') + try { + const group = await postJSON<Group>('groups', { + user_id: userId, + basis, + value: value.trim(), + title: title.trim(), + description: description.trim(), + session_ids: times, + }) + onCreated(group) + } catch (err) { + setError( + err instanceof ApiError && err.status === 422 + ? 'One of those times is no longer free for you. Pick again.' + : 'Could not create the meetup. Try again.', + ) + setSaving(false) + } + } + + return ( + <form className="group-dialog-body" onSubmit={submit}> + <div className="group-dialog-head"> + <h2 id="propose-title">Propose a meetup</h2> + <button type="button" className="icon-button" aria-label="Close" onClick={onCancel}> + <X size={18} aria-hidden="true" /> + </button> + </div> + + <div className="group-field-row"> + <label className="group-field"> + <span>For people who share a</span> + <select + value={basis} + onChange={(e) => { + const b = e.target.value as Basis + setBasis(b) + retitle(b, value) + }} + > + {BASES.map((b) => ( + <option key={b} value={b}> + {BASIS_LABEL[b]} + </option> + ))} + </select> + </label> + <label className="group-field group-field-grow"> + <span>{BASIS_LABEL[basis]}</span> + <input + type="text" + required + maxLength={TITLE_CHARS} + value={value} + autoComplete="off" + onChange={(e) => { + setValue(e.target.value) + retitle(basis, e.target.value) + }} + /> + </label> + </div> + + <label className="group-field"> + <span>Title</span> + <input + ref={titleRef} + type="text" + required + maxLength={TITLE_CHARS} + value={title} + autoComplete="off" + onChange={(e) => { + setTitle(e.target.value) + setTitleEdited(true) + }} + /> + </label> + + <label className="group-field"> + <span>Description (optional)</span> + <textarea + rows={2} + maxLength={DESCRIPTION_CHARS} + value={description} + placeholder="Who it is for and what you will talk about" + onChange={(e) => setDescription(e.target.value)} + /> + </label> + + {load.status === 'loading' && ( + <p className="meet-status" role="status"> + <LoaderCircle size={15} className="spin" aria-hidden="true" /> + Finding breaks you are free for… + </p> + )} + {load.status === 'failed' && ( + <p className="meet-status" role="alert"> + Could not load your free breaks. Try again later. + </p> + )} + {load.status === 'ready' && load.slots.length === 0 && ( + <p className="meet-status" role="status"> + You have no free food or coffee break today or on the next conference day. + </p> + )} + {load.status === 'ready' && load.slots.length > 0 && ( + <SlotList + name="propose-times" + legend="Times people can vote on" + hint={`Pick up to ${MAX_TIMES} breaks you are free for. ${times.length} of ${MAX_TIMES} chosen.`} + slots={load.slots} + selected={times} + max={MAX_TIMES} + onSelect={toggleTime} + /> + )} + + {error && ( + <p className="meet-error" role="alert"> + {error} + </p> + )} + + <div className="group-dialog-actions"> + <button type="button" className="group-btn" onClick={onCancel}> + Cancel + </button> + <button type="submit" className="btn-primary" disabled={saving || !value.trim() || times.length === 0}> + {saving ? <LoaderCircle size={15} className="spin" aria-hidden="true" /> : <Plus size={15} aria-hidden="true" />} + Create + </button> + </div> + </form> + ) +} diff --git a/frontend/src/components/groups/fields.ts b/frontend/src/components/groups/fields.ts new file mode 100644 index 0000000..5dca3d7 --- /dev/null +++ b/frontend/src/components/groups/fields.ts @@ -0,0 +1,37 @@ +import type { LucideIcon } from 'lucide-react' +import { Building2, GraduationCap, Globe, Sparkles, Users } from 'lucide-react' +import type { WhyField } from '../people/types.ts' +import type { Basis } from './types.ts' + +export const BASES: Basis[] = ['school', 'country', 'community', 'company', 'interest'] + +export const BASIS_LABEL: Record<Basis, string> = { + school: 'School', + country: 'Country', + community: 'Community', + company: 'Company', + interest: 'Interest', +} + +export const BASIS_ICON: Record<Basis, LucideIcon> = { + school: GraduationCap, + country: Globe, + community: Users, + company: Building2, + interest: Sparkles, +} + +/** Match reasons that can seed a meetup; city and bio mentions cannot. */ +export const WHY_BASIS: Partial<Record<WhyField, Basis>> = { + schools: 'school', + communities: 'community', + company: 'company', + interests: 'interest', +} + +/** The default title for a meetup around one value, as the API names it. */ +export function defaultTitle(basis: Basis, value: string): string { + if (basis === 'school') return `${value} alumni meetup` + if (basis === 'company') return `${value} folks meetup` + return `${value} meetup` +} diff --git a/frontend/src/components/groups/types.ts b/frontend/src/components/groups/types.ts new file mode 100644 index 0000000..1598521 --- /dev/null +++ b/frontend/src/components/groups/types.ts @@ -0,0 +1,102 @@ +// Shapes returned by /api/groups. Kept with the feature so parallel pages do not share one types file. +import type { Slot } from '../connect/types.ts' + +export type Basis = 'school' | 'country' | 'company' | 'community' | 'interest' + +export type GroupSlot = { + session_id: string + title: string + starts_at: string + ends_at: string + room?: string | null +} + +/** A proposed time with its votes, as one user sees it. */ +export type TallySlot = GroupSlot & { votes: number; voted: boolean } + +export type Group = { + id: string + title: string + basis: Basis + value: string + description: string + host_id: string + host_name: string + members: string[] + member_names: string[] + max_members: number + proposed_slots: GroupSlot[] + fixed_slot: GroupSlot | null + status: 'open' | 'fixed' + created_at: string + sample: boolean + member_count: number + spots_left: number + is_member: boolean + /** After fix: members not given the meetup because they were busy then. */ + busy_members?: string[] + is_host: boolean + /** Why the group is relevant to the user ("You studied at University of Utah"), if it is. */ + match: { basis: Basis; value: string; label: string } | null + tally: TallySlot[] + /** session_id of the time with most votes, or null when nobody has voted. */ + leading: string | null +} + +/** GET /api/groups */ +export type GroupsResponse = { groups: Group[]; mine: Group[] } + +/** GET /api/groups/suggest: a value the user shares and how many people here share it. */ +export type Suggestion = { + basis: Basis + value: string + count: number + label: string + title: string + /** Ids of open groups already formed around this value. */ + existing: string[] +} + +export type SuggestResponse = { suggestions: Suggestion[] } + +/** What the Propose dialog opens with. */ +export type ProposeSeed = { basis: Basis; value: string; title?: string } + +export type SlotsResponse = { slots: Slot[] } + +/** A hallway board post (GET /api/groups/board). */ +export type BoardPost = { + kind: 'post' + id: string + text: string + place: string + tags: string[] + author_id: string + author_name: string + created_at: string + expires_at: string + sample: boolean + /** Tags matching the viewer's interests; for_you when there is at least one. */ + matching: string[] + for_you: boolean + mine: boolean +} + +/** A meetup group as it appears in the board feed. */ +export type BoardGroup = { + kind: 'group' + id: string + title: string + basis: Basis + value: string + status: 'open' | 'fixed' + fixed_slot: GroupSlot | null + member_count: number + author_name: string + created_at: string + for_you: boolean + is_member: boolean + sample: boolean +} + +export type BoardResponse = { items: (BoardPost | BoardGroup)[]; interests: string[]; minutes: number[] } diff --git a/frontend/src/components/people/PersonCard.tsx b/frontend/src/components/people/PersonCard.tsx index b955999..b4c2046 100644 --- a/frontend/src/components/people/PersonCard.tsx +++ b/frontend/src/components/people/PersonCard.tsx @@ -1,7 +1,9 @@ import { useRef, useState } from 'react' -import { Check, Coffee, Undo2, Users, X } from 'lucide-react' +import { Check, Coffee, Plus, Undo2, Users, X } from 'lucide-react' import { postJSON } from '../../api.ts' import MeetPanel from '../connect/MeetPanel.tsx' +import { WHY_BASIS } from '../groups/fields.ts' +import type { Basis } from '../groups/types.ts' import type { Meeting } from '../connect/types.ts' import { dayLabel, hhmm } from '../schedule/time.ts' import Avatar from './Avatar.tsx' @@ -18,9 +20,20 @@ type Props = { meeting?: Meeting onRequested?: (meeting: Meeting) => void onWithdrawn?: (personId: string) => void + /** Offer a meetup for the first shared school, community, company or interest (Groups tab). */ + onPropose?: (basis: Basis, value: string) => void } -export default function PersonCard({ person, onWhy, userId, request, meeting, onRequested, onWithdrawn }: Props) { +export default function PersonCard({ + person, + onWhy, + userId, + request, + meeting, + onRequested, + onWithdrawn, + onPropose, +}: Props) { const role = [person.title, person.company].filter(Boolean).join(' · ') const [open, setOpen] = useState(false) const [sent, setSent] = useState<Meeting | null>(null) @@ -31,6 +44,7 @@ export default function PersonCard({ person, onWhy, userId, request, meeting, on const isRequested = pending !== null const [withdrawing, setWithdrawing] = useState(false) const [withdrawFailed, setWithdrawFailed] = useState(false) + const shared = person.why.find((w) => WHY_BASIS[w.field]) const withdraw = async () => { if (!pending) return @@ -144,6 +158,16 @@ export default function PersonCard({ person, onWhy, userId, request, meeting, on })} </ul> )} + {onPropose && shared && ( + <button + type="button" + className="link-button person-propose" + onClick={() => onPropose(WHY_BASIS[shared.field]!, shared.value)} + > + <Plus size={13} aria-hidden="true" /> + Propose {/^[aeio]/i.test(shared.value) ? 'an' : 'a'} {shared.value} meetup + </button> + )} {open && !isRequested && ( <MeetPanel id={panelId} userId={userId} person={person} onSent={onSent} onClose={close} /> )} diff --git a/frontend/src/pages/People.tsx b/frontend/src/pages/People.tsx index 781070e..d50d044 100644 --- a/frontend/src/pages/People.tsx +++ b/frontend/src/pages/People.tsx @@ -1,20 +1,48 @@ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState, type KeyboardEvent } from 'react' import { LoaderCircle, Search, SearchX, X } from 'lucide-react' import { DEMO_USER, getJSON } from '../api.ts' +import ConnectionsTab from '../components/connect/ConnectionsTab.tsx' import type { ConnectResponse, Meeting } from '../components/connect/types.ts' +import GroupsTab from '../components/groups/GroupsTab.tsx' +import type { Basis, ProposeSeed } from '../components/groups/types.ts' import MatchFilters from '../components/people/MatchFilters.tsx' import PersonCard from '../components/people/PersonCard.tsx' import { WHY_FILTER } from '../components/people/fields.ts' import type { FilterKey, Filters, Kind, MatchResponse, Why } from '../components/people/types.ts' import '../styles/people.css' import '../styles/connect.css' +import '../styles/groups.css' const KINDS: { value: Kind; label: string }[] = [ { value: 'attendee', label: 'Attendees' }, { value: 'speaker', label: 'Speakers' }, ] +type Tab = 'match' | 'connections' | 'groups' +const TABS: { value: Tab; label: string; lead: string }[] = [ + { + value: 'match', + label: 'Match', + lead: 'People worth meeting, ranked by what you share. Click a reason to see everyone who shares it.', + }, + { value: 'connections', label: 'Connections', lead: 'Meeting requests to and from you, and the meetings you have.' }, + { + value: 'groups', + label: 'Groups', + lead: 'Meetups for people who share your school, country, company, community or interests.', + }, +] + +function initialTab(): Tab { + const t = new URLSearchParams(window.location.search).get('tab') + return TABS.some((x) => x.value === t) ? (t as Tab) : 'match' +} + export default function People() { + const [tab, setTabState] = useState<Tab>(initialTab) + const [seed, setSeed] = useState<ProposeSeed | null>(null) + const tabRefs = useRef<Record<Tab, HTMLButtonElement | null>>({ match: null, connections: null, groups: null }) + const [connectVersion, setConnectVersion] = useState(0) const [kind, setKind] = useState<Kind>('attendee') // My brief links here with ?q=<name> to open one person. const [text, setText] = useState(() => new URLSearchParams(window.location.search).get('q') ?? '') @@ -52,6 +80,7 @@ export default function People() { return () => ctrl.abort() }, [key]) + // Reloaded when the Connections tab changes something, so Match cards show the same state. useEffect(() => { const ctrl = new AbortController() getJSON<ConnectResponse>('connect', { user_id: DEMO_USER }, { signal: ctrl.signal }) @@ -61,7 +90,29 @@ export default function People() { }) .catch((err: unknown) => !ctrl.signal.aborted && console.warn('connections failed', err)) return () => ctrl.abort() - }, []) + }, [connectVersion]) + + // The tab lives in the address (?tab=groups) so it survives a reload and can be linked to. + const setTab = (next: Tab, proposal: ProposeSeed | null = null) => { + setTabState(next) + setSeed(proposal) + const url = new URL(window.location.href) + if (next === 'match') url.searchParams.delete('tab') + else url.searchParams.set('tab', next) + window.history.replaceState(window.history.state, '', url) + } + + const onTabKey = (e: KeyboardEvent) => { + const i = TABS.findIndex((t) => t.value === tab) + const step = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0 + const to = e.key === 'Home' ? 0 : e.key === 'End' ? TABS.length - 1 : step ? (i + step + TABS.length) % TABS.length : -1 + if (to < 0) return + e.preventDefault() + setTab(TABS[to].value) + tabRefs.current[TABS[to].value]?.focus() + } + + const propose = (basis: Basis, value: string) => setTab('groups', { basis, value }) const addRequested = (m: Meeting) => setRequested((prev) => new Map(prev).set(m.with_id, m)) const removeRequested = (personId: string) => @@ -95,8 +146,43 @@ export default function People() { return ( <section className="page people-page" aria-labelledby="page-title"> <h1 id="page-title">People</h1> - <p className="page-lead">People worth meeting, ranked by what you share. Click a reason to see everyone who shares it.</p> + <p className="page-lead">{TABS.find((t) => t.value === tab)?.lead}</p> + <div className="people-tabs" role="tablist" aria-label="People views" onKeyDown={onTabKey}> + {TABS.map((t) => ( + <button + key={t.value} + ref={(el) => { + tabRefs.current[t.value] = el + }} + id={`people-tab-${t.value}`} + type="button" + role="tab" + aria-selected={tab === t.value} + aria-controls={`people-panel-${t.value}`} + tabIndex={tab === t.value ? 0 : -1} + className="people-tab" + onClick={() => setTab(t.value)} + > + {t.label} + </button> + ))} + </div> + + {tab === 'connections' && ( + <div id="people-panel-connections" role="tabpanel" aria-labelledby="people-tab-connections"> + <ConnectionsTab userId={DEMO_USER} onChanged={() => setConnectVersion((v) => v + 1)} /> + </div> + )} + + {tab === 'groups' && ( + <div id="people-panel-groups" role="tabpanel" aria-labelledby="people-tab-groups"> + <GroupsTab userId={DEMO_USER} seed={seed} /> + </div> + )} + + {tab === 'match' && ( + <div id="people-panel-match" role="tabpanel" aria-labelledby="people-tab-match"> <div className="people-controls"> <label className="people-search"> <Search size={16} aria-hidden="true" /> @@ -184,12 +270,15 @@ export default function People() { meeting={meetings.get(p.id)} onRequested={addRequested} onWithdrawn={removeRequested} + onPropose={propose} /> </li> ))} </ol> )} </div> + </div> + )} </section> ) } diff --git a/frontend/src/styles/groups.css b/frontend/src/styles/groups.css new file mode 100644 index 0000000..ba041eb --- /dev/null +++ b/frontend/src/styles/groups.css @@ -0,0 +1,249 @@ +/* People tabs, Connections and Groups. Colours come only from the tokens in index.css. */ + +.people-tabs { + display: flex; + gap: 4px; + margin: 4px 0 14px; + border-bottom: 1px solid var(--line); + overflow-x: auto; + scrollbar-width: none; +} +.people-tab { + flex: none; + padding: 9px 14px; + border: 0; + border-bottom: 2px solid transparent; + background: transparent; + color: var(--text-2); + font-weight: 600; + cursor: pointer; +} +.people-tab:hover { color: var(--text); } +.people-tab[aria-selected="true"] { border-bottom-color: var(--accent); color: var(--accent-ink); } + +.person-propose { display: inline-flex; align-items: center; gap: 4px; margin-top: 8px; text-align: left; } + +/* Shared bits */ +.group-section-label { display: flex; align-items: center; gap: 6px; margin-top: 22px; } +.group-section-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px; } +.group-section-head .section-label { margin: 0; } +.group-empty { display: flex; align-items: center; gap: 6px; margin: 0; color: var(--muted); font-size: 13px; } +.group-said { margin: 0 0 10px; padding: 8px 12px; border-radius: 10px; background: var(--ok-soft); color: var(--text); font-size: 13px; } +.group-btn { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 6px 11px; + border: 1px solid var(--line-strong); + border-radius: 9px; + background: var(--panel-2); + color: var(--text); + font-size: 13px; + font-weight: 500; + cursor: pointer; + white-space: nowrap; +} +.group-btn:hover { background: var(--panel-3); } +.group-btn:disabled, .btn-primary:disabled { opacity: 0.6; cursor: default; } +.group-btn.is-on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-ink); } +.group-btn-fix { border-color: var(--ok); color: var(--ok); background: var(--ok-soft); } +.group-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; } +.group-actions:empty { display: none; } + +/* Suggested for you */ +.suggest-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; margin: 10px 0 0; padding: 0; list-style: none; } +.suggest-card { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 10px 12px; + border: 1px dashed var(--line-strong); + border-radius: 12px; + background: var(--panel); + text-align: left; + cursor: pointer; +} +.suggest-card:hover { border-color: var(--accent); background: var(--panel-2); } +.suggest-icon { flex: none; color: var(--accent-ink); } +.suggest-plus { flex: none; margin-left: auto; color: var(--muted); } +.suggest-body { display: flex; flex-direction: column; min-width: 0; } +.suggest-title { font-weight: 600; overflow-wrap: anywhere; } +.suggest-meta { color: var(--muted); font-size: 12.5px; } + +/* Group cards */ +.group-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 10px; margin: 0; padding: 0; list-style: none; } +.group-card { + height: 100%; + padding: 14px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); +} +.group-head { display: flex; align-items: flex-start; gap: 8px; } +.group-title { margin: 0; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; } +.group-sample { margin-left: auto; padding: 1px 8px; font-size: 11px; } +.group-meta { margin-top: 8px; } +.group-meta .chip { font-size: 11.5px; padding: 2px 9px; } +.group-basis { max-width: 100%; } +.group-basis span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.group-status-open { background: var(--warn-soft); color: var(--warn); } +.group-status-fixed { background: var(--ok-soft); color: var(--ok); } +.group-host-chip { background: var(--panel-3); color: var(--text); } +.group-match { display: flex; align-items: center; gap: 6px; margin: 8px 0 0; color: var(--accent-ink); font-size: 12.5px; font-weight: 500; } +.group-desc { margin: 6px 0 0; color: var(--text-2); font-size: 13px; } +.group-members { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-top: 10px; } +.group-avatars { display: inline-flex; } +.group-avatar { width: 26px; height: 26px; margin-left: -6px; border: 2px solid var(--panel); font-size: 10.5px; } +.group-avatar:first-child { margin-left: 0; } +.group-avatar-more { background: var(--panel-3); color: var(--text-2); } +.group-count-text { color: var(--muted); font-size: 12.5px; } + +.group-fixed { + display: flex; + align-items: center; + gap: 8px; + margin: 12px 0 0; + padding: 8px 10px; + border-radius: 10px; + background: var(--ok-soft); + color: var(--text); + font-size: 13px; +} +.group-fixed svg { flex: none; color: var(--ok); } +.group-fixed time { font-family: var(--font); } + +.group-times { display: flex; flex-direction: column; gap: 6px; margin-top: 12px; } +.group-time { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 8px 10px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--bg-2); +} +.group-time.is-leading { border-color: var(--accent); } +.group-time-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1 1 160px; } +.group-time-label { font-family: var(--font); font-size: 13px; font-weight: 500; overflow-wrap: anywhere; } +.group-votes { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; } +.group-vote-bar { position: relative; width: 70px; height: 6px; border-radius: 999px; background: var(--panel-3); overflow: hidden; } +.group-vote-bar span { position: absolute; inset: 0 auto 0 0; border-radius: 999px; background: var(--accent); } +.group-time-actions { display: flex; gap: 6px; } +.group-hint { margin: 2px 0 0; color: var(--muted); font-size: 12px; } + +/* Propose dialog (native modal) */ +.group-dialog { + width: min(520px, calc(100vw - 24px)); + max-height: calc(100dvh - 32px); + padding: 0; + border: 1px solid var(--line-strong); + border-radius: var(--radius); + background: var(--bg-2); + color: var(--text); + box-shadow: var(--shadow); +} +.group-dialog::backdrop { background: var(--overlay); } +.group-dialog-body { display: flex; flex-direction: column; gap: 14px; padding: 16px 18px 18px; } +.group-dialog-head { display: flex; align-items: center; justify-content: space-between; } +.group-dialog-head h2 { margin: 0; font-size: 17px; } +.group-field-row { display: flex; flex-wrap: wrap; gap: 10px; } +.group-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.group-field-grow { flex: 1 1 200px; } +.group-field > span { color: var(--text-2); font-size: 12.5px; } +.group-field input, +.group-field select, +.group-field textarea { + width: 100%; + min-width: 0; + padding: 8px 10px; + border: 1px solid var(--line-strong); + border-radius: 9px; + background: var(--panel); + color: var(--text); + font: inherit; +} +.group-field textarea { resize: vertical; } +.group-field input::placeholder, .group-field textarea::placeholder { color: var(--muted); } +.group-field :focus-visible { outline: 2px solid var(--focus); outline-offset: 0; } +.group-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; } +.slot-hint { margin: -2px 0 4px; color: var(--muted); font-size: 12px; } +.slot.is-disabled { opacity: 0.55; cursor: default; } + +/* Connections */ +.conn-list { display: flex; flex-direction: column; gap: 8px; margin: 0; padding: 0; list-style: none; } +.conn-card { + display: flex; + gap: 12px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); +} +.conn-card-ok { border-color: color-mix(in srgb, var(--ok) 35%, transparent); } +.conn-group-avatar { background: var(--ok-soft); color: var(--ok); } +.conn-body { flex: 1; min-width: 0; } +.conn-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; } +.conn-head h3 { margin: 0; font-size: 14.5px; font-weight: 600; overflow-wrap: anywhere; } +.conn-head .chip { font-size: 11px; padding: 1px 8px; } +.conn-when, .conn-message { display: flex; align-items: flex-start; gap: 6px; margin: 4px 0 0; color: var(--text-2); font-size: 13px; } +.conn-when svg, .conn-message svg { flex: none; margin-top: 3px; color: var(--muted); } +.conn-when time { font-size: 12.5px; } + +@media (max-width: 767px) { + .group-list, .suggest-list { grid-template-columns: minmax(0, 1fr); } + .group-card { padding: 12px; } + .group-dialog-body { padding: 14px; } + .group-dialog-actions .btn-primary { flex: 1; justify-content: center; } +} + +/* Hallway board */ +.board-form { + display: flex; + flex-direction: column; + gap: 10px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); +} +.board-count { margin: -6px 0 0; color: var(--muted); font-size: 11.5px; text-align: right; } +.board-tags { margin: 0; padding: 0; border: 0; min-width: 0; } +.board-tags legend { margin-bottom: 6px; padding: 0; color: var(--text-2); font-size: 12.5px; } +.board-tag { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border: 1px solid var(--line-strong); + border-radius: 999px; + color: var(--text-2); + font-size: 12.5px; + cursor: pointer; +} +.board-tag input { margin: 0; accent-color: var(--accent-fill); } +.board-tag.is-on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-ink); } +.board-tag:focus-within { outline: 2px solid var(--focus); outline-offset: 1px; } +.board-list { display: flex; flex-direction: column; gap: 8px; margin: 12px 0 0; padding: 0; list-style: none; } +.board-item { + padding: 10px 14px; + border: 1px solid var(--line); + border-left: 3px solid var(--line-strong); + border-radius: 12px; + background: var(--panel); +} +.board-item.is-for-you { border-left-color: var(--accent); background: color-mix(in srgb, var(--accent-soft) 45%, var(--panel)); } +.board-group { background: var(--bg-2); } +.board-item-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; } +.board-author { color: var(--text-2); font-size: 12.5px; font-weight: 600; } +.board-group-icon { color: var(--muted); } +.board-for-you { padding: 1px 8px; font-size: 11px; } +.board-text { margin: 4px 0 0; overflow-wrap: anywhere; } +.board-meta { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 4px 0 0; color: var(--muted); font-size: 12px; } +.board-meta span { display: inline-flex; align-items: center; gap: 4px; } +.board-meta time { font-size: 11.5px; } +.board-item-tags { margin-top: 6px; } +.board-item-tags .chip { padding: 1px 8px; font-size: 11px; } +.board-tag-plain { background: var(--panel-2); color: var(--text-2); }