From 72eb2d8c3d0bb2d3f18c7646f8239bcb9b9a150b Mon Sep 17 00:00:00 2001 From: Richie Cahill Date: Tue, 28 Apr 2026 22:50:53 -0400 Subject: [PATCH] adding website --- pipelines/web/__init__.py | 1 + pipelines/web/db.py | 31 + pipelines/web/main.py | 589 ++++++++ pipelines/web/repository.py | 670 +++++++++ pipelines/web/scoring.py | 100 ++ pipelines/web/static/styles.css | 1215 +++++++++++++++++ pipelines/web/static/vendor/htmx.min.js | 1 + pipelines/web/svg.py | 231 ++++ pipelines/web/templates/base.html | 40 + pipelines/web/templates/compare.html | 87 ++ pipelines/web/templates/dashboard.html | 30 + pipelines/web/templates/legislators.html | 148 ++ pipelines/web/templates/login.html | 45 + pipelines/web/templates/partials/_chart.html | 30 + .../web/templates/partials/_dashboard.html | 25 + .../templates/partials/_issue_filters.html | 46 + .../partials/_legislator_suggestions.html | 11 + .../web/templates/partials/_rankings.html | 61 + pipelines/web/templates/setup_error.html | 15 + 19 files changed, 3376 insertions(+) create mode 100644 pipelines/web/__init__.py create mode 100644 pipelines/web/db.py create mode 100644 pipelines/web/main.py create mode 100644 pipelines/web/repository.py create mode 100644 pipelines/web/scoring.py create mode 100644 pipelines/web/static/styles.css create mode 100644 pipelines/web/static/vendor/htmx.min.js create mode 100644 pipelines/web/svg.py create mode 100644 pipelines/web/templates/base.html create mode 100644 pipelines/web/templates/compare.html create mode 100644 pipelines/web/templates/dashboard.html create mode 100644 pipelines/web/templates/legislators.html create mode 100644 pipelines/web/templates/login.html create mode 100644 pipelines/web/templates/partials/_chart.html create mode 100644 pipelines/web/templates/partials/_dashboard.html create mode 100644 pipelines/web/templates/partials/_issue_filters.html create mode 100644 pipelines/web/templates/partials/_legislator_suggestions.html create mode 100644 pipelines/web/templates/partials/_rankings.html create mode 100644 pipelines/web/templates/setup_error.html diff --git a/pipelines/web/__init__.py b/pipelines/web/__init__.py new file mode 100644 index 0000000..3e59862 --- /dev/null +++ b/pipelines/web/__init__.py @@ -0,0 +1 @@ +"""FastAPI HTMX front end for the legislative database.""" diff --git a/pipelines/web/db.py b/pipelines/web/db.py new file mode 100644 index 0000000..4687d03 --- /dev/null +++ b/pipelines/web/db.py @@ -0,0 +1,31 @@ +"""Database access for the FastAPI web app.""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from functools import lru_cache + +from sqlalchemy.engine import Engine +from sqlalchemy.orm import Session + +from pipelines.orm.common import get_postgres_engine + + +@lru_cache(maxsize=1) +def get_engine() -> Engine: + """Return the lazily-created DATA_SCIENCE_DEV SQLAlchemy engine.""" + return get_postgres_engine(name="DATA_SCIENCE_DEV") + + +def validate_database_connection() -> None: + """Fail fast if the configured DATA_SCIENCE_DEV database is unavailable.""" + with get_engine().connect(): + pass + + +@contextmanager +def session_scope() -> Iterator[Session]: + """Yield a SQLAlchemy session for a read-only request.""" + with Session(get_engine()) as session: + yield session diff --git a/pipelines/web/main.py b/pipelines/web/main.py new file mode 100644 index 0000000..1944a54 --- /dev/null +++ b/pipelines/web/main.py @@ -0,0 +1,589 @@ +"""FastAPI app for the HTMX legislative dashboard.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from dataclasses import dataclass +import hashlib +import hmac +from os import getenv +from pathlib import Path +import secrets +from typing import Any +from urllib.parse import parse_qs + +from fastapi import Depends, FastAPI, HTTPException, Request, Response, status +from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates + +from pipelines.web import repository +from pipelines.web.db import session_scope, validate_database_connection +from pipelines.web.repository import Chamber, RankingResult +from pipelines.web.scoring import normalize_issues +from pipelines.web.svg import render_compare_radar_svg, render_score_history_svg + +BASE_DIR = Path(__file__).resolve().parent +TEMPLATES_DIR = BASE_DIR / "templates" +STATIC_DIR = BASE_DIR / "static" + +templates = Jinja2Templates(directory=TEMPLATES_DIR) +ADMIN_USERNAME = "admin" +ADMIN_PASSWORD = "admin" +SESSION_COOKIE = "nornsight_admin" +SESSION_SECRET = "nornsight-local-dev-session-secret" + + +@asynccontextmanager +async def lifespan(_: FastAPI): + """Validate database access when the CLI starts the web server.""" + if getenv("PYTEST_CURRENT_TEST") is None: + validate_database_connection() + yield + + +app = FastAPI(title="Nornsight Legislative Dashboard", lifespan=lifespan) +app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") + + +@dataclass(frozen=True) +class DashboardState: + """Dashboard query-string state.""" + + issues: list[str] + chamber: Chamber + congress: int | None + compare: list[int] + + +@app.get("/healthz", response_class=PlainTextResponse) +def healthz() -> str: + """Return a simple liveness response.""" + return "ok" + + +@app.get("/login", response_class=HTMLResponse) +def login(request: Request) -> Response: + """Render the integrated login page.""" + next_path = _safe_next_path(request.query_params.get("next")) + if _authenticated_user(request) is not None: + return RedirectResponse(next_path, status_code=status.HTTP_303_SEE_OTHER) + return templates.TemplateResponse( + request, + "login.html", + { + "error": "", + "is_authenticated": False, + "show_primary_nav": False, + "next_path": next_path, + "username": "", + }, + ) + + +@app.post("/login", response_class=HTMLResponse) +async def login_submit(request: Request) -> Response: + """Authenticate the hard-coded admin user and set a session cookie.""" + form = parse_qs((await request.body()).decode()) + username = form.get("username", [""])[0] + password = form.get("password", [""])[0] + next_path = _safe_next_path(form.get("next", [request.query_params.get("next")])[0]) + + username_ok = secrets.compare_digest(username, ADMIN_USERNAME) + password_ok = secrets.compare_digest(password, ADMIN_PASSWORD) + if not (username_ok and password_ok): + return templates.TemplateResponse( + request, + "login.html", + { + "error": "Invalid username or password.", + "is_authenticated": False, + "show_primary_nav": False, + "next_path": next_path, + "username": username, + }, + status_code=status.HTTP_401_UNAUTHORIZED, + ) + + response = RedirectResponse(next_path, status_code=status.HTTP_303_SEE_OTHER) + response.set_cookie( + SESSION_COOKIE, + _sign_session(username), + httponly=True, + samesite="lax", + ) + return response + + +@app.get("/logout") +def logout() -> Response: + """Clear the local admin session.""" + response = RedirectResponse("/login", status_code=status.HTTP_303_SEE_OTHER) + response.delete_cookie(SESSION_COOKIE) + return response + + +def require_admin(request: Request) -> str: + """Redirect unauthenticated users to the in-site login page.""" + username = _authenticated_user(request) + if username is not None: + return username + next_path = request.url.path + if request.url.query: + next_path = f"{next_path}?{request.url.query}" + login_url = request.url_for("login").include_query_params(next=next_path) + raise HTTPException( + status_code=status.HTTP_303_SEE_OTHER, + headers={"Location": str(login_url)}, + ) + + +def _authenticated_user(request: Request) -> str | None: + token = request.cookies.get(SESSION_COOKIE) + if token is None: + return None + try: + username, signature = token.split(":", 1) + except ValueError: + return None + if username != ADMIN_USERNAME: + return None + expected = _session_signature(username) + if secrets.compare_digest(signature, expected): + return username + return None + + +def _sign_session(username: str) -> str: + return f"{username}:{_session_signature(username)}" + + +def _session_signature(username: str) -> str: + return hmac.new( + SESSION_SECRET.encode(), + username.encode(), + hashlib.sha256, + ).hexdigest() + + +def _safe_next_path(value: str | None) -> str: + if value and value.startswith("/") and not value.startswith("//"): + return value + return "/" + + +@app.get("/", response_class=HTMLResponse) +def dashboard(request: Request, _: str = Depends(require_admin)) -> Response: + """Render the full dashboard page.""" + context = _dashboard_context(request) + if request.headers.get("hx-request") == "true": + return templates.TemplateResponse(request, "partials/_dashboard.html", context) + return templates.TemplateResponse(request, "dashboard.html", context) + + +@app.get("/partials/dashboard", response_class=HTMLResponse) +def dashboard_partial(request: Request, _: str = Depends(require_admin)) -> Response: + """Render the filter-dependent dashboard body.""" + context = _dashboard_context(request) + return templates.TemplateResponse(request, "partials/_dashboard.html", context) + + +@app.get("/partials/issues", response_class=HTMLResponse) +def issues_partial(request: Request, _: str = Depends(require_admin)) -> Response: + """Render only issue filters.""" + context = _dashboard_context(request) + return templates.TemplateResponse(request, "partials/_issue_filters.html", context) + + +@app.get("/partials/rankings", response_class=HTMLResponse) +def rankings_partial(request: Request, _: str = Depends(require_admin)) -> Response: + """Render only ranking panels.""" + context = _dashboard_context(request) + return templates.TemplateResponse(request, "partials/_rankings.html", context) + + +@app.get("/partials/chart", response_class=HTMLResponse) +def chart_partial(request: Request, _: str = Depends(require_admin)) -> Response: + """Render only the SVG chart panel.""" + context = _dashboard_context(request) + return templates.TemplateResponse(request, "partials/_chart.html", context) + + +@app.get("/legislators", response_class=HTMLResponse) +def legislators(request: Request, _: str = Depends(require_admin)) -> Response: + """Render the legislator profile/search page.""" + context = _legislators_context(request) + return templates.TemplateResponse(request, "legislators.html", context) + + +@app.get("/partials/legislator-suggestions", response_class=HTMLResponse) +def legislator_suggestions_partial( + request: Request, _: str = Depends(require_admin) +) -> Response: + """Render legislator search suggestions for the HTMX typeahead.""" + query = request.query_params.get("q", "").strip() + context: dict[str, Any] = { + "q": query if len(query) >= 2 else "", + "matches": [], + "build_legislator_url": _build_legislator_url, + } + if len(query) >= 2: + with session_scope() as session: + context["matches"] = repository.search_legislators( + session, query=query, limit=8 + ) + return templates.TemplateResponse( + request, "partials/_legislator_suggestions.html", context + ) + + +@app.get("/compare", response_class=HTMLResponse) +def compare(request: Request, _: str = Depends(require_admin)) -> Response: + """Render the legislator radar comparison page.""" + context = _compare_context(request) + return templates.TemplateResponse(request, "compare.html", context) + + +def _dashboard_context(request: Request) -> dict[str, Any]: + state = _parse_state(request) + base_context: dict[str, Any] = { + "state": state, + "issues": state.issues, + "selected_issue_label": " + ".join(state.issues) if state.issues else "", + "chamber": state.chamber, + "congress": state.congress, + "latest_score_year": None, + "last_updated": None, + "suggestions": [], + "rankings": RankingResult(supportive=[], opposed=[]), + "compare": [], + "chart_svg": render_score_history_svg([]), + "chart_series": [], + "has_votes": False, + "has_scores": False, + "empty_message": "", + "build_url": _build_url, + "toggle_compare": _toggle_compare, + } + with session_scope() as session: + congress = state.congress or repository.latest_congress(session) + base_context["congress"] = congress + base_context["has_scores"] = repository.has_scores(session) + base_context["latest_score_year"] = repository.latest_score_year(session) + base_context["last_updated"] = repository.latest_vote_date(session, congress) + base_context["suggestions"] = repository.issue_suggestions( + session, congress=congress + ) + + if not base_context["has_scores"]: + base_context["empty_message"] = ( + "No legislator scores are loaded yet. Run the score calculator first." + ) + return base_context + + if congress is None: + base_context["congress"] = "Computed" + + if not state.issues: + base_context["empty_message"] = ( + "Choose one or more issue areas to calculate roll-call support scores." + ) + return base_context + + rankings = repository.get_rankings( + session, + issues=state.issues, + chamber=state.chamber, + congress=congress, + ) + base_context["rankings"] = rankings + compare = state.compare or [row.legislator_id for row in rankings.supportive[:2]] + base_context["compare"] = compare + if not rankings.supportive and not rankings.opposed: + base_context["empty_message"] = "No matching roll-call votes." + return base_context + + history = repository.get_score_history( + session, + issues=state.issues, + chamber=state.chamber, + congress=congress, + legislator_ids=compare, + ) + base_context["chart_series"] = history + base_context["chart_svg"] = render_score_history_svg(history) + return base_context + + +def _parse_state(request: Request) -> DashboardState: + query = request.query_params + chamber = query.get("chamber", "senate").lower() + if chamber not in {"house", "senate", "all"}: + chamber = "senate" + congress = _parse_int(query.get("congress")) + compare = [ + value + for value in (_parse_int(raw) for raw in query.getlist("compare")) + if value is not None + ] + return DashboardState( + issues=normalize_issues(query.getlist("issues")), + chamber=chamber, # type: ignore[arg-type] + congress=congress, + compare=compare, + ) + + +def _legislators_context(request: Request) -> dict[str, Any]: + query = request.query_params.get("q", "").strip() + legislator_id = _parse_int(request.query_params.get("legislator_id")) + selected_topic = request.query_params.get("topic", "").strip() + per_page = _parse_per_page(request.query_params.get("per_page")) + page = max(_parse_int(request.query_params.get("page")) or 1, 1) + base_context: dict[str, Any] = { + "q": query, + "profile": None, + "matches": [], + "result_count": 0, + "page": page, + "per_page": per_page, + "per_page_options": [10, 25, 50], + "total_pages": 1, + "previous_page": None, + "next_page": None, + "selected_topic": selected_topic, + "history_svg": render_score_history_svg([]), + "history_series": [], + "build_legislator_url": _build_legislator_url, + "build_legislator_search_url": _build_legislator_search_url, + } + with session_scope() as session: + result_count = repository.count_legislators(session, query=query) if query else 0 + total_pages = max((result_count + per_page - 1) // per_page, 1) + if page > total_pages: + page = total_pages + base_context["page"] = page + matches = ( + repository.search_legislators( + session, + query=query, + limit=per_page, + offset=(page - 1) * per_page, + ) + if query + else [] + ) + profile = repository.get_legislator_profile( + session, legislator_id=legislator_id, query=None + ) + base_context["profile"] = profile + base_context["matches"] = matches + base_context["result_count"] = result_count + base_context["total_pages"] = total_pages + base_context["previous_page"] = page - 1 if page > 1 else None + base_context["next_page"] = page + 1 if page < total_pages else None + if profile is None: + return base_context + if not selected_topic: + if profile.bottom_topics: + selected_topic = profile.bottom_topics[0].topic + elif profile.top_topics: + selected_topic = profile.top_topics[0].topic + base_context["selected_topic"] = selected_topic + if selected_topic: + history = repository.get_single_legislator_history( + session, + legislator_id=profile.legislator.legislator_id, + topic=selected_topic, + ) + base_context["history_series"] = history + base_context["history_svg"] = render_score_history_svg(history) + return base_context + + +def _compare_context(request: Request) -> dict[str, Any]: + selected_legislators = _parse_int_list( + request.query_params.getlist("legislator_id") + or request.query_params.getlist("compare") + )[:4] + topics = normalize_issues( + request.query_params.getlist("topic") or request.query_params.getlist("issues") + )[:8] + query = request.query_params.get("q", "").strip() + base_context: dict[str, Any] = { + "selected_legislators": selected_legislators, + "selected_legislator_options": [], + "topics": topics, + "q": query, + "series": [], + "radar_svg": render_compare_radar_svg([], []), + "legislator_options": [], + "topic_options": [], + "build_compare_url": _build_compare_url, + } + with session_scope() as session: + default_legislators, default_topics = repository.get_compare_defaults(session) + if not selected_legislators and not query: + selected_legislators = default_legislators[:3] + if not topics: + topics = default_topics[:6] + selected_legislator_options = repository.get_legislator_options( + session, selected_legislators + ) + series = repository.get_compare_radar_series( + session, legislator_ids=selected_legislators, topics=topics + ) + base_context.update( + { + "selected_legislators": selected_legislators, + "selected_legislator_options": selected_legislator_options, + "topics": topics, + "q": query, + "series": series, + "radar_svg": render_compare_radar_svg(topics, series), + "legislator_options": repository.search_legislators( + session, query=query or None, limit=12 + ), + "topic_options": repository.issue_suggestions( + session, congress=None, limit=12 + ), + } + ) + return base_context + + +def _parse_int(value: str | None) -> int | None: + if value is None or value == "": + return None + try: + return int(value) + except ValueError: + return None + + +def _parse_int_list(values: list[str]) -> list[int]: + parsed: list[int] = [] + seen: set[int] = set() + for value in values: + integer = _parse_int(value) + if integer is not None and integer not in seen: + parsed.append(integer) + seen.add(integer) + return parsed + + +def _parse_per_page(value: str | None) -> int: + parsed = _parse_int(value) + return parsed if parsed in {10, 25, 50} else 10 + + +def _build_url( + request: Request, + *, + issues: list[str] | None = None, + chamber: str | None = None, + congress: int | None = None, + compare: list[int] | None = None, +) -> str: + params: list[tuple[str, str]] = [] + chosen_issues = ( + issues + if issues is not None + else normalize_issues(request.query_params.getlist("issues")) + ) + chosen_chamber = ( + chamber + if chamber is not None + else request.query_params.get("chamber", "senate") + ) + chosen_congress = ( + congress + if congress is not None + else _parse_int(request.query_params.get("congress")) + ) + chosen_compare = ( + compare + if compare is not None + else [ + value + for value in ( + _parse_int(raw) for raw in request.query_params.getlist("compare") + ) + if value is not None + ] + ) + for issue in chosen_issues: + params.append(("issues", issue)) + params.append(("chamber", chosen_chamber)) + if chosen_congress is not None: + params.append(("congress", str(chosen_congress))) + for legislator_id in chosen_compare: + params.append(("compare", str(legislator_id))) + if not params: + return "/" + from urllib.parse import urlencode + + return f"/?{urlencode(params, doseq=True)}" + + +def _toggle_compare(compare: list[int], legislator_id: int) -> list[int]: + """Return compare IDs with the legislator added or removed.""" + if legislator_id in compare: + return [value for value in compare if value != legislator_id] + return [*compare, legislator_id] + + +def _build_legislator_url( + *, + legislator_id: int | None = None, + q: str | None = None, + topic: str | None = None, + per_page: int | None = None, +) -> str: + from urllib.parse import urlencode + + params: list[tuple[str, str]] = [] + if legislator_id is not None: + params.append(("legislator_id", str(legislator_id))) + if q: + params.append(("q", q)) + if topic: + params.append(("topic", topic)) + if per_page in {10, 25, 50} and per_page != 10: + params.append(("per_page", str(per_page))) + return f"/legislators?{urlencode(params)}" if params else "/legislators" + + +def _build_legislator_search_url( + *, + q: str, + per_page: int, + page: int = 1, +) -> str: + from urllib.parse import urlencode + + params: list[tuple[str, str]] = [] + if q: + params.append(("q", q)) + params.append(("per_page", str(per_page))) + if page > 1: + params.append(("page", str(page))) + return f"/legislators?{urlencode(params)}" if params else "/legislators" + + +def _build_compare_url( + *, + legislator_ids: list[int], + topics: list[str], + q: str | None = None, +) -> str: + from urllib.parse import urlencode + + params: list[tuple[str, str]] = [] + for legislator_id in legislator_ids[:4]: + params.append(("legislator_id", str(legislator_id))) + for topic in topics[:8]: + params.append(("topic", topic)) + if q: + params.append(("q", q)) + return f"/compare?{urlencode(params, doseq=True)}" if params else "/compare" diff --git a/pipelines/web/repository.py b/pipelines/web/repository.py new file mode 100644 index 0000000..919f2b6 --- /dev/null +++ b/pipelines/web/repository.py @@ -0,0 +1,670 @@ +"""Congress database queries for the web dashboard.""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date +from typing import Literal + +from sqlalchemy import ColumnElement, Select, case, desc, false, func, or_, select, true +from sqlalchemy.orm import Session + +from pipelines.orm.data_science_dev.congress import ( + BillTopic, + Legislator, + LegislatorScore, + Vote, +) +from pipelines.web.scoring import normalize_issues + +Chamber = Literal["house", "senate", "all"] + +STATE_ALIASES = { + "alabama": "AL", + "alaska": "AK", + "arizona": "AZ", + "arkansas": "AR", + "california": "CA", + "colorado": "CO", + "connecticut": "CT", + "delaware": "DE", + "florida": "FL", + "georgia": "GA", + "hawaii": "HI", + "idaho": "ID", + "illinois": "IL", + "indiana": "IN", + "iowa": "IA", + "kansas": "KS", + "kentucky": "KY", + "louisiana": "LA", + "maine": "ME", + "maryland": "MD", + "massachusetts": "MA", + "michigan": "MI", + "minnesota": "MN", + "mississippi": "MS", + "missouri": "MO", + "montana": "MT", + "nebraska": "NE", + "nevada": "NV", + "new hampshire": "NH", + "new jersey": "NJ", + "new mexico": "NM", + "new york": "NY", + "north carolina": "NC", + "north dakota": "ND", + "ohio": "OH", + "oklahoma": "OK", + "oregon": "OR", + "pennsylvania": "PA", + "rhode island": "RI", + "south carolina": "SC", + "south dakota": "SD", + "tennessee": "TN", + "texas": "TX", + "utah": "UT", + "vermont": "VT", + "virginia": "VA", + "washington": "WA", + "west virginia": "WV", + "wisconsin": "WI", + "wyoming": "WY", + "district of columbia": "DC", +} + + +@dataclass(frozen=True) +class RankingRow: + """A legislator support score row.""" + + legislator_id: int + display_name: str + party: str | None + state: str | None + chamber: str | None + score: float | None + supportive: int + opposed: int + + @property + def total(self) -> int: + return self.supportive + self.opposed + + +@dataclass(frozen=True) +class RankingResult: + """Supportive and opposed ranking lists.""" + + supportive: list[RankingRow] + opposed: list[RankingRow] + + +@dataclass(frozen=True) +class TimePoint: + """One yearly chart point.""" + + year: int + score: float + + +@dataclass(frozen=True) +class ChartSeries: + """One legislator score-history series.""" + + legislator_id: int + label: str + party: str | None + state: str | None + points: list[TimePoint] + + +@dataclass(frozen=True) +class TopicScore: + """Average score for one topic.""" + + topic: str + score: float + count: int + + +@dataclass(frozen=True) +class LegislatorOption: + """Compact legislator metadata for search and comparison controls.""" + + legislator_id: int + display_name: str + party: str | None + state: str | None + chamber: str | None + + +@dataclass(frozen=True) +class LegislatorProfile: + """Legislator metadata plus issue score summary.""" + + legislator: LegislatorOption + overall_score: float | None + serving_since: int | None + top_topics: list[TopicScore] + bottom_topics: list[TopicScore] + + +@dataclass(frozen=True) +class RadarSeries: + """One legislator polygon for the compare radar chart.""" + + legislator: LegislatorOption + average_score: float | None + scores_by_topic: dict[str, float] + + +def latest_congress(session: Session) -> int | None: + """Return the latest congress number in the vote table.""" + return session.scalar(select(func.max(Vote.congress))) + + +def latest_vote_date(session: Session, congress: int | None = None) -> date | None: + """Return the most recent vote date, optionally scoped to a congress.""" + stmt = select(func.max(Vote.vote_date)) + if congress is not None: + stmt = stmt.where(Vote.congress == congress) + return session.scalar(stmt) + + +def latest_score_year(session: Session) -> int | None: + """Return the latest year in the precomputed legislator score table.""" + return session.scalar(select(func.max(LegislatorScore.year))) + + +def has_scores(session: Session) -> bool: + """Return True when the database has at least one precomputed score.""" + return session.scalar(select(LegislatorScore.id).limit(1)) is not None + + +def issue_suggestions( + session: Session, + *, + congress: int | None, + limit: int = 12, +) -> list[str]: + """Return common precomputed score topics for issue filter suggestions.""" + stmt = ( + select(LegislatorScore.topic, func.count(LegislatorScore.id).label("score_count")) + .where(LegislatorScore.topic != "") + .group_by(LegislatorScore.topic) + .order_by(desc("score_count"), LegislatorScore.topic) + .limit(limit) + ) + suggestions = [row[0] for row in session.execute(stmt).all()] + if suggestions: + return suggestions + + fallback = ( + select(BillTopic.topic, func.count(BillTopic.id).label("topic_count")) + .where(BillTopic.topic != "") + .group_by(BillTopic.topic) + .order_by(desc("topic_count"), BillTopic.topic) + .limit(limit) + ) + return [row[0] for row in session.execute(fallback).all()] + + +def ranking_query( + *, + issues: list[str], + chamber: Chamber, + congress: int, +) -> Select: + """Build the aggregate ranking query from precomputed scores.""" + average_score = func.avg(LegislatorScore.score).label("score") + supportive = func.sum(case((LegislatorScore.score >= 50, 1), else_=0)).label( + "supportive" + ) + opposed = func.sum(case((LegislatorScore.score < 50, 1), else_=0)).label("opposed") + + stmt = ( + select( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + Legislator.current_chamber, + average_score, + supportive, + opposed, + ) + .join(LegislatorScore, LegislatorScore.legislator_id == Legislator.id) + .where(_score_topic_match_condition(issues)) + .group_by( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + Legislator.current_chamber, + ) + ) + if chamber != "all": + stmt = stmt.where(Legislator.current_chamber == _db_chamber(chamber)) + return stmt + + +def get_rankings( + session: Session, + *, + issues: list[str], + chamber: Chamber, + congress: int, + limit: int = 10, +) -> RankingResult: + """Return top supportive and opposed legislators from precomputed scores.""" + rows = [ + _ranking_row(row) + for row in session.execute( + ranking_query(issues=issues, chamber=chamber, congress=congress) + ) + ] + scored = [row for row in rows if row.score is not None] + supportive = sorted( + scored, key=lambda row: (-float(row.score), -row.total, row.display_name) + )[:limit] + opposed = sorted( + scored, key=lambda row: (float(row.score), -row.total, row.display_name) + )[:limit] + return RankingResult(supportive=supportive, opposed=opposed) + + +def get_score_history( + session: Session, + *, + issues: list[str], + chamber: Chamber, + congress: int, + legislator_ids: list[int], +) -> list[ChartSeries]: + """Return yearly score history from precomputed scores.""" + if not legislator_ids: + return [] + + average_score = func.avg(LegislatorScore.score).label("score") + stmt = ( + select( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + LegislatorScore.year, + average_score, + ) + .join(LegislatorScore, LegislatorScore.legislator_id == Legislator.id) + .where( + Legislator.id.in_(legislator_ids), + _score_topic_match_condition(issues), + ) + .group_by( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + LegislatorScore.year, + ) + .order_by(Legislator.id, LegislatorScore.year) + ) + if chamber != "all": + stmt = stmt.where(Legislator.current_chamber == _db_chamber(chamber)) + + by_legislator: dict[int, ChartSeries] = {} + for row in session.execute(stmt): + if row.score is None: + continue + series = by_legislator.setdefault( + row.id, + ChartSeries( + legislator_id=row.id, + label=_display_name(row.official_full_name, row.last_name), + party=row.current_party, + state=row.current_state, + points=[], + ), + ) + series.points.append(TimePoint(year=int(row.year), score=float(row.score))) + return list(by_legislator.values()) + + +def _ranking_row(row: object) -> RankingRow: + return RankingRow( + legislator_id=row.id, + display_name=_display_name(row.official_full_name, row.last_name), + party=row.current_party, + state=row.current_state, + chamber=row.current_chamber, + score=float(row.score) if row.score is not None else None, + supportive=row.supportive or 0, + opposed=row.opposed or 0, + ) + + +def _score_topic_match_condition( + issues: list[str] | tuple[str, ...], +) -> ColumnElement[bool]: + normalized = normalize_issues(list(issues)) + if not normalized: + return false() + return or_(*(LegislatorScore.topic.ilike(f"%{issue}%") for issue in normalized)) + + +def search_legislators( + session: Session, + *, + query: str | None = None, + limit: int = 12, + offset: int = 0, +) -> list[LegislatorOption]: + """Search ingested legislators, preferring those with computed scores.""" + return [ + _legislator_option(row) + for row in session.execute( + legislator_search_query(query=query, limit=limit, offset=offset) + ) + ] + + +def count_legislators(session: Session, *, query: str | None = None) -> int: + """Return the total number of legislators matching a search query.""" + return int( + session.scalar( + select(func.count(Legislator.id)).where(_legislator_search_condition(query)) + ) + or 0 + ) + + +def get_legislator_options( + session: Session, legislator_ids: list[int] +) -> list[LegislatorOption]: + """Return legislator options in the same order as the selected IDs.""" + options = { + option.legislator_id: option + for option in ( + _get_legislator_option(session, legislator_id) + for legislator_id in legislator_ids + ) + if option is not None + } + return [ + options[legislator_id] + for legislator_id in legislator_ids + if legislator_id in options + ] + + +def legislator_search_query( + *, + query: str | None = None, + limit: int = 12, + offset: int = 0, +) -> Select: + """Build the legislator search query used by profile and compare controls.""" + score_count = func.count(LegislatorScore.id).label("score_count") + stmt = ( + select( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + Legislator.current_chamber, + score_count, + ) + .outerjoin(LegislatorScore, LegislatorScore.legislator_id == Legislator.id) + .group_by( + Legislator.id, + Legislator.official_full_name, + Legislator.first_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + Legislator.current_chamber, + Legislator.bioguide_id, + ) + .order_by(desc("score_count"), Legislator.last_name, Legislator.first_name) + .limit(limit) + .offset(offset) + ) + return stmt.where(_legislator_search_condition(query)) + + +def _legislator_search_condition(query: str | None) -> ColumnElement[bool]: + cleaned_query = query.strip() if query else "" + if not cleaned_query: + return true() + + pattern = f"%{cleaned_query}%" + state_alias = _state_alias(cleaned_query) + conditions: list[ColumnElement[bool]] = [ + Legislator.official_full_name.ilike(pattern), + Legislator.first_name.ilike(pattern), + Legislator.last_name.ilike(pattern), + Legislator.current_state.ilike(pattern), + Legislator.bioguide_id.ilike(pattern), + ] + if state_alias is not None: + conditions.append(Legislator.current_state == state_alias) + return or_(*conditions) + + +def _state_alias(query: str) -> str | None: + normalized = " ".join(query.lower().replace(".", "").split()) + if len(normalized) == 2 and normalized.isalpha(): + return normalized.upper() + return STATE_ALIASES.get(normalized) + + +def get_legislator_profile( + session: Session, + *, + legislator_id: int | None = None, + query: str | None = None, +) -> LegislatorProfile | None: + """Return the selected legislator profile and top/bottom topic scores.""" + selected = _get_legislator_option(session, legislator_id) + cleaned_query = query.strip() if query else "" + if selected is None and cleaned_query: + matches = search_legislators(session, query=query, limit=1) + selected = matches[0] if matches else None + if selected is None: + return None + + topic_scores = get_legislator_topic_scores( + session, legislator_id=selected.legislator_id + ) + top_topics = sorted(topic_scores, key=lambda item: (-item.score, item.topic))[:3] + bottom_topics = sorted(topic_scores, key=lambda item: (item.score, item.topic))[:3] + overall_score = session.scalar( + select(func.avg(LegislatorScore.score)).where( + LegislatorScore.legislator_id == selected.legislator_id + ) + ) + serving_since = session.scalar( + select(func.min(LegislatorScore.year)).where( + LegislatorScore.legislator_id == selected.legislator_id + ) + ) + return LegislatorProfile( + legislator=selected, + overall_score=float(overall_score) if overall_score is not None else None, + serving_since=int(serving_since) if serving_since is not None else None, + top_topics=top_topics, + bottom_topics=bottom_topics, + ) + + +def get_legislator_topic_scores( + session: Session, + *, + legislator_id: int, +) -> list[TopicScore]: + """Return all average topic scores for one legislator.""" + rows = session.execute( + select( + LegislatorScore.topic, + func.avg(LegislatorScore.score).label("score"), + func.count(LegislatorScore.id).label("count"), + ) + .where(LegislatorScore.legislator_id == legislator_id) + .group_by(LegislatorScore.topic) + .order_by(LegislatorScore.topic) + ) + return [ + TopicScore(topic=row.topic, score=float(row.score), count=row.count) + for row in rows + if row.score is not None + ] + + +def get_single_legislator_history( + session: Session, + *, + legislator_id: int, + topic: str, +) -> list[ChartSeries]: + """Return score history for one legislator/topic pair.""" + option = _get_legislator_option(session, legislator_id) + if option is None: + return [] + + rows = session.execute( + select( + LegislatorScore.year, + func.avg(LegislatorScore.score).label("score"), + ) + .where( + LegislatorScore.legislator_id == legislator_id, + LegislatorScore.topic == topic, + ) + .group_by(LegislatorScore.year) + .order_by(LegislatorScore.year) + ) + points = [ + TimePoint(year=int(row.year), score=float(row.score)) + for row in rows + if row.score is not None + ] + return [ + ChartSeries( + legislator_id=option.legislator_id, + label=option.display_name, + party=option.party, + state=option.state, + points=points, + ) + ] + + +def get_compare_defaults(session: Session) -> tuple[list[int], list[str]]: + """Return default compare legislators and topics.""" + legislators = search_legislators(session, limit=3) + topics = issue_suggestions(session, congress=None, limit=6) + return [item.legislator_id for item in legislators], topics + + +def get_compare_radar_series( + session: Session, + *, + legislator_ids: list[int], + topics: list[str], +) -> list[RadarSeries]: + """Return radar chart scores for selected legislators and topics.""" + if not legislator_ids: + return [] + + options = { + option.legislator_id: option + for option in ( + _get_legislator_option(session, legislator_id) + for legislator_id in legislator_ids + ) + if option is not None + } + if not options: + return [] + + scores: dict[int, dict[str, float]] = { + legislator_id: {} for legislator_id in options + } + if topics: + rows = session.execute( + select( + LegislatorScore.legislator_id, + LegislatorScore.topic, + func.avg(LegislatorScore.score).label("score"), + ) + .where( + LegislatorScore.legislator_id.in_(list(options)), + LegislatorScore.topic.in_(topics), + ) + .group_by(LegislatorScore.legislator_id, LegislatorScore.topic) + ) + for row in rows: + scores[row.legislator_id][row.topic] = float(row.score) + + series: list[RadarSeries] = [] + for legislator_id in legislator_ids: + option = options.get(legislator_id) + if option is None: + continue + topic_scores = scores.get(legislator_id, {}) + values = list(topic_scores.values()) + series.append( + RadarSeries( + legislator=option, + average_score=sum(values) / len(values) if values else None, + scores_by_topic=topic_scores, + ) + ) + return series + + +def _display_name(official_full_name: str | None, last_name: str | None) -> str: + if official_full_name: + parts = official_full_name.split() + if len(parts) > 1: + return f"{parts[-1]}, {' '.join(parts[:-1])}" + return official_full_name + return last_name or "Unknown" + + +def _legislator_option(row: object) -> LegislatorOption: + return LegislatorOption( + legislator_id=row.id, + display_name=_display_name(row.official_full_name, row.last_name), + party=row.current_party, + state=row.current_state, + chamber=row.current_chamber, + ) + + +def _get_legislator_option( + session: Session, legislator_id: int | None +) -> LegislatorOption | None: + if legislator_id is None: + return None + row = session.execute( + select( + Legislator.id, + Legislator.official_full_name, + Legislator.last_name, + Legislator.current_party, + Legislator.current_state, + Legislator.current_chamber, + ).where(Legislator.id == legislator_id) + ).first() + return _legislator_option(row) if row is not None else None + + +def _db_chamber(chamber: Chamber) -> str: + return {"house": "House", "senate": "Senate", "all": "all"}[chamber] diff --git a/pipelines/web/scoring.py b/pipelines/web/scoring.py new file mode 100644 index 0000000..be615a8 --- /dev/null +++ b/pipelines/web/scoring.py @@ -0,0 +1,100 @@ +"""Issue matching and voting score helpers.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from sqlalchemy import ColumnElement, false, func, or_ +from sqlalchemy.sql.elements import BinaryExpression + +from pipelines.orm.data_science_dev.congress import Bill, BillTopicPosition, Vote + +SUPPORT_POSITIONS = frozenset({"yea", "aye", "yes"}) +OPPOSE_POSITIONS = frozenset({"nay", "no"}) + + +@dataclass(frozen=True) +class ScoreCounts: + """Support/opposition counts for one legislator or time bucket.""" + + supportive: int + opposed: int + + @property + def total(self) -> int: + return self.supportive + self.opposed + + +def normalize_position(position: str | None) -> str | None: + """Normalize a raw roll-call position into support/oppose/ignore buckets.""" + if position is None: + return None + value = position.strip().lower() + if value in SUPPORT_POSITIONS: + return "support" + if value in OPPOSE_POSITIONS: + return "oppose" + return None + + +def score_vote_position( + position: str | None, + support_position: BillTopicPosition | str, +) -> str | None: + """Score a raw vote as support/opposition for an extracted bill topic.""" + normalized_vote = normalize_position(position) + if normalized_vote is None: + return None + + topic_position = BillTopicPosition(support_position) + if topic_position is BillTopicPosition.FOR: + return normalized_vote + if normalized_vote == "support": + return "oppose" + return "support" + + +def calculate_score(counts: ScoreCounts) -> int | None: + """Calculate the 0-100 support score, or None when there are no scored votes.""" + if counts.total == 0: + return None + return round(100 * counts.supportive / counts.total) + + +def normalize_issues(issues: list[str] | tuple[str, ...]) -> list[str]: + """Trim, de-duplicate, and preserve issue order for display and queries.""" + normalized: list[str] = [] + seen: set[str] = set() + for issue in issues: + value = issue.strip() + key = value.casefold() + if value and key not in seen: + normalized.append(value) + seen.add(key) + return normalized + + +def issue_match_condition(issues: list[str] | tuple[str, ...]) -> ColumnElement[bool]: + """Build the SQLAlchemy condition for issue text matching.""" + normalized = normalize_issues(list(issues)) + if not normalized: + return false() + + fields: tuple[ColumnElement[str | None], ...] = ( + Bill.subjects_top_term, + Bill.title, + Bill.title_short, + Bill.official_title, + Vote.question, + Vote.result_text, + ) + terms: list[BinaryExpression[bool]] = [] + for issue in normalized: + pattern = f"%{issue}%" + terms.extend(field.ilike(pattern) for field in fields) + return or_(*terms) + + +def normalized_position_expression(column: ColumnElement[str]) -> ColumnElement[str | None]: + """Lowercase and trim a SQL column containing raw vote positions.""" + return func.lower(func.trim(column)) diff --git a/pipelines/web/static/styles.css b/pipelines/web/static/styles.css new file mode 100644 index 0000000..a41d6f5 --- /dev/null +++ b/pipelines/web/static/styles.css @@ -0,0 +1,1215 @@ +:root { + color-scheme: dark; + --bg: #061614; + --panel: #0a201d; + --panel-2: #0f2824; + --line: #1c4a43; + --line-bright: #2c7b6d; + --text: #e7f0ed; + --muted: #91a39e; + --teal: #2fbd9f; + --teal-dark: #0e5f53; + --amber: #d8892d; + --purple: #8f6ff0; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + background: radial-gradient(circle at 40% -20%, #10352f 0, #061614 38rem); + color: var(--text); + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; +} + +a { + color: inherit; + text-decoration: none; +} + +.topbar { + align-items: center; + background: #041411; + border-bottom: 1px solid #12362f; + display: flex; + justify-content: space-between; + padding: 0.75rem 1.5rem; +} + +.brand, +.primary-nav, +.account-nav, +.heading-actions, +.controls-grid, +.rankings-grid, +.chart-card header { + display: flex; +} + +.brand { + align-items: center; + font-size: 1.1rem; + font-weight: 760; + gap: 0.75rem; +} + +.brand-mark { + color: var(--teal); + font-size: 1.7rem; + line-height: 1; +} + +.primary-nav { + gap: 0.25rem; + margin-right: auto; + margin-left: 1rem; +} + +.primary-nav a { + border: 1px solid #173f38; + border-radius: 8px; + color: #d9e7e3; + font-weight: 720; + min-width: 8.5rem; + padding: 0.9rem 1.2rem; + text-align: center; +} + +.primary-nav a:hover, +.result-chips a:hover, +.axis-chips a:hover { + border-color: var(--line-bright); + color: white; +} + +.account-nav { + align-items: center; + gap: 0.75rem; +} + +.account-nav a, +.account-menu summary, +.heading-actions a, +.heading-actions span, +.chart-card header a, +.issue-form button { + background: #0a201d; + border: 1px solid #173f38; + border-radius: 7px; + color: #c2d1cc; + font-size: 0.88rem; + padding: 0.55rem 0.8rem; +} + +.account-menu { + position: relative; +} + +.account-menu summary { + cursor: pointer; + list-style: none; +} + +.account-menu summary::-webkit-details-marker { + display: none; +} + +.account-menu summary::after { + color: var(--muted); + content: "▾"; + font-size: 0.75rem; + margin-left: 0.45rem; +} + +.account-menu[open] summary { + border-color: var(--line-bright); + color: white; +} + +.account-menu[open] summary::after { + content: "▴"; +} + +.account-menu-panel { + background: #061614; + border: 1px solid var(--line); + border-radius: 8px; + box-shadow: 0 18px 40px rgba(0, 0, 0, 0.3); + min-width: 12rem; + padding: 0.45rem; + position: absolute; + right: 0; + top: calc(100% + 0.45rem); + z-index: 20; +} + +.account-menu-panel a { + display: block; + margin: 0.2rem 0; + text-align: left; +} + +.account-menu-panel .sign-out { + background: #0d5f53; + border-color: #16806f; + color: white; +} + +.account-nav .sign-in { + background: #0d5f53; + border-color: #16806f; + color: white; +} + +.shell { + margin: 0 auto; + max-width: 1180px; + padding: 1.25rem 1.5rem 2rem; +} + +.login-shell { + align-items: center; + display: flex; + justify-content: center; + min-height: calc(100vh - 4.25rem); + padding: 2rem 1.5rem; +} + +.login-panel { + background: color-mix(in srgb, var(--panel) 88%, transparent); + border: 1px solid var(--line); + border-radius: 8px; + display: grid; + gap: 1.5rem; + grid-template-columns: minmax(0, 0.9fr) minmax(18rem, 1fr); + max-width: 56rem; + padding: 1.4rem; + width: 100%; +} + +.login-copy { + border-right: 1px solid rgba(44, 123, 109, 0.45); + padding: 0.6rem 1.5rem 0.6rem 0.2rem; +} + +.login-copy .eyebrow { + color: var(--teal); + font-size: 0.82rem; + font-weight: 800; + letter-spacing: 0.08em; + margin: 0 0 0.8rem; + text-transform: uppercase; +} + +.login-copy h1 { + font-size: 2rem; + line-height: 1.1; + margin: 0; +} + +.login-copy p:last-child { + color: var(--muted); + margin-bottom: 0; +} + +.login-form { + display: grid; + gap: 0.65rem; +} + +.login-form label { + color: #cfe0dc; + font-size: 0.9rem; + font-weight: 700; +} + +.login-form input { + background: #132923; + border: 1px solid #2a4b43; + border-radius: 6px; + color: var(--text); + font: inherit; + min-height: 2.7rem; + padding: 0.6rem 0.75rem; + width: 100%; +} + +.login-form input:focus { + border-color: var(--line-bright); + outline: 2px solid rgba(47, 189, 159, 0.22); +} + +.login-form button { + background: var(--teal-dark); + border: 1px solid #16806f; + border-radius: 7px; + color: white; + cursor: pointer; + font: inherit; + font-weight: 800; + margin-top: 0.35rem; + min-height: 2.8rem; +} + +.form-error { + background: rgba(216, 137, 45, 0.14); + border: 1px solid rgba(216, 137, 45, 0.45); + border-radius: 6px; + color: #f4c27d; + margin: 0 0 0.25rem; + padding: 0.7rem 0.75rem; +} + +.page-heading { + align-items: end; + display: flex; + gap: 1rem; + justify-content: space-between; +} + +.stacked-heading { + align-items: start; + display: block; +} + +.page-heading h1 { + font-size: clamp(1.7rem, 2vw, 2.3rem); + line-height: 1.1; + margin: 0; +} + +.page-heading p, +.score-note, +.footer, +.empty-state, +.setup-error p { + color: var(--muted); +} + +.page-heading p { + margin: 0.4rem 0 0; +} + +.heading-actions { + flex-wrap: wrap; + gap: 0.65rem; + justify-content: end; +} + +.notice, +.filter-card, +.chamber-card, +.ranking-card, +.chart-card, +.setup-error { + background: color-mix(in srgb, var(--panel) 88%, transparent); + border: 1px solid var(--line); + border-radius: 8px; +} + +.notice { + color: #b8cbc5; + margin: 1rem 0; + padding: 0.75rem 1rem; +} + +.controls-grid { + gap: 1.25rem; + margin-top: 1.1rem; +} + +.filter-card { + flex: 1 1 auto; + padding: 1rem; +} + +h2 { + font-size: 1.1rem; + margin: 0 0 0.75rem; +} + +.issue-form { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 0.7rem; +} + +.chip, +.suggestions a { + align-items: center; + background: #123a34; + border: 1px solid #1f6b5f; + border-radius: 6px; + color: #d9f4ee; + display: inline-flex; + min-height: 2.35rem; + padding: 0.45rem 0.75rem; +} + +.chip a { + color: #bedbd5; + font-size: 1.2rem; + margin-left: 0.5rem; +} + +.search-box { + flex: 1 1 14rem; +} + +.search-box input { + background: #132923; + border: 1px solid #2a4b43; + border-radius: 6px; + color: var(--text); + min-height: 2.35rem; + padding: 0.45rem 0.75rem; + width: 100%; +} + +.wide-search { + align-items: center; + border: 1px solid var(--line); + border-radius: 8px; + display: flex; + gap: 0.75rem; + margin: 1.4rem 0 1rem; + padding: 0.65rem; +} + +.wide-search input { + background: transparent; + border: 0; + color: var(--text); + flex: 1; + font-size: 1rem; + outline: 0; + padding: 0.55rem 0.7rem; +} + +.wide-search button { + background: var(--teal-dark); + border: 1px solid #16806f; + border-radius: 7px; + color: white; + padding: 0.65rem 1rem; +} + +.wide-search select { + background: #102722; + border: 1px solid #2a4b43; + border-radius: 7px; + color: var(--text); + font: inherit; + min-height: 2.55rem; + padding: 0.45rem 0.65rem; +} + +.issue-form button { + cursor: pointer; +} + +.suggestions { + display: flex; + flex-wrap: wrap; + gap: 0.55rem; + margin-top: 0.8rem; +} + +.suggestions a { + background: transparent; + color: #a8c6c0; + font-size: 0.84rem; + min-height: 1.9rem; +} + +.suggestion-empty { + color: var(--muted); + margin: 0.4rem 0 1rem; +} + +.result-chips, +.axis-chips { + display: flex; + flex-wrap: wrap; + gap: 0.65rem; + margin: 0.8rem 0 1.3rem; +} + +.result-chips a, +.axis-chips a { + align-items: center; + border: 1px solid #1d554c; + border-radius: 999px; + color: #c9dcd7; + display: inline-flex; + gap: 0.45rem; + min-height: 2.15rem; + padding: 0.4rem 0.85rem; +} + +.result-chips .dashed-chip { + border-style: dashed; + color: #79a99d; +} + +.phonebook-results { + background: color-mix(in srgb, var(--panel) 88%, transparent); + border: 1px solid var(--line); + border-radius: 8px; + margin: 1rem 0 1.25rem; + overflow: hidden; +} + +.phonebook-results header, +.pagination { + align-items: center; + display: flex; + justify-content: space-between; +} + +.phonebook-results header { + border-bottom: 1px solid rgba(44, 123, 109, 0.36); + padding: 0.9rem 1rem; +} + +.phonebook-results header h2 { + margin: 0; +} + +.phonebook-results header span, +.phonebook-meta, +.pagination span, +.pagination strong { + color: var(--muted); +} + +.phonebook-list { + list-style-position: inside; + margin: 0; + padding: 0; +} + +.phonebook-list li { + border-bottom: 1px solid rgba(44, 123, 109, 0.22); + color: var(--muted); +} + +.phonebook-list li:last-child { + border-bottom: 0; +} + +.phonebook-list a { + align-items: center; + display: grid; + gap: 0.75rem; + grid-template-columns: minmax(0, 1fr) auto; + margin-left: 1.1rem; + min-height: 3.1rem; + padding: 0.55rem 1rem 0.55rem 0; +} + +.phonebook-list a:hover { + color: white; +} + +.phonebook-name { + color: var(--text); + font-weight: 760; + min-width: 0; +} + +.phonebook-meta { + font-size: 0.86rem; + white-space: nowrap; +} + +.pagination { + border-top: 1px solid rgba(44, 123, 109, 0.36); + gap: 0.8rem; + padding: 0.8rem 1rem; +} + +.pagination a, +.pagination span { + border: 1px solid #1d554c; + border-radius: 7px; + min-width: 5.8rem; + padding: 0.48rem 0.75rem; + text-align: center; +} + +.pagination span { + opacity: 0.55; +} + +.chamber-card { + align-items: stretch; + display: grid; + flex: 0 0 28rem; + grid-template-columns: repeat(3, 1fr); + overflow: hidden; + padding: 0.75rem; +} + +.segment { + align-items: center; + border-radius: 7px; + color: var(--muted); + display: flex; + font-weight: 700; + justify-content: center; + min-height: 4.4rem; +} + +.segment.active { + background: #105f54; + color: white; + outline: 1px solid #258778; +} + +.score-note { + font-size: 0.86rem; + margin: 0.8rem 0; +} + +.rankings-grid { + gap: 1.25rem; +} + +.ranking-card { + flex: 1 1 0; + overflow: hidden; +} + +.ranking-card header, +.chart-card header { + align-items: center; + justify-content: space-between; + padding: 1rem 1rem 0.65rem; +} + +.ranking-card header span { + color: var(--muted); + font-size: 0.86rem; +} + +.ranking-list { + list-style: none; + margin: 0; + padding: 0; +} + +.ranking-list li { + border-top: 1px solid rgba(44, 123, 109, 0.22); +} + +.ranking-list li.selected { + background: rgba(47, 189, 159, 0.16); + box-shadow: inset 0 0 0 1px rgba(47, 189, 159, 0.55); +} + +.ranking-list a { + align-items: center; + display: grid; + gap: 0.7rem; + grid-template-columns: 2.2rem 3.2rem minmax(0, 1fr) 4rem; + min-height: 3.2rem; + padding: 0.45rem 0.9rem; +} + +.rank, +.votes { + color: var(--muted); + font-variant-numeric: tabular-nums; + text-align: right; +} + +.score { + border-radius: 5px; + color: white; + font-variant-numeric: tabular-nums; + padding: 0.42rem 0.2rem; + text-align: center; +} + +.score.positive { + background: linear-gradient(90deg, #0e6d5e, #2fbd9f); +} + +.score.negative { + background: linear-gradient(90deg, #76420e, var(--amber)); +} + +.profile-card, +.compare-card, +.compare-controls { + background: color-mix(in srgb, var(--panel) 88%, transparent); + border: 1px solid var(--line); + border-radius: 18px; + overflow: hidden; +} + +.profile-header { + align-items: center; + display: flex; + justify-content: space-between; + padding: 1.55rem 1.75rem; +} + +.profile-identity { + align-items: center; + display: flex; + gap: 1.2rem; +} + +.avatar { + align-items: center; + background: #0d372f; + border: 1px solid #1d554c; + border-radius: 999px; + color: #8fe2d0; + display: inline-flex; + font-weight: 800; + height: 4.4rem; + justify-content: center; + width: 4.4rem; +} + +.profile-header h2 { + font-size: 1.65rem; + margin: 0; +} + +.profile-header p, +.overall-score span, +.overall-score small, +.compare-legend small, +.compare-legend p { + color: var(--muted); +} + +.party-pill { + background: #0b2a3b; + border-radius: 5px; + color: #83b9e7; + font-size: 0.8rem; + padding: 0.2rem 0.45rem; +} + +.overall-score { + text-align: right; +} + +.overall-score strong { + display: inline-block; + font-size: 2rem; + margin-top: 0.3rem; +} + +.topic-panels { + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); + display: grid; + grid-template-columns: 1fr 1fr; +} + +.topic-panels article { + padding: 1.35rem 1.6rem; +} + +.topic-panels article + article { + border-left: 1px solid var(--line); +} + +.topic-panels h3, +.profile-history h3 { + color: var(--teal); + margin: 0 0 0.9rem; +} + +.topic-panels .opposed-heading { + color: var(--amber); +} + +.topic-row { + align-items: center; + border-left: 3px solid transparent; + border-radius: 6px; + display: grid; + gap: 0.75rem; + grid-template-columns: 3.4rem minmax(0, 1fr) 9rem; + margin: 0.65rem 0; + padding: 0.35rem 0.5rem; +} + +.topic-row.active { + background: rgba(216, 137, 45, 0.12); + border-left-color: var(--amber); +} + +.topic-row span { + font-weight: 650; +} + +.topic-row i { + background: currentColor; + border-radius: 999px; + color: #75c9b8; + display: block; + height: 0.3rem; + max-width: 100%; +} + +.profile-history { + padding: 1.2rem 1.6rem 1.4rem; +} + +.compare-controls { + border-radius: 8px; + margin-top: 1.4rem; + padding: 1.1rem 1.25rem 0.4rem; +} + +.compare-controls h2 { + color: #6fa89b; + font-size: 0.9rem; + letter-spacing: 0.08em; + margin-top: 0.4rem; + text-transform: uppercase; +} + +.axis-chips a { + border-radius: 6px; +} + +.compare-card { + align-items: stretch; + display: grid; + grid-template-columns: minmax(0, 1.25fr) minmax(18rem, 0.75fr); + margin-top: 1.4rem; + padding: 1.6rem; +} + +.radar-frame { + min-height: 31rem; +} + +.radar-chart { + display: block; + height: auto; + width: 100%; +} + +.radar-ring { + fill: transparent; + stroke: rgba(55, 105, 94, 0.55); +} + +.radar-axis { + stroke: rgba(70, 116, 106, 0.4); +} + +.radar-label { + fill: #72a99c; + font-size: 15px; + font-weight: 650; +} + +.compare-legend { + padding: 1rem 0 1rem 1.5rem; +} + +.legend-row { + align-items: center; + display: flex; + gap: 0.8rem; + margin: 1rem 0; +} + +.legend-line { + border-radius: 999px; + display: inline-block; + height: 0.25rem; + width: 2.2rem; +} + +.legend-dot { + border-radius: 999px; + display: inline-block; + height: 0.7rem; + width: 0.7rem; +} + +.line-0, +.dot-0 { background: #2fbd9f; } +.line-1, +.dot-1 { background: #8f6ff0; } +.line-2, +.dot-2 { background: #f4b860; } +.line-3, +.dot-3 { background: #7bdff2; } + +.member { + min-width: 0; +} + +.member strong, +.member small { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.member small { + color: var(--muted); + font-size: 0.78rem; +} + +.empty-state { + border-top: 1px solid rgba(44, 123, 109, 0.22); + margin: 0; + min-height: 10rem; + padding: 2.2rem 1rem; + text-align: center; +} + +.chart-card { + margin-top: 1.25rem; +} + +.chart-frame { + padding: 0.5rem 1rem 0.85rem; +} + +.chart-legend { + display: grid; + gap: 0.65rem; + grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); + padding: 0 1rem 0.85rem; +} + +.chart-legend.compact { + grid-template-columns: minmax(0, 1fr); + padding-top: 0.15rem; +} + +.chart-legend.compact .chart-legend-row { + align-items: flex-start; + display: flex; + gap: 0.65rem; +} + +.chart-legend.compact .chart-legend-line, +.chart-legend.compact .chart-legend-marker { + flex: 0 0 auto; + margin-top: 0.3rem; +} + +.chart-legend.compact .chart-legend-copy { + flex: 1 1 auto; +} + +.chart-legend-row { + align-items: flex-start; + background: rgba(12, 38, 33, 0.78); + border: 1px solid rgba(44, 123, 109, 0.28); + border-radius: 8px; + box-shadow: inset 0 0 0 1px rgba(8, 54, 47, 0.22); + display: flex; + gap: 0.7rem; + min-height: 3.4rem; + padding: 0.65rem 0.8rem; +} + +.chart-legend-line, +.chart-legend-marker { + display: inline-block; + flex: 0 0 auto; +} + +.chart-legend-line { + align-self: flex-start; + border-top: 4px solid currentColor; + color: inherit; + margin-top: 0.6rem; + width: 2.25rem; +} + +.chart-legend-marker { + background: currentColor; + color: inherit; + height: 0.85rem; + margin-top: 0.2rem; + width: 0.85rem; +} + +.chart-legend-copy, +.chart-legend-label, +.chart-legend-meta { + min-width: 0; +} + +.chart-legend-copy { + display: grid; + gap: 0.2rem; +} + +.chart-legend-label { + color: var(--text); + display: block; + font-size: 1.08rem; + font-weight: 760; + letter-spacing: -0.01em; + overflow-wrap: anywhere; +} + +.chart-legend-meta { + color: var(--muted); + display: block; + font-size: 0.82rem; + text-align: left; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.score-chart { + display: block; + height: auto; + min-height: 18rem; + width: 100%; +} + +.chart-grid { + stroke: #33544d; + stroke-dasharray: 4 5; +} + +.chart-year-line { + stroke: rgba(51, 84, 77, 0.45); + stroke-dasharray: 3 8; +} + +.chart-axis { + stroke: #48635d; +} + +.chart-axis-label, +.chart-series-label, +.chart-empty { + fill: #9fb0ac; + font-size: 13px; +} + +.chart-empty { + font-size: 16px; +} + +.line-0, +.marker-0 { + color: #009e73; +} + +.line-1, +.marker-1 { + color: #0072b2; +} + +.line-2, +.marker-2 { + color: #e69f00; +} + +.line-3, +.marker-3 { + color: #cc79a7; +} + +.line-1 { + border-top-style: dashed; +} + +.line-2 { + border-top-style: dotted; +} + +.line-3 { + background-image: linear-gradient( + to right, + currentColor 0 45%, + transparent 45% 60%, + currentColor 60% 75%, + transparent 75% 90%, + currentColor 90% 100% + ); + background-repeat: repeat-x; + background-size: 1.8rem 100%; + border-top: 0; + height: 4px; +} + +.marker-0 { + border-radius: 999px; +} + +.marker-1 { + border-radius: 2px; +} + +.marker-2 { + transform: rotate(45deg); +} + +.marker-3 { + background: transparent; + border-bottom: 0.9rem solid currentColor; + border-left: 0.45rem solid transparent; + border-right: 0.45rem solid transparent; + height: 0; + width: 0; +} + +.footer { + border-top: 1px solid #12362f; + display: flex; + flex-wrap: wrap; + gap: 1rem; + justify-content: center; + padding: 1.1rem; +} + +.footer span { + border-right: 1px solid #31514a; + padding-right: 1rem; +} + +.footer span:last-child { + border-right: 0; +} + +.setup-error { + margin-top: 3rem; + padding: 1.25rem; +} + +.setup-error pre { + background: #020c0a; + border: 1px solid #284b44; + border-radius: 6px; + color: #d3e5e0; + overflow: auto; + padding: 1rem; +} + +.sr-only { + clip: rect(0, 0, 0, 0); + border: 0; + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} + +@media (max-width: 860px) { + .page-heading, + .controls-grid, + .rankings-grid, + .topic-panels, + .compare-card, + .login-panel { + display: block; + } + + .heading-actions, + .chamber-card { + margin-top: 1rem; + } + + .ranking-card + .ranking-card { + margin-top: 1rem; + } + + .topbar { + align-items: flex-start; + gap: 0.8rem; + } + + .account-nav { + flex-wrap: wrap; + justify-content: flex-end; + } + + .primary-nav { + order: 3; + margin: 0.7rem 0 0; + width: 100%; + } + + .primary-nav a { + flex: 1; + min-width: 0; + } + + .topic-panels article + article { + border-left: 0; + border-top: 1px solid var(--line); + } + + .profile-header { + align-items: flex-start; + display: block; + } + + .overall-score { + margin-top: 1rem; + text-align: left; + } + + .compare-legend { + padding-left: 0; + } + + .chart-legend-row { + grid-template-columns: 2.25rem 1rem minmax(0, 1fr); + } + + .chart-legend-meta { + justify-self: start; + text-align: left; + } + + .wide-search { + align-items: stretch; + display: grid; + grid-template-columns: 1fr auto; + } + + .wide-search input { + grid-column: 1 / -1; + } + + .phonebook-results header, + .pagination, + .phonebook-list a { + align-items: flex-start; + display: grid; + grid-template-columns: 1fr; + } + + .phonebook-meta { + white-space: normal; + } + + .login-copy { + border-right: 0; + border-bottom: 1px solid rgba(44, 123, 109, 0.45); + margin-bottom: 1rem; + padding: 0 0 1rem; + } +} diff --git a/pipelines/web/static/vendor/htmx.min.js b/pipelines/web/static/vendor/htmx.min.js new file mode 100644 index 0000000..faafa3e --- /dev/null +++ b/pipelines/web/static/vendor/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function B(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function X(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function V(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function j(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function $(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function _(e,t){e=w(e);if(t){b().setTimeout(function(){_(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function z(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(P(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=z(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=D(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!X()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||ne(e,"hx-push-url");const c=t.etc.replace||ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/pipelines/web/svg.py b/pipelines/web/svg.py new file mode 100644 index 0000000..8b40b01 --- /dev/null +++ b/pipelines/web/svg.py @@ -0,0 +1,231 @@ +"""Inline SVG rendering helpers.""" + +from __future__ import annotations + +from html import escape +from math import cos, pi, sin + +from pipelines.web.repository import ChartSeries, RadarSeries + +SERIES_STYLES = ( + { + "color": "#009e73", + "dasharray": None, + "marker": "circle", + }, + { + "color": "#0072b2", + "dasharray": "10 6", + "marker": "square", + }, + { + "color": "#e69f00", + "dasharray": "4 5", + "marker": "diamond", + }, + { + "color": "#cc79a7", + "dasharray": "14 5 3 5", + "marker": "triangle", + }, +) + + +def render_score_history_svg(series: list[ChartSeries]) -> str: + """Render a responsive inline SVG score history chart.""" + width = 880 + height = 300 + margin_left = 70 + margin_right = 28 + margin_top = 24 + margin_bottom = 48 + plot_width = width - margin_left - margin_right + plot_height = height - margin_top - margin_bottom + + all_years = sorted({point.year for item in series for point in item.points}) + if not all_years: + return _empty_svg(width, height, "No score history for this selection") + + min_year = min(all_years) + max_year = max(all_years) + year_span = max(max_year - min_year, 1) + + def x_for(year: int) -> float: + return margin_left + ((year - min_year) / year_span) * plot_width + + def y_for(score: int) -> float: + return margin_top + ((100 - score) / 100) * plot_height + + parts: list[str] = [ + f'', + '', + ] + + for score in (0, 25, 50, 75, 100): + y = y_for(score) + parts.append( + f'' + ) + parts.append( + f'{score}' + ) + + tick_years = _tick_years(all_years) + for year in tick_years: + x = x_for(year) + parts.append( + f'' + ) + parts.append( + f'{year}' + ) + + parts.append( + f'' + ) + parts.append( + f'' + ) + + for index, item in enumerate(series): + points = sorted(item.points, key=lambda point: point.year) + if not points: + continue + style = SERIES_STYLES[index % len(SERIES_STYLES)] + color = style["color"] + path = " ".join( + f"{'M' if point_index == 0 else 'L'} {x_for(point.year):.2f} {y_for(point.score):.2f}" + for point_index, point in enumerate(points) + ) + label = escape(item.label) + dash_attr = ( + f' stroke-dasharray="{style["dasharray"]}"' + if style["dasharray"] + else "" + ) + parts.append( + f'' + f"{label}" + ) + for point in points: + parts.append( + _point_marker( + marker=style["marker"], + x=x_for(point.year), + y=y_for(point.score), + color=color, + label=f"{label}: {point.score:.0f} in {point.year}", + ) + ) + last = points[-1] + parts.append( + f'' + f"{last.score:.0f}" + ) + + parts.append("") + return "".join(parts) + + +def _empty_svg(width: int, height: int, message: str) -> str: + return ( + f'' + '' + f'{escape(message)}' + "" + ) + + +def _tick_years(years: list[int]) -> list[int]: + first = years[0] + last = years[-1] + start = first - (first % 5) + tick_years = {year for year in range(start, last + 1, 5) if first <= year <= last} + tick_years.add(first) + tick_years.add(last) + return sorted(tick_years) + + +def render_compare_radar_svg(topics: list[str], series: list[RadarSeries]) -> str: + """Render a server-side radar chart for legislator comparison.""" + width = 720 + height = 560 + center_x = 285 + center_y = 280 + radius = 200 + if len(topics) < 3 or not series: + return _empty_svg(width, height, "Choose at least 3 axes and 1 legislator") + + axis_count = len(topics) + + def point_for(index: int, score: float) -> tuple[float, float]: + angle = -pi / 2 + (2 * pi * index / axis_count) + distance = radius * max(0, min(score, 100)) / 100 + return center_x + cos(angle) * distance, center_y + sin(angle) * distance + + def ring_points(score: float) -> str: + return " ".join( + f"{point_for(index, score)[0]:.2f},{point_for(index, score)[1]:.2f}" + for index in range(axis_count) + ) + + parts: list[str] = [ + f'', + '', + ] + for ring in (25, 50, 75, 100): + parts.append(f'') + for index, topic in enumerate(topics): + outer_x, outer_y = point_for(index, 100) + label_x, label_y = point_for(index, 113) + parts.append( + f'' + ) + anchor = "middle" + if label_x < center_x - 24: + anchor = "end" + elif label_x > center_x + 24: + anchor = "start" + parts.append( + f'{escape(topic)}' + ) + + for index, item in enumerate(series): + color = SERIES_STYLES[index % len(SERIES_STYLES)]["color"] + points = " ".join( + f"{point_for(topic_index, item.scores_by_topic.get(topic, 50.0))[0]:.2f}," + f"{point_for(topic_index, item.scores_by_topic.get(topic, 50.0))[1]:.2f}" + for topic_index, topic in enumerate(topics) + ) + label = escape(item.legislator.display_name) + parts.append( + f'' + f"{label}" + ) + parts.append("") + return "".join(parts) + + +def _point_marker(*, marker: str, x: float, y: float, color: str, label: str) -> str: + title = f"{escape(label)}" + if marker == "square": + return ( + f'{title}' + ) + if marker == "diamond": + points = ( + f"{x:.2f},{y - 5.2:.2f} " + f"{x + 5.2:.2f},{y:.2f} " + f"{x:.2f},{y + 5.2:.2f} " + f"{x - 5.2:.2f},{y:.2f}" + ) + return f'{title}' + if marker == "triangle": + points = ( + f"{x:.2f},{y - 5.5:.2f} " + f"{x + 5.5:.2f},{y + 4.5:.2f} " + f"{x - 5.5:.2f},{y + 4.5:.2f}" + ) + return f'{title}' + return f'{title}' diff --git a/pipelines/web/templates/base.html b/pipelines/web/templates/base.html new file mode 100644 index 0000000..719b180 --- /dev/null +++ b/pipelines/web/templates/base.html @@ -0,0 +1,40 @@ + + + + + + {% block title %}Nornsight{% endblock %} + + + + +
+ + N + Nornsight + + {% if show_primary_nav|default(true) %} + + {% endif %} + +
+ {% block body %}{% endblock %} + + diff --git a/pipelines/web/templates/compare.html b/pipelines/web/templates/compare.html new file mode 100644 index 0000000..b4da2dd --- /dev/null +++ b/pipelines/web/templates/compare.html @@ -0,0 +1,87 @@ +{% extends "base.html" %} + +{% block title %}Compare Legislators{% endblock %} + +{% block body %} +
+
+
+

Compare legislators

+

Up to 4 legislators · up to 8 issue axes · each polygon = one legislator's full issue profile

+
+
+ +
+ + +

Legislators ({{ selected_legislator_options|length }} / 4)

+
+ {% for legislator in selected_legislator_options %} + {% set without = selected_legislators | reject('equalto', legislator.legislator_id) | list %} + {{ legislator.display_name }}{% if legislator.state %} — {{ legislator.state }}{% endif %} × + {% endfor %} + {% if selected_legislator_options|length < 4 %} + {% for option in legislator_options %} + {% if option.legislator_id not in selected_legislators %} + + {{ option.display_name }} + {% endif %} + {% endfor %} + {% endif %} +
+ +

Issue axes ({{ topics|length }} / 8)

+
+ {% for topic in topics %} + {% set without_topic = topics[:loop.index0] + topics[loop.index:] %} + {{ topic }} × + {% endfor %} + {% if topics|length < 8 %} + {% for topic in topic_options %} + {% if topic not in topics %} + {{ topic }} + {% endif %} + {% endfor %} + {% endif %} +
+
+ +
+
{{ radar_svg | safe }}
+ +
+
+
+ Actual record, not rhetoric + Source: congressional roll-call votes + Not affiliated with any political party or organization +
+{% endblock %} diff --git a/pipelines/web/templates/dashboard.html b/pipelines/web/templates/dashboard.html new file mode 100644 index 0000000..c454cfd --- /dev/null +++ b/pipelines/web/templates/dashboard.html @@ -0,0 +1,30 @@ +{% extends "base.html" %} + +{% block title %}Legislative Accountability{% endblock %} + +{% block body %} +
+
+
+

Legislative accountability

+

US legislative accountability · precomputed legislator topic scores{% if latest_score_year %} through {{ latest_score_year }}{% endif %}

+
+
+ Methodology + Data sources + Last updated: {{ last_updated.strftime("%b %Y") if last_updated else "Unavailable" }} +
+
+ +
Choose one or more score topics, then select lawmakers to compare computed records over time.
+ +
+ {% include "partials/_dashboard.html" %} +
+
+
+ Actual record, not rhetoric + Source: congressional roll-call votes + Not affiliated with any political party or organization +
+{% endblock %} diff --git a/pipelines/web/templates/legislators.html b/pipelines/web/templates/legislators.html new file mode 100644 index 0000000..66c525f --- /dev/null +++ b/pipelines/web/templates/legislators.html @@ -0,0 +1,148 @@ +{% extends "base.html" %} + +{% block title %}Legislator Profiles{% endblock %} + +{% block body %} +
+
+
+

Legislator profiles

+

Full issue taxonomy · search any current legislator

+
+
+ + + +
+ + {% if q %} +
+
+

Matching legislators

+ {{ result_count }} result{{ "" if result_count == 1 else "s" }} +
+ {% if matches %} +
    + {% for option in matches %} +
  1. + + {{ option.display_name }} + + {{ option.state or "US" }}{% if option.party %} · {{ option.party }}{% endif %}{% if option.chamber %} · {{ option.chamber }}{% endif %} + + +
  2. + {% endfor %} +
+ + {% else %} +

No legislators matched this search.

+ {% endif %} +
+ {% endif %} + + {% if profile %} +
+
+
+ {{ profile.legislator.display_name.split(',')[0][:1] }}{{ profile.legislator.display_name.split(',')[-1].strip()[:1] }} +
+

{{ profile.legislator.display_name }} {{ profile.legislator.chamber or "LEG" }}

+

{{ profile.legislator.state or "US" }} · {{ profile.legislator.party or "Unaffiliated" }}{% if profile.serving_since %} · Serving since {{ profile.serving_since }}{% endif %}

+
+
+
+ Overall avg + {{ profile.overall_score|round(0) if profile.overall_score is not none else "—" }} + / 100 +
+
+ + {% if profile.top_topics or profile.bottom_topics %} +
+ + +
+ +
+

{{ selected_topic or "Topic" }} — score history

+
{{ history_svg | safe }}
+ {% if history_series %} +
+ {% for item in history_series %} +
+ + +
+ {{ item.label }} + + {% if item.party %}{{ item.party }}{% endif %}{% if item.party and item.state %} · {% endif %}{% if item.state %}{{ item.state }}{% endif %} + +
+
+ {% endfor %} +
+ {% endif %} +
+ {% else %} +

No issue scores are available for this legislator yet.

+ {% endif %} +
+ {% endif %} +
+
+ Actual record, not rhetoric + Source: congressional roll-call votes + Not affiliated with any political party or organization +
+{% endblock %} diff --git a/pipelines/web/templates/login.html b/pipelines/web/templates/login.html new file mode 100644 index 0000000..009dd49 --- /dev/null +++ b/pipelines/web/templates/login.html @@ -0,0 +1,45 @@ +{% extends "base.html" %} + +{% block title %}Sign in | Nornsight{% endblock %} + +{% block body %} +
+ +
+{% endblock %} diff --git a/pipelines/web/templates/partials/_chart.html b/pipelines/web/templates/partials/_chart.html new file mode 100644 index 0000000..7328789 --- /dev/null +++ b/pipelines/web/templates/partials/_chart.html @@ -0,0 +1,30 @@ +
+
+

Score history{% if selected_issue_label %} — {{ selected_issue_label }}{% endif %}

+ Clear comparison +
+
+ {{ chart_svg | safe }} +
+ {% if chart_series %} +
+ {% for item in chart_series %} + {% set style_index = loop.index0 % 4 %} +
+ + +
+ {{ item.label }} + + {% if item.party %}{{ item.party }}{% endif %}{% if item.party and item.state %} · {% endif %}{% if item.state %}{{ item.state }}{% endif %} + +
+
+ {% endfor %} +
+ {% endif %} +

Scores reflect averaged precomputed topic rows per year. Sparse years are omitted rather than plotted as zero.

+
diff --git a/pipelines/web/templates/partials/_dashboard.html b/pipelines/web/templates/partials/_dashboard.html new file mode 100644 index 0000000..bc7358b --- /dev/null +++ b/pipelines/web/templates/partials/_dashboard.html @@ -0,0 +1,25 @@ +
+ {% include "partials/_issue_filters.html" %} +
+ House + Senate + All +
+
+ +

Support score: 1-100 precomputed from bill topic stance and roll-call votes. Higher means more aligned with the topic.

+ +{% include "partials/_rankings.html" %} +{% include "partials/_chart.html" %} diff --git a/pipelines/web/templates/partials/_issue_filters.html b/pipelines/web/templates/partials/_issue_filters.html new file mode 100644 index 0000000..037b617 --- /dev/null +++ b/pipelines/web/templates/partials/_issue_filters.html @@ -0,0 +1,46 @@ +
+

Issue filters

+
+ + {% if congress %} + + {% endif %} + {% for legislator_id in compare %} + + {% endfor %} + {% for issue in issues %} + + {{ issue }} + × + + + {% endfor %} + + +
+ + {% if suggestions %} +
+ {% for suggestion in suggestions %} + {% if suggestion not in issues %} + {{ suggestion }} + {% endif %} + {% endfor %} +
+ {% endif %} +
diff --git a/pipelines/web/templates/partials/_legislator_suggestions.html b/pipelines/web/templates/partials/_legislator_suggestions.html new file mode 100644 index 0000000..1c47677 --- /dev/null +++ b/pipelines/web/templates/partials/_legislator_suggestions.html @@ -0,0 +1,11 @@ +{% if matches %} + +{% elif q %} +

No matches

+{% endif %} diff --git a/pipelines/web/templates/partials/_rankings.html b/pipelines/web/templates/partials/_rankings.html new file mode 100644 index 0000000..ef6b857 --- /dev/null +++ b/pipelines/web/templates/partials/_rankings.html @@ -0,0 +1,61 @@ +
+ + + +
diff --git a/pipelines/web/templates/setup_error.html b/pipelines/web/templates/setup_error.html new file mode 100644 index 0000000..210a175 --- /dev/null +++ b/pipelines/web/templates/setup_error.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} + +{% block title %}Database Setup Required{% endblock %} + +{% block body %} +
+
+
+

Database setup required

+

Configure DATA_SCIENCE_DEV before opening the dashboard.

+
+
+
{{ error }}
+
+{% endblock %}