From c838f31ca8f3f8df44606f1d9ac870974aa2d4a1 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Tue, 10 Nov 2026 13:28:10 -0500 Subject: [PATCH 1/8] Open conferences from a Conference Committees menu, with the hero on its own page Readers come to conference committees to give input, so the navbar's Conference Committees entry is now a menu, like About and Learn: what a conference committee is, the Conference Explorer, then under "Taking input" every conference still sitting, in the rail's order. It opens on a click on desktop and on a phone alike. The list is read in the browser once per visit rather than added to every page's props. /conferences is now the hero alone, with a link to the conference the landing used to open on and one to the explorer; a court with no conferences keeps the hero with only the explorer link, where it used to redirect. Conference pages lose the hero above them, and with it the scroll snapping and landing logic that existed only to move between the two. The hero's button now reads "Browse the committees". Unlike the brief, a click on the entry opens the menu rather than the hero; the hero is the menu's first item, to match About and Learn. Closes hyphacoop/maple#132 Verified: yarn check-types, yarn lint (nothing in changed files), yarn check-formatting (only local ignored files flagged), yarn test:website (43 suites) and yarn test (24 suites) pass. Against yarn dev on the dev backend, before the final cleanup: the menu opens on click at 1280px and 390px, items in order with divider and header, Escape closes it, a conference link navigates and closes it, and it lists the 11 appointed conferences the backend holds; /conferences shows the hero alone. Not verified: the menu after the final cleanup moved its dropdown shell into Navbar.tsx; conference pages in a browser (no hero, section jumps under the navbar); keyboard navigation through the menu items; the hero link when the court has no conferences, outside unit tests. Co-Authored-By: Claude Opus 5.5 --- components/Navbar.tsx | 21 ++- components/NavbarComponents.test.tsx | 71 ++++++++ components/NavbarComponents.tsx | 57 ++++--- .../conference/ConferenceDetails.test.tsx | 66 +------- components/conference/ConferenceDetails.tsx | 25 +-- components/conference/ConferenceHero.test.tsx | 44 +++++ components/conference/ConferenceHero.tsx | 59 +++---- components/conference/hooks.ts | 154 +++--------------- components/conference/load.test.ts | 23 ++- components/conference/load.ts | 29 ++-- components/conference/navbar.ts | 29 ---- components/conference/types.ts | 14 +- components/db/conferences.ts | 8 + pages/conferences/index.tsx | 29 ++-- public/locales/en/common.json | 3 + public/locales/en/conferences.json | 2 +- 16 files changed, 292 insertions(+), 342 deletions(-) create mode 100644 components/NavbarComponents.test.tsx create mode 100644 components/conference/ConferenceHero.test.tsx diff --git a/components/Navbar.tsx b/components/Navbar.tsx index 96d194c11..11836294b 100644 --- a/components/Navbar.tsx +++ b/components/Navbar.tsx @@ -10,7 +10,7 @@ import { flags } from "./featureFlags" import { Avatar, NavbarLinkBallotQuestions, - NavbarLinkConferences, + NavbarConferenceItems, DESKTOP_NAV_ITEM_CLASS, NavbarLinkAI, NavbarLinkBills, @@ -79,7 +79,12 @@ const MobileNav: React.FC> = () => { ) : null} {flags().conferences ? ( - + + + ) : null} {flags().hearingsAndTranscriptions ? ( @@ -233,7 +238,17 @@ const DesktopNav: React.FC> = () => { {flags().conferences ? (
- + + + {t("navigation.conferences")} + + + + +
) : null} diff --git a/components/NavbarComponents.test.tsx b/components/NavbarComponents.test.tsx new file mode 100644 index 000000000..e82eed973 --- /dev/null +++ b/components/NavbarComponents.test.tsx @@ -0,0 +1,71 @@ +import "@testing-library/jest-dom" +import { act, render, screen } from "@testing-library/react" +import { Dropdown } from "./bootstrap" +import { NavbarConferenceItems } from "./NavbarComponents" + +jest.mock("usehooks-ts", () => ({ useMediaQuery: () => false })) +jest.mock("next-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) +jest.mock("next/router", () => ({ + useRouter: () => ({ pathname: "/bills", asPath: "/bills" }) +})) +jest.mock("./auth", () => ({ useAuth: () => ({}) })) +jest.mock("./db", () => ({ useProfile: () => ({}) })) +// Its module pulls in an ESM-only package. +jest.mock("./shared/CommonComponents", () => ({ BetaTag: () => null })) +let mockConferences = [ + { id: "data-privacy", court: 194, title: "An Act", name: "Data Privacy" }, + { id: "hemp", court: 194, title: "An Act relative to hemp" } +] +jest.mock("./conference/hooks", () => ({ + useAppointedConferences: () => mockConferences +})) + +/** The items in an open menu, as the navbar shows them, once Popper has + * placed it. */ +const renderMenu = async () => { + render( + + + + + + ) + await act(async () => {}) +} + +const shownLinks = () => + screen.getAllByRole("link").map(a => [a.textContent, a.getAttribute("href")]) + +describe("NavbarConferenceItems", () => { + it("leads with what a conference committee is and the explorer, then the conferences taking input", async () => { + await renderMenu() + expect(shownLinks()).toEqual([ + ["navigation.conferencesOverview", "/conferences"], + ["navigation.conferenceExplorer", "/conferences/explorer"], + ["Data Privacy", "/conferences/194/data-privacy"], + ["An Act relative to hemp", "/conferences/194/hemp"] + ]) + // The overview set apart from the list, and the list named. + expect(screen.getByRole("separator")).toBeInTheDocument() + expect( + screen.getByText("navigation.conferencesTakingInput") + ).toBeInTheDocument() + }) + + it("still leads to the overview and the explorer where none is taking input", async () => { + const all = mockConferences + mockConferences = [] + await renderMenu() + expect(shownLinks()).toEqual([ + ["navigation.conferencesOverview", "/conferences"], + ["navigation.conferenceExplorer", "/conferences/explorer"] + ]) + expect(screen.queryByRole("separator")).not.toBeInTheDocument() + expect( + screen.queryByText("navigation.conferencesTakingInput") + ).not.toBeInTheDocument() + mockConferences = all + }) +}) diff --git a/components/NavbarComponents.tsx b/components/NavbarComponents.tsx index 9cb990d89..cdd23e418 100644 --- a/components/NavbarComponents.tsx +++ b/components/NavbarComponents.tsx @@ -3,8 +3,10 @@ import { useRouter } from "next/router" import Image from "react-bootstrap/Image" import { useMediaQuery } from "usehooks-ts" import { useAuth } from "./auth" -import { Nav, NavDropdown } from "./bootstrap" +import { Dropdown, Nav, NavDropdown } from "./bootstrap" +import { conferenceName } from "./conference/types" import { useProfile } from "./db" +import { useAppointedConferences } from "./conference/hooks" import { NavLink } from "./Navlink" import { maple, Wrap } from "./links" import { BetaTag } from "./shared/CommonComponents" @@ -186,29 +188,42 @@ export const NavbarLinkBallotQuestions: React.FC< ) } -export const NavbarLinkConferences: React.FC< - React.PropsWithChildren<{ - handleClick?: any - other?: any - }> -> = ({ handleClick, other }) => { +/** + * The Conference Committees menu's items, which the navbar puts in a menu as + * it does About's and Learn's: what a conference committee is and the + * explorer, then the conferences taking input. + */ +export const NavbarConferenceItems: React.FC<{ handleClick?: any }> = ({ + handleClick +}) => { const isMobile = useMediaQuery("(max-width: 768px)") const { t } = useTranslation(["common", "auth"]) - const { pathname } = useRouter() + const conferences = useAppointedConferences() + const link = (href: string, label: string) => ( + + {label} + + ) return ( - - - {t("navigation.conferences")} - - + <> + {link(maple.conferences(), t("navigation.conferencesOverview"))} + {link(maple.conferenceExplorer(), t("navigation.conferenceExplorer"))} + {conferences.length > 0 && ( + <> + {/* The overview set apart, and the list said for what it is. */} + + + {t("navigation.conferencesTakingInput")} + + {conferences.map(c => link(maple.conference(c), conferenceName(c)))} + + )} + ) } diff --git a/components/conference/ConferenceDetails.test.tsx b/components/conference/ConferenceDetails.test.tsx index 2827f41f6..ffd62e1bb 100644 --- a/components/conference/ConferenceDetails.test.tsx +++ b/components/conference/ConferenceDetails.test.tsx @@ -1,6 +1,5 @@ import "@testing-library/jest-dom" import { act, fireEvent, render, screen, within } from "@testing-library/react" -import Router from "next/router" import { ConferenceDetails } from "./ConferenceDetails" import type { ConferencePageProps } from "./types" @@ -40,13 +39,8 @@ let asPath = "/conferences/194/data-privacy" let mockQuery: Record = {} const mockReplace = jest.fn(async () => true) jest.mock("next/router", () => ({ - __esModule: true, - default: { events: { on: jest.fn() } }, useRouter: () => ({ asPath, query: mockQuery, replace: mockReplace }) })) -/** Next starting a change of address, as the hooks hear it. */ -const routeChangeStart = (url: string) => - jest.mocked(Router.events.on).mock.calls[0][1](url) jest.mock("usehooks-ts", () => ({ useMediaQuery: () => false })) // react-markdown ships ESM only. This reads one link, as the gist writes it. @@ -309,8 +303,6 @@ describe("ConferenceDetails", () => { beforeEach(() => { asPath = "/conferences/194/data-privacy" - // Arriving by a link, unless a test says otherwise. - routeChangeStart("/conferences/194/elsewhere") window.scrollTo = jest.fn() }) @@ -321,66 +313,14 @@ describe("ConferenceDetails", () => { mockReplace.mockClear() mockDispatch.mockClear() window.scrollTo = scrollTo - Object.defineProperty(window, "scrollY", { value: 0, configurable: true }) - }) - - it("leaves a reader Back brought, even to the top, then re-lands them on a new address", () => { - routeChangeStart(location.pathname) - const { rerender } = render() - expect(window.scrollTo).not.toHaveBeenCalled() - - asPath = "/conferences/194/other" - rerender() - expect(window.scrollTo).toHaveBeenCalledWith( - expect.objectContaining({ behavior: "auto" }) - ) }) - it("lands a reader a link brought, scrolled or not, at the conference", () => { - // A rail click from the landing keeps the landing's scroll; Next starts - // the change before the address moves. - Object.defineProperty(window, "scrollY", { value: 900, configurable: true }) - routeChangeStart("/conferences/194/data-privacy") + it("has one h1, the conference's, and no hero above it", () => { render() - expect(window.scrollTo).toHaveBeenCalledWith( - expect.objectContaining({ behavior: "auto" }) - ) - // Back has moved it already. - jest.mocked(window.scrollTo).mockClear() - routeChangeStart(location.pathname) - render() - expect(window.scrollTo).not.toHaveBeenCalled() - }) - - it("has one h1: the conference's, or the hero's on the landing", () => { - const { unmount } = render() - expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1) - unmount() - render() expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1) - }) - - it("opens a conference's address at the conference, under the hero", () => { - render() expect( - screen.getByRole("heading", { name: "hero.steps.0.h" }) - ).toBeInTheDocument() - expect(window.scrollTo).toHaveBeenCalledWith( - expect.objectContaining({ top: 0, behavior: "auto" }) - ) - }) - - it("opens the landing on the hero and links to the explorer", () => { - render() - expect(screen.getAllByRole("listitem").length).toBeGreaterThanOrEqual(5) - expect(screen.getByRole("link", { name: "explorer" })).toHaveAttribute( - "href", - "/conferences/explorer" - ) - fireEvent.click(screen.getByRole("button", { name: /hero.see/ })) - expect(window.scrollTo).toHaveBeenLastCalledWith( - expect.objectContaining({ behavior: "smooth" }) - ) + screen.queryByRole("heading", { name: "hero.steps.0.h" }) + ).not.toBeInTheDocument() }) it("names the six, the chairs, the bills and the hearing", () => { diff --git a/components/conference/ConferenceDetails.tsx b/components/conference/ConferenceDetails.tsx index 39dda51c9..a12cfff96 100644 --- a/components/conference/ConferenceDetails.tsx +++ b/components/conference/ConferenceDetails.tsx @@ -15,7 +15,6 @@ import styled from "styled-components" import { ConferenceByline } from "./ConferenceByline" import { ConferenceCommittee } from "./ConferenceCommittee" import { ConferenceDifferences } from "./ConferenceDifferences" -import { ConferenceHero } from "./ConferenceHero" import { ConferencePicker } from "./ConferencePicker" import { ConferenceRail } from "./ConferenceRail" import { ConferenceResolution, OutcomeFilter } from "./ConferenceResolution" @@ -31,7 +30,7 @@ import { } from "../db" import { useAppDispatch } from "../hooks" import { maple, siteUrl } from "../links" -import { useConferenceTop, usePinnedNavbar } from "./hooks" +import { usePinnedNavbar } from "./hooks" import { InputContext } from "./input/context" import { CosignForm, CosignStep } from "./input/CosignForm" import { CosignLetter } from "./input/CosignLetter" @@ -50,8 +49,6 @@ import { conferenceName, ConferencePageProps, ConferenceSummary } from "./types" const Page = styled(PageColumn)` display: flex; gap: 1.5rem; - scroll-snap-align: start; - scroll-snap-stop: always; @media (min-width: 992px) { max-width: 1320px; @@ -157,13 +154,10 @@ const RESOLVED_LABELS = { decided: "tab_resolved" } /** * One conference: who is deciding, and the two texts they are deciding - * between, under a hero on what a conference committee is. The list of every - * conference runs down the left from md up; below that the title opens it. - * The landing alone opens on the hero (`openOnHero`). + * between. The list of every conference runs down the left from md up; below + * that the title opens it. */ -export function ConferenceDetails( - props: ConferencePageProps & { openOnHero?: boolean } -) { +export function ConferenceDetails(props: ConferencePageProps) { // Keyed so moving to another conference starts clean: the panel's draft hook // is fixed to the conference it first mounted on, and would keep filing on // the old one. @@ -178,10 +172,8 @@ function Details({ gist, differences, similarities, - testimonyCount, - openOnHero = false -}: ConferencePageProps & { openOnHero?: boolean }) { - const { top, hero, toConference } = useConferenceTop(openOnHero) + testimonyCount +}: ConferencePageProps) { const { t } = useTranslation("conferences") const { user, authenticated, loading: authLoading, authFlowStep } = useAuth() const dispatch = useAppDispatch() @@ -433,8 +425,7 @@ function Details({ { "--shift": `${open && !filled ? width : 0}px` } as CSSProperties } > - - + - {subject} + {subject} {taking && ( )} diff --git a/components/conference/ConferenceHero.test.tsx b/components/conference/ConferenceHero.test.tsx new file mode 100644 index 000000000..64605833e --- /dev/null +++ b/components/conference/ConferenceHero.test.tsx @@ -0,0 +1,44 @@ +import "@testing-library/jest-dom" +import { render, screen } from "@testing-library/react" +import { ConferenceHero } from "./ConferenceHero" + +const steps = Array.from({ length: 5 }, (_, i) => ({ + h: `step ${i + 1}`, + p: `about step ${i + 1}` +})) + +jest.mock("next-i18next", () => ({ + useTranslation: () => ({ + t: (key: string, opts?: { returnObjects?: boolean }) => + key === "hero.steps" && opts?.returnObjects ? steps : key + }), + Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey +})) + +describe("ConferenceHero", () => { + it("is the page's one h1, with the five steps under it", () => { + render() + expect(screen.getAllByRole("heading", { level: 1 })).toHaveLength(1) + expect(screen.getAllByRole("heading", { level: 2 })).toHaveLength(5) + }) + + it("leads on to the landing conference and the explorer", () => { + render() + expect(screen.getByRole("link", { name: /hero.see/ })).toHaveAttribute( + "href", + "/conferences/194/data-privacy" + ) + expect(screen.getByRole("link", { name: /explorer/ })).toHaveAttribute( + "href", + "/conferences/explorer" + ) + }) + + it("leads only to the explorer in a court with no conferences", () => { + render() + expect( + screen.queryByRole("link", { name: /hero.see/ }) + ).not.toBeInTheDocument() + expect(screen.getByRole("link", { name: /explorer/ })).toBeInTheDocument() + }) +}) diff --git a/components/conference/ConferenceHero.tsx b/components/conference/ConferenceHero.tsx index c5fc91f8d..cf64ab610 100644 --- a/components/conference/ConferenceHero.tsx +++ b/components/conference/ConferenceHero.tsx @@ -1,28 +1,21 @@ -import { forwardRef } from "react" import { Trans, useTranslation } from "next-i18next" import styled from "styled-components" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" -import { faArrowDown, faArrowRight } from "@fortawesome/free-solid-svg-icons" +import { faArrowRight } from "@fortawesome/free-solid-svg-icons" import { External, Internal, maple } from "../links" import { PageColumn } from "./styles" +import { ConferenceLanding } from "./types" const JOINT_RULES = "https://malegislature.gov/Laws/Rules/Joint" const MAPLE_PROCESS = "https://www.mapletestimony.org/learn/legislative-process" -/** - * A screen of its own above the conference, so the conference begins below - * the fold and the button is what says it is there. One of the page's two - * resting places for scroll snapping, the conference being the other. - */ +/** A screen under the navbar, with the block centred down it. */ const Section = styled(PageColumn)` - min-height: calc(100lvh - var(--conference-nav, var(--maple-navbar-height))); - scroll-margin-top: var(--conference-nav, 0px); + min-height: calc(100lvh - var(--maple-navbar-height)); padding-top: 2rem; padding-bottom: 2rem; display: flex; flex-direction: column; - scroll-snap-align: start; - scroll-snap-stop: always; .block { margin: auto 0; @@ -109,8 +102,7 @@ const StepList = styled.div` min-width: 0; padding-top: 5px; } - h2, - h3 { + h2 { margin: 0; font-size: 1rem; font-weight: 600; @@ -147,7 +139,7 @@ const StepList = styled.div` } ` -const Button = styled.button` +const SeeLink = styled(Internal)` display: inline-flex; align-items: center; gap: 0.5rem; @@ -158,9 +150,11 @@ const Button = styled.button` font-weight: 600; background: var(--maple-brand-primary); color: #fff; + text-decoration: none; &:hover { background: var(--maple-brand-primary-strong); + color: #fff; } ` @@ -173,27 +167,24 @@ const ExplorerLink = styled(Internal)` ` /** - * What a conference committee is and the five steps it goes through, above - * whichever conference is open. `onSee` takes the reader down to the - * conference; the explorer is reached from here. + * What a conference committee is and the five steps it goes through: the + * Conference Committees page. It leads on to a conference (`landing`, where + * the court has one) and to the explorer. */ -export const ConferenceHero = forwardRef< - HTMLElement, - { onSee: () => void; landing?: boolean } ->(function ConferenceHero({ onSee, landing = false }, ref) { +export function ConferenceHero({ + landing +}: { + landing: ConferenceLanding | null +}) { const { t } = useTranslation("conferences") - const Heading = landing ? "h1" : "h2" - // A level under the hero's own heading, whichever that is. - const Step = landing ? "h2" : "h3" const steps = t("hero.steps", { returnObjects: true }) as { h: string p: string }[] return ( -
+
- {/* Conference addresses have their own h1. */} - {t("index_title")} +

{t("index_title")}

{t("hero.lead")}

    @@ -202,7 +193,7 @@ export const ConferenceHero = forwardRef< {i < steps.length - 1 && } {i + 1}
    - {step.h} +

    {step.h}

    {step.p}

    @@ -220,10 +211,12 @@ export const ConferenceHero = forwardRef< />

    - + {landing && ( + + {t("hero.see")} + + + )} {t("explorer")} @@ -232,4 +225,4 @@ export const ConferenceHero = forwardRef<
) -}) +} diff --git a/components/conference/hooks.ts b/components/conference/hooks.ts index d260aef5d..2755f36a7 100644 --- a/components/conference/hooks.ts +++ b/components/conference/hooks.ts @@ -1,26 +1,17 @@ -import Router, { useRouter } from "next/router" import { RefObject, useCallback, useLayoutEffect, useMemo, - useRef, useState } from "react" +import { useAsync } from "react-async-hook" import { useMediaQuery } from "usehooks-ts" +import { currentGeneralCourt } from "functions/src/shared" import { useProfile } from "../db" -import { jumping, navbarBottom } from "./navbar" - -/** Whether the page arriving is one Back or Forward reached within the app, - * where the browser puts the reader back. Those have moved the address by the - * time Next starts the change; a link, such as a rail click from a scrolled - * landing, moves it after. A reload is not one: Layout renders nothing until - * the client mounts, so the browser has nothing to restore against. */ -let returning = false -if (typeof window !== "undefined") - Router.events.on("routeChangeStart", (url: string) => { - returning = new URL(url, location.href).href === location.href - }) +import { Conference, listAppointedConferences } from "../db/conferences" +import { byName } from "./types" +import { navbarBottom } from "./navbar" /** * What the pointer is over, and a setter that ignores it on a coarse pointer: @@ -50,123 +41,6 @@ export function useMyLegislators() { ) } -/** How far into the conference the window still snaps, in px: enough that a - * flick coming up through it is already being snapped at its top. */ -const SNAP_REACH = 120 - -/** Where `el` starts in the document, in px. */ -const topOf = (el: HTMLElement | null) => - el ? Math.max(0, el.getBoundingClientRect().top + window.scrollY) : 0 - -/** - * Where a conference page rests: on the whole hero, or on the conference from - * its top. Returns the ref for the conference's column and the scroll that - * puts the reader at its top. - * - * The landing opens on the hero and every other address on the conference, - * on each change of address, since a rail click is a client navigation that - * Next would otherwise scroll to the hero. The browser's own mandatory snap - * keeps the reader off the stretch where both would share the screen; it is - * on only near the top, because a snapping window eases every scroll further - * down too. - */ -export function useConferenceTop(openOnHero: boolean) { - // A change to the query alone, such as the page letting go of a link's - // `?cosign`, leaves the reader where they are. - const path = useRouter().asPath.split(/[?#]/)[0] - const top = useRef(null) - const mounted = useRef(false) - const hero = useRef(null) - const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)") - - const toConference = useCallback( - () => - window.scrollTo({ - top: topOf(top.current), - behavior: reduceMotion ? "auto" : "smooth" - }), - [reduceMotion] - ) - - // The site's header scrolls away above the hero. Resting on the hero means - // resting at the document's top with the header showing, so the hero's snap - // point and height are measured from where it starts. - // - // Where the conference starts is measured here, not on each scroll event, - // and again whenever the page's size changes: the header can change height - // without a resize, from a webfont arriving or the nav items changing with - // sign-in. - useLayoutEffect(() => { - const root = document.documentElement - let offset = -1 - let reach = 0 - const sync = () => { - // A jump from near the top is on its way further down. - if (jumping()) return - const want = window.scrollY <= reach ? "y mandatory" : "" - if (root.style.scrollSnapType !== want) root.style.scrollSnapType = want - } - const measure = () => { - if (!hero.current) return - const next = topOf(hero.current) - if (next !== offset) { - offset = next - root.style.setProperty("--conference-nav", `${offset}px`) - } - reach = topOf(top.current) + SNAP_REACH - sync() - } - measure() - const observer = - typeof ResizeObserver === "undefined" - ? undefined - : new ResizeObserver(measure) - // The hero's own height is where the conference starts: it follows the - // window's height and its text's wrapping. - if (hero.current) observer?.observe(hero.current) - // Whatever sits above the hero moves it when it changes height, however - // far up: the siblings before it and before each of its ancestors. The - // body is no use, being a fixed-height box. - for (let el = hero.current; el && el !== document.body; ) { - if (el.previousElementSibling) - observer?.observe(el.previousElementSibling) - el = el.parentElement - } - window.addEventListener("scroll", sync, { passive: true }) - return () => { - observer?.disconnect() - window.removeEventListener("scroll", sync) - root.style.removeProperty("--conference-nav") - root.style.scrollSnapType = "" - } - }, []) - - useLayoutEffect(() => { - // On arriving by Back the browser has put the reader back, at the top - // too: leave them there. Any other arrival, or a later change of address, - // is a click. - const restored = !mounted.current && returning - mounted.current = true - if (location.hash || restored) return - const start = openOnHero ? 0 : topOf(top.current) - window.scrollTo({ top: start, behavior: "auto" }) - if (openOnHero) return - // A font arriving after the jump can resize the hero; put the reader - // back unless they have scrolled since. - let stale = false - document.fonts?.ready.then(() => { - // A jump begun meanwhile, to a linked card, has not moved them yet. - if (stale || jumping() || Math.abs(window.scrollY - start) > 1) return - window.scrollTo({ top: topOf(top.current), behavior: "auto" }) - }) - return () => { - stale = true - } - }, [path, openOnHero]) - - return { top, hero, toConference } -} - /** * Publishes where the site navbar's bottom edge is on `scope` as * --maple-navbar-height, so what pins under it pins flush, and follows it as @@ -216,3 +90,21 @@ export function usePinnedNavbar(scope: RefObject) { } }, [scope]) } + +/** Read once per visit: every page's navbar asks for the same list. */ +let appointed: Promise | undefined +const loadAppointed = () => + (appointed ??= listAppointedConferences(currentGeneralCourt) + // As the rail sorts them: all of these are appointed, so by name. + .then(all => all.sort(byName)) + .catch(() => { + // A failed read leaves the menu without them; try again next page. + appointed = undefined + return [] + })) + +/** The current court's conferences taking input, for the navbar's menu. + * Empty while loading, and where there are none or the read fails. */ +export function useAppointedConferences(): Conference[] { + return useAsync(loadAppointed, []).result ?? [] +} diff --git a/components/conference/load.test.ts b/components/conference/load.test.ts index 5679667ae..f2ca7c07e 100644 --- a/components/conference/load.test.ts +++ b/components/conference/load.test.ts @@ -1,11 +1,7 @@ import { currentGeneralCourt } from "functions/src/shared" import { Conference, listConferences } from "../db/conferences" import { getMember, getMemberSearchIndex } from "../db/members" -import { - loadConferenceIndex, - loadConferencePage, - loadLandingPage -} from "./load" +import { loadConferenceIndex, loadConferencePage, loadLanding } from "./load" jest.mock("../db/conferences") jest.mock("../db/events", () => ({ getEventSummary: jest.fn() })) @@ -183,7 +179,7 @@ describe("coverage", () => { expect(page?.conference.reportBillId).toBeNull() }) - it("opens the landing on the first covered conference", async () => { + it("points the landing at the first covered conference", async () => { jest .mocked(listConferences) .mockResolvedValue([ @@ -191,13 +187,16 @@ describe("coverage", () => { conference("b", []) ]) - const page = await loadLandingPage(currentGeneralCourt) + expect(await loadLanding(currentGeneralCourt)).toEqual({ + court: currentGeneralCourt, + id: "b" + }) + }) - expect(page?.conference.id).toBe("b") - expect(page?.conferences.map(c => [c.id, c.covered])).toEqual([ - ["a", false], - ["b", true] - ]) + it("points the landing nowhere in a court with no conferences", async () => { + jest.mocked(listConferences).mockResolvedValue([]) + + expect(await loadLanding(currentGeneralCourt)).toBeNull() }) it("still opens an uncovered conference by its address", async () => { diff --git a/components/conference/load.ts b/components/conference/load.ts index 57440a392..a6bd84952 100644 --- a/components/conference/load.ts +++ b/components/conference/load.ts @@ -19,6 +19,7 @@ import { byActivity, ConfereeView, ConferenceIndexProps, + ConferenceLanding, ConferencePageProps, ConferenceSummary, HearingView @@ -39,6 +40,9 @@ const summarize = (c: Conference): ConferenceSummary => ({ reportBillId: c.reportBillId ?? null }) +/** Every conference as the rail lists them: active first, then by name. */ +const railOf = (all: Conference[]) => all.map(summarize).sort(byActivity) + /** The member's cell on the map: their district id, or null where the map has * no such seat. */ const seatFor = (branch: Branch, district: string) => { @@ -116,25 +120,24 @@ export async function loadConferencePage( return pageFor(court, await listConferences(court), id) } -/** The page for the first covered conference in the rail's order, which the - * landing opens on; null where the court has none. */ -export async function loadLandingPage( +/** Where the landing's button goes: the first covered conference in the + * rail's order, else the rail's first; null where the court has none. */ +export async function loadLanding( court: number -): Promise { - return pageFor(court, await listConferences(court)) +): Promise { + const rail = railOf(await listConferences(court)) + const landing = rail.find(c => c.covered) ?? rail[0] + return landing ? { court: landing.court, id: landing.id } : null } -/** The page for conference `id` among `all`, or for the rail's first where - * there is no `id`. */ +/** The page for conference `id` among `all`. */ async function pageFor( court: number, all: Conference[], - id?: string + id: string ): Promise { - const rail = all.map(summarize).sort(byActivity) - const summary = id - ? rail.find(c => c.id === id) - : rail.find(c => c.covered) ?? rail[0] + const rail = railOf(all) + const summary = rail.find(c => c.id === id) const conference = all.find(c => c.id === summary?.id) if (!summary || !conference) return null const [members, hearings] = await Promise.all([ @@ -193,7 +196,7 @@ export async function loadConferenceIndex( ? membersFromIndex(index) : await membersByRead(court, confereeCodes(all)) return { - conferences: all.map(summarize).sort(byActivity), + conferences: railOf(all), conferees: resolveConferees(all, members) } } diff --git a/components/conference/navbar.ts b/components/conference/navbar.ts index 925128776..081450dab 100644 --- a/components/conference/navbar.ts +++ b/components/conference/navbar.ts @@ -23,12 +23,6 @@ const bottomAt = (y: number, { height, letsGo }: ReturnType) => * holds, less as it goes, none once it has gone. */ export const navbarBottom = () => bottomAt(window.scrollY, navbar()) -/** Ends the jump under way, if one is. */ -let endJump: (() => void) | undefined - -/** Whether a jump is on its way, which the hero's snap waits out. */ -export const jumping = () => endJump !== undefined - /** * Scrolls `el` to its scroll margin under the navbar, where the navbar will be * on arrival. The browser's own jump takes the margin as it is before the @@ -44,29 +38,6 @@ export function jumpTo(el: HTMLElement) { // Short of where the navbar lets go it is there on arrival, taking its // height; past it, it is gone. Partly gone has no resting place to aim at. const to = top <= bar.letsGo ? top - bar.height : top - // The hero's snap, on near the conference's top, would snap the landing - // too, holding a jump to a section further down short of it. Off for the - // jump, and held off until it arrives: the hero turns it back on near the - // top, which cuts a smooth jump from there short on its first frame. - const root = document.documentElement - root.style.scrollSnapType = "" - endJump?.() - // A scroll already running when the jump began ends too; only arriving - // ends this one. The page may be too short to reach `to`. - const arrived = () => { - const most = root.scrollHeight - window.innerHeight - if (Math.abs(window.scrollY - Math.min(to, most)) < 2) end() - } - // A jump to where the reader already is, or one they take over, never - // arrives. - const timer = setTimeout(() => end(), 2000) - const end = () => { - window.removeEventListener("scrollend", arrived) - clearTimeout(timer) - endJump = undefined - } - endJump = end - window.addEventListener("scrollend", arrived) window.scrollTo({ top: to, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches diff --git a/components/conference/types.ts b/components/conference/types.ts index 685e53b0f..a973eede5 100644 --- a/components/conference/types.ts +++ b/components/conference/types.ts @@ -88,10 +88,18 @@ export type ConferenceIndexProps = { } /** The short name where there is one, else the act title. */ -export const conferenceName = (c: { name?: string | null; title: string }) => - c.name?.trim() || c.title.trim() +export const conferenceName = (c: Named) => c.name?.trim() || c.title.trim() + +type Named = { name?: string | null; title: string } + +/** Alphabetical by the name a conference goes by. */ +export const byName = (a: Named, b: Named) => + conferenceName(a).localeCompare(conferenceName(b)) /** The ordering the rail uses: still sitting first, then finished. */ export const byActivity = (a: ConferenceSummary, b: ConferenceSummary) => Number(b.status === "appointed") - Number(a.status === "appointed") || - conferenceName(a).localeCompare(conferenceName(b)) + byName(a, b) + +/** The conference the landing's button opens. */ +export type ConferenceLanding = Pick diff --git a/components/db/conferences.ts b/components/db/conferences.ts index 91613de59..4cae059e3 100644 --- a/components/db/conferences.ts +++ b/components/db/conferences.ts @@ -21,6 +21,14 @@ export async function listConferences(court: number) { return snap.docs.map(d => d.data() as Conference) } +/** The conferences still sitting, unordered. */ +export async function listAppointedConferences(court: number) { + const snap = await getDocs( + query(conferences(court), where("status", "==", "appointed")) + ) + return snap.docs.map(d => d.data() as Conference) +} + export async function getConference(court: number, id: string) { const snap = await getDoc(doc(conferences(court), id)) return snap.data() as Conference | undefined diff --git a/pages/conferences/index.tsx b/pages/conferences/index.tsx index 227d88271..2b4dc684d 100644 --- a/pages/conferences/index.tsx +++ b/pages/conferences/index.tsx @@ -2,18 +2,19 @@ import { GetServerSideProps } from "next" import { serverSideTranslations } from "next-i18next/serverSideTranslations" import { currentGeneralCourt } from "functions/src/shared" import { flags } from "components/featureFlags" -import { ConferenceDetails } from "components/conference/ConferenceDetails" -import { loadLandingPage } from "components/conference/load" -import { ConferencePageProps } from "components/conference/types" -import { maple } from "components/links" +import { ConferenceHero } from "components/conference/ConferenceHero" +import { loadLanding } from "components/conference/load" +import { ConferenceLanding } from "components/conference/types" import { createPage } from "../../components/page" -export default createPage({ +type Props = { landing: ConferenceLanding | null } + +export default createPage({ titleI18nKey: "titles.conferences", - Page: props => + Page: ({ landing }) => }) -export const getServerSideProps: GetServerSideProps = async ctx => { +export const getServerSideProps: GetServerSideProps = async ctx => { if (!flags().conferences) return { notFound: true } ctx.res.setHeader( "Cache-Control", @@ -21,16 +22,12 @@ export const getServerSideProps: GetServerSideProps = async ctx => { ) const locale = ctx.locale ?? ctx.defaultLocale ?? "en" - const [page, translations] = await Promise.all([ - loadLandingPage(currentGeneralCourt), + const [landing, translations] = await Promise.all([ + loadLanding(currentGeneralCourt), serverSideTranslations(locale, ["auth", "common", "footer", "conferences"]) ]) - // A court with no conferences yet has nothing to open on; the explorer says - // so, where a 404 would leave the navbar's link dead. - if (!page) - return { - redirect: { destination: maple.conferenceExplorer(), permanent: false } - } - return { props: { ...page, ...translations } } + // A court with no conferences yet still has the hero, with the explorer + // its only way on. + return { props: { landing, ...translations } } } diff --git a/public/locales/en/common.json b/public/locales/en/common.json index cabd121f0..d8ce11710 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -110,6 +110,9 @@ "ai": "How MAPLE Uses AI", "ballotQuestions": "Ballot Questions", "conferences": "Conference Committees", + "conferencesOverview": "What is a conference committee?", + "conferenceExplorer": "Conference Explorer", + "conferencesTakingInput": "Taking input", "bills": "Bills", "browseBills": "Browse Bills", "browseBallotQuestions": "Browse Ballot Questions", diff --git a/public/locales/en/conferences.json b/public/locales/en/conferences.json index eb4e69817..8e218d0de 100644 --- a/public/locales/en/conferences.json +++ b/public/locales/en/conferences.json @@ -71,7 +71,7 @@ } ], "sources": "From MAPLE’s <1>guide to the legislative process and the legislature’s <3>Joint Rules.", - "see": "See the committees" + "see": "Browse the committees" }, "bill_text": "Bill Text", "version": "Version", From c1a70bcc19277d7eef0d0363eeae46934d39a830 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Tue, 10 Nov 2026 16:36:51 -0500 Subject: [PATCH 2/8] Link to what a conference committee is from the conference headings, not the menu The Conference Committees menu now opens with the Conference Explorer and the conferences taking input. "What is a conference committee?" moves to the heading of the explorer and of every conference page, where a reader who lands on one without context can find it: at the right of the explorer's title, and over the "Share your input" button on a conference page, with the title level with the button. On a phone the link sits over the title (the picker there) and the button stays at the left under it. This replaces the menu's first item described in the previous commit. Verified: yarn check-types, yarn lint (nothing in changed files), prettier --check on the changed files, and yarn test:website (43 suites, 286 tests, with new tests for the link on both pages) pass. Against yarn dev on the dev backend at 1280px and 390px: the link's place on the explorer and on a conference page taking input, the menu without the entry, and the title band pinned under the navbar after scrolling. Not verified: a conference page not taking input, where the link sits level with the title, in a browser; opening the phone picker after it moved into the title row. Co-Authored-By: Claude Opus 5.5 --- components/NavbarComponents.test.tsx | 8 +-- components/NavbarComponents.tsx | 7 +-- .../conference/ConferenceDetails.test.tsx | 7 +++ components/conference/ConferenceDetails.tsx | 58 ++++++++++++++----- .../conference/ConferenceExplorer.test.tsx | 7 +++ components/conference/ConferenceExplorer.tsx | 25 +++++++- components/conference/OverviewLink.tsx | 20 +++++++ public/locales/en/common.json | 1 - public/locales/en/conferences.json | 1 + 9 files changed, 109 insertions(+), 25 deletions(-) create mode 100644 components/conference/OverviewLink.tsx diff --git a/components/NavbarComponents.test.tsx b/components/NavbarComponents.test.tsx index e82eed973..a3f8d34ae 100644 --- a/components/NavbarComponents.test.tsx +++ b/components/NavbarComponents.test.tsx @@ -39,27 +39,25 @@ const shownLinks = () => screen.getAllByRole("link").map(a => [a.textContent, a.getAttribute("href")]) describe("NavbarConferenceItems", () => { - it("leads with what a conference committee is and the explorer, then the conferences taking input", async () => { + it("leads with the explorer, then the conferences taking input", async () => { await renderMenu() expect(shownLinks()).toEqual([ - ["navigation.conferencesOverview", "/conferences"], ["navigation.conferenceExplorer", "/conferences/explorer"], ["Data Privacy", "/conferences/194/data-privacy"], ["An Act relative to hemp", "/conferences/194/hemp"] ]) - // The overview set apart from the list, and the list named. + // The explorer set apart from the list, and the list named. expect(screen.getByRole("separator")).toBeInTheDocument() expect( screen.getByText("navigation.conferencesTakingInput") ).toBeInTheDocument() }) - it("still leads to the overview and the explorer where none is taking input", async () => { + it("still leads to the explorer where none is taking input", async () => { const all = mockConferences mockConferences = [] await renderMenu() expect(shownLinks()).toEqual([ - ["navigation.conferencesOverview", "/conferences"], ["navigation.conferenceExplorer", "/conferences/explorer"] ]) expect(screen.queryByRole("separator")).not.toBeInTheDocument() diff --git a/components/NavbarComponents.tsx b/components/NavbarComponents.tsx index cdd23e418..f21573f99 100644 --- a/components/NavbarComponents.tsx +++ b/components/NavbarComponents.tsx @@ -190,8 +190,8 @@ export const NavbarLinkBallotQuestions: React.FC< /** * The Conference Committees menu's items, which the navbar puts in a menu as - * it does About's and Learn's: what a conference committee is and the - * explorer, then the conferences taking input. + * it does About's and Learn's: the explorer, then the conferences taking + * input. */ export const NavbarConferenceItems: React.FC<{ handleClick?: any }> = ({ handleClick @@ -211,11 +211,10 @@ export const NavbarConferenceItems: React.FC<{ handleClick?: any }> = ({ ) return ( <> - {link(maple.conferences(), t("navigation.conferencesOverview"))} {link(maple.conferenceExplorer(), t("navigation.conferenceExplorer"))} {conferences.length > 0 && ( <> - {/* The overview set apart, and the list said for what it is. */} + {/* The explorer set apart, and the list said for what it is. */} {t("navigation.conferencesTakingInput")} diff --git a/components/conference/ConferenceDetails.test.tsx b/components/conference/ConferenceDetails.test.tsx index ffd62e1bb..d867c2a5d 100644 --- a/components/conference/ConferenceDetails.test.tsx +++ b/components/conference/ConferenceDetails.test.tsx @@ -323,6 +323,13 @@ describe("ConferenceDetails", () => { ).not.toBeInTheDocument() }) + it("leads back to what a conference committee is", () => { + render() + expect( + screen.getByRole("link", { name: "what_is_conference_committee" }) + ).toHaveAttribute("href", "/conferences") + }) + it("names the six, the chairs, the bills and the hearing", () => { const { container } = render() diff --git a/components/conference/ConferenceDetails.tsx b/components/conference/ConferenceDetails.tsx index a12cfff96..082d6c629 100644 --- a/components/conference/ConferenceDetails.tsx +++ b/components/conference/ConferenceDetails.tsx @@ -42,6 +42,7 @@ import { useFollowedAuthors } from "./input/useFollowedAuthors" import { Close } from "./input/Close" import { X } from "./input/icons" import { jumpToSection } from "./navbar" +import { OverviewLink } from "./OverviewLink" import { Notice, PageColumn, Title } from "./styles" import { conferenceName, ConferencePageProps, ConferenceSummary } from "./types" @@ -69,12 +70,36 @@ const Shift = styled.div` } ` -/** The title, with the way to share input at its end. */ -const TitleRow = styled.div` - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 24px; +/** The title level with the share button, and the overview link over the + * button; level with the title itself where there is no button. Below md the + * picker stands for the title, with the link over it and the button under it + * at the left. */ +const TitleRow = styled.div<{ $taking: boolean }>` + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: ${({ $taking }) => + $taking ? `". link" "title share"` : `"title link"`}; + align-items: center; + gap: 0.5rem 24px; + + @media (max-width: 767.98px) { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: ${({ $taking }) => + $taking ? `"link" "picker" "share"` : `"link" "picker"`}; + } +` + +const Picker = styled.div` + grid-area: picker; +` + +const Share = styled.div` + grid-area: share; + justify-self: end; + + @media (max-width: 767.98px) { + justify-self: start; + } ` /** The header and the sections under it. */ @@ -86,6 +111,8 @@ const Main = styled.div` /** Below md the picker shows the name, so the heading is there for screen * readers alone. */ const PageTitle = styled(Title)` + grid-area: title; + @media (max-width: 767.98px) { position: absolute; width: 1px; @@ -433,16 +460,19 @@ function Details({ />
-
- -
- + + + + {subject} + {taking && ( - + + + )} {refusal && ( diff --git a/components/conference/ConferenceExplorer.test.tsx b/components/conference/ConferenceExplorer.test.tsx index f90b7572e..bb70468bb 100644 --- a/components/conference/ConferenceExplorer.test.tsx +++ b/components/conference/ConferenceExplorer.test.tsx @@ -153,6 +153,13 @@ const row = (container: HTMLElement, name: string) => within(table(container)).getByText(name).closest("tr")! describe("ConferenceExplorer", () => { + it("leads back to what a conference committee is", () => { + render() + expect( + screen.getByRole("link", { name: "what_is_conference_committee" }) + ).toHaveAttribute("href", "/conferences") + }) + it("lists every conference and lights every conferee's seat", () => { const { container } = render() expect(table(container).querySelectorAll("tbody tr")).toHaveLength(2) diff --git a/components/conference/ConferenceExplorer.tsx b/components/conference/ConferenceExplorer.tsx index 618ed1e7c..f08a67cd4 100644 --- a/components/conference/ConferenceExplorer.tsx +++ b/components/conference/ConferenceExplorer.tsx @@ -9,6 +9,7 @@ import { Chair, Conferees, ConfereeFace, yoursKey } from "./Conferees" import { ConferenceList, ConferenceTable } from "./ConferenceTable" import { DistrictMap, seatsOf } from "./DistrictMap" import { useHover, useMyLegislators } from "./hooks" +import { OverviewLink } from "./OverviewLink" import { Card, DottedInternal, Eyebrow, PageColumn, Title } from "./styles" import { CHAMBERS, @@ -37,6 +38,25 @@ const Page = styled(PageColumn)` padding-top: 1.25rem; ` +/** The title, with the overview link at its right; over it below md, as on + * the conference pages. */ +const Heading = styled.div` + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: "title link"; + align-items: center; + gap: 0.5rem 1.5rem; + + @media (max-width: 767.98px) { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: "link" "title"; + } +` + +const HeadingTitle = styled(Title)` + grid-area: title; +` + const Intro = styled.p` margin: 0.375rem 0 1rem; padding-left: 4px; @@ -296,7 +316,10 @@ export function ConferenceExplorer({ return ( - {t("index_title")} + + {t("index_title")} + + {t("index_intro")} diff --git a/components/conference/OverviewLink.tsx b/components/conference/OverviewLink.tsx new file mode 100644 index 000000000..103c8d467 --- /dev/null +++ b/components/conference/OverviewLink.tsx @@ -0,0 +1,20 @@ +import { useTranslation } from "next-i18next" +import styled from "styled-components" +import { maple } from "../links" +import { DottedInternal } from "./styles" + +/** Placed in its heading's `link` grid area, at the right. */ +const Link = styled(DottedInternal)` + grid-area: link; + justify-self: end; + font-size: 0.875rem; + white-space: nowrap; +` + +/** The link to what a conference committee is, beside a page's heading. */ +export function OverviewLink() { + const { t } = useTranslation("conferences") + return ( + {t("what_is_conference_committee")} + ) +} diff --git a/public/locales/en/common.json b/public/locales/en/common.json index d8ce11710..c21e04dda 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -110,7 +110,6 @@ "ai": "How MAPLE Uses AI", "ballotQuestions": "Ballot Questions", "conferences": "Conference Committees", - "conferencesOverview": "What is a conference committee?", "conferenceExplorer": "Conference Explorer", "conferencesTakingInput": "Taking input", "bills": "Bills", diff --git a/public/locales/en/conferences.json b/public/locales/en/conferences.json index 8e218d0de..b37ae579c 100644 --- a/public/locales/en/conferences.json +++ b/public/locales/en/conferences.json @@ -36,6 +36,7 @@ "chair_col": "Chair", "minority_col": "Minority", "explorer": "Conference Explorer", + "what_is_conference_committee": "What is a conference committee?", "explorer_empty": "Select a committee, map area, or toggle to highlight specific legislators.", "clear": "Clear", "clear_committee": "Clear this committee", From adeb05f1b42ed07acf0ad71d5abe102048b28255 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Wed, 11 Nov 2026 14:29:23 -0500 Subject: [PATCH 3/8] Fold conferences no longer taking input to the bottom of the rail, and hide them everywhere behind a flag The rail beside a conference listed every conference, so the ones whose report is filed, enacted or dissolved crowded the ones still taking input. They now sit in a "No longer taking input" group below the rest, in the rail and in the picker that stands in for it on phones. The group starts folded, opens on arriving at a conference in it so the one being read is never hidden, and otherwise stays as the reader left it while they move between conferences. A full page load folds it again. A new closedConferences flag decides whether those conferences exist on the site at all. Off, the loaders leave them out, so they are gone from the rail, the picker, the explorer and the landing, the bill banner and the hearing's link back name none, and their pages are not found. It is on in development and off in production and test. The flag is read on the server, so a ?closedConferences=enabled query cannot bring them back. "Still sitting" is now one shared predicate, used by the sort, the grouping, the flag and takesTestimony, so they cannot drift apart. Closes hyphacoop/maple#133 Verified: yarn check-types, yarn lint, yarn test:website and yarn test pass, with new loader tests for the flag on and off and rail and page-switching tests for the group. On yarn dev against the dev backend at 1280px and 390px: the group folded on an appointed conference and open on an enacted one, the reader's choice kept across conferences, and the phone picker staying open while the group is expanded. With the development default flipped off for the check: an enacted conference's page 404s, the explorer lists only appointed conferences, the landing opens an appointed one and a bill in an enacted conference has no banner. Not verified: a hearing page linked to a closed conference (jest only); a reportFiled or dissolved conference in a browser, since the dev backend has only enacted ones; which flag defaults the Vercel deployments use, since nothing in the repo sets NEXT_PUBLIC_ENV_NAME. Co-Authored-By: Claude Opus 5.5 --- .../ConferenceDetails.switching.test.tsx | 45 ++++++- components/conference/ConferenceDetails.tsx | 36 +++++- components/conference/ConferencePicker.tsx | 8 +- components/conference/ConferenceRail.test.tsx | 93 ++++++++++++++ components/conference/ConferenceRail.tsx | 119 +++++++++++++++--- components/conference/load.test.ts | 104 ++++++++++++++- components/conference/load.ts | 24 ++-- components/conference/types.ts | 4 +- components/featureFlags.ts | 14 ++- functions/src/shared/conferences.ts | 7 +- public/locales/en/conferences.json | 1 + 11 files changed, 413 insertions(+), 42 deletions(-) create mode 100644 components/conference/ConferenceRail.test.tsx diff --git a/components/conference/ConferenceDetails.switching.test.tsx b/components/conference/ConferenceDetails.switching.test.tsx index d4bdf848f..ab2972dd9 100644 --- a/components/conference/ConferenceDetails.switching.test.tsx +++ b/components/conference/ConferenceDetails.switching.test.tsx @@ -94,10 +94,14 @@ const phoneFree = summary( "H5366" ) const privacy = summary("data-privacy", "S2619", "H5479") +const enacted = { + ...summary("home-care", "S3183", "H4706"), + status: "enacted" as const +} const page = (conference: ConferencePageProps["conference"]) => ({ conference, - conferences: [phoneFree, privacy], + conferences: [phoneFree, privacy, enacted], conferees: [], hearings: [], gist: null, @@ -126,4 +130,43 @@ describe("moving between conferences", () => { // ...and the draft hook was mounted afresh, so it files on the new one. expect(mounted).toEqual([phoneFree.id, privacy.id]) }) + + describe("the group of conferences no longer taking input", () => { + // The rail's: the picker's menu holds a copy only once it is opened. + const folds = (c: HTMLElement) => + [...c.querySelectorAll("details")].map(d => d.open) + + it("starts folded on a conference still sitting", () => { + const { container } = render() + expect(folds(container)).toEqual([false]) + }) + + it("opens on arriving at a conference in it", () => { + const { container, rerender } = render( + + ) + rerender() + expect(folds(container)).toEqual([true]) + }) + + it("stays open on moving back to a conference still sitting", () => { + const { container, rerender } = render( + + ) + rerender() + expect(folds(container)).toEqual([true]) + }) + + it("stays as the reader left it between conferences still sitting", () => { + const { container, rerender } = render( + + ) + const details = container.querySelector("details")! + details.open = true + fireEvent(details, new Event("toggle")) + + rerender() + expect(folds(container)).toEqual([true]) + }) + }) }) diff --git a/components/conference/ConferenceDetails.tsx b/components/conference/ConferenceDetails.tsx index 082d6c629..772ed6edc 100644 --- a/components/conference/ConferenceDetails.tsx +++ b/components/conference/ConferenceDetails.tsx @@ -9,14 +9,18 @@ import { } from "react" import { useTranslation } from "next-i18next" import { useRouter } from "next/router" -import { hasReport, takesTestimony } from "../../functions/src/shared" +import { + hasReport, + isSitting, + takesTestimony +} from "../../functions/src/shared" import { uncosignable } from "../../functions/src/testimony/cosign" import styled from "styled-components" import { ConferenceByline } from "./ConferenceByline" import { ConferenceCommittee } from "./ConferenceCommittee" import { ConferenceDifferences } from "./ConferenceDifferences" import { ConferencePicker } from "./ConferencePicker" -import { ConferenceRail } from "./ConferenceRail" +import { ClosedFold, ConferenceRail } from "./ConferenceRail" import { ConferenceResolution, OutcomeFilter } from "./ConferenceResolution" import { ConferenceTabs, TABS_H } from "./ConferenceTabs" import { ConferenceText } from "./ConferenceText" @@ -185,10 +189,29 @@ const RESOLVED_LABELS = { decided: "tab_resolved" } * that the title opens it. */ export function ConferenceDetails(props: ConferencePageProps) { + const fold = useClosedFold(props.conference) // Keyed so moving to another conference starts clean: the panel's draft hook // is fixed to the conference it first mounted on, and would keep filing on // the old one. - return
+ return
+} + +/** + * Whether the rail's group of conferences no longer taking input is open, + * held above the keyed page so it lasts from one conference to the next. It + * starts open only on a conference in the group, and opens on arriving at + * one, so the conference being read is never folded away; otherwise it stays + * as the reader left it. + */ +function useClosedFold(conference: ConferenceSummary): ClosedFold { + const closed = !isSitting(conference) + const [open, setOpen] = useState(closed) + const [at, setAt] = useState(conference.id) + if (at !== conference.id) { + setAt(conference.id) + if (closed) setOpen(true) + } + return { open, onToggle: setOpen } } function Details({ @@ -199,8 +222,9 @@ function Details({ gist, differences, similarities, - testimonyCount -}: ConferencePageProps) { + testimonyCount, + fold +}: ConferencePageProps & { fold: ClosedFold }) { const { t } = useTranslation("conferences") const { user, authenticated, loading: authLoading, authFlowStep } = useAuth() const dispatch = useAppDispatch() @@ -457,6 +481,7 @@ function Details({ className="d-none d-md-block" conferences={conferences} current={conference.id} + fold={fold} />
@@ -465,6 +490,7 @@ function Details({ {subject} diff --git a/components/conference/ConferencePicker.tsx b/components/conference/ConferencePicker.tsx index fb24b4327..6e9a33d0b 100644 --- a/components/conference/ConferencePicker.tsx +++ b/components/conference/ConferencePicker.tsx @@ -3,7 +3,7 @@ import styled from "styled-components" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faChevronDown } from "@fortawesome/free-solid-svg-icons" import { Dropdown } from "../bootstrap" -import { RailList } from "./ConferenceRail" +import { ClosedFold, RailList } from "./ConferenceRail" import { Title } from "./styles" import { conferenceName, ConferenceSummary } from "./types" @@ -53,10 +53,12 @@ const Menu = styled(Dropdown.Menu)` */ export function ConferencePicker({ conferences, - current + current, + fold }: { conferences: ConferenceSummary[] current: ConferenceSummary + fold: ClosedFold }) { const { t } = useTranslation("conferences") return ( @@ -66,7 +68,7 @@ export function ConferencePicker({ - + ) diff --git a/components/conference/ConferenceRail.test.tsx b/components/conference/ConferenceRail.test.tsx new file mode 100644 index 000000000..d255e0c79 --- /dev/null +++ b/components/conference/ConferenceRail.test.tsx @@ -0,0 +1,93 @@ +import "@testing-library/jest-dom" +import { fireEvent, render, screen } from "@testing-library/react" +import { RailList } from "./ConferenceRail" +import { ConferenceSummary } from "./types" + +jest.mock("next-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +const conference = ( + id: string, + status: ConferenceSummary["status"] = "appointed" +): ConferenceSummary => ({ + id, + court: 194, + name: id, + title: id, + senateBillId: "S1", + houseBillId: "H1", + canonicalBillId: "S1", + status, + covered: true, + reportBillId: null +}) + +const conferences = [ + conference("sitting"), + conference("enacted", "enacted"), + conference("dissolved", "dissolved") +] + +const fold = () => screen.getByText("rail_closed").closest("details")! +const folded = { open: false, onToggle: () => {} } + +describe("RailList", () => { + it("folds the conferences no longer taking input below the rest, closed", () => { + render( + + ) + + expect(fold()).not.toHaveAttribute("open") + expect(fold()).toContainElement( + screen.getByRole("link", { name: /enacted/ }) + ) + expect(fold()).not.toContainElement( + screen.getByRole("link", { name: /sitting/ }) + ) + }) + + it("opens as the page says, marking the conference being read", () => { + render( + {} }} + /> + ) + + expect(fold()).toHaveAttribute("open") + expect(screen.getByRole("link", { name: /enacted/ })).toHaveAttribute( + "aria-current", + "page" + ) + }) + + it("tells the page when the reader opens it", () => { + const onToggle = jest.fn() + render( + + ) + + fold().open = true + fireEvent(fold(), new Event("toggle")) + + expect(onToggle).toHaveBeenCalledWith(true) + }) + + it("has no fold when every conference is still sitting", () => { + render( + + ) + + expect(screen.queryByText("rail_closed")).not.toBeInTheDocument() + }) +}) diff --git a/components/conference/ConferenceRail.tsx b/components/conference/ConferenceRail.tsx index 1cb2c8b18..cdcd66a06 100644 --- a/components/conference/ConferenceRail.tsx +++ b/components/conference/ConferenceRail.tsx @@ -1,5 +1,8 @@ import { useTranslation } from "next-i18next" import styled from "styled-components" +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" +import { faChevronDown } from "@fortawesome/free-solid-svg-icons" +import { isSitting } from "../../functions/src/shared" import { formatBillId } from "../formatting" import { Internal, maple } from "../links" import { conferenceName, ConferenceSummary } from "./types" @@ -67,6 +70,46 @@ const RailRow = styled(Internal)<{ $on: boolean; $covered: boolean }>` } ` +/** The conferences no longer taking input, folded under the ones that are. */ +const Closed = styled.details` + margin-top: 0.75rem; + + > summary { + display: flex; + align-items: center; + gap: 0.375rem; + padding: 0.4375rem 0.5rem 0.4375rem calc(0.6875rem + 3px); + border-radius: 0 var(--maple-radius-md) var(--maple-radius-md) 0; + font-size: 0.75rem; + line-height: 1.35; + color: var(--maple-text-muted); + cursor: pointer; + list-style: none; + transition: background-color 120ms ease; + + &::-webkit-details-marker { + display: none; + } + &:hover { + background: rgba(0, 0, 0, 0.05); + } + &:focus-visible { + outline: 3px solid var(--maple-focus-ring); + outline-offset: -3px; + } + .chevron { + font-size: 0.625rem; + transition: transform 150ms ease; + } + } + &[open] > summary .chevron { + transform: rotate(180deg); + } + > ul { + margin-top: 2px; + } +` + /** "S.1234 · H.5678", the status once the conference has finished, and a * label where we haven't covered it. The caller styles `.status`. */ export function BillLine({ c }: { c: ConferenceSummary }) { @@ -90,46 +133,88 @@ export function BillLine({ c }: { c: ConferenceSummary }) { export function ConferenceRail({ conferences, current, + fold, className }: { conferences: ConferenceSummary[] current: string + fold: ClosedFold className?: string }) { const { t } = useTranslation("conferences") return ( ) } -/** The rows, shared by the rail and the picker that stands in for it. */ +/** Whether the group of conferences no longer taking input is open, and how + * the reader opens or folds it. The page holds it, so the rail and the picker + * share it and it lasts between conferences. */ +export type ClosedFold = { + open: boolean + onToggle: (open: boolean) => void +} + +/** + * The rows, shared by the rail and the picker that stands in for it: the + * conferences still sitting, then the rest in a group below them that the + * reader opens and folds. + */ export function RailList({ conferences, - current + current, + fold }: { conferences: ConferenceSummary[] current: string + fold: ClosedFold }) { - return ( + const { t } = useTranslation("conferences") + const sitting = conferences.filter(isSitting) + const closed = conferences.filter(c => !isSitting(c)) + const rows = (cs: ConferenceSummary[]) => ( - {conferences.map(c => ( + {cs.map(c => (
  • - - {conferenceName(c)} - - - - +
  • ))}
    ) + return ( + <> + {rows(sitting)} + {closed.length > 0 && ( + fold.onToggle(e.currentTarget.open)} + > + + {t("rail_closed", { count: closed.length })} + + + {rows(closed)} + + )} + + ) +} + +function Row({ c, on }: { c: ConferenceSummary; on: boolean }) { + return ( + + {conferenceName(c)} + + + + + ) } diff --git a/components/conference/load.test.ts b/components/conference/load.test.ts index f2ca7c07e..0072d721a 100644 --- a/components/conference/load.test.ts +++ b/components/conference/load.test.ts @@ -1,11 +1,24 @@ import { currentGeneralCourt } from "functions/src/shared" -import { Conference, listConferences } from "../db/conferences" +import { + Conference, + getConferenceForBill, + getConferenceForHearing, + listConferences +} from "../db/conferences" import { getMember, getMemberSearchIndex } from "../db/members" -import { loadConferenceIndex, loadConferencePage, loadLanding } from "./load" +import { + loadConferenceForBill, + loadConferenceForHearing, + loadConferenceIndex, + loadConferencePage, + loadLanding +} from "./load" jest.mock("../db/conferences") jest.mock("../db/events", () => ({ getEventSummary: jest.fn() })) jest.mock("../db/members") +const mockFlags = { closedConferences: true } +jest.mock("../featureFlags", () => ({ flags: () => mockFlags })) const conference = (id: string, memberCodes: string[]): Conference => ({ id, @@ -52,6 +65,7 @@ const names = (props: Awaited>) => beforeEach(() => { jest.resetAllMocks() + mockFlags.closedConferences = true jest .mocked(listConferences) .mockResolvedValue([conference("a", ["X", "Y"]), conference("b", ["X"])]) @@ -209,3 +223,89 @@ describe("coverage", () => { expect(page?.conference.covered).toBe(false) }) }) + +describe("closed conferences", () => { + const closed = (id: string, status: Conference["status"]): Conference => ({ + ...conference(id, ["X"]), + status + }) + + beforeEach(() => { + jest + .mocked(listConferences) + .mockResolvedValue([ + closed("a-enacted", "enacted"), + conference("b", ["X"]), + closed("c-filed", "reportFiled"), + closed("d-dissolved", "dissolved") + ]) + jest + .mocked(getMemberSearchIndex) + .mockResolvedValue(index(facts("X", "Xena"))) + jest.mocked(getMember).mockResolvedValue(facts("X", "Xena") as any) + }) + + const ids = (cs: { id: string }[]) => cs.map(c => c.id) + + it("lists them after the conferences still sitting, behind the flag", async () => { + const props = await loadConferenceIndex(currentGeneralCourt) + + expect(ids(props.conferences)).toEqual([ + "b", + "a-enacted", + "c-filed", + "d-dissolved" + ]) + }) + + describe("with the flag off", () => { + beforeEach(() => { + mockFlags.closedConferences = false + }) + + it("leaves them out of the index and its conferees", async () => { + const props = await loadConferenceIndex(currentGeneralCourt) + + expect(ids(props.conferences)).toEqual(["b"]) + expect(Object.keys(props.conferees)).toEqual(["b"]) + }) + + it("leaves them out of the rail and finds no page for them", async () => { + const page = await loadConferencePage(currentGeneralCourt, "b") + + expect(ids(page!.conferences)).toEqual(["b"]) + expect( + await loadConferencePage(currentGeneralCourt, "a-enacted") + ).toBeNull() + }) + + it("points the landing past them", async () => { + expect(await loadLanding(currentGeneralCourt)).toEqual({ + court: currentGeneralCourt, + id: "b" + }) + }) + + it("names none on the bill and hearing pages", async () => { + jest + .mocked(getConferenceForBill) + .mockResolvedValue(closed("a-enacted", "enacted")) + jest + .mocked(getConferenceForHearing) + .mockResolvedValue(closed("d-dissolved", "dissolved")) + + expect(await loadConferenceForBill(currentGeneralCourt, "S1")).toBeNull() + expect( + await loadConferenceForHearing(String(currentGeneralCourt), "1") + ).toBeNull() + }) + + it("still names one still sitting", async () => { + jest.mocked(getConferenceForBill).mockResolvedValue(conference("b", [])) + + expect((await loadConferenceForBill(currentGeneralCourt, "S1"))?.id).toBe( + "b" + ) + }) + }) +}) diff --git a/components/conference/load.ts b/components/conference/load.ts index a6bd84952..2d92af8d7 100644 --- a/components/conference/load.ts +++ b/components/conference/load.ts @@ -1,5 +1,5 @@ import { districtId } from "functions/src/districts/normalize" -import { currentGeneralCourt } from "functions/src/shared" +import { currentGeneralCourt, isSitting } from "functions/src/shared" import type { Branch } from "../../functions/src/common" import { Conference, @@ -8,6 +8,7 @@ import { listConferences } from "../db/conferences" import { getEventSummary } from "../db/events" +import { flags } from "../featureFlags" import { getMember, getMemberSearchIndex, @@ -40,7 +41,16 @@ const summarize = (c: Conference): ConferenceSummary => ({ reportBillId: c.reportBillId ?? null }) -/** Every conference as the rail lists them: active first, then by name. */ +/** Whether the site shows a conference: one still sitting always, one no + * longer taking input only behind the closedConferences flag. */ +const shown = (c: Pick) => + isSitting(c) || flags().closedConferences + +/** Every conference in the court the site shows. */ +const listShown = async (court: number) => + (await listConferences(court)).filter(shown) + +/** Conferences as the rail lists them: active first, then by name. */ const railOf = (all: Conference[]) => all.map(summarize).sort(byActivity) /** The member's cell on the map: their district id, or null where the map has @@ -117,7 +127,7 @@ export async function loadConferencePage( id: string ): Promise { // The rail needs every conference, and the page's own is among them. - return pageFor(court, await listConferences(court), id) + return pageFor(court, await listShown(court), id) } /** Where the landing's button goes: the first covered conference in the @@ -125,7 +135,7 @@ export async function loadConferencePage( export async function loadLanding( court: number ): Promise { - const rail = railOf(await listConferences(court)) + const rail = railOf(await listShown(court)) const landing = rail.find(c => c.covered) ?? rail[0] return landing ? { court: landing.court, id: landing.id } : null } @@ -189,7 +199,7 @@ export async function loadConferenceIndex( ): Promise { // The index doesn't depend on the conferences, so read both at once. const [all, index] = await Promise.all([ - listConferences(court), + listShown(court), court === currentGeneralCourt ? getMemberSearchIndex() : undefined ]) const members = index @@ -207,7 +217,7 @@ export async function loadConferenceForBill( billId: string ): Promise { const c = await getConferenceForBill(court, billId) - return c ? summarize(c) : null + return c && shown(c) ? summarize(c) : null } /** The conference a hearing belongs to, by the hearing page's numeric id. */ @@ -220,5 +230,5 @@ export async function loadConferenceForHearing( Number(generalCourtNumber), `hearing-${hearingId}` ) - return c ? summarize(c) : null + return c && shown(c) ? summarize(c) : null } diff --git a/components/conference/types.ts b/components/conference/types.ts index a973eede5..80f23c379 100644 --- a/components/conference/types.ts +++ b/components/conference/types.ts @@ -1,4 +1,5 @@ import type { Branch } from "../../functions/src/common" +import { isSitting } from "../../functions/src/shared" import type { ConferenceAddressedBy, ConferenceOutcome, @@ -98,8 +99,7 @@ export const byName = (a: Named, b: Named) => /** The ordering the rail uses: still sitting first, then finished. */ export const byActivity = (a: ConferenceSummary, b: ConferenceSummary) => - Number(b.status === "appointed") - Number(a.status === "appointed") || - byName(a, b) + Number(isSitting(b)) - Number(isSitting(a)) || byName(a, b) /** The conference the landing's button opens. */ export type ConferenceLanding = Pick diff --git a/components/featureFlags.ts b/components/featureFlags.ts index 105316516..8ca731ec9 100644 --- a/components/featureFlags.ts +++ b/components/featureFlags.ts @@ -21,7 +21,10 @@ export const FeatureFlags = z.object({ /** Legislators Page feature **/ legislators: z.boolean().default(false), /** Conference committee pages and their links from bills and hearings */ - conferences: z.boolean().default(false) + conferences: z.boolean().default(false), + /** Conferences no longer taking input (report filed, enacted, dissolved): + * off, they appear nowhere and their pages are not found */ + closedConferences: z.boolean().default(false) }) export type FeatureFlags = z.infer @@ -44,7 +47,8 @@ const defaults: Record = { phoneVerificationUI: true, ballotQuestions: false, legislators: true, - conferences: true + conferences: true, + closedConferences: true }, production: { testimonyDiffing: false, @@ -56,7 +60,8 @@ const defaults: Record = { phoneVerificationUI: false, ballotQuestions: false, legislators: false, - conferences: false + conferences: false, + closedConferences: false }, test: { testimonyDiffing: false, @@ -68,7 +73,8 @@ const defaults: Record = { phoneVerificationUI: true, ballotQuestions: false, legislators: false, - conferences: false + conferences: false, + closedConferences: false } } diff --git a/functions/src/shared/conferences.ts b/functions/src/shared/conferences.ts index 3ce9fd47c..0f065be6a 100644 --- a/functions/src/shared/conferences.ts +++ b/functions/src/shared/conferences.ts @@ -5,8 +5,13 @@ import type { Conference } from "../conferences/types" export const hasReport = (c: Pick) => c.status === "reportFiled" || c.status === "enacted" +/** The committee is still deciding which version to report: neither a report + * filed, nor enacted, nor dissolved. */ +export const isSitting = (c: Pick) => + c.status === "appointed" + /** Testimony is taken while the committee is still deciding which version to * report, on the conferences we cover. A document synced before `covered` * existed counts as covered. */ export const takesTestimony = (c: Pick) => - c.status === "appointed" && c.covered !== false + isSitting(c) && c.covered !== false diff --git a/public/locales/en/conferences.json b/public/locales/en/conferences.json index b37ae579c..f123156d0 100644 --- a/public/locales/en/conferences.json +++ b/public/locales/en/conferences.json @@ -23,6 +23,7 @@ "hearing_scheduled": "Hearing scheduled for {{date}}", "no_hearings": "No hearings have been disclosed.", "pick_conference": "Choose a conference committee", + "rail_closed": "No longer taking input ({{count}})", "bill_banner": { "appointed": "This bill is in a conference committee: <1>{{name}}", "reportFiled": "The conference committee on this bill has filed its report: <1>{{name}}", From 21ba26c5f23df278b59b5835779f2b5f14c4db62 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Fri, 13 Nov 2026 09:49:59 -0500 Subject: [PATCH 4/8] Follow a conference committee, and hear of its new input in the newsfeed and the email digest A reader could follow a bill, a person or an organization, but not a conference committee, and conference input is kept off its bill's followers on purpose, so it reached only the author's followers. A Follow control now sits beside Share on a conference's page, behind the notifications flag. Following writes a conference subscription; pressing it again, or Unfollow on the profile's Following tab, removes it. A signed-out reader is sent to log in. New input on a followed conference, by anyone but the reader, reaches their newsfeed as "You follow {conference}" (and the author, when they follow both, on the same card), and their digest in a new Conference Committees section with the count for each stance, linked to the conference's input. The notification event names the conference once, when the input is published, so neither path reads it again. Once a conference stops taking input nothing new can arrive. The control then shows only to readers who already follow it, so they can unfollow, and it stays after an unfollow so that can be taken back. Subscriptions are kept for status alerts later. A conference hidden by the closedConferences flag still lists on the Following tab, unlinked. The follow logic in BaseFollowButton moves into a useFollowTopic hook that both controls use. A conference's name and whether the site shows it are each one shared rule now, and the integration tests share one conference fixture. Closes hyphacoop/maple#135 Verified: yarn check-types, yarn lint, yarn check-formatting, yarn test and yarn test:website pass, with new tests for the digest's conference section and template, the event's conference name, the Follow control and the newsfeed title. Against the Docker emulators, conferenceFollowing.test.ts (subscription shape, unfollow, another user refused, and a follower's feed getting the input while the author's does not) and testimony.test.ts pass. Running deliverNotifications against the emulators wrote a digest with the conference section and stance counts, read in a browser. The conference page's control at 1280px and 390px. Not verified: the scheduled 9:47 ET run, since the emulator never fires it; unfollowing from the Following tab in a browser; the control on a closed conference in a browser. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/repo-checks.yml | 1 + components/EditProfilePage/FollowingTab.tsx | 83 +++++++++-- components/Newsfeed/Newsfeed.tsx | 2 + components/Newsfeed/NotificationProps.tsx | 2 + components/NewsfeedCard/NewsfeedCard.test.tsx | 35 +++++ components/NewsfeedCard/NewsfeedCard.tsx | 4 + components/NewsfeedCard/NewsfeedCardTitle.tsx | 24 ++++ .../ConferenceDetails.switching.test.tsx | 10 ++ .../conference/ConferenceDetails.test.tsx | 43 ++++++ components/conference/ConferenceDetails.tsx | 30 ++-- .../conference/FollowConference.test.tsx | 127 +++++++++++++++++ components/conference/FollowConference.tsx | 114 ++++++++++++++++ components/conference/input/icons.tsx | 24 ++++ components/conference/load.ts | 15 +- components/conference/types.ts | 10 +- components/shared/FollowButton.tsx | 112 ++++++++++----- components/shared/FollowingQueries.tsx | 27 ++++ functions/src/email/digestEmail.handlebars | 2 + functions/src/email/digestEmail.test.ts | 81 +++++++++++ .../conferences/conference.handlebars | 34 +++++ .../conferences/conferences.handlebars | 44 ++++++ functions/src/email/partials/index.ts | 4 + .../deliverNotifications.test.ts | 99 +++++++++++++- .../src/notifications/deliverNotifications.ts | 48 +++++-- functions/src/notifications/emailTypes.ts | 20 +++ ...timonySubmissionNotificationEvents.test.ts | 66 ++++++++- ...teTestimonySubmissionNotificationEvents.ts | 18 ++- .../src/notifications/publishNotifications.ts | 16 ++- functions/src/notifications/types.ts | 5 + functions/src/shared/conferences.ts | 6 + functions/src/subscriptions/types.ts | 5 + public/locales/en/conferences.json | 5 + public/locales/en/editProfile.json | 1 + scripts/firebase-admin/sendTestEmail.ts | 4 +- .../NotificationDigestEmail.stories.tsx | 36 ++++- tests/integration/common.ts | 30 ++++ tests/integration/conferenceFollowing.test.ts | 129 ++++++++++++++++++ tests/integration/testimony.test.ts | 30 +--- 38 files changed, 1232 insertions(+), 114 deletions(-) create mode 100644 components/conference/FollowConference.test.tsx create mode 100644 components/conference/FollowConference.tsx create mode 100644 functions/src/email/digestEmail.test.ts create mode 100644 functions/src/email/partials/conferences/conference.handlebars create mode 100644 functions/src/email/partials/conferences/conferences.handlebars create mode 100644 tests/integration/conferenceFollowing.test.ts diff --git a/.github/workflows/repo-checks.yml b/.github/workflows/repo-checks.yml index 99606a1a9..b183e37e1 100644 --- a/.github/workflows/repo-checks.yml +++ b/.github/workflows/repo-checks.yml @@ -96,6 +96,7 @@ jobs: tests/integration/ballotQuestions.test.ts tests/integration/backfillTestimonyScope.test.ts tests/integration/conferences.test.ts + tests/integration/conferenceFollowing.test.ts components/auth/hooks.test.ts components/db/useUpcoming.test.ts components/db/testimony diff --git a/components/EditProfilePage/FollowingTab.tsx b/components/EditProfilePage/FollowingTab.tsx index e7f6f9ba3..9170fcb82 100644 --- a/components/EditProfilePage/FollowingTab.tsx +++ b/components/EditProfilePage/FollowingTab.tsx @@ -2,10 +2,13 @@ import { flags } from "components/featureFlags" import { dbService } from "components/db/api" import { useBill } from "components/db" import { formatBillId } from "components/formatting" -import { Internal } from "components/links" +import { Internal, maple } from "components/links" +import { conferenceName, isShown } from "components/conference/types" +import { getConference } from "components/db/conferences" import { FollowBallotQuestionButton, - FollowBillButton + FollowBillButton, + FollowConferenceTopicButton } from "components/shared/FollowButton" import { collection, onSnapshot, query, where } from "firebase/firestore" import { useTranslation } from "next-i18next" @@ -23,6 +26,7 @@ import { export function FollowingTab({ className }: { className?: string }) { const { t } = useTranslation("editProfile") const followedBallotQuestions = useFollowedBallotQuestions() + const followedConferences = useFollowedConferences() return ( <> )} + {flags().conferences && ( + + )} > => useTopicSubscription("ballotQuestion") +const useFollowedConferences = (): LoadableItemsState< + ComponentProps +> => useTopicSubscription("conference") + const useFollowedUsers = (): LoadableItemsState< ComponentProps > => useTopicSubscription("testimony") +/** The field of a subscription doc that says what is followed, by type. */ +const TOPIC_KEYS = { + bill: "billLookup", + ballotQuestion: "ballotQuestionLookup", + conference: "conferenceLookup", + testimony: "userLookup" +} as const + function useTopicSubscription( - type: "bill" | "ballotQuestion" | "testimony" + type: keyof typeof TOPIC_KEYS ): LoadableItemsState { const [state, setState] = useState>({ items: [], @@ -78,12 +102,7 @@ function useTopicSubscription( : null, [uid] ) - const topicKey = - type === "bill" - ? "billLookup" - : type === "ballotQuestion" - ? "ballotQuestionLookup" - : "userLookup" + const topicKey = TOPIC_KEYS[type] useEffect(() => { if (!subscriptionRef || !uid) return @@ -190,3 +209,49 @@ function FollowedBallotQuestionCard({ ) } + +/** A followed conference. One that is hidden, no longer taking input while + * closed conferences are off, keeps its row without a link, so the reader can + * still unfollow it. */ +function FollowedConferenceCard({ + conferenceId, + court +}: { + conferenceId: string + court: number +}) { + const { t } = useTranslation("editProfile") + const uid = useAuth().user?.uid + const { + loading, + error, + result: conference + } = useAsync(() => getConference(court, conferenceId), [court, conferenceId]) + if (loading) return + if (error) return {t("content.error")} + + const shown = conference && isShown(conference) + + return ( +
    + + + {shown ? ( + + {conferenceName(conference)} + + ) : ( +
    {conference ? conferenceName(conference) : conferenceId}
    + )} + + + + +
    +
    +
    + ) +} diff --git a/components/Newsfeed/Newsfeed.tsx b/components/Newsfeed/Newsfeed.tsx index 57be0a7a5..2fa6afa60 100644 --- a/components/Newsfeed/Newsfeed.tsx +++ b/components/Newsfeed/Newsfeed.tsx @@ -252,9 +252,11 @@ export default function Newsfeed() { billId={element.billId} bodyText={element.bodyText} conferenceId={element.conferenceId} + conferenceName={element.conferenceName} court={element.court} header={element.header} isBillMatch={element.isBillMatch} + isConferenceMatch={element.isConferenceMatch} isUserMatch={element.isUserMatch} isBallotQuestionMatch={ element.isBallotQuestionMatch diff --git a/components/Newsfeed/NotificationProps.tsx b/components/Newsfeed/NotificationProps.tsx index a9ba4211e..ada6198f9 100644 --- a/components/Newsfeed/NotificationProps.tsx +++ b/components/Newsfeed/NotificationProps.tsx @@ -25,6 +25,8 @@ export type NotificationProps = { ballotStatus?: string // Set on testimony to a committee of conference conferenceId?: string | null + conferenceName?: string | null + isConferenceMatch?: boolean // is subscribed to the conference } export type Notifications = NotificationProps[] diff --git a/components/NewsfeedCard/NewsfeedCard.test.tsx b/components/NewsfeedCard/NewsfeedCard.test.tsx index 094481630..09b234652 100644 --- a/components/NewsfeedCard/NewsfeedCard.test.tsx +++ b/components/NewsfeedCard/NewsfeedCard.test.tsx @@ -106,6 +106,41 @@ describe("NewsfeedCard", () => { expect(document.querySelector("a[href^='/testimony/']")).toBeNull() }) + it("says a reader follows the conference, by name, when that is the match", () => { + render( + + ) + + const reason = screen.getByText("newsfeed.follow").closest(".card-title")! + expect(reason).toHaveTextContent("newsfeed.followPhone-Free Schools") + expect(reason).not.toHaveTextContent("Alice") + }) + + it("names the conference and the author when the reader follows both", () => { + render( + + ) + + // With no name stored, the conference goes by its bill's title. + const titles = Array.from(document.querySelectorAll(".card-title")) + expect(titles.map(t => t.textContent)).toContain( + "newsfeed.followAn Act relative to student learningnewsfeed.andAlice" + ) + }) + it("keeps bill testimony on its bill, testimony page and thumbs", () => { render() diff --git a/components/NewsfeedCard/NewsfeedCard.tsx b/components/NewsfeedCard/NewsfeedCard.tsx index 92ba56d64..765945843 100644 --- a/components/NewsfeedCard/NewsfeedCard.tsx +++ b/components/NewsfeedCard/NewsfeedCard.tsx @@ -22,10 +22,12 @@ export const NewsfeedCard = (props: { billId?: string bodyText: string conferenceId?: string | null + conferenceName?: string | null court?: string header: string isBallotQuestionMatch?: boolean isBillMatch?: boolean + isConferenceMatch?: boolean isUserMatch?: boolean position?: string subheader?: string @@ -45,10 +47,12 @@ export const NewsfeedCard = (props: { authorUid={props.authorUid} billId={props.billId} conferenceHref={conferenceHref} + conferenceName={props.conferenceName} court={props.court} header={props.header} isBallotQuestionMatch={props.isBallotQuestionMatch} isBillMatch={props.isBillMatch} + isConferenceMatch={props.isConferenceMatch} isUserMatch={props.isUserMatch} subheader={props.subheader} timestamp={formattedTimestamp} diff --git a/components/NewsfeedCard/NewsfeedCardTitle.tsx b/components/NewsfeedCard/NewsfeedCardTitle.tsx index a49f76f42..60cd40824 100644 --- a/components/NewsfeedCard/NewsfeedCardTitle.tsx +++ b/components/NewsfeedCard/NewsfeedCardTitle.tsx @@ -9,6 +9,8 @@ interface NewsfeedCardTitleProps { billId?: string /** Set on testimony to a committee of conference: its conference page */ conferenceHref?: string + /** The conference's name, for a reader who follows it */ + conferenceName?: string | null court?: string header?: string subheader?: string @@ -17,6 +19,7 @@ interface NewsfeedCardTitleProps { inHeaderElement?: ReactElement isBallotQuestionMatch?: boolean isBillMatch?: boolean + isConferenceMatch?: boolean isUserMatch?: boolean type?: string userRole?: string @@ -28,10 +31,12 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { authorUid, billId, conferenceHref, + conferenceName, court, header, isBillMatch, isBallotQuestionMatch, + isConferenceMatch, isUserMatch, subheader, type, @@ -55,7 +60,9 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { {isNewsfeed ? ( { const CardTitleFollowing = (props: NewsfeedCardTitleProps) => { const { billId, + conferenceName, header, isBallotQuestionMatch, isBillMatch, + isConferenceMatch, isUserMatch, subheader, type @@ -211,6 +220,21 @@ const CardTitleFollowing = (props: NewsfeedCardTitleProps) => { )} ) + } else if (isConferenceMatch) { + return ( + + {t("newsfeed.follow")} + {conferenceName || header} + {isUserMatch && ( + <> + {t("newsfeed.and")} + {subheader} + + )} + + ) } else if (isBillMatch && isUserMatch) { return ( ({ useFlags: () => ({ legislators: false, hearingsAndTranscriptions: true }) })) jest.mock("../hooks", () => ({ useAppDispatch: () => jest.fn() })) +// Following has its own tests; here it is a switch. +let mockFollowVisible = false +jest.mock("./FollowConference", () => ({ + ...jest.requireActual("./FollowConference"), + useConferenceFollow: () => ({ + visible: mockFollowVisible, + following: false, + toggle: jest.fn() + }) +})) jest.mock("./input/useFollowedAuthors", () => ({ useFollowedAuthors: () => new Set() })) diff --git a/components/conference/ConferenceDetails.test.tsx b/components/conference/ConferenceDetails.test.tsx index d867c2a5d..a1d2e4135 100644 --- a/components/conference/ConferenceDetails.test.tsx +++ b/components/conference/ConferenceDetails.test.tsx @@ -128,6 +128,16 @@ jest.mock("../hooks", () => ({ useAppDispatch: () => mockDispatch })) // A card's actions reach for the report API; the page's own tests do not. jest.mock("./input/Kebab", () => ({ Kebab: () => null })) jest.mock("./input/EntryModal", () => ({ EntryModal: () => null })) +// Following has its own tests; here it is a switch. +let mockFollowVisible = false +jest.mock("./FollowConference", () => ({ + ...jest.requireActual("./FollowConference"), + useConferenceFollow: () => ({ + visible: mockFollowVisible, + following: false, + toggle: jest.fn() + }) +})) jest.mock("./input/useFollowedAuthors", () => ({ useFollowedAuthors: () => new Set() })) @@ -445,6 +455,39 @@ describe("ConferenceDetails", () => { expect(screen.getByText("input.empty_title")).toBeInTheDocument() }) + describe("the Follow control", () => { + afterEach(() => { + mockFollowVisible = false + }) + + it("sits beside the title's button while the conference takes input", () => { + mockFollowVisible = true + render() + const follow = screen.getByRole("button", { name: "follow.follow" }) + const [share] = screen.getAllByRole("button", { name: "input.share" }) + expect(follow.parentElement).toBe(share.parentElement) + }) + + it("stands alone on a closed conference, where it is shown", () => { + mockFollowVisible = true + const enacted = { ...conference, status: "enacted" as const } + render() + expect( + screen.getByRole("button", { name: "follow.follow" }) + ).toBeInTheDocument() + expect( + screen.queryByRole("button", { name: "input.share" }) + ).not.toBeInTheDocument() + }) + + it("is absent where the hook hides it", () => { + render() + expect( + screen.queryByRole("button", { name: "follow.follow" }) + ).not.toBeInTheDocument() + }) + }) + it("greys the title's button once the reader has filed", () => { mockUser = { uid: "reader", emailVerified: true } mockItems = [ diff --git a/components/conference/ConferenceDetails.tsx b/components/conference/ConferenceDetails.tsx index 772ed6edc..80e116735 100644 --- a/components/conference/ConferenceDetails.tsx +++ b/components/conference/ConferenceDetails.tsx @@ -19,6 +19,7 @@ import styled from "styled-components" import { ConferenceByline } from "./ConferenceByline" import { ConferenceCommittee } from "./ConferenceCommittee" import { ConferenceDifferences } from "./ConferenceDifferences" +import { FollowConferenceButton, useConferenceFollow } from "./FollowConference" import { ConferencePicker } from "./ConferencePicker" import { ClosedFold, ConferenceRail } from "./ConferenceRail" import { ConferenceResolution, OutcomeFilter } from "./ConferenceResolution" @@ -78,18 +79,18 @@ const Shift = styled.div` * button; level with the title itself where there is no button. Below md the * picker stands for the title, with the link over it and the button under it * at the left. */ -const TitleRow = styled.div<{ $taking: boolean }>` +const TitleRow = styled.div<{ $actions: boolean }>` display: grid; grid-template-columns: minmax(0, 1fr) auto; - grid-template-areas: ${({ $taking }) => - $taking ? `". link" "title share"` : `"title link"`}; + grid-template-areas: ${({ $actions }) => + $actions ? `". link" "title share"` : `"title link"`}; align-items: center; gap: 0.5rem 24px; @media (max-width: 767.98px) { grid-template-columns: minmax(0, 1fr); - grid-template-areas: ${({ $taking }) => - $taking ? `"link" "picker" "share"` : `"link" "picker"`}; + grid-template-areas: ${({ $actions }) => + $actions ? `"link" "picker" "share"` : `"link" "picker"`}; } ` @@ -100,6 +101,9 @@ const Picker = styled.div` const Share = styled.div` grid-area: share; justify-self: end; + display: flex; + align-items: center; + gap: 18px; @media (max-width: 767.98px) { justify-self: start; @@ -264,6 +268,8 @@ function Details({ const followed = useFollowedAuthors(user?.uid) const subject = conferenceName(conference) const taking = takesTestimony(conference) + const follow = useConferenceFollow(conference) + const actions = taking || follow.visible const decided = differences.length > 0 || similarities.length > 0 // Once the report is filed, each question says how the law resolved it. const resolved = hasReport(conference) && differences.length > 0 @@ -485,7 +491,7 @@ function Details({ />
    - + {subject} - {taking && ( + {actions && ( - + {follow.visible && ( + + )} + {taking && ( + + )} )} diff --git a/components/conference/FollowConference.test.tsx b/components/conference/FollowConference.test.tsx new file mode 100644 index 000000000..faeabadbb --- /dev/null +++ b/components/conference/FollowConference.test.tsx @@ -0,0 +1,127 @@ +import "@testing-library/jest-dom" +import { render, screen, waitFor } from "@testing-library/react" +import userEvent from "@testing-library/user-event" +import { useState } from "react" +import { FollowContext, OrgFollowStatus } from "../shared/FollowContext" +import { FollowConferenceButton, useConferenceFollow } from "./FollowConference" +import type { ConferenceStatus } from "../../functions/src/conferences/types" + +jest.mock("next-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }) +})) + +const push = jest.fn() +jest.mock("next/router", () => ({ + useRouter: () => ({ push, asPath: "/conferences/194/phones" }) +})) + +const mockFlags = { notifications: true } +jest.mock("../featureFlags", () => ({ useFlags: () => mockFlags })) + +let uid: string | undefined +jest.mock("../auth", () => ({ + useAuth: () => ({ user: uid ? { uid } : null }) +})) + +let followed = false +jest.mock("../shared/FollowingQueries", () => ({ + ...jest.requireActual("../shared/FollowingQueries"), + followsTopic: jest.fn(async () => followed), + followConference: jest.fn(async () => {}), + unfollowConference: jest.fn(async () => {}) +})) +const queries = jest.requireMock("../shared/FollowingQueries") + +function Harness({ status }: { status: ConferenceStatus }) { + const follow = useConferenceFollow({ id: "phones", court: 194, status }) + return follow.visible ? ( + + ) : null +} + +function Page({ status = "appointed" }: { status?: ConferenceStatus }) { + const [followStatus, setFollowStatus] = useState({}) + return ( + + + + ) +} + +describe("following a conference", () => { + beforeEach(() => { + jest.clearAllMocks() + uid = undefined + followed = false + mockFlags.notifications = true + }) + + it("sends a signed-out reader to log in", async () => { + render() + + await userEvent.click(screen.getByRole("button", { name: "follow.follow" })) + + expect(queries.followConference).not.toHaveBeenCalled() + expect(push).toHaveBeenCalledWith( + "/login?redirect=%2Fconferences%2F194%2Fphones" + ) + }) + + it("follows, then unfollows, the conference on its topic", async () => { + uid = "reader" + render() + + const button = await screen.findByRole("button", { pressed: false }) + await userEvent.click(button) + expect(queries.followConference).toHaveBeenCalledWith("reader", { + id: "phones", + court: 194 + }) + expect(queries.followsTopic).toHaveBeenCalledWith( + "reader", + "conference-194-phones" + ) + expect(button).toHaveAttribute("aria-pressed", "true") + expect(button).toHaveTextContent("follow.following") + + await userEvent.click(button) + expect(queries.unfollowConference).toHaveBeenCalledWith("reader", { + id: "phones", + court: 194 + }) + expect(button).toHaveAttribute("aria-pressed", "false") + }) + + it("is hidden on a closed conference the reader doesn't follow", async () => { + uid = "reader" + render() + + await waitFor(() => expect(queries.followsTopic).toHaveBeenCalled()) + expect(screen.queryByRole("button")).not.toBeInTheDocument() + }) + + it("lets a follower unfollow a closed conference, and take it back", async () => { + uid = "reader" + followed = true + render() + + const button = await screen.findByRole("button", { pressed: true }) + await userEvent.click(button) + expect(queries.unfollowConference).toHaveBeenCalled() + // Still there, so the unfollow can be undone. + expect(button).toHaveAttribute("aria-pressed", "false") + + await userEvent.click(button) + expect(queries.followConference).toHaveBeenCalled() + }) + + it("is hidden behind the notifications flag", () => { + mockFlags.notifications = false + render() + + expect(screen.queryByRole("button")).not.toBeInTheDocument() + }) +}) diff --git a/components/conference/FollowConference.tsx b/components/conference/FollowConference.tsx new file mode 100644 index 000000000..6b3189374 --- /dev/null +++ b/components/conference/FollowConference.tsx @@ -0,0 +1,114 @@ +import { useTranslation } from "next-i18next" +import { useState } from "react" +import styled from "styled-components" +import { isSitting } from "../../functions/src/shared" +import { useAuth } from "../auth" +import { useFlags } from "../featureFlags" +import { useFollowTopic } from "../shared/FollowButton" +import { + conferenceTopicName, + followConference, + unfollowConference +} from "../shared/FollowingQueries" +import { Bell, BellOff, BellPlus, BellRing } from "./input/icons" +import { ConferenceSummary } from "./types" + +type Followable = Pick + +/** + * Following a conference sends its new input to the reader's newsfeed and + * digest. Once it no longer takes input nothing new can arrive, so the control + * is there only for a reader who already follows it, to unfollow; it stays + * once shown, so an unfollow can be taken back. + */ +export function useConferenceFollow(conference: Followable) { + const uid = useAuth().user?.uid + const { notifications } = useFlags() + const ref = { id: conference.id, court: conference.court } + const follow = useFollowTopic( + conferenceTopicName(conference.court, conference.id), + () => followConference(uid, ref), + () => unfollowConference(uid, ref), + notifications + ) + const [kept, setKept] = useState() + const closedFollowed = + !isSitting(conference) && follow.loaded && follow.following + if (closedFollowed && kept !== conference.id) setKept(conference.id) + // Setting state during render re-renders before commit, so once closedFollowed + // is true, kept already matches. + const visible = + notifications && (isSitting(conference) || kept === conference.id) + return { ...follow, visible } +} + +const Button = styled.button` + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 6px; + padding: 0; + border: 0; + background: none; + color: var(--maple-brand-primary); + font-size: 0.875rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; + + &:hover { + color: var(--maple-brand-primary-strong); + } + + /* Each half swaps to the sign of what a press would do on hover, so the + outcome shows before it happens. */ + .on-hover { + display: none; + } + &:hover .on-hover { + display: inline-flex; + } + &:hover .off-hover { + display: none; + } +` + +/** + * The mockup's Follow control: a word and a bell, blue in both states, since + * it stays a control to press again and the icon and word say which way. + */ +export function FollowConferenceButton({ + following, + toggle +}: { + following: boolean + toggle: () => unknown +}) { + const { t } = useTranslation("conferences") + return ( + + ) +} diff --git a/components/conference/input/icons.tsx b/components/conference/input/icons.tsx index a70800f24..e4bf3defe 100644 --- a/components/conference/input/icons.tsx +++ b/components/conference/input/icons.tsx @@ -182,3 +182,27 @@ export const Minimize2 = (p: Props) => ( ) + +const BellBase = () => +export const Bell = (p: Props) => ( + + + + +) +export const BellRing = (p: Props) => ( + + + + + + +) +export const BellOff = (p: Props) => ( + + + + + + +) diff --git a/components/conference/load.ts b/components/conference/load.ts index 2d92af8d7..421faaf96 100644 --- a/components/conference/load.ts +++ b/components/conference/load.ts @@ -1,5 +1,5 @@ import { districtId } from "functions/src/districts/normalize" -import { currentGeneralCourt, isSitting } from "functions/src/shared" +import { currentGeneralCourt } from "functions/src/shared" import type { Branch } from "../../functions/src/common" import { Conference, @@ -8,7 +8,6 @@ import { listConferences } from "../db/conferences" import { getEventSummary } from "../db/events" -import { flags } from "../featureFlags" import { getMember, getMemberSearchIndex, @@ -18,6 +17,7 @@ import { import { cells } from "./map/geometry" import { byActivity, + isShown, ConfereeView, ConferenceIndexProps, ConferenceLanding, @@ -41,14 +41,9 @@ const summarize = (c: Conference): ConferenceSummary => ({ reportBillId: c.reportBillId ?? null }) -/** Whether the site shows a conference: one still sitting always, one no - * longer taking input only behind the closedConferences flag. */ -const shown = (c: Pick) => - isSitting(c) || flags().closedConferences - /** Every conference in the court the site shows. */ const listShown = async (court: number) => - (await listConferences(court)).filter(shown) + (await listConferences(court)).filter(isShown) /** Conferences as the rail lists them: active first, then by name. */ const railOf = (all: Conference[]) => all.map(summarize).sort(byActivity) @@ -217,7 +212,7 @@ export async function loadConferenceForBill( billId: string ): Promise { const c = await getConferenceForBill(court, billId) - return c && shown(c) ? summarize(c) : null + return c && isShown(c) ? summarize(c) : null } /** The conference a hearing belongs to, by the hearing page's numeric id. */ @@ -230,5 +225,5 @@ export async function loadConferenceForHearing( Number(generalCourtNumber), `hearing-${hearingId}` ) - return c && shown(c) ? summarize(c) : null + return c && isShown(c) ? summarize(c) : null } diff --git a/components/conference/types.ts b/components/conference/types.ts index 80f23c379..6b924b674 100644 --- a/components/conference/types.ts +++ b/components/conference/types.ts @@ -1,11 +1,12 @@ import type { Branch } from "../../functions/src/common" -import { isSitting } from "../../functions/src/shared" +import { conferenceName, isSitting } from "../../functions/src/shared" import type { ConferenceAddressedBy, ConferenceOutcome, ConferenceStatus } from "../../functions/src/conferences/types" import type { EventSummary } from "../db/events" +import { flags } from "../featureFlags" /** The chambers in the order every view shows them: Senate first. */ export const CHAMBERS = ["Senate", "House"] as const @@ -89,10 +90,15 @@ export type ConferenceIndexProps = { } /** The short name where there is one, else the act title. */ -export const conferenceName = (c: Named) => c.name?.trim() || c.title.trim() +export { conferenceName } type Named = { name?: string | null; title: string } +/** Whether the site shows a conference: one still sitting always, one no + * longer taking input only behind the closedConferences flag. */ +export const isShown = (c: Pick) => + isSitting(c) || flags().closedConferences + /** Alphabetical by the name a conference goes by. */ export const byName = (a: Named, b: Named) => conferenceName(a).localeCompare(conferenceName(b)) diff --git a/components/shared/FollowButton.tsx b/components/shared/FollowButton.tsx index 7a09057f5..7aee4a6b7 100644 --- a/components/shared/FollowButton.tsx +++ b/components/shared/FollowButton.tsx @@ -15,7 +15,11 @@ import { profileTopicName, ballotQuestionTopicName, followBallotQuestion, - unfollowBallotQuestion + unfollowBallotQuestion, + ConferenceRef, + conferenceTopicName, + followConference, + unfollowConference } from "./FollowingQueries" import { FollowContext } from "./FollowContext" import { Modal } from "components/bootstrap" @@ -70,6 +74,54 @@ export function FollowBillButton({ ) } +/** + * Whether the reader follows a topic, shared through FollowContext so every + * control for the topic agrees, and a toggle that sends a signed-out reader + * to log in first. `loaded` is false until a signed-in reader's status is + * read. + */ +export function useFollowTopic( + topicName: string, + followAction: () => Promise, + unfollowAction: () => Promise, + /** False skips reading the follow status, for a control that can't show. */ + enabled = true +) { + const uid = useAuth().user?.uid + const router = useRouter() + const { followStatus, setFollowStatus } = useContext(FollowContext) + + useEffect(() => { + if (!uid || !enabled) return + followsTopic(uid, topicName).then(result => + setFollowStatus(prev => ({ ...prev, [topicName]: result })) + ) + }, [uid, topicName, setFollowStatus, enabled]) + + const follow = async () => { + await followAction() + setFollowStatus(prev => ({ ...prev, [topicName]: true })) + } + + const unfollow = async () => { + await unfollowAction() + setFollowStatus(prev => ({ ...prev, [topicName]: false })) + } + + const following = !!uid && !!followStatus[topicName] + const loaded = !uid || topicName in followStatus + + const toggle = () => { + if (!uid) { + router.push(`/login?redirect=${encodeURIComponent(router.asPath)}`) + return + } + return following ? unfollow() : follow() + } + + return { following, loaded, follow, unfollow, toggle } +} + export const BaseFollowButton = ({ topicName, followAction, @@ -89,45 +141,19 @@ export const BaseFollowButton = ({ }) => { const { t } = useTranslation(["profile"]) - const { user } = useAuth() - const uid = user?.uid - const router = useRouter() - - const { followStatus, setFollowStatus } = useContext(FollowContext) const [modalAction, setModalAction] = useState<"follow" | "unfollow" | null>( null ) + const { + following: isFollowing, + follow: FollowClick, + unfollow: UnfollowClick, + toggle + } = useFollowTopic(topicName, followAction, unfollowAction) - useEffect(() => { - if (!uid) return - followsTopic(uid, topicName).then(result => - setFollowStatus(prev => ({ ...prev, [topicName]: result })) - ) - }, [uid, topicName, setFollowStatus]) - - const FollowClick = async () => { - await followAction() - setFollowStatus(prev => ({ ...prev, [topicName]: true })) - } - - const UnfollowClick = async () => { - await unfollowAction() - setFollowStatus(prev => ({ ...prev, [topicName]: false })) - } - - const isFollowing = followStatus[topicName] - const text = isFollowing ? t("button.following") : t("button.follow") - const checkmark = isFollowing ? ( - - ) : null const handleClick = (event: any) => { event.preventDefault() - if (!uid) { - const currentPath = router.asPath - router.push(`/login?redirect=${encodeURIComponent(currentPath)}`) - return - } - isFollowing ? UnfollowClick() : FollowClick() + toggle() } return ( @@ -222,3 +248,21 @@ export function FollowBallotQuestionButton({ /> ) } + +export function FollowConferenceTopicButton({ + conference, + confirmUnfollow +}: { + conference: ConferenceRef + confirmUnfollow?: boolean +}) { + const uid = useAuth().user?.uid + return ( + followConference(uid, conference)} + unfollowAction={() => unfollowConference(uid, conference)} + confirmUnfollow={confirmUnfollow} + /> + ) +} diff --git a/components/shared/FollowingQueries.tsx b/components/shared/FollowingQueries.tsx index 30c488a7c..7609eff6e 100644 --- a/components/shared/FollowingQueries.tsx +++ b/components/shared/FollowingQueries.tsx @@ -14,6 +14,11 @@ export const billTopicName = (court: number, billId: string) => export const profileTopicName = (profileId: string) => `testimony-${profileId}` export const ballotQuestionTopicName = (court: number, id: string) => `ballot-question-${court}-${id}` +export const conferenceTopicName = (court: number, id: string) => + `conference-${court}-${id}` + +/** What following a conference needs to know of it. */ +export type ConferenceRef = { id: string; court: number } export const followBill = async (uid: string | undefined, bill: Bill) => { const topicName = billTopicName(bill.court, bill.id) @@ -82,6 +87,28 @@ export const unfollowBallotQuestion = async ( ballotQuestionTopicName(ballotQuestion.court, ballotQuestion.id) ) +export const followConference = async ( + uid: string | undefined, + conference: ConferenceRef +) => { + const topicName = conferenceTopicName(conference.court, conference.id) + await setDoc(getTopicRef(uid, topicName), { + topicName, + uid, + conferenceLookup: { + conferenceId: conference.id, + court: conference.court + }, + type: "conference" + }) +} + +export const unfollowConference = async ( + uid: string | undefined, + conference: ConferenceRef +) => + await unfollowTopic(uid, conferenceTopicName(conference.court, conference.id)) + export const followsTopic = async ( uid: string | undefined, topicName: string diff --git a/functions/src/email/digestEmail.handlebars b/functions/src/email/digestEmail.handlebars index 017d59c95..6e1478deb 100644 --- a/functions/src/email/digestEmail.handlebars +++ b/functions/src/email/digestEmail.handlebars @@ -9,6 +9,8 @@ {{> bills }} + {{> conferences }} + {{> ballotQuestions }} {{> users }} diff --git a/functions/src/email/digestEmail.test.ts b/functions/src/email/digestEmail.test.ts new file mode 100644 index 000000000..92399ca74 --- /dev/null +++ b/functions/src/email/digestEmail.test.ts @@ -0,0 +1,81 @@ +import * as fs from "fs" +import * as handlebars from "handlebars" +import * as path from "path" +import { NotificationEmailDigest } from "../notifications/emailTypes" +import { registerHelpers, registerPartials } from "./handlebarsHelpers" + +const render = (digest: NotificationEmailDigest) => { + registerHelpers() + registerPartials(path.join(__dirname, "partials")) + const source = fs.readFileSync( + path.join(__dirname, "digestEmail.handlebars"), + "utf8" + ) + return handlebars.compile(source)(digest) +} + +const empty: NotificationEmailDigest = { + notificationFrequency: "Weekly", + startDate: new Date("2025-02-22"), + endDate: new Date("2025-03-01"), + bills: [], + numBillsWithNewTestimony: 0, + users: [], + numUsersWithNewTestimony: 0, + ballotQuestions: [], + numBallotQuestionsWithNewTestimony: 0, + conferences: [], + numConferencesWithNewTestimony: 0 +} + +describe("digest email, conferences", () => { + it("links a followed conference and words its stances", () => { + const html = render({ + ...empty, + conferences: [ + { + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + court: "194", + newTestimonyCount: 3, + stances: [ + { stance: "Please pass something", count: 2 }, + { stance: "Don't pass anything", count: 1 } + ] + } + ], + numConferencesWithNewTestimony: 1 + }) + + expect(html).toContain("Conference Committees") + expect(html).toContain( + "https://mapletestimony.org/conferences/194/phones#input" + ) + expect(html).toContain("Phone-Free Schools") + expect(html).toContain("New Testimonies") + expect(html).toMatch(/2<\/td>\s*]*>Please pass something/) + expect(html).toContain("Don't pass anything") + }) + + it("leaves the section out for a reader following no conference", () => { + expect(render(empty)).not.toContain("Conference Committees") + }) + + it("points to the rest past four conferences", () => { + const conference = { + conferenceId: "c", + conferenceName: "C", + court: "194", + newTestimonyCount: 1, + stances: [] + } + const html = render({ + ...empty, + conferences: [conference, conference, conference, conference], + numConferencesWithNewTestimony: 6 + }) + expect(html).toContain( + "2 other conference committees you follow received testimony" + ) + }) +}) diff --git a/functions/src/email/partials/conferences/conference.handlebars b/functions/src/email/partials/conferences/conference.handlebars new file mode 100644 index 000000000..a60b37a4c --- /dev/null +++ b/functions/src/email/partials/conferences/conference.handlebars @@ -0,0 +1,34 @@ +{{!-- A followed committee of conference. Its stances are in words: the + position images are bill stances --}} + diff --git a/functions/src/email/partials/conferences/conferences.handlebars b/functions/src/email/partials/conferences/conferences.handlebars new file mode 100644 index 000000000..b3010bb14 --- /dev/null +++ b/functions/src/email/partials/conferences/conferences.handlebars @@ -0,0 +1,44 @@ +{{!-- Only for readers following a conference with new testimony: unlike + bills, there is no empty state, so other readers' digests don't change --}} +{{#if conferences.length}} +
    +
    +
    + Conference Committees +
    +
    +
    +
    + {{#each conferences}} + {{> conference}} + {{/each}} +
    +
    + {{#ifGreaterThan numConferencesWithNewTestimony 4}} +
    +
    + {{#ifGreaterThan numConferencesWithNewTestimony 5}} + {{minusFour numConferencesWithNewTestimony}} other conference committees you follow received testimony since your last update + {{else}} + {{minusFour numConferencesWithNewTestimony}} other conference committee you follow received testimony since your last update + {{/ifGreaterThan}} +
    + +
    + {{/ifGreaterThan}} +
    +
    +{{/if}} diff --git a/functions/src/email/partials/index.ts b/functions/src/email/partials/index.ts index f72d99a2c..1cc372e97 100644 --- a/functions/src/email/partials/index.ts +++ b/functions/src/email/partials/index.ts @@ -2,7 +2,9 @@ import ballotQuestion from "./ballotQuestions/ballotQuestion.handlebars" import ballotQuestions from "./ballotQuestions/ballotQuestions.handlebars" import bill from "./bills/bill.handlebars" import bills from "./bills/bills.handlebars" +import conference from "./conferences/conference.handlebars" import conferenceItem from "./users/conferenceItem.handlebars" +import conferences from "./conferences/conferences.handlebars" import footer from "./footer.handlebars" import header from "./header.handlebars" import newsFeedLink from "./newsFeedLink.handlebars" @@ -15,7 +17,9 @@ export const partials = { ballotQuestions, bill, bills, + conference, conferenceItem, + conferences, footer, header, newsFeedLink, diff --git a/functions/src/notifications/deliverNotifications.test.ts b/functions/src/notifications/deliverNotifications.test.ts index 9213de33c..1a8d7ef83 100644 --- a/functions/src/notifications/deliverNotifications.test.ts +++ b/functions/src/notifications/deliverNotifications.test.ts @@ -1,4 +1,5 @@ -import { buildDigestData, CONFERENCE_STANCES } from "./deliverNotifications" +import { buildDigestData } from "./deliverNotifications" +import { CONFERENCE_STANCES } from "./emailTypes" import { Timestamp } from "../firebase" // Mock firebase module @@ -352,6 +353,102 @@ describe("buildDigestData — conference testimony", () => { }) }) +describe("buildDigestData — conferences", () => { + const conferenceDoc = (overrides: object) => ({ + type: "testimony", + isBillMatch: false, + isUserMatch: false, + isBallotQuestionMatch: false, + isConferenceMatch: true, + billId: "S2581", + header: "An Act relative to phones", + court: "194", + position: "passSomething", + timestamp: now, + authorUid: "author1", + subheader: "Alice", + bodyText: "", + testimonyId: "t1", + userRole: "user", + delivered: false, + ballotQuestionId: null, + ballotQuestionCourt: null, + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + ...overrides + }) + + it("counts a followed conference's testimony by stance, every stance listed", async () => { + setupCollection([ + conferenceDoc({ testimonyId: "t1", position: "passSomething" }), + conferenceDoc({ testimonyId: "t2", position: "passSomething" }), + conferenceDoc({ testimonyId: "t3", position: "passNothing" }) + ]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences).toEqual([ + { + conferenceId: "phones", + conferenceName: "Phone-Free Schools", + court: "194", + newTestimonyCount: 3, + stances: [ + { stance: "Please pass something", count: 2 }, + { stance: "Pass the Senate version", count: 0 }, + { stance: "Pass the House version", count: 0 }, + { stance: "Don't pass anything", count: 1 } + ] + } + ]) + expect(result.numConferencesWithNewTestimony).toBe(1) + // A conference-only reader has something to send, and nothing else. + expect(result.numBillsWithNewTestimony).toBe(0) + expect(result.numUsersWithNewTestimony).toBe(0) + }) + + it("names the conference from the bill's title when it has no name", async () => { + setupCollection([conferenceDoc({ conferenceName: null })]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences[0].conferenceName).toBe( + "An Act relative to phones" + ) + }) + + it("caps conferences at 4, most testimony first, and reports the full count", async () => { + setupCollection([ + ...Array.from({ length: 6 }, (_, i) => + conferenceDoc({ testimonyId: `t${i}`, conferenceId: `c${i}` }) + ), + conferenceDoc({ testimonyId: "extra", conferenceId: "c5" }) + ]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.conferences).toHaveLength(4) + expect(result.conferences[0].conferenceId).toBe("c5") + expect(result.numConferencesWithNewTestimony).toBe(6) + }) + + it("shows testimony matching both the conference and its author in each section", async () => { + setupCollection([conferenceDoc({ isUserMatch: true })]) + + const result = await buildDigestData("uid1", now as any, "Weekly") + + expect(result.numConferencesWithNewTestimony).toBe(1) + expect(result.users[0].bills).toEqual([ + { + billId: "S2581", + court: "194", + conferenceId: "phones", + stance: "Please pass something" + } + ]) + }) +}) + describe("CONFERENCE_STANCES", () => { it("says what the site says", () => { const { input } = require("../../../public/locales/en/conferences.json") diff --git a/functions/src/notifications/deliverNotifications.ts b/functions/src/notifications/deliverNotifications.ts index f7c159c0b..239d731ac 100644 --- a/functions/src/notifications/deliverNotifications.ts +++ b/functions/src/notifications/deliverNotifications.ts @@ -13,6 +13,8 @@ import { BallotQuestionDigest, BillDigest, BillResult, + CONFERENCE_STANCES, + ConferenceDigest, NotificationEmailDigest, Position, UserDigest @@ -26,16 +28,9 @@ const NUM_BILLS_TO_DISPLAY = 4 const NUM_USERS_TO_DISPLAY = 4 const NUM_TESTIMONIES_TO_DISPLAY = 6 const NUM_BALLOT_QUESTIONS_TO_DISPLAY = 4 +const NUM_CONFERENCES_TO_DISPLAY = 4 const EMAIL_TEMPLATE_PATH = "../email/digestEmail.handlebars" -// The site's wording, conferences input.position.*.long; a test holds them equal. -export const CONFERENCE_STANCES: Record = { - passSomething: "Please pass something", - passSenateVersion: "Pass the Senate version", - passHouseVersion: "Pass the House version", - passNothing: "Don't pass anything" -} - const path = require("path") const getVerifiedUserEmail = async (uid: string) => { @@ -117,7 +112,8 @@ const deliverEmailNotifications = async () => { if ( digestData.numBillsWithNewTestimony === 0 && digestData.numUsersWithNewTestimony === 0 && - digestData.numBallotQuestionsWithNewTestimony === 0 + digestData.numBallotQuestionsWithNewTestimony === 0 && + digestData.numConferencesWithNewTestimony === 0 ) { console.log( `No new notifications for ${profileDoc.id} - not sending email` @@ -181,10 +177,14 @@ export const buildDigestData = async ( const billsById: { [billId: string]: BillDigest } = {} const usersById: { [userId: string]: UserDigest } = {} const ballotQuestionsById: { [bqId: string]: BallotQuestionDigest } = {} + const conferencesById: { [conferenceId: string]: ConferenceDigest } = {} notificationsSnapshot.docs.forEach(notificationDoc => { const { notification } = notificationDoc.data() as TestimonySubmissionNotificationFields + // Read only for conference testimony; a bill position has no stance. + const stance = + CONFERENCE_STANCES[notification.position as ConferencePosition] if (notification.isBillMatch) { if (billsById[notification.billId]) { @@ -223,8 +223,7 @@ export const buildDigestData = async ( ...(notification.conferenceId ? { conferenceId: notification.conferenceId, - stance: - CONFERENCE_STANCES[notification.position as ConferencePosition] + stance } : { position: notification.position as Position }) } @@ -270,6 +269,25 @@ export const buildDigestData = async ( } } } + + if (notification.isConferenceMatch && notification.conferenceId) { + const id = notification.conferenceId + const conference = (conferencesById[id] ??= { + conferenceId: id, + conferenceName: notification.conferenceName || notification.header, + court: notification.court, + newTestimonyCount: 0, + stances: Object.values(CONFERENCE_STANCES).map(stance => ({ + stance, + count: 0 + })) + }) + const row = conference.stances.find(s => s.stance === stance) + if (row) row.count++ + else + console.error(`Unknown conference position: ${notification.position}`) + conference.newTestimonyCount++ + } }) const bills = Object.values(billsById).sort((a, b) => { @@ -299,6 +317,10 @@ export const buildDigestData = async ( ) }) + const conferences = Object.values(conferencesById).sort( + (a, b) => b.newTestimonyCount - a.newTestimonyCount + ) + return { notificationFrequency, startDate: startDate.toDate(), @@ -308,7 +330,9 @@ export const buildDigestData = async ( users: users.slice(0, NUM_USERS_TO_DISPLAY), numUsersWithNewTestimony: users.length, ballotQuestions: ballotQuestions.slice(0, NUM_BALLOT_QUESTIONS_TO_DISPLAY), - numBallotQuestionsWithNewTestimony: ballotQuestions.length + numBallotQuestionsWithNewTestimony: ballotQuestions.length, + conferences: conferences.slice(0, NUM_CONFERENCES_TO_DISPLAY), + numConferencesWithNewTestimony: conferences.length } } diff --git a/functions/src/notifications/emailTypes.ts b/functions/src/notifications/emailTypes.ts index ae6fe0bd8..1d0622232 100644 --- a/functions/src/notifications/emailTypes.ts +++ b/functions/src/notifications/emailTypes.ts @@ -1,4 +1,13 @@ import { Frequency } from "../auth/types" +import type { ConferencePosition } from "../testimony/types" + +// The site's wording, conferences input.position.*.long; a test holds them equal. +export const CONFERENCE_STANCES: Record = { + passSomething: "Please pass something", + passSenateVersion: "Pass the Senate version", + passHouseVersion: "Pass the House version", + passNothing: "Don't pass anything" +} export type BillDigest = { billId: string @@ -31,6 +40,15 @@ export type BallotQuestionDigest = { neutralCount: number opposeCount: number } +/** Testimony on a followed committee of conference, counted by stance. */ +export type ConferenceDigest = { + conferenceId: string + conferenceName: string + court: string + newTestimonyCount: number + /** Every stance, in the site's order, so digests compare at a glance. */ + stances: { stance: string; count: number }[] +} export type NotificationEmailDigest = { notificationFrequency: Frequency startDate: Date @@ -41,4 +59,6 @@ export type NotificationEmailDigest = { numUsersWithNewTestimony: number ballotQuestions: BallotQuestionDigest[] // cap of 4 numBallotQuestionsWithNewTestimony: number + conferences: ConferenceDigest[] // cap of 4 + numConferencesWithNewTestimony: number } diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts index 682ac1441..8e8288dc3 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts @@ -11,7 +11,8 @@ jest.mock("firebase-functions/logger", () => ({ // The Testimony type needs the admin package's own Timestamp class. jest.mock("../firebase", () => ({ db: { - collection: jest.fn() + collection: jest.fn(), + doc: jest.fn() }, Timestamp: jest.requireActual("firebase-admin/firestore").Timestamp })) @@ -57,6 +58,12 @@ const makeEvent = (before: object | null, after: object | null) => ({ params: { userId: "author-uid", testimonyId: "testimony-id" } }) +/** The conference document the event names its conference from. */ +const setupConference = (data: object | undefined) => + mockDb.doc.mockReturnValue({ + get: jest.fn().mockResolvedValue({ data: () => data }) + }) + beforeEach(() => { jest.clearAllMocks() }) @@ -81,6 +88,63 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { ) }) + it("names the conference on conference testimony", async () => { + setupCollection(true) + setupConference({ name: "Phone-Free Schools", title: "An Act relative" }) + + const event = makeEvent( + null, + makeTestimony({ conferenceId: "phones", position: "passSomething" }) + ) + await populateTestimonySubmissionNotificationEventsHandler(event as any) + + expect(mockDb.doc).toHaveBeenCalledWith( + "/generalCourts/194/conferences/phones" + ) + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + conferenceId: "phones", + conferenceName: "Phone-Free Schools" + }) + ) + }) + + it("falls back to the conference's title, then to no name", async () => { + setupCollection(true) + setupConference({ title: "An Act relative to phones" }) + const testimony = makeTestimony({ + conferenceId: "phones", + position: "passSomething" + }) + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, testimony) as any + ) + expect(mockAdd).toHaveBeenLastCalledWith( + expect.objectContaining({ conferenceName: "An Act relative to phones" }) + ) + + setupConference(undefined) + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, testimony) as any + ) + expect(mockAdd).toHaveBeenLastCalledWith( + expect.objectContaining({ conferenceId: "phones", conferenceName: null }) + ) + }) + + it("names no conference on bill testimony", async () => { + setupCollection(true) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, makeTestimony()) as any + ) + + expect(mockDb.doc).not.toHaveBeenCalled() + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ conferenceId: null, conferenceName: null }) + ) + }) + it.each(["court", "authorUid", "billId", "position", "content", "version"])( "logs an error and skips new testimony missing %s", async field => { diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts index 943c60a70..737a58fab 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts @@ -12,9 +12,21 @@ import { } from "firebase-functions/v2/firestore" import * as logger from "firebase-functions/logger" import { db, Timestamp } from "../firebase" +import { conferenceName } from "../shared" import { Testimony } from "../testimony/types" import { TestimonySubmissionNotification } from "./types" +/** The conference's name for headings, as the site shows it: its short name, + * falling back to its title. Null when the document is missing, so the + * notification still goes out. */ +const conferenceNameOf = async (court: number, conferenceId: string) => { + const snap = await db + .doc(`/generalCourts/${court}/conferences/${conferenceId}`) + .get() + const data = snap.data() + return (data && conferenceName(data)) || null +} + export const populateTestimonySubmissionNotificationEventsHandler = async ( event: FirestoreEvent< Change | undefined, @@ -49,6 +61,7 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( const testimony = checked.value const bqId = testimony.ballotQuestionId ?? null + const conferenceId = testimony.conferenceId ?? null const newNotificationEvent: TestimonySubmissionNotification = { type: "testimony", @@ -67,7 +80,10 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( ballotQuestionId: bqId, ballotQuestionCourt: bqId ? testimony.court : null, - conferenceId: testimony.conferenceId ?? null, + conferenceId, + conferenceName: conferenceId + ? await conferenceNameOf(testimony.court, conferenceId) + : null, updateTime: Timestamp.now() } diff --git a/functions/src/notifications/publishNotifications.ts b/functions/src/notifications/publishNotifications.ts index 9b86f34db..a4d382b32 100644 --- a/functions/src/notifications/publishNotifications.ts +++ b/functions/src/notifications/publishNotifications.ts @@ -69,13 +69,15 @@ const createNotificationFields = ( isBillMatch: false, isUserMatch: false, isBallotQuestionMatch: false, + isConferenceMatch: false, delivered: false, authorUid: entity.userId, testimonyId: entity.testimonyId, userRole: entity.userRole, ballotQuestionId: entity.ballotQuestionId ?? null, ballotQuestionCourt: entity.ballotQuestionCourt ?? null, - conferenceId: entity.conferenceId ?? null + conferenceId: entity.conferenceId ?? null, + conferenceName: entity.conferenceName ?? null }, createdAt: Timestamp.now() } @@ -141,11 +143,11 @@ export const publishNotifications = onDocumentWritten( ] : [ `testimony-${topic.userId}`, - // Conference testimony is kept off its bill, so the bill's - // followers don't hear of it. - ...(topic.conferenceId - ? [] - : [`bill-${topic.billCourt}-${topic.billId}`]), + // Conference testimony goes to the conference's followers and + // is kept off its bill, so the bill's followers don't hear of it. + topic.conferenceId + ? `conference-${topic.billCourt}-${topic.conferenceId}` + : `bill-${topic.billCourt}-${topic.billId}`, ...(topic.ballotQuestionId && topic.ballotQuestionCourt != null ? [ `ballot-question-${topic.ballotQuestionCourt}-${topic.ballotQuestionId}` @@ -179,6 +181,8 @@ export const publishNotifications = onDocumentWritten( users[uid].notification.isUserMatch = true } else if (type === "ballotQuestion") { users[uid].notification.isBallotQuestionMatch = true + } else if (type === "conference") { + users[uid].notification.isConferenceMatch = true } else { users[uid].notification.isBillMatch = true } diff --git a/functions/src/notifications/types.ts b/functions/src/notifications/types.ts index 33c4aa5e3..f9920e84c 100644 --- a/functions/src/notifications/types.ts +++ b/functions/src/notifications/types.ts @@ -27,6 +27,8 @@ export type TestimonySubmissionNotification = Notification & { ballotQuestionId?: string | null ballotQuestionCourt?: number | null conferenceId?: string | null + /** The conference's name for headings, set with conferenceId. */ + conferenceName?: string | null } export interface TestimonySubmissionNotificationFields { @@ -43,6 +45,8 @@ export interface TestimonySubmissionNotificationFields { isBillMatch: boolean isUserMatch: boolean isBallotQuestionMatch: boolean + /** The reader follows the conference the testimony was filed on. */ + isConferenceMatch?: boolean delivered: boolean testimonyId: string userRole: string @@ -50,6 +54,7 @@ export interface TestimonySubmissionNotificationFields { ballotQuestionId?: string | null ballotQuestionCourt?: number | null conferenceId?: string | null + conferenceName?: string | null } createdAt: FirebaseFirestore.Timestamp } diff --git a/functions/src/shared/conferences.ts b/functions/src/shared/conferences.ts index 0f065be6a..97954b8d1 100644 --- a/functions/src/shared/conferences.ts +++ b/functions/src/shared/conferences.ts @@ -15,3 +15,9 @@ export const isSitting = (c: Pick) => * existed counts as covered. */ export const takesTestimony = (c: Pick) => isSitting(c) && c.covered !== false + +type Named = { name?: string | null; title?: string | null } + +/** The short name where there is one, else the act title. */ +export const conferenceName = (c: Named) => + c.name?.trim() || c.title?.trim() || "" diff --git a/functions/src/subscriptions/types.ts b/functions/src/subscriptions/types.ts index 6a45ff3ac..90c03308b 100644 --- a/functions/src/subscriptions/types.ts +++ b/functions/src/subscriptions/types.ts @@ -16,4 +16,9 @@ export interface TopicSubscription { ballotQuestionId: string court: number } + + conferenceLookup?: { + conferenceId: string + court: number + } } diff --git a/public/locales/en/conferences.json b/public/locales/en/conferences.json index f123156d0..af4cd1111 100644 --- a/public/locales/en/conferences.json +++ b/public/locales/en/conferences.json @@ -286,5 +286,10 @@ "cosign_closed": "This conference committee is no longer taking input, so your cosign could not be filed.", "fill_window": "Fill the window", "leave_full": "Leave full screen" + }, + "follow": { + "follow": "Follow", + "following": "Following", + "unfollow": "Unfollow" } } diff --git a/public/locales/en/editProfile.json b/public/locales/en/editProfile.json index 2bc1b45be..29374735e 100644 --- a/public/locales/en/editProfile.json +++ b/public/locales/en/editProfile.json @@ -27,6 +27,7 @@ "follow": { "bills": "Bills I Follow", "ballotQuestions": "Ballot Questions I Follow", + "conferences": "Conference Committees I Follow", "orgs": "Users I Follow", "your_followers": "Your Followers", "unfollow": "Unfollow", diff --git a/scripts/firebase-admin/sendTestEmail.ts b/scripts/firebase-admin/sendTestEmail.ts index 1c6dfc1c7..a63b571a6 100644 --- a/scripts/firebase-admin/sendTestEmail.ts +++ b/scripts/firebase-admin/sendTestEmail.ts @@ -201,7 +201,9 @@ const generateTestData = ( numBillsWithNewTestimony: numBills, numUsersWithNewTestimony: numUsers, ballotQuestions: [], - numBallotQuestionsWithNewTestimony: 0 + numBallotQuestionsWithNewTestimony: 0, + conferences: [], + numConferencesWithNewTestimony: 0 } } diff --git a/stories/emailTemplates/NotificationDigestEmail.stories.tsx b/stories/emailTemplates/NotificationDigestEmail.stories.tsx index dc3d1d5c5..96355cd3d 100644 --- a/stories/emailTemplates/NotificationDigestEmail.stories.tsx +++ b/stories/emailTemplates/NotificationDigestEmail.stories.tsx @@ -4,6 +4,8 @@ import { EmailTemplateRenderer } from "./EmailTemplateRenderer" import { BillDigest, BillResult, + CONFERENCE_STANCES, + ConferenceDigest, NotificationEmailDigest, UserDigest } from "functions/src/notifications/emailTypes" @@ -145,10 +147,34 @@ const users = [ generateTestUserData("QDPq42rNB0O6wqVzfMmDHmNE8sN3", "Iranout Ofnameideas", 3) ] +// Invented conference committees, counted by stance. +const conferenceStances = (counts: number[]) => + Object.values(CONFERENCE_STANCES).map((stance, i) => ({ + stance, + count: counts[i] + })) +const conferences: ConferenceDigest[] = [ + { + conferenceId: "quiet-libraries", + conferenceName: "Quiet Libraries", + court: "194", + newTestimonyCount: 6, + stances: conferenceStances([3, 1, 0, 2]) + }, + { + conferenceId: "harbor-ferries", + conferenceName: "Harbor Ferries", + court: "194", + newTestimonyCount: 1, + stances: conferenceStances([0, 0, 1, 0]) + } +] + const generateTestData = ( frequency: Exclude, numBills: number, - numUsers: number + numUsers: number, + numConferences = 0 ): NotificationEmailDigest => { const endDateDay = { Monthly: "30", @@ -164,7 +190,9 @@ const generateTestData = ( numBillsWithNewTestimony: numBills, numUsersWithNewTestimony: numUsers, ballotQuestions: [], - numBallotQuestionsWithNewTestimony: 0 + numBallotQuestionsWithNewTestimony: 0, + conferences: conferences.slice(0, numConferences), + numConferencesWithNewTestimony: numConferences } } @@ -190,6 +218,10 @@ export const OnlyBills: Story = createDigestStory( generateTestData("Weekly", 5, 0) ) +export const OnlyConferences: Story = createDigestStory( + generateTestData("Weekly", 0, 0, 2) +) + export const OnlyUsers: Story = createDigestStory( generateTestData("Weekly", 0, 5) ) diff --git a/tests/integration/common.ts b/tests/integration/common.ts index 0a9c59489..4371fdb2b 100644 --- a/tests/integration/common.ts +++ b/tests/integration/common.ts @@ -91,6 +91,36 @@ export async function deleteOrg(id: string) { export const createFakeBill = () => createNewBill().then(b => b) +/** A conference on `billId`, taking input unless `fields` say otherwise. */ +export async function createConference( + billId: string, + fields: Record = {} +) { + const id = `conference-${nanoid()}`.toLowerCase() + await testDb + .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`) + .set({ + id, + court: currentGeneralCourt, + title: "Test conference", + senateBillId: billId, + houseBillId: "H1", + canonicalBillId: billId, + conferees: [], + status: "appointed", + hearingIds: [], + differences: [], + similarities: [], + testimonyCount: 0, + passNothingCount: 0, + passSomethingCount: 0, + passSenateVersionCount: 0, + passHouseVersionCount: 0, + ...fields + }) + return id +} + export async function expectPermissionDenied(work: Promise) { const warn = console.warn console.warn = jest.fn() diff --git a/tests/integration/conferenceFollowing.test.ts b/tests/integration/conferenceFollowing.test.ts new file mode 100644 index 000000000..f637b8015 --- /dev/null +++ b/tests/integration/conferenceFollowing.test.ts @@ -0,0 +1,129 @@ +import { waitFor } from "@testing-library/react" +import { currentGeneralCourt } from "functions/src/shared" +import { doc, setDoc } from "firebase/firestore" +import { httpsCallable } from "firebase/functions" +import { nanoid } from "nanoid" +import { firestore, functions } from "../../components/firebase" +import { + followConference, + unfollowConference +} from "../../components/shared/FollowingQueries" +import { terminateFirebase, testDb } from "../testUtils" +import { + createConference, + createFakeBill, + deleteBill, + expectPermissionDenied, + signInUser1, + signInUser2 +} from "./common" + +afterAll(terminateFirebase) + +const court = currentGeneralCourt +const publishTestimony = httpsCallable< + { draftId: string }, + { publicationId: string } +>(functions, "publishTestimonyV2") + +const subscription = (uid: string, topicName: string) => + testDb.doc(`/users/${uid}/activeTopicSubscriptions/${topicName}`) + +const feedFor = (uid: string, testimonyId: string) => + testDb + .collection(`/users/${uid}/userNotificationFeed`) + .where("notification.testimonyId", "==", testimonyId) + .get() + +describe("following a conference", () => { + let billId: string + let conferenceId: string + let topicName: string + + beforeEach(async () => { + billId = await createFakeBill() + conferenceId = await createConference(billId, { + title: "An Act relative to quiet libraries", + name: "Quiet Libraries" + }) + topicName = `conference-${court}-${conferenceId}` + }) + + afterEach(async () => { + await Promise.all([ + testDb + .doc(`/generalCourts/${court}/conferences/${conferenceId}`) + .delete(), + deleteBill(billId) + ]) + }) + + it("writes a conference subscription, and unfollowing deletes it", async () => { + const { uid } = await signInUser1() + const conference = { id: conferenceId, court } + + await followConference(uid, conference) + expect((await subscription(uid, topicName).get()).data()).toEqual({ + topicName, + uid, + type: "conference", + conferenceLookup: { conferenceId, court } + }) + + await unfollowConference(uid, conference) + expect((await subscription(uid, topicName).get()).exists).toBe(false) + }) + + it("won't let a user follow for someone else", async () => { + const user1 = await signInUser1() + await signInUser2() + + await expectPermissionDenied( + followConference(user1.uid, { id: conferenceId, court }) + ) + }) + + it("sends new input on the conference to its followers, and only them", async () => { + const follower = await signInUser2() + await followConference(follower.uid, { id: conferenceId, court }) + + const author = await signInUser1() + const draftId = nanoid() + await setDoc( + doc(firestore, `/users/${author.uid}/draftTestimony/${draftId}`), + { + billId, + court, + content: "Keep the libraries quiet.", + position: "passSenateVersion", + attachmentId: null, + ballotQuestionId: null, + conferenceId + } + ) + const { + data: { publicationId } + } = await publishTestimony({ draftId }) + + await waitFor( + async () => { + const feed = await feedFor(follower.uid, publicationId) + expect(feed.size).toBe(1) + expect(feed.docs[0].data().notification).toMatchObject({ + type: "testimony", + conferenceId, + conferenceName: "Quiet Libraries", + isConferenceMatch: true, + isBillMatch: false, + isUserMatch: false, + position: "passSenateVersion" + }) + }, + { timeout: 20000, interval: 500 } + ) + // The author hears nothing of their own input. + expect((await feedFor(author.uid, publicationId)).size).toBe(0) + + await subscription(follower.uid, topicName).delete() + }, 30000) +}) diff --git a/tests/integration/testimony.test.ts b/tests/integration/testimony.test.ts index 2287727b5..2a4609ec0 100644 --- a/tests/integration/testimony.test.ts +++ b/tests/integration/testimony.test.ts @@ -21,7 +21,8 @@ import { signInUser1, signInUser2, signInUser3, - signInUser4 + signInUser4, + createConference } from "./common" type BaseTestimony = { @@ -727,7 +728,7 @@ describe("publishTestimony", () => { it.each(["reportFiled", "enacted", "dissolved"])( "Refuses testimony on a conference that is %s", async status => { - const closedId = await createConference(billId, status) + const closedId = await createConference(billId, { status }) const { draftId: conferenceDraftId } = await createConferenceDraft( uid, billId, @@ -1621,31 +1622,6 @@ async function createDraftAttachment(uid: string, id: string, content: string) { /** A conference whose canonical bill is `billId`, with its counts zeroed. It * takes testimony only while `status` is appointed. */ -async function createConference(billId: string, status = "appointed") { - const id = `conference-${nanoid()}`.toLowerCase() - await testDb - .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`) - .set({ - id, - court: currentGeneralCourt, - title: "Test conference", - senateBillId: billId, - houseBillId: "H1", - canonicalBillId: billId, - conferees: [], - status, - hearingIds: [], - differences: [], - similarities: [], - testimonyCount: 0, - passNothingCount: 0, - passSomethingCount: 0, - passSenateVersionCount: 0, - passHouseVersionCount: 0 - }) - return id -} - async function getConference(id: string) { const doc = await testDb .doc(`/generalCourts/${currentGeneralCourt}/conferences/${id}`) From ba2e4425b303bb9c6d65773ac735f2571e2c6ae1 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Fri, 13 Nov 2026 09:50:33 -0500 Subject: [PATCH 5/8] Tag a cosign in the newsfeed and quote the input it cosigns A cosign reached the newsfeed as its own words alone, so one posted without a line of its own showed as an empty quote, and none said what was cosigned. The card now tags it Cosigned, shows the cosigner's line when they wrote one, then "Cosigned {author}'s input:" with that input quoted under it, in the order the cosign's email to legislators uses. The notification event carries the cosigned input's id, author and text, read once when the cosign is published, so the newsfeed reads nothing more. It is the input as it read then; a later edit does not reach feed items. When the cosigned input is gone the field is empty and the notification still goes out. Earlier feed items have no such field and look as before. Verified: yarn check-types, yarn lint, yarn check-formatting, yarn test and yarn test:website pass, with new tests for the event on a cosign, on a cosign whose input is gone and on input that cosigns nothing, and for the card with a line of its own, without one and on input that cosigns nothing. Against the Docker emulators, conferenceFollowing.test.ts passes with a new case: a cosign with no line reaches the conference's follower with the cosigned input attached. Not verified: the card in a browser. Co-Authored-By: Claude Opus 5.5 --- components/Newsfeed/Newsfeed.tsx | 1 + components/Newsfeed/NotificationProps.tsx | 9 +++ components/NewsfeedCard/NewsfeedCard.test.tsx | 60 ++++++++++++++ components/NewsfeedCard/NewsfeedCard.tsx | 3 + components/NewsfeedCard/NewsfeedCardBody.tsx | 38 +++++++-- ...timonySubmissionNotificationEvents.test.ts | 78 +++++++++++++++++++ ...teTestimonySubmissionNotificationEvents.ts | 33 +++++++- .../src/notifications/publishNotifications.ts | 3 +- functions/src/notifications/types.ts | 12 +++ public/locales/en/common.json | 2 + tests/integration/conferenceFollowing.test.ts | 57 +++++++++++++- 11 files changed, 282 insertions(+), 14 deletions(-) diff --git a/components/Newsfeed/Newsfeed.tsx b/components/Newsfeed/Newsfeed.tsx index 2fa6afa60..f41109148 100644 --- a/components/Newsfeed/Newsfeed.tsx +++ b/components/Newsfeed/Newsfeed.tsx @@ -253,6 +253,7 @@ export default function Newsfeed() { bodyText={element.bodyText} conferenceId={element.conferenceId} conferenceName={element.conferenceName} + cosignOf={element.cosignOf} court={element.court} header={element.header} isBillMatch={element.isBillMatch} diff --git a/components/Newsfeed/NotificationProps.tsx b/components/Newsfeed/NotificationProps.tsx index ada6198f9..cc25b86a9 100644 --- a/components/Newsfeed/NotificationProps.tsx +++ b/components/Newsfeed/NotificationProps.tsx @@ -1,5 +1,13 @@ import { Timestamp } from "firebase/firestore" +/** The testimony a cosign cosigns, as it read when the cosign was published. */ +export type CosignOf = { + id: string + authorUid: string + authorName: string + content: string +} + export type NotificationProps = { authorUid: string // Testimony author billId: string @@ -27,6 +35,7 @@ export type NotificationProps = { conferenceId?: string | null conferenceName?: string | null isConferenceMatch?: boolean // is subscribed to the conference + cosignOf?: CosignOf | null // set when the testimony cosigns another } export type Notifications = NotificationProps[] diff --git a/components/NewsfeedCard/NewsfeedCard.test.tsx b/components/NewsfeedCard/NewsfeedCard.test.tsx index 09b234652..cec44e781 100644 --- a/components/NewsfeedCard/NewsfeedCard.test.tsx +++ b/components/NewsfeedCard/NewsfeedCard.test.tsx @@ -141,6 +141,66 @@ describe("NewsfeedCard", () => { ) }) + describe("a cosign", () => { + const cosignOf = { + id: "lead", + authorUid: "author2", + authorName: "Grace", + content: "Pass a strong final bill this session." + } + const quoted = () => document.querySelector("blockquote") + + it("is tagged, with its own line first and the cosigned input under it", () => { + render( + + ) + + expect(screen.getByText("newsfeed.cosigned")).toBeInTheDocument() + const line = screen.getByText('"As a parent, this matters to me."') + const credit = screen.getByText("newsfeed.cosignedInput") + expect( + line.compareDocumentPosition(credit) & Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy() + expect(quoted()).toHaveTextContent(cosignOf.content) + }) + + it("shows the cosigned input without an empty quote when it has no line", () => { + render( + + ) + + expect(screen.getByText("newsfeed.cosigned")).toBeInTheDocument() + expect(screen.queryByText('""')).toBeNull() + expect(screen.getByText("newsfeed.cosignedInput")).toBeInTheDocument() + expect(quoted()).toHaveTextContent(cosignOf.content) + }) + + it("isn't tagged on input that cosigns nothing", () => { + render( + + ) + + expect(screen.queryByText("newsfeed.cosigned")).toBeNull() + expect(quoted()).toBeNull() + }) + }) + it("keeps bill testimony on its bill, testimony page and thumbs", () => { render() diff --git a/components/NewsfeedCard/NewsfeedCard.tsx b/components/NewsfeedCard/NewsfeedCard.tsx index 765945843..1cb3e97ef 100644 --- a/components/NewsfeedCard/NewsfeedCard.tsx +++ b/components/NewsfeedCard/NewsfeedCard.tsx @@ -10,6 +10,7 @@ import { } from "./NewsfeedCardBody" import NewsfeedCardTitle from "./NewsfeedCardTitle" import { maple } from "components/links" +import { CosignOf } from "../Newsfeed/NotificationProps" const Container = styled.div` max-width: 700px; @@ -23,6 +24,7 @@ export const NewsfeedCard = (props: { bodyText: string conferenceId?: string | null conferenceName?: string | null + cosignOf?: CosignOf | null court?: string header: string isBallotQuestionMatch?: boolean @@ -75,6 +77,7 @@ export const NewsfeedCard = (props: { { /** Testimony on a committee of conference: the stance is the conference * page's chip, and the card leads to the conference, not the bill. */ +/** + * Conference input in the feed. A cosign is tagged, with the cosigner's own + * line first when they wrote one and the input they cosigned quoted under it, + * as the email to their legislators sets it out. + */ export const NewsfeedConferenceTestimonyCardBody = (props: { billText?: string conferenceHref: string + cosignOf?: CosignOf | null position?: string text?: string timestamp?: string }) => { - const { billText, conferenceHref, text, timestamp } = props + const { billText, conferenceHref, cosignOf, text, timestamp } = props const { t } = useTranslation("common") return ( @@ -215,13 +222,28 @@ export const NewsfeedConferenceTestimonyCardBody = (props: { {billText}
    - {ConferencePosition.guard(props.position) && ( - +
    + {ConferencePosition.guard(props.position) && ( + + )} + {cosignOf && {t("newsfeed.cosigned")}} +
    + {(text || !cosignOf) && ( + {`"${truncateText( + text, + 600 + )}"`} + )} + {cosignOf && ( + <> +
    + {t("newsfeed.cosignedInput", { name: cosignOf.authorName })} +
    +
    + {truncateText(cosignOf.content, 600)} +
    + )} - {`"${truncateText( - text, - 600 - )}"`}
    diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts index 8e8288dc3..f4f896af4 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts @@ -64,6 +64,12 @@ const setupConference = (data: object | undefined) => get: jest.fn().mockResolvedValue({ data: () => data }) }) +/** Documents the handler reads, by path; any other path is missing. */ +const setupDocs = (byPath: Record) => + mockDb.doc.mockImplementation((path: string) => ({ + get: jest.fn().mockResolvedValue({ data: () => byPath[path] }) + })) + beforeEach(() => { jest.clearAllMocks() }) @@ -145,6 +151,78 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { ) }) + describe("on a cosign", () => { + const cosign = (content = "") => + makeTestimony({ + conferenceId: "phones", + position: "passSomething", + content, + cosignOfId: "lead-id", + cosignOfAuthorUid: "lead-uid" + }) + + it("carries the input it cosigns, credited to its author", async () => { + setupCollection(true) + setupDocs({ + "/generalCourts/194/conferences/phones": { name: "Phone-Free Schools" }, + "/users/lead-uid/publishedTestimony/lead-id": { + fullName: "Lead Author", + content: "Keep phones out of classrooms." + } + }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign()) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + conferenceName: "Phone-Free Schools", + testimonyContent: "", + cosignOf: { + id: "lead-id", + authorUid: "lead-uid", + authorName: "Lead Author", + content: "Keep phones out of classrooms." + } + }) + ) + }) + + it("still goes out when the cosigned input is gone", async () => { + setupCollection(true) + setupDocs({}) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign("My own line.")) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + testimonyContent: "My own line.", + cosignOf: null + }) + ) + }) + }) + + it("reads nothing more for testimony that cosigns nothing", async () => { + setupCollection(true) + setupConference({ name: "Phone-Free Schools" }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent( + null, + makeTestimony({ conferenceId: "phones", position: "passSomething" }) + ) as any + ) + + expect(mockDb.doc).toHaveBeenCalledTimes(1) + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ cosignOf: null }) + ) + }) + it.each(["court", "authorUid", "billId", "position", "content", "version"])( "logs an error and skips new testimony missing %s", async field => { diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts index 737a58fab..7bfbc8658 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts @@ -14,7 +14,7 @@ import * as logger from "firebase-functions/logger" import { db, Timestamp } from "../firebase" import { conferenceName } from "../shared" import { Testimony } from "../testimony/types" -import { TestimonySubmissionNotification } from "./types" +import { CosignOf, TestimonySubmissionNotification } from "./types" /** The conference's name for headings, as the site shows it: its short name, * falling back to its title. Null when the document is missing, so the @@ -27,6 +27,28 @@ const conferenceNameOf = async (court: number, conferenceId: string) => { return (data && conferenceName(data)) || null } +/** What a cosign cosigns, as it reads now, for the newsfeed to quote. Null + * when the testimony isn't a cosign or the cosigned testimony is gone, so the + * notification still goes out. */ +const cosignOfIn = async ({ + cosignOfId, + cosignOfAuthorUid +}: Testimony): Promise => { + if (!cosignOfId || !cosignOfAuthorUid) return null + const snap = await db + .doc(`/users/${cosignOfAuthorUid}/publishedTestimony/${cosignOfId}`) + .get() + const data = snap.data() + return data + ? { + id: cosignOfId, + authorUid: cosignOfAuthorUid, + authorName: data.fullName ?? "", + content: data.content ?? "" + } + : null +} + export const populateTestimonySubmissionNotificationEventsHandler = async ( event: FirestoreEvent< Change | undefined, @@ -62,6 +84,10 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( const bqId = testimony.ballotQuestionId ?? null const conferenceId = testimony.conferenceId ?? null + const [conferenceName, cosignOf] = await Promise.all([ + conferenceId ? conferenceNameOf(testimony.court, conferenceId) : null, + cosignOfIn(testimony) + ]) const newNotificationEvent: TestimonySubmissionNotification = { type: "testimony", @@ -81,9 +107,8 @@ export const populateTestimonySubmissionNotificationEventsHandler = async ( ballotQuestionId: bqId, ballotQuestionCourt: bqId ? testimony.court : null, conferenceId, - conferenceName: conferenceId - ? await conferenceNameOf(testimony.court, conferenceId) - : null, + conferenceName, + cosignOf, updateTime: Timestamp.now() } diff --git a/functions/src/notifications/publishNotifications.ts b/functions/src/notifications/publishNotifications.ts index a4d382b32..9f72315bd 100644 --- a/functions/src/notifications/publishNotifications.ts +++ b/functions/src/notifications/publishNotifications.ts @@ -77,7 +77,8 @@ const createNotificationFields = ( ballotQuestionId: entity.ballotQuestionId ?? null, ballotQuestionCourt: entity.ballotQuestionCourt ?? null, conferenceId: entity.conferenceId ?? null, - conferenceName: entity.conferenceName ?? null + conferenceName: entity.conferenceName ?? null, + cosignOf: entity.cosignOf ?? null }, createdAt: Timestamp.now() } diff --git a/functions/src/notifications/types.ts b/functions/src/notifications/types.ts index f9920e84c..d46dd2d87 100644 --- a/functions/src/notifications/types.ts +++ b/functions/src/notifications/types.ts @@ -15,6 +15,15 @@ export type BillHistoryUpdateNotification = Notification & { billHistory: BillHistory } +/** The testimony a cosign cosigns, as it read when the cosign was published, + * so the newsfeed can quote it. */ +export type CosignOf = { + id: string + authorUid: string + authorName: string + content: string +} + export type TestimonySubmissionNotification = Notification & { type: "testimony" userId: string @@ -29,6 +38,8 @@ export type TestimonySubmissionNotification = Notification & { conferenceId?: string | null /** The conference's name for headings, set with conferenceId. */ conferenceName?: string | null + /** Set on a cosign whose cosigned testimony still exists. */ + cosignOf?: CosignOf | null } export interface TestimonySubmissionNotificationFields { @@ -55,6 +66,7 @@ export interface TestimonySubmissionNotificationFields { ballotQuestionCourt?: number | null conferenceId?: string | null conferenceName?: string | null + cosignOf?: CosignOf | null } createdAt: FirebaseFirestore.Timestamp } diff --git a/public/locales/en/common.json b/public/locales/en/common.json index c21e04dda..e347e142f 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -160,6 +160,8 @@ "notFollowEither": "You do not follow either", "conferenceInput": " gave input to the conference committee on ", "conferenceInputPost": "Input Posted ", + "cosigned": "Cosigned", + "cosignedInput": "Cosigned {{name}}’s input:", "endorsed": " endorsed ", "endorsementPost": "Endorsement Posted ", "follow": "You follow ", diff --git a/tests/integration/conferenceFollowing.test.ts b/tests/integration/conferenceFollowing.test.ts index f637b8015..07a779bb5 100644 --- a/tests/integration/conferenceFollowing.test.ts +++ b/tests/integration/conferenceFollowing.test.ts @@ -15,7 +15,8 @@ import { deleteBill, expectPermissionDenied, signInUser1, - signInUser2 + signInUser2, + signInUser3 } from "./common" afterAll(terminateFirebase) @@ -126,4 +127,58 @@ describe("following a conference", () => { await subscription(follower.uid, topicName).delete() }, 30000) + + it("sends a cosign with the input it cosigns, even with no line of its own", async () => { + const follower = await signInUser2() + await followConference(follower.uid, { id: conferenceId, court }) + + const author = await signInUser1() + const lead = await publishInput(author.uid, { + content: "Keep the libraries quiet.", + position: "passSenateVersion" + }) + + const cosigner = await signInUser3() + const cosign = await publishInput(cosigner.uid, { + content: "", + position: "passSenateVersion", + cosignOfId: lead, + cosignOfAuthorUid: author.uid + }) + + await waitFor( + async () => { + const feed = await feedFor(follower.uid, cosign) + expect(feed.size).toBe(1) + expect(feed.docs[0].data().notification).toMatchObject({ + isConferenceMatch: true, + bodyText: "", + cosignOf: { + id: lead, + authorUid: author.uid, + authorName: expect.any(String), + content: "Keep the libraries quiet." + } + }) + }, + { timeout: 20000, interval: 500 } + ) + + await subscription(follower.uid, topicName).delete() + }, 30000) + + /** Publishes input on the conference as the signed-in user. */ + async function publishInput(uid: string, fields: Record) { + const draftId = nanoid() + await setDoc(doc(firestore, `/users/${uid}/draftTestimony/${draftId}`), { + billId, + court, + attachmentId: null, + ballotQuestionId: null, + conferenceId, + ...fields + }) + const { data } = await publishTestimony({ draftId }) + return data.publicationId + } }) From a3aaf6005bb8acad9ee0daa322e3272f7047887b Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Fri, 13 Nov 2026 11:54:04 -0500 Subject: [PATCH 6/8] Say a cosign was cosigned in its newsfeed heading, and name its author as the site does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A cosign's card still opened with "gave input to the conference committee", which read as input of its own; it now says "cosigned input to the conference committee". Other conference input keeps its wording. The quoted author is named as the conference page names them, by full name or else display name, so an organization without a full name no longer reads "Cosigned ’s input:". That rule moves into the code the site and the functions share. The event now carries only the author's name and the first 600 characters of the cosigned input, the most the card shows, instead of the whole input copied onto every follower's feed item; the id and author uid it also carried were never read. Verified: yarn check-types, yarn lint, yarn check-formatting, yarn test and yarn test:website pass, with new tests for the heading, the display name fallback and the trimming. Against the Docker emulators, conferenceFollowing.test.ts passes. The new heading on the newsfeed at desktop and phone width, in a browser. Not verified: a trimmed quote or a display-name author in a browser. Co-Authored-By: Claude Opus 5.5 --- components/Newsfeed/NotificationProps.tsx | 9 +--- components/NewsfeedCard/NewsfeedCard.test.tsx | 5 ++- components/NewsfeedCard/NewsfeedCard.tsx | 1 + components/NewsfeedCard/NewsfeedCardBody.tsx | 12 +++--- components/NewsfeedCard/NewsfeedCardTitle.tsx | 27 ++++++++---- components/conference/input/accounts.ts | 7 ++-- ...timonySubmissionNotificationEvents.test.ts | 42 +++++++++++++------ ...teTestimonySubmissionNotificationEvents.ts | 23 ++++++---- functions/src/notifications/types.ts | 4 +- functions/src/shared/names.ts | 6 +++ public/locales/en/common.json | 1 + tests/integration/conferenceFollowing.test.ts | 22 ++-------- 12 files changed, 90 insertions(+), 69 deletions(-) diff --git a/components/Newsfeed/NotificationProps.tsx b/components/Newsfeed/NotificationProps.tsx index cc25b86a9..63787cc14 100644 --- a/components/Newsfeed/NotificationProps.tsx +++ b/components/Newsfeed/NotificationProps.tsx @@ -1,12 +1,7 @@ import { Timestamp } from "firebase/firestore" +import type { CosignOf } from "functions/src/notifications/types" -/** The testimony a cosign cosigns, as it read when the cosign was published. */ -export type CosignOf = { - id: string - authorUid: string - authorName: string - content: string -} +export type { CosignOf } export type NotificationProps = { authorUid: string // Testimony author diff --git a/components/NewsfeedCard/NewsfeedCard.test.tsx b/components/NewsfeedCard/NewsfeedCard.test.tsx index cec44e781..984a709e7 100644 --- a/components/NewsfeedCard/NewsfeedCard.test.tsx +++ b/components/NewsfeedCard/NewsfeedCard.test.tsx @@ -143,8 +143,6 @@ describe("NewsfeedCard", () => { describe("a cosign", () => { const cosignOf = { - id: "lead", - authorUid: "author2", authorName: "Grace", content: "Pass a strong final bill this session." } @@ -162,6 +160,8 @@ describe("NewsfeedCard", () => { ) expect(screen.getByText("newsfeed.cosigned")).toBeInTheDocument() + expect(screen.getByText("newsfeed.conferenceCosign")).toBeInTheDocument() + expect(screen.queryByText("newsfeed.conferenceInput")).toBeNull() const line = screen.getByText('"As a parent, this matters to me."') const credit = screen.getByText("newsfeed.cosignedInput") expect( @@ -197,6 +197,7 @@ describe("NewsfeedCard", () => { ) expect(screen.queryByText("newsfeed.cosigned")).toBeNull() + expect(screen.getByText("newsfeed.conferenceInput")).toBeInTheDocument() expect(quoted()).toBeNull() }) }) diff --git a/components/NewsfeedCard/NewsfeedCard.tsx b/components/NewsfeedCard/NewsfeedCard.tsx index 1cb3e97ef..055f55022 100644 --- a/components/NewsfeedCard/NewsfeedCard.tsx +++ b/components/NewsfeedCard/NewsfeedCard.tsx @@ -50,6 +50,7 @@ export const NewsfeedCard = (props: { billId={props.billId} conferenceHref={conferenceHref} conferenceName={props.conferenceName} + cosigned={!!props.cosignOf} court={props.court} header={props.header} isBallotQuestionMatch={props.isBallotQuestionMatch} diff --git a/components/NewsfeedCard/NewsfeedCardBody.tsx b/components/NewsfeedCard/NewsfeedCardBody.tsx index e67cdaa97..6686464cb 100644 --- a/components/NewsfeedCard/NewsfeedCardBody.tsx +++ b/components/NewsfeedCard/NewsfeedCardBody.tsx @@ -197,12 +197,12 @@ export const NewsfeedTestimonyCardBody = (props: NewsfeedCardBodyProps) => { ) } -/** Testimony on a committee of conference: the stance is the conference - * page's chip, and the card leads to the conference, not the bill. */ /** - * Conference input in the feed. A cosign is tagged, with the cosigner's own - * line first when they wrote one and the input they cosigned quoted under it, - * as the email to their legislators sets it out. + * Testimony on a committee of conference: the stance is the conference page's + * chip, and the card leads to the conference, not the bill. A cosign is + * tagged, with the cosigner's own line first when they wrote one and the + * input they cosigned quoted under it, as the email to their legislators sets + * it out. That quote arrives already trimmed. */ export const NewsfeedConferenceTestimonyCardBody = (props: { billText?: string @@ -240,7 +240,7 @@ export const NewsfeedConferenceTestimonyCardBody = (props: { {t("newsfeed.cosignedInput", { name: cosignOf.authorName })}
    - {truncateText(cosignOf.content, 600)} + {cosignOf.content}
    )} diff --git a/components/NewsfeedCard/NewsfeedCardTitle.tsx b/components/NewsfeedCard/NewsfeedCardTitle.tsx index 60cd40824..673329d84 100644 --- a/components/NewsfeedCard/NewsfeedCardTitle.tsx +++ b/components/NewsfeedCard/NewsfeedCardTitle.tsx @@ -11,6 +11,8 @@ interface NewsfeedCardTitleProps { conferenceHref?: string /** The conference's name, for a reader who follows it */ conferenceName?: string | null + /** The testimony cosigns another */ + cosigned?: boolean court?: string header?: string subheader?: string @@ -32,6 +34,7 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { billId, conferenceHref, conferenceName, + cosigned, court, header, isBillMatch, @@ -52,6 +55,7 @@ export const NewsfeedCardTitle = (props: NewsfeedCardTitleProps) => { authorUid={authorUid} billId={billId} conferenceHref={conferenceHref} + cosigned={cosigned} court={court} header={header} subheader={subheader} @@ -109,9 +113,22 @@ const CardHeaderImg = (props: NewsfeedCardTitleProps) => { } const CardTitleHeadline = (props: NewsfeedCardTitleProps) => { - const { authorUid, billId, conferenceHref, court, header, subheader, type } = - props + const { + authorUid, + billId, + conferenceHref, + cosigned, + court, + header, + subheader, + type + } = props const { t } = useTranslation("common") + const action = !conferenceHref + ? "newsfeed.endorsed" + : cosigned + ? "newsfeed.conferenceCosign" + : "newsfeed.conferenceInput" switch (type) { case "testimony": @@ -125,11 +142,7 @@ const CardTitleHeadline = (props: NewsfeedCardTitleProps) => { {subheader} - {t( - conferenceHref - ? "newsfeed.conferenceInput" - : "newsfeed.endorsed" - )} + {t(action)} {billId && {formatBillId(billId)}} diff --git a/components/conference/input/accounts.ts b/components/conference/input/accounts.ts index e998fc16d..023b8146a 100644 --- a/components/conference/input/accounts.ts +++ b/components/conference/input/accounts.ts @@ -1,5 +1,8 @@ import { Role } from "functions/src/auth/types" +/** The name an entry is shown under. */ +export { nameOf } from "functions/src/shared" + export type AccountType = "individual" | "organization" | "government" export const accountTypes: AccountType[] = [ @@ -15,10 +18,6 @@ export const accountTypeOf = (role: Role): AccountType => ? "government" : "individual" -/** The name an entry is shown under. */ -export const nameOf = (t: { fullName?: string; authorDisplayName: string }) => - t.fullName || t.authorDisplayName - /** Two letters for the disc, where the account has no picture of its own. */ export const initialsOf = (name: string) => name diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts index f4f896af4..ea84fe718 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.test.ts @@ -58,18 +58,14 @@ const makeEvent = (before: object | null, after: object | null) => ({ params: { userId: "author-uid", testimonyId: "testimony-id" } }) -/** The conference document the event names its conference from. */ -const setupConference = (data: object | undefined) => - mockDb.doc.mockReturnValue({ - get: jest.fn().mockResolvedValue({ data: () => data }) - }) - /** Documents the handler reads, by path; any other path is missing. */ -const setupDocs = (byPath: Record) => +const setupDocs = (byPath: Record) => mockDb.doc.mockImplementation((path: string) => ({ get: jest.fn().mockResolvedValue({ data: () => byPath[path] }) })) +const PHONES = "/generalCourts/194/conferences/phones" + beforeEach(() => { jest.clearAllMocks() }) @@ -96,7 +92,9 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { it("names the conference on conference testimony", async () => { setupCollection(true) - setupConference({ name: "Phone-Free Schools", title: "An Act relative" }) + setupDocs({ + [PHONES]: { name: "Phone-Free Schools", title: "An Act relative" } + }) const event = makeEvent( null, @@ -117,7 +115,7 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { it("falls back to the conference's title, then to no name", async () => { setupCollection(true) - setupConference({ title: "An Act relative to phones" }) + setupDocs({ [PHONES]: { title: "An Act relative to phones" } }) const testimony = makeTestimony({ conferenceId: "phones", position: "passSomething" @@ -129,7 +127,7 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { expect.objectContaining({ conferenceName: "An Act relative to phones" }) ) - setupConference(undefined) + setupDocs({ [PHONES]: undefined }) await populateTestimonySubmissionNotificationEventsHandler( makeEvent(null, testimony) as any ) @@ -180,8 +178,6 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { conferenceName: "Phone-Free Schools", testimonyContent: "", cosignOf: { - id: "lead-id", - authorUid: "lead-uid", authorName: "Lead Author", content: "Keep phones out of classrooms." } @@ -189,6 +185,26 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { ) }) + it("names an author without a full name as the site does, and trims a long input", async () => { + setupCollection(true) + setupDocs({ + "/users/lead-uid/publishedTestimony/lead-id": { + authorDisplayName: "Lead Org", + content: "x".repeat(700) + } + }) + + await populateTestimonySubmissionNotificationEventsHandler( + makeEvent(null, cosign()) as any + ) + + expect(mockAdd).toHaveBeenCalledWith( + expect.objectContaining({ + cosignOf: { authorName: "Lead Org", content: `${"x".repeat(600)}...` } + }) + ) + }) + it("still goes out when the cosigned input is gone", async () => { setupCollection(true) setupDocs({}) @@ -208,7 +224,7 @@ describe("populateTestimonySubmissionNotificationEventsHandler", () => { it("reads nothing more for testimony that cosigns nothing", async () => { setupCollection(true) - setupConference({ name: "Phone-Free Schools" }) + setupDocs({ [PHONES]: { name: "Phone-Free Schools" } }) await populateTestimonySubmissionNotificationEventsHandler( makeEvent( diff --git a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts index 7bfbc8658..94353e3d0 100644 --- a/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts +++ b/functions/src/notifications/populateTestimonySubmissionNotificationEvents.ts @@ -12,7 +12,7 @@ import { } from "firebase-functions/v2/firestore" import * as logger from "firebase-functions/logger" import { db, Timestamp } from "../firebase" -import { conferenceName } from "../shared" +import { conferenceName, nameOf } from "../shared" import { Testimony } from "../testimony/types" import { CosignOf, TestimonySubmissionNotification } from "./types" @@ -27,6 +27,10 @@ const conferenceNameOf = async (court: number, conferenceId: string) => { return (data && conferenceName(data)) || null } +/** The most of a cosigned input the newsfeed quotes; the event, and each + * follower's copy of it, carries no more. */ +const QUOTE_LENGTH = 600 + /** What a cosign cosigns, as it reads now, for the newsfeed to quote. Null * when the testimony isn't a cosign or the cosigned testimony is gone, so the * notification still goes out. */ @@ -39,14 +43,15 @@ const cosignOfIn = async ({ .doc(`/users/${cosignOfAuthorUid}/publishedTestimony/${cosignOfId}`) .get() const data = snap.data() - return data - ? { - id: cosignOfId, - authorUid: cosignOfAuthorUid, - authorName: data.fullName ?? "", - content: data.content ?? "" - } - : null + if (!data) return null + const content: string = data.content ?? "" + return { + authorName: nameOf(data), + content: + content.length > QUOTE_LENGTH + ? `${content.slice(0, QUOTE_LENGTH)}...` + : content + } } export const populateTestimonySubmissionNotificationEventsHandler = async ( diff --git a/functions/src/notifications/types.ts b/functions/src/notifications/types.ts index d46dd2d87..a939c0b36 100644 --- a/functions/src/notifications/types.ts +++ b/functions/src/notifications/types.ts @@ -16,10 +16,8 @@ export type BillHistoryUpdateNotification = Notification & { } /** The testimony a cosign cosigns, as it read when the cosign was published, - * so the newsfeed can quote it. */ + * so the newsfeed can quote it: its author's name and its first words. */ export type CosignOf = { - id: string - authorUid: string authorName: string content: string } diff --git a/functions/src/shared/names.ts b/functions/src/shared/names.ts index 3bba53745..914afe8e4 100644 --- a/functions/src/shared/names.ts +++ b/functions/src/shared/names.ts @@ -21,3 +21,9 @@ export function splitMemberName(fullName: string) { export const extractLastName = (fullName: string) => splitMemberName(fullName).surname + +/** The name a piece of testimony is shown under. */ +export const nameOf = (t: { + fullName?: string | null + authorDisplayName?: string | null +}) => t.fullName || t.authorDisplayName || "" diff --git a/public/locales/en/common.json b/public/locales/en/common.json index e347e142f..a5e54ac6b 100644 --- a/public/locales/en/common.json +++ b/public/locales/en/common.json @@ -159,6 +159,7 @@ "and": " and ", "notFollowEither": "You do not follow either", "conferenceInput": " gave input to the conference committee on ", + "conferenceCosign": " cosigned input to the conference committee on ", "conferenceInputPost": "Input Posted ", "cosigned": "Cosigned", "cosignedInput": "Cosigned {{name}}’s input:", diff --git a/tests/integration/conferenceFollowing.test.ts b/tests/integration/conferenceFollowing.test.ts index 07a779bb5..d8f51bc35 100644 --- a/tests/integration/conferenceFollowing.test.ts +++ b/tests/integration/conferenceFollowing.test.ts @@ -89,22 +89,10 @@ describe("following a conference", () => { await followConference(follower.uid, { id: conferenceId, court }) const author = await signInUser1() - const draftId = nanoid() - await setDoc( - doc(firestore, `/users/${author.uid}/draftTestimony/${draftId}`), - { - billId, - court, - content: "Keep the libraries quiet.", - position: "passSenateVersion", - attachmentId: null, - ballotQuestionId: null, - conferenceId - } - ) - const { - data: { publicationId } - } = await publishTestimony({ draftId }) + const publicationId = await publishInput(author.uid, { + content: "Keep the libraries quiet.", + position: "passSenateVersion" + }) await waitFor( async () => { @@ -154,8 +142,6 @@ describe("following a conference", () => { isConferenceMatch: true, bodyText: "", cosignOf: { - id: lead, - authorUid: author.uid, authorName: expect.any(String), content: "Keep the libraries quiet." } From 8f608a5e995f28e2c2b1d54c82373e8944810435 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Fri, 13 Nov 2026 14:08:28 -0500 Subject: [PATCH 7/8] Count a conference's new input as input in the email digest The digest's Conference Committees cards counted new input as "New Testimonies", the bills' and people's word, while the site calls what readers give a conference committee input. They now say "New Input", the same for one item or many. People's cards keep their wording. Verified: yarn test and prettier pass, with the digest template test now checking for "New Input". A digest rendered from the emulators, read in a browser, shows "New Input" on each conference card. Co-Authored-By: Claude Opus 5.5 --- functions/src/email/digestEmail.test.ts | 2 +- .../src/email/partials/conferences/conference.handlebars | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/functions/src/email/digestEmail.test.ts b/functions/src/email/digestEmail.test.ts index 92399ca74..4b2157920 100644 --- a/functions/src/email/digestEmail.test.ts +++ b/functions/src/email/digestEmail.test.ts @@ -52,7 +52,7 @@ describe("digest email, conferences", () => { "https://mapletestimony.org/conferences/194/phones#input" ) expect(html).toContain("Phone-Free Schools") - expect(html).toContain("New Testimonies") + expect(html).toContain("New Input") expect(html).toMatch(/2<\/td>\s*]*>Please pass something/) expect(html).toContain("Don't pass anything") }) diff --git a/functions/src/email/partials/conferences/conference.handlebars b/functions/src/email/partials/conferences/conference.handlebars index a60b37a4c..e553ecfff 100644 --- a/functions/src/email/partials/conferences/conference.handlebars +++ b/functions/src/email/partials/conferences/conference.handlebars @@ -14,11 +14,7 @@
    - {{#ifGreaterThan this.newTestimonyCount 1}} - New Testimonies - {{else}} - New Testimony - {{/ifGreaterThan}} + New Input
    From 593e050edf94ab0fcd0f6c416a6a637039958825 Mon Sep 17 00:00:00 2001 From: Dante Sanchez Date: Fri, 13 Nov 2026 14:15:36 -0500 Subject: [PATCH 8/8] Say "New Inputs" for more than one, and "received input", in the digest's conference section A conference card in the digest read "New Input" whatever the count. It now says "New Inputs" for more than one and "New Input" for one, as people's cards switch between "New Testimonies" and "New Testimony". The line under the section for readers following more than four now says the other conference committees "received input" rather than "received testimony". Verified: yarn test and prettier pass, with the digest template test checking both forms of the label and the new line. A digest rendered from the emulators, read in a browser, shows both changes. Co-Authored-By: Claude Opus 5.5 --- functions/src/email/digestEmail.test.ts | 6 ++++-- .../src/email/partials/conferences/conference.handlebars | 6 +++++- .../src/email/partials/conferences/conferences.handlebars | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/functions/src/email/digestEmail.test.ts b/functions/src/email/digestEmail.test.ts index 4b2157920..4b2d0c609 100644 --- a/functions/src/email/digestEmail.test.ts +++ b/functions/src/email/digestEmail.test.ts @@ -52,7 +52,7 @@ describe("digest email, conferences", () => { "https://mapletestimony.org/conferences/194/phones#input" ) expect(html).toContain("Phone-Free Schools") - expect(html).toContain("New Input") + expect(html).toContain("New Inputs") expect(html).toMatch(/2<\/td>\s*]*>Please pass something/) expect(html).toContain("Don't pass anything") }) @@ -75,7 +75,9 @@ describe("digest email, conferences", () => { numConferencesWithNewTestimony: 6 }) expect(html).toContain( - "2 other conference committees you follow received testimony" + "2 other conference committees you follow received input" ) + expect(html).toContain("New Input") + expect(html).not.toContain("New Inputs") }) }) diff --git a/functions/src/email/partials/conferences/conference.handlebars b/functions/src/email/partials/conferences/conference.handlebars index e553ecfff..41e52fb79 100644 --- a/functions/src/email/partials/conferences/conference.handlebars +++ b/functions/src/email/partials/conferences/conference.handlebars @@ -14,7 +14,11 @@
    - New Input + {{#ifGreaterThan this.newTestimonyCount 1}} + New Inputs + {{else}} + New Input + {{/ifGreaterThan}}
    diff --git a/functions/src/email/partials/conferences/conferences.handlebars b/functions/src/email/partials/conferences/conferences.handlebars index b3010bb14..e541c344b 100644 --- a/functions/src/email/partials/conferences/conferences.handlebars +++ b/functions/src/email/partials/conferences/conferences.handlebars @@ -20,9 +20,9 @@ border-radius: 12px; margin-bottom: 36px;">
    {{#ifGreaterThan numConferencesWithNewTestimony 5}} - {{minusFour numConferencesWithNewTestimony}} other conference committees you follow received testimony since your last update + {{minusFour numConferencesWithNewTestimony}} other conference committees you follow received input since your last update {{else}} - {{minusFour numConferencesWithNewTestimony}} other conference committee you follow received testimony since your last update + {{minusFour numConferencesWithNewTestimony}} other conference committee you follow received input since your last update {{/ifGreaterThan}}