AgPerry's picture
Add WebsiteBench card, manifest, and the medium task
bc7aa4f verified
Raw History Blame
37.7 kB
"""Escaped server-rendered views for the Medium offline clone."""
from __future__ import annotations
import html
import json
from typing import Any, Iterable, Mapping
from urllib.parse import quote_plus
import site_data
def e(value: Any) -> str:
return html.escape(str(value if value is not None else ""), quote=True)
def safe_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False).replace("</", "<\\/")
def safe_next(value: str | None, fallback: str = "/") -> str:
target = str(value or "")
return target if target.startswith("/") and not target.startswith("//") else fallback
def account_sidebar(account: Mapping[str, Any]) -> str:
profile_path = f'/@{e(site_data.profile_slug(dict(account)))}'
links = (
('Home', '/', '<path d="M4.5 11.5 12 5l7.5 6.5v7H14v-5h-4v5H4.5v-7Z"/>', None),
('Library', '/me/lists', '<path d="M5 4.5h11.5A2.5 2.5 0 0 1 19 7v12.5H7.5A2.5 2.5 0 0 1 5 17V4.5Zm2.5 10.8H19M9 8h6"/>', None),
('Profile', profile_path, '<circle cx="12" cy="8" r="3.5"/><path d="M5.5 19a6.5 6.5 0 0 1 13 0"/>', None),
('Stories', '/me/stories', '<path d="M5 4.5h14v15H5v-15Zm3.5 4h7M8.5 12h7M8.5 15.5H13"/>', None),
('Stats', '/me/stats', '<path d="M5 19V9m5 10V5m5 14v-7m4 7V3"/>', None),
)
rows = ''.join(
f'<a href="{href}" class="sidebar-link{(" active" if label == "Home" else "")}"{(" aria-current=\"page\"" if current else "")}><svg viewBox="0 0 24 24" aria-hidden="true">{path}</svg><span>{label}</span></a>'
for label, href, path, current in links
)
return f'''<aside class="account-sidebar" id="account-sidebar" aria-label="Medium navigation" data-open="true"><nav class="account-sidebar-primary">{rows}</nav><section class="account-sidebar-following"><a href="/me/following-feed/writers" class="sidebar-link"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="3"/><path d="M3.5 18a5.5 5.5 0 0 1 11 0M18 7v6m-3-3h6"/></svg><span>Following</span></a><p>Find writers and publications to follow.</p><a class="sidebar-suggestion" href="/me/following/suggestions">See suggestions</a></section></aside>'''
def layout(
title: str,
body: str,
*,
account: Mapping[str, Any] | None = None,
page_class: str = "",
editor: bool = False,
) -> str:
sidebar_enabled = bool(account) and not editor and "onboarding-page" not in page_class
if account:
account_name = e(account.get("display_name") or "Writer")
profile_path = f'/@{e(site_data.profile_slug(dict(account)))}'
nav = f'''<button type="button" class="get-app" id="get-app" aria-haspopup="dialog" aria-controls="get-app-popover" aria-expanded="false"><span class="qr-icon" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span>Get app</span></button><section class="app-popover" id="get-app-popover" role="dialog" aria-labelledby="get-app-title" hidden><button type="button" class="app-popover-close" id="get-app-close" aria-label="Close">×</button><strong id="get-app-title">Get the Medium app</strong><div class="app-qr" role="img" aria-label="QR code"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><p>Scan the QR code to read Medium on your phone.</p></section><a href="/new-story" class="write-link"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4.5 5.5h9m-9 0v14h14v-9M11 15l1.3-4.1L18.9 4.3l2.8 2.8-6.6 6.6L11 15Z"/></svg>Write</a><a class="notification-button" id="notifications" href="/me/notifications" aria-label="Notifications"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.5 17.5h13l-1.8-2.4v-4.3a4.7 4.7 0 0 0-9.4 0v4.3l-1.8 2.4Zm4.5 2a2.2 2.2 0 0 0 4 0"/></svg></a><button class="avatar" id="account-menu" aria-label="Account menu" aria-expanded="false">{account_name[:1]}</button><div class="account-popover" id="account-popover" hidden><a class="account-profile-row" href="{profile_path}"><span class="account-profile-avatar">{account_name[:1]}</span><span><strong>{account_name}</strong><small>View profile</small></span></a><a href="/me/settings">Settings</a><a href="/help">Help</a><hr><a href="/plans">Become a Medium member <b aria-hidden="true">✦</b></a><a href="/help?q=partner+program">Apply to the Partner Program</a><hr><button id="sign-out">Sign out<small>Local account</small></button><footer><a href="/about">About</a><a href="/blog">Blog</a><a href="/jobs-at-medium/work-at-medium-959d1a85284e">Careers</a><a href="/medium-privacy-policy-f03bf92035c9">Privacy</a><a href="/medium-terms-of-service-9db0094a1e0f">Terms</a><a href="/medium/">Text to speech</a><span>More</span></footer></div>'''
else:
nav = '<button type="button" class="get-app" id="get-app" aria-haspopup="dialog" aria-controls="get-app-popover" aria-expanded="false"><span class="qr-icon" aria-hidden="true"><i></i><i></i><i></i><i></i></span>Get app</button><section class="app-popover" id="get-app-popover" role="dialog" aria-labelledby="get-app-title" hidden><button type="button" class="app-popover-close" id="get-app-close" aria-label="Close">×</button><strong id="get-app-title">Get the Medium app</strong><div class="app-qr" role="img" aria-label="QR code"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div><p>Scan the QR code to read Medium on your phone.</p></section><a href="/new-story" class="write-link"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4.5 5.5h9m-9 0v14h14v-9M11 15l1.3-4.1L18.9 4.3l2.8 2.8-6.6 6.6L11 15Z"/></svg>Write</a><a class="header-signup" href="/m/signup">Sign up</a><a href="/m/signin">Sign in</a><span class="ghost-avatar" aria-hidden="true"></span>'
editor_class = " editor-shell" if editor else ""
if any(surface in page_class for surface in ("store-surface", "speechify-surface", "membership-error-surface")):
header = ""
elif "about-surface" in page_class:
header = '''<header class="about-header"><a class="about-wordmark" href="/">Medium</a><nav><a class="about-signin" href="/m/signin?operation=login">Sign in</a><a class="about-signup" href="/m/signup?operation=register">Sign up</a></nav></header>'''
elif "help-center-surface" in page_class:
header = '''<header class="help-center-header"><div><a class="wordmark" href="/">Medium</a><span>Help Center</span></div><nav><a href="/">Back to medium.com</a><a class="help-request" href="/help#contact">Submit a request</a></nav></header>'''
elif "status-surface" in page_class:
header = '''<header class="status-header"><a class="wordmark" href="/">Medium</a><nav><a href="/status#report">Report a problem</a><a href="/status#subscribe">Subscribe to updates</a></nav></header>'''
elif not account and "home-page" in page_class:
nav = '<a href="/about">Our story</a><a href="/membership">Membership</a><a id="home-write-trigger" href="/m/signin?operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2Fnew-story&amp;source=--------------------------new_post_topnav------------------">Write</a><a id="home-signin-trigger" href="/m/signin?operation=login&amp;redirect=https%3A%2F%2Fmedium.com%2F&amp;source=--------------------------lo_home_nav------------------">Sign in</a><a class="pill dark" id="home-signup-trigger" href="/m/signin?operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F&amp;source=--------------------------lo_home_nav------------------">Get started</a>'
header = f'''<header class="site-header marketing-header"><a class="wordmark" href="/">Medium</a><nav>{nav}</nav></header>'''
else:
sidebar_toggle = '''<button class="sidebar-toggle" id="sidebar-toggle" aria-label="Sidebar menu" aria-controls="account-sidebar" aria-expanded="true"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6.5h16M4 12h16M4 17.5h16"/></svg></button>''' if sidebar_enabled else ""
header = f'''<header class="site-header reader-header"><div class="reader-header-start">{sidebar_toggle}<a class="wordmark" href="/">Medium</a><form class="header-search" action="/search" method="get" role="search"><span class="search-icon" aria-hidden="true"></span><input type="search" name="q" aria-label="search" placeholder="Search"></form></div><nav>{nav}</nav></header>'''
footer = "" if any(surface in page_class for surface in ("about-surface", "help-center-surface", "status-surface", "store-surface", "speechify-surface", "membership-error-surface")) else '''<footer class="site-footer" aria-label="Medium footer"><a href="/hc/en-us">Help</a><a href="/status">Status</a><a href="/about?autoplay=1">About</a><a href="/jobs-at-medium/work-at-medium-959d1a85284e">Careers</a><a href="mailto://pressinquiries@medium.com">Press</a><a href="/blog">Blog</a><a href="/store/medium/">Store</a><a href="/medium-privacy-policy-f03bf92035c9">Privacy</a><a href="/medium-rules-30e5502c4eb4">Rules</a><a href="/medium-terms-of-service-9db0094a1e0f">Terms</a><a href="/medium/">Text to speech</a></footer>'''
content = f'''<div class="account-shell">{account_sidebar(account or {})}<main id="account-content">{body}</main></div>''' if sidebar_enabled else f'''<main>{body}</main>'''
shell_class = " account-layout" if sidebar_enabled else ""
return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{e(title)}</title><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='5' fill='%23242424'/%3E%3Cpath d='M5 23V9h4l7 8 7-8h4v14h-4v-8l-7 8-7-8v8Z' fill='white'/%3E%3C/svg%3E"><link rel="stylesheet" href="/static/site.css"><script defer src="/static/app.js"></script></head><body class="{e(page_class)}{editor_class}{shell_class}">{header}{content}{footer}</body></html>'''
def notice(message: str, kind: str = "ok", *, ident: str = "") -> str:
if not message:
return ""
attr = f' id="{e(ident)}"' if ident else ""
return f'<div class="notice {e(kind)}" role="status"{attr}>{e(message)}</div>'
def join_modal() -> str:
"""Anonymous-home registration dialog matching the observed Start reading state."""
return '''<section class="home-join-overlay" id="home-join-overlay" hidden><div class="home-join-modal auth-modal options-step" id="home-join-dialog" role="dialog" aria-modal="true" aria-labelledby="home-join-title"><button class="modal-close" id="home-join-close" type="button" aria-label="Close">×</button><h2 id="home-join-title">Join Medium.</h2><div class="identity-options"><a class="identity" href="/m/signup?step=email"><span aria-hidden="true">✉</span><span>Sign up with email</span><span></span></a><button class="identity" disabled title="Unavailable in the offline clone"><span>G</span><span>Continue with Google</span><span></span></button><button class="identity" disabled title="Unavailable in the offline clone"><span>●</span><span>Continue with Apple</span><span></span></button></div><label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">Already have an account? <a href="/m/signin">Sign in</a></p><small>By creating an account, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small></div></section><section class="home-join-overlay" id="home-signup-overlay" hidden><div class="auth-modal signup options-step signup-intent" role="dialog" aria-modal="true" aria-labelledby="home-signup-title"><button class="modal-close" id="home-signup-close" type="button" aria-label="Close">×</button><h1 id="home-signup-title">Join Medium.</h1><div class="identity-options"><a class="identity" href="/m/signup?step=email"><span aria-hidden="true">✉</span><span>Sign up with email</span><span></span></a><button class="identity" disabled title="Unavailable in the offline clone"><span>G</span><span>Continue with Google</span><span></span></button><button class="identity" disabled title="Unavailable in the offline clone"><span>●</span><span>Continue with Apple</span><span></span></button></div><label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">Already have an account? <a href="/m/signin?operation=login">Sign in</a></p><small>By clicking “Sign up”, you accept Medium&apos;s <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small></div></section><section class="home-join-overlay" id="home-write-overlay" hidden><div class="auth-modal signup options-step write-intent" role="dialog" aria-modal="true" aria-labelledby="home-write-title"><button class="modal-close" id="home-write-close" type="button" aria-label="Close">×</button><h1 id="home-write-title">Create an account to start writing.</h1><div class="identity-options"><a class="identity" href="/m/signup?step=email&amp;next=%2Fnew-story&amp;intent=write"><span aria-hidden="true">✉</span><span>Sign up with email</span><span></span></a><button class="identity" disabled title="Unavailable in the offline clone"><span>G</span><span>Continue with Google</span><span></span></button><button class="identity" disabled title="Unavailable in the offline clone"><span>●</span><span>Continue with Apple</span><span></span></button></div><label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">Already have an account? <a href="/m/signin?operation=login&amp;next=%2Fnew-story">Sign in</a></p><small>By clicking “Sign up”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small></div></section><section class="home-join-overlay" id="home-signin-overlay" hidden><div class="auth-modal signin options-step simplified-signin" role="dialog" aria-modal="true" aria-labelledby="home-signin-title"><button class="modal-close" id="home-signin-close" type="button" aria-label="Close">×</button><h1 id="home-signin-title">Welcome back.</h1><div class="identity-options"><a class="identity" href="/m/signin?step=email"><span aria-hidden="true">✉</span><span>Sign in with email</span><span></span></a><button class="identity" disabled title="Unavailable in the offline clone"><span>G</span><span>Continue with Google</span><span></span></button><button class="identity" disabled title="Unavailable in the offline clone"><span>●</span><span>Continue with Apple</span><span></span></button></div><label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">No account? <a href="/m/signup?operation=register">Create one</a></p><p class="auth-help">Forgot email or trouble signing in? <a href="/help">Get help.</a></p><small>By clicking “Sign in”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small></div></section>'''
def auth_page(
*,
signup: bool = False,
email_step: bool = False,
message: str = "",
write_intent: bool = False,
email_step_href: str = "",
) -> str:
title = "Create an account to start writing." if write_intent else ("Join Medium." if signup else "Welcome back.")
switch = 'Already have an account? <a href="/m/signin">Sign in</a>' if signup else 'No account? <a href="/m/signup">Create one</a>'
envelope = '''<svg class="envelope-icon" viewBox="0 0 52 40" aria-hidden="true"><path d="M7 13.5 28 4l13 10-19 14L7 13.5Zm0 0-2 19 17-4m19-14 4 16-23-2m3-18 3 14"/></svg>'''
if not email_step:
email_href = email_step_href or ("/m/signup?step=email" if signup else "/m/signin?step=email")
email_label = "Sign up with email" if signup else "Sign in with email"
provider_options = '''<button class="identity" disabled title="Unavailable in the offline clone"><span>G</span><span>Continue with Google</span><span></span></button><button class="identity" disabled title="Unavailable in the offline clone"><span>●</span><span>Continue with Apple</span><span></span></button>''' if signup else ""
primary = f'''<div class="identity-options"><a class="identity" href="{e(email_href)}"><span aria-hidden="true">✉</span><span>{email_label}</span><span></span></a>{provider_options}</div>'''
else:
if signup:
fields = '''<div class="auth-email-stage"><label>Your full name<input name="display_name" autocomplete="name" required maxlength="80" placeholder="Enter your full name"></label><label>Your email<input name="email" type="email" autocomplete="email" required placeholder="Enter your email address"></label></div><div class="auth-password-stage" hidden><p class="auth-stage-copy">Create a local password to secure this offline account.</p><label>Create a password<input name="password" type="password" autocomplete="new-password" minlength="10" placeholder="At least 10 characters"></label></div>'''
form_id = "register-form"
else:
fields = '''<div class="auth-email-stage"><label>Your email<input name="email" type="email" autocomplete="email" required placeholder="Enter your email address"></label></div><div class="auth-password-stage" hidden><p class="auth-stage-copy">Enter your local account password.</p><label>Password<input name="password" type="password" autocomplete="current-password" placeholder="Enter your password"></label></div>'''
form_id = "sign-in-form"
primary = f'<form id="{form_id}" class="auth-form" data-auth-stage="email">{fields}</form>'
verify = '''<form id="verify-form" class="auth-form" hidden><h2>Check your local inbox</h2><p>No external email was sent. Enter the fixture verification code shown above.</p><label>Verification code<input name="code" inputmode="numeric" pattern="[0-9]{6}" required></label><button class="auth-submit">Verify and continue</button></form>''' if signup else ""
mode = "signup" if signup else "signin"
step = "email-step" if email_step else "options-step"
heading = ("Sign up with email" if signup else "Sign in with email") if email_step else title
back = f'<a class="back-options" href="/m/{"signup" if signup else "signin"}">Back to sign {"up" if signup else "in"} options</a>' if email_step else ""
submit = f'<button class="auth-submit" form="{form_id}">{"Create account" if signup else "Continue"}</button>' if email_step else ""
if write_intent:
detail = '''<label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">Already have an account? <a href="/m/signin?operation=login&amp;next=%2Fnew-story">Sign in</a></p><small>By clicking “Sign up”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small>'''
elif email_step and not signup:
detail = f'''<label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label>{submit}{back}<p class="auth-help"><a href="/m/recovery">Forgot password?</a></p>'''
elif email_step:
detail = f'''<label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label>{submit}{back}<p class="auth-switch">{switch}</p><small>By clicking “Create Account”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.<br>This site uses reCaptcha and the Google Privacy Policy and Terms of Service apply.</small>'''
elif signup:
detail = '''<label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">Already have an account? <a href="/m/signin?operation=login">Sign in</a></p><small>By clicking “Sign up”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small>'''
else:
detail = '''<label class="remember"><input type="checkbox" checked> Remember me for faster sign in</label><p class="auth-switch">No account? <a href="/m/signup?operation=register">Create one</a></p><p class="auth-help">Forgot email or trouble signing in? <a href="/help">Get help.</a></p><small>By clicking “Sign in”, you accept Medium's <a href="/policy/medium-terms-of-service-9db0094a1e0f">Terms of Service</a> and <a href="/policy/medium-privacy-policy-f03bf92035c9">Privacy Policy</a>.</small>'''
modal_class = (
"write-intent"
if write_intent
else ("signup-intent" if signup and not email_step else ("simplified-signin" if not email_step else ""))
)
modal = f'''<section class="auth-backdrop"><div class="auth-modal {mode} {step} {modal_class}"><a href="/" class="modal-close" aria-label="Close">×</a>{envelope if email_step else ''}<h1>{heading}</h1>{notice(message, "error", ident="auth-notice") if message else '<div id="auth-notice" role="status"></div>'}{primary}{verify}{detail}</div></section>'''
if email_step:
content = f'''<section class="auth-origin-error" aria-hidden="true"><p>PAGE NOT FOUND</p><strong>404</strong></section>{modal}'''
page_class = f"auth-surface auth-{mode}"
else:
content = f'''<section class="landing-hero"><div class="hero-copy"><h1><span>Human</span><span>stories <span class="mobile-title-line">&amp; ideas</span></span></h1><p>A place to read, write, and deepen your understanding</p><a class="pill dark big" href="/search">Start reading</a></div><div class="hero-art" aria-hidden="true"></div></section>{modal}'''
page_class = f"home-page auth-surface auth-{mode}"
return layout(f"{title} – Medium", content, page_class=page_class)
def recovery_page() -> str:
"""Three-step local-only password reset surface.
A correct code is available only through the session-owned fixture inbox
while the offline-harbor LOCAL_ONLY profile is active. The UI deliberately
states that no external message was delivered.
"""
body = '''<section class="auth-origin-error" aria-hidden="true"><p>PAGE NOT FOUND</p><strong>404</strong></section><section class="auth-backdrop"><div class="auth-modal recovery email-step"><a href="/" class="modal-close" aria-label="Close">×</a><h1>Reset your password</h1><div id="recovery-notice" role="status"></div><form id="recovery-start-form" class="auth-form"><label>Your email<input name="email" type="email" autocomplete="email" required placeholder="Enter your email address"></label><button class="auth-submit">Continue</button></form><form id="recovery-verify-form" class="auth-form" hidden><p class="auth-stage-copy">Check the local fixture inbox, then enter your verification code.</p><label>Verification code<input name="code" inputmode="numeric" pattern="[0-9]{6}" required></label><button class="auth-submit">Verify code</button></form><form id="recovery-complete-form" class="auth-form" hidden><p class="auth-stage-copy">Choose a new local password.</p><label>New password<input name="password" type="password" autocomplete="new-password" minlength="8" required></label><button class="auth-submit">Reset password</button></form><p class="auth-help">No account? <a href="/m/signup?step=email">Create one</a>. <a href="/m/signin?step=email">Back to sign in</a>.</p><small>Local-only verification: no real email address is contacted by this offline clone.</small></div></section>'''
return layout("Reset your password – Medium", body, page_class="auth-surface auth-recovery")
def story_card(story: Mapping[str, Any], *, manage: bool = False) -> str:
status = str(story.get("status", ""))
title = e(story.get("title") or "Untitled story")
subtitle = e(story.get("subtitle") or str(story.get("body") or "")[:150])
href = f'/p/{e(story["story_id"])}' if status == "published" else f'/p/{e(story["story_id"])}/edit'
topics = "".join(f'<span class="topic">{e(topic)}</span>' for topic in story.get("topics", []))
actions = f'<a href="/p/{e(story["story_id"])}/edit">Edit</a><a href="/p/{e(story["story_id"])}">View</a>' if manage else '<span>4 min read</span>'
return f'''<article class="story-card" data-story-id="{e(story['story_id'])}"><div><p class="byline">{e(site_data.display_name(str(story.get("owner_subject_id", ""))))} · {e(str(story.get("updated_at", ""))[:10])}</p><a href="{href}"><h2>{title}</h2><p>{subtitle}</p></a><div class="card-meta">{topics}{actions}<span class="status {e(status)}">{e(status.title())}</span></div></div><div class="story-art" aria-hidden="true"><span>✦</span></div></article>'''
def editor(story: Mapping[str, Any], media: Iterable[Mapping[str, Any]], revisions: Iterable[Mapping[str, Any]], account: Mapping[str, Any]) -> str:
story_id = e(story["story_id"])
topics = ", ".join(str(value) for value in story.get("topics", []))
media_rows = "".join(f'''<article class="media-row" data-media-id="{e(row['media_id'])}"><span>▧</span><div><strong>{e(row['filename'])}</strong><small>{e(row['alt_text'])}</small></div><button type="button" data-remove-media="{e(row['media_id'])}">Remove</button></article>''' for row in media)
revision_rows = "".join(f'<li><strong>Version {e(row["revision"])}</strong> · {e(str(row["event"]).replace("-", " ").title())} <time>{e(row["created_at"])}</time></li>' for row in revisions)
story_has_content = any(
bool(story.get(field))
for field in ("title", "subtitle", "body", "heading", "link_label", "link_url", "embed_url", "topics", "seo_title", "seo_description")
)
story_action_disabled = "" if story_has_content else " disabled"
more_menu = f'''<div id="editor-more-menu" class="editor-more-menu" hidden><ul role="menu" aria-label="More story options"><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="share-draft"{story_action_disabled}>Share draft link</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="share-x"{story_action_disabled}>Share to X</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="featured-image"{story_action_disabled}>Change featured image</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="display-title"{story_action_disabled}>Change display title / subtitle</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="topics"{story_action_disabled}>Change topics</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="revision-history"{story_action_disabled}>See revision history</button></li><li class="editor-more-story-action"><button type="button" role="menuitem" data-editor-more="settings"{story_action_disabled}>More settings</button></li><li class="editor-more-separator" role="separator"></li><li><button type="button" role="menuitem" data-editor-more="shortcuts">Hints and keyboard shortcuts</button></li><li><a role="menuitem" href="/help#writing-editing">More help</a></li></ul></div>'''
add_content = '''<div class="editor-add-control"><button type="button" id="editor-add-content" aria-label="Add an image, video, embed, or new part" title="Add an image, video, embed, or new part" aria-controls="editor-add-menu" aria-expanded="false"><span aria-hidden="true">+</span></button><div id="editor-add-menu" class="editor-add-menu" hidden><button type="button" data-add-content="image" aria-label="Add an image" title="Add an image"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><rect x="9.5" y="10.5" width="13" height="11" rx="1"/><circle cx="19.5" cy="13.5" r="1.5"/><path d="m10 20 4-4 3 3 2-2 3 3"/></svg></button><button type="button" data-add-content="unsplash" aria-label="Add an image from Unsplash" title="Add an image from Unsplash"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><path d="M13 10h6v4h-6zM10 16h4v4h4v-4h4v7H10z" class="fill"/></svg></button><button type="button" data-add-content="video" aria-label="Add a video" title="Add a video"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><rect x="9.5" y="10.5" width="13" height="11" rx="1"/><path d="m14 14 5 3-5 3z" class="fill"/></svg></button><button type="button" data-add-content="embed" aria-label="Add an embed" title="Add an embed"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><path d="m13.5 11-5 5 5 5M18.5 11l5 5-5 5"/></svg></button><button type="button" data-add-content="code" aria-label="Add a new code block" title="Add a new code block"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><path d="m14 10-3 2v8l3 2M18 10l3 2v8l-3 2"/></svg></button><button type="button" data-add-content="part" aria-label="Add a new part" title="Add a new part"><svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15.5"/><path d="M9 12h14M9 20h14"/><circle cx="12" cy="16" r="1" class="fill no-stroke"/><circle cx="16" cy="16" r="1" class="fill no-stroke"/><circle cx="20" cy="16" r="1" class="fill no-stroke"/></svg></button></div></div>'''
body = f'''<section class="editor" data-story-id="{story_id}" data-revision="{e(story['revision'])}" data-status="{e(story['status'])}"><div class="editor-toolbar"><span class="draft-label">{e(story['status'].title())}</span><span id="save-state">Saved</span><button type="button" id="open-preview" class="text-button">Preview</button><button type="button" id="open-publish" class="pill green">Publish</button><button type="button" id="more-editor" class="dots" aria-label="More story options" title="More story options" aria-haspopup="menu" aria-controls="editor-more-menu" aria-expanded="false">•••</button>{more_menu}</div><div id="editor-notice" role="status"></div><form id="editor-form"><textarea name="title" class="story-title" placeholder="Title" maxlength="180" aria-label="Story title">{e(story['title'])}</textarea><textarea name="subtitle" class="story-subtitle" placeholder="Subtitle" maxlength="240" aria-label="Story subtitle">{e(story['subtitle'])}</textarea><textarea name="body" class="story-body" placeholder="Tell your story…" aria-label="Story body">{e(story['body'])}</textarea><details class="format-panel"><summary>Formatting, links, embeds and metadata</summary><label>Section heading<input name="heading" maxlength="160" value="{e(story['heading'])}"></label><div class="two"><label>Link text<input name="link_label" maxlength="80" value="{e(story['link_label'])}"></label><label>Local link<input name="link_url" placeholder="/p/story" value="{e(story['link_url'])}"></label></div><label>Safe embed reference<input name="embed_url" placeholder="local://embed/reference" value="{e(story['embed_url'])}"></label><label>Topics<input name="topics" value="{e(topics)}" placeholder="Writing, Technology"></label><label>SEO title<input name="seo_title" maxlength="180" value="{e(story['seo_title'])}"></label><label>SEO description<textarea name="seo_description" maxlength="320">{e(story['seo_description'])}</textarea></label></details></form><details class="media-panel"><summary>Story media</summary><p>Upload a local image and alternative text. Files never leave this clone.</p><form id="media-form"><input type="file" name="media" accept="image/png,image/jpeg,image/gif,image/webp" required><input name="alt_text" placeholder="Describe this image" maxlength="180" required><button class="secondary">Add image</button></form><div id="media-list">{media_rows or '<p class="muted">No inline media yet.</p>'}</div></details><details class="history-panel"><summary>Version history</summary><ol id="revision-list">{revision_rows}</ol></details><div class="lifecycle-row"><button data-lifecycle="unpublish" type="button">Unpublish</button><button data-lifecycle="delete" type="button">Delete story</button><button data-lifecycle="recover" type="button">Recover story</button></div></section><dialog id="preview-dialog" class="preview-dialog"><button class="dialog-close" aria-label="Close">×</button><p class="eyebrow">Story preview</p><article id="preview-content"></article><p class="muted">Preview only · unpublished edits remain private</p></dialog><dialog id="publish-dialog" class="publish-dialog"><button class="dialog-close" aria-label="Close">×</button><h2>Publish your story</h2><p>Add up to five topics so readers know what your story is about.</p><div id="publish-notice"></div><button id="publish-now" class="pill green wide">Publish now</button><hr><label>Schedule for a future UTC time<input id="scheduled-at" type="datetime-local"></label><button id="schedule-story" class="secondary wide">Schedule story</button></dialog>'''
body = body.replace(
'<div id="editor-notice" role="status"></div>',
f'<div id="editor-notice" role="status"></div>{add_content}',
1,
)
return layout(f"{story.get('title') or 'New story'} – Medium", body, account=account, editor=True)
def public_story(story: Mapping[str, Any], engagement: Mapping[str, Any], *, account: Mapping[str, Any] | None = None, owner: bool = False) -> str:
topic_rows = "".join(f'<a class="topic" href="/search?q={quote_plus(str(topic))}">{e(topic)}</a>' for topic in story.get("topics", []))
highlight_rows = "".join(
f'<li><mark>{e(row["quote"])}</mark></li>'
for row in engagement.get("highlights", [])
)
responses: list[Mapping[str, Any]] = list(engagement.get("responses", []))
roots = [row for row in responses if not row.get("parent_id")]
response_html = ""
for row in roots:
children = [child for child in responses if child.get("parent_id") == row.get("response_id")]
child_html = "".join(f'<article class="response reply"><strong>{e(site_data.display_name(str(child["actor_subject_id"])))}</strong><p>{e(child["body"])}</p></article>' for child in children)
response_html += f'''<article class="response" data-response-id="{e(row['response_id'])}"><strong>{e(site_data.display_name(str(row['actor_subject_id'])))}</strong><p>{e(row['body'])}</p>{child_html}<button type="button" data-reply="{e(row['response_id'])}">Reply</button></article>'''
state_note = "" if story["status"] == "published" else notice(f"This story is {story['status']}. Only its owner can see this recovery view.", "warning")
body = f'''<article class="reading-page" data-story-id="{e(story['story_id'])}">{state_note}<header><div class="author-line"><div class="avatar">{e(site_data.display_name(str(story['owner_subject_id']))[:1])}</div><div><strong>{e(site_data.display_name(str(story['owner_subject_id'])))}</strong><p>{e(str(story.get('published_at') or story['updated_at'])[:10])} · 4 min read</p></div></div><h1>{e(story['title'] or 'Untitled story')}</h1><p class="dek">{e(story['subtitle'])}</p><div class="story-actions"><button id="clap-story" aria-label="Clap"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 13 2-8c.4-1.5 2.2-1 2 .5L11 11l2-7c.3-1.5 2.2-1.1 2 .5l-1 6 2-5c.5-1.4 2.2-.7 1.7.7l-1.5 5 1.8-3c.8-1.3 2.4-.2 1.7 1.1L16.5 16a6 6 0 0 1-5.4 3.3H9.8A5.8 5.8 0 0 1 4 13.5V10c0-1.4 1.8-1.8 2.4-.6L8 13Z"/></svg><span id="clap-count">{e(engagement.get('claps', 0))}</span></button><a href="#responses" aria-label="Responses"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 5.5h14v10H9l-4 3v-13Z"/></svg>{len(responses)}</a>{'<a href="/p/'+e(story['story_id'])+'/edit">Edit story</a>' if owner else ''}</div></header><div class="story-copy">{f'<h2>{e(story["heading"])}</h2>' if story.get('heading') else ''}<p>{e(story['body'])}</p>{f'<p><a href="{e(story["link_url"])}">{e(story["link_label"])}</a></p>' if story.get('link_url') else ''}{f'<aside class="embed-card">Embedded local reference · {e(story["embed_url"])}</aside>' if story.get('embed_url') else ''}</div><div class="topics">{topic_rows}</div><form id="highlight-form"><label>Highlight words from this story<input name="quote" placeholder="Paste a phrase from the story"></label><button class="secondary">Save highlight</button></form><section class="saved-highlights"><h2>Saved highlights ({len(engagement.get('highlights', []))})</h2><ul>{highlight_rows or '<li class="muted">No saved highlights yet.</li>'}</ul></section><section id="responses" class="responses"><h2>Responses ({len(responses)})</h2><div id="response-notice"></div><form id="response-form"><input type="hidden" name="parent_id"><textarea name="body" placeholder="What are your thoughts?" required></textarea><button class="pill green">Respond</button></form><div id="response-list">{response_html or '<p class="muted">Be the first to respond.</p>'}</div></section></article>'''
return layout(f"{story.get('title') or 'Story'} – Medium", body, account=account)
def error_page(title: str, heading: str, message: str, *, account: Mapping[str, Any] | None = None) -> str:
body = f'''<section class="error-page"><p class="eyebrow">PAGE NOT FOUND</p><h1>{e(heading)}</h1><h2>Out of nothing, something.</h2><p>{e(message)}<br>Maybe these stories will take you somewhere new?</p><div><a href="/">Home</a><a href="/search">Browse stories</a><a href="/help">Get help</a></div></section>'''
return layout(title, body, account=account, page_class="error-surface")