File size: 10,323 Bytes
c6af477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""HTML rendering helpers for the Insureon offline clone.

Page chrome (header, primary navigation, footer, meta) is rendered from the
captured content modules so every page shares the same source-grounded shell.
"""

from __future__ import annotations

import html
from typing import Any, Iterable, Mapping, Sequence

import assets
from content import site as S

LOGO = assets.LOGO
LOGO_MOBILE = assets.LOGO_MOBILE
# www.insureon.com serves no favicon.ico (it 404s at source), so the tab icon
# uses a captured brand mark instead of a path that would 404 in the clone too.
FAVICON = assets.find("logos/insureon/logo/logo_insureon_vertical") or LOGO


def esc(value: Any) -> str:
    """HTML-escape any value, including None."""
    return html.escape("" if value is None else str(value), quote=True)


def money(cents: int) -> str:
    """Render integer cents as $X,XXX (no cents) or $X,XXX.YY when non-round."""
    if cents is None:
        return ""
    whole, rem = divmod(int(cents), 100)
    if rem:
        return f"${whole:,}.{rem:02d}"
    return f"${whole:,}"


def _nav_children(children: Iterable[Mapping[str, str]]) -> str:
    return "".join(
        f'<a href="{esc(c.get("href", "#"))}">{esc(c.get("label", ""))}</a>'
        for c in children or []
    )


def header(active: str = "", logged_in: bool = False, account_name: str = "") -> str:
    items = []
    for group in S.NAV:
        label = esc(group.get("label", ""))
        href = esc(group.get("href", "#"))
        children = group.get("children") or []
        is_active = ' aria-current="true"' if group.get("href") == active else ""
        caret = '<span class="mainnav__caret" aria-hidden="true">▾</span>' if children else ""
        panel = (
            f'<div class="mainnav__panel">{_nav_children(children)}</div>'
            if children else ""
        )
        items.append(
            f'<div class="mainnav__item">'
            f'<a class="mainnav__top" href="{href}"{is_active}>{label}{caret}</a>'
            f"{panel}</div>"
        )
    if logged_in:
        account = ('<a class="login" href="/account">My account</a>'
                   '<a class="login" href="/account/logout">Log out</a>')
    else:
        account = '<a class="login" href="/account/login">Log in</a>'
    # Captured mobile header composition (390x844): the toggle sits BEFORE the
    # wordmark, the wordmark is a distinct mobile asset, "Log in" and the search
    # field are not rendered, and a round white-on-purple call button precedes
    # the Get Quotes pill. Desktop keeps its own composition.
    menu_glyph = (f'<img src="{assets.MENU_ICON}" alt="">' if assets.MENU_ICON
                  else '\u2630')
    call_button = (
        f'<a class="header-call" href="tel:{esc(S.PHONE["tel"])}" '
        f'aria-label="Call {esc(S.PHONE["display"])}">'
        f'<img src="{assets.CALL_ICON}" alt=""></a>'
        if assets.CALL_ICON else ""
    )
    return f"""<a class="skip-link" href="#main">Skip to main content</a>
<header class="site-header">
  <div class="site-header__inner">
    <button class="navtoggle" type="button" aria-label="Open menu" aria-expanded="false"
            data-navtoggle>{menu_glyph}</button>
    <a class="brand" href="/" aria-label="Insureon home">
      <img class="brand__desktop" src="{LOGO}" alt="Insureon">
      <img class="brand__mobile" src="{LOGO_MOBILE}" alt="Insureon">
    </a>
    <nav class="mainnav" data-mainnav aria-label="Primary">{''.join(items)}</nav>
    <div class="header-actions">
      {account}
      <form class="header-search" action="/search" method="get" role="search">
        <label class="sr-only" for="hdr-q" style="position:absolute;left:-9999px">Search Insureon</label>
        <input id="hdr-q" type="search" name="q" placeholder="Search" aria-label="Search Insureon">
        <button type="submit" aria-label="Search">⌕</button>
      </form>
      {call_button}
      <a class="btn btn--primary btn--sm" href="/start-quote">Get Quotes</a>
    </div>
  </div>
</header>"""


def _footer_cols() -> str:
    out = []
    for col in S.FOOTER:
        links = "".join(
            f'<li><a href="{esc(link.get("href", "#"))}">'
            f'{esc(link.get("label", ""))}</a></li>'
            for link in col.get("links", [])
        )
        out.append(f'<div><h4>{esc(col.get("heading", ""))}</h4><ul>{links}</ul></div>')
    return "".join(out)


def footer() -> str:
    legal = getattr(S, "FOOTER_LEGAL", {}) or {}
    links = "".join(
        f'<a href="{esc(link.get("href", "#"))}">{esc(link.get("label", ""))}</a>'
        + ('<span aria-hidden="true">|</span>'
           if i < len(legal.get("links", [])) - 1 else "")
        for i, link in enumerate(legal.get("links", []))
    )
    phone = getattr(S, "PHONE", {}) or {}
    disclaimer = legal.get("disclaimer", "")
    return f"""<footer class="site-footer">
  <div class="wrap footer-disclaimer">{esc(legal.get("premium_note", ""))}</div>
  <div class="footer-phone">
    <a href="tel:{esc(phone.get('tel', ''))}">Call {esc(phone.get('display', ''))}</a>
    <span>{esc(phone.get('hours', ''))}</span>
  </div>
  <div class="wrap"><div class="footer-cols">{_footer_cols()}</div></div>
  <div class="wrap footer-legal">
    <div class="footer-legal__links">{links}</div>
    <p>{esc(legal.get("copyright", ""))}</p>
    <p>{esc(legal.get("address", ""))}</p>
    <p>{esc(disclaimer)}</p>
  </div>
</footer>"""


def page(
    body: str,
    *,
    title: str,
    description: str = "",
    active: str = "",
    canonical: str = "",
    logged_in: bool = False,
    account_name: str = "",
    body_class: str = "",
) -> str:
    """Wrap page body in the full document shell."""
    canon = f'<link rel="canonical" href="{esc(canonical)}">' if canonical else ""
    return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{esc(title)}</title>
<meta name="description" content="{esc(description)}">
<meta property="og:title" content="{esc(title)}">
<meta property="og:description" content="{esc(description)}">
<meta property="og:type" content="website">
{canon}
<link rel="icon" href="{FAVICON}">
<link rel="stylesheet" href="/static/site.css">
</head>
<body class="{esc(body_class)}">
{header(active=active, logged_in=logged_in, account_name=account_name)}
<main id="main">
{body}
</main>
{footer()}
<script src="/static/site.js" defer></script>
</body>
</html>"""


# --- small shared blocks -----------------------------------------------------

def page_head(h1: str, intro: str = "", crumbs: Sequence[tuple[str, str]] = ()) -> str:
    crumb_html = ""
    if crumbs:
        parts = []
        for i, (label, href) in enumerate(crumbs):
            last = i == len(crumbs) - 1
            parts.append(
                esc(label) if last or not href
                else f'<a href="{esc(href)}">{esc(label)}</a>'
            )
        crumb_html = f'<div class="breadcrumb">{" / ".join(parts)}</div>'
    lede = f'<p class="lede" style="margin-left:0">{esc(intro)}</p>' if intro else ""
    return f'<section class="page-head"><div class="wrap">{crumb_html}<h1>{esc(h1)}</h1>{lede}</div></section>'


def stepper(steps: Sequence[tuple[str, str]], current: str) -> str:
    """steps: sequence of (key, label). Marks done/current by position."""
    keys = [k for k, _ in steps]
    try:
        idx = keys.index(current)
    except ValueError:
        idx = 0
    out = []
    for i, (key, label) in enumerate(steps):
        cls = "stepper__step"
        if i < idx:
            cls += " stepper__step--done"
        elif i == idx:
            cls += " stepper__step--current"
        mark = "✓" if i < idx else str(i + 1)
        out.append(
            f'<div class="{cls}"><span class="stepper__bullet">{mark}</span>'
            f"<span>{esc(label)}</span></div>"
        )
    return f'<div class="stepper">{"".join(out)}</div>'


def field(
    name: str,
    label: str,
    *,
    value: str = "",
    kind: str = "text",
    hint: str = "",
    error: str = "",
    required: bool = False,
    options: Sequence[tuple[str, str]] = (),
    placeholder: str = "",
    attrs: str = "",
) -> str:
    cls = "field field--error" if error else "field"
    req = " required" if required else ""
    star = ' <span aria-hidden="true" style="color:#c62828">*</span>' if required else ""
    err_id = f"{name}-error"
    described = f' aria-describedby="{err_id}"' if error else ""
    invalid = ' aria-invalid="true"' if error else ""
    if kind == "select":
        opts = "".join(
            f'<option value="{esc(v)}"{" selected" if str(v) == str(value) else ""}>{esc(t)}</option>'
            for v, t in options
        )
        control = (
            f'<select id="{esc(name)}" name="{esc(name)}"{req}{described}{invalid} {attrs}>{opts}</select>'
        )
    elif kind == "textarea":
        control = (
            f'<textarea id="{esc(name)}" name="{esc(name)}" rows="4"'
            f' placeholder="{esc(placeholder)}"{req}{described}{invalid} {attrs}>{esc(value)}</textarea>'
        )
    else:
        control = (
            f'<input id="{esc(name)}" name="{esc(name)}" type="{esc(kind)}"'
            f' value="{esc(value)}" placeholder="{esc(placeholder)}"'
            f"{req}{described}{invalid} {attrs}>"
        )
    hint_html = f'<div class="hint">{esc(hint)}</div>' if hint else ""
    err_html = f'<div class="field__error" id="{err_id}">{esc(error)}</div>' if error else ""
    return (
        f'<div class="{cls}"><label for="{esc(name)}">{esc(label)}{star}</label>'
        f"{control}{hint_html}{err_html}</div>"
    )


def error_summary(errors: Mapping[str, str]) -> str:
    if not errors:
        return ""
    items = "".join(f"<li>{esc(v)}</li>" for v in errors.values())
    return (
        '<div class="form-error" role="alert">'
        f"<strong>Please correct {len(errors)} field"
        f'{"s" if len(errors) != 1 else ""} before continuing.</strong>'
        f"<ul style='margin:.5rem 0 0;padding-left:1.1rem'>{items}</ul></div>"
    )


def notice(text: str) -> str:
    return f'<div class="form-notice">{esc(text)}</div>' if text else ""


def badge(status: str) -> str:
    return f'<span class="badge badge--{esc(status)}">{esc(status.title())}</span>'