"""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(" 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', '/', '', None), ('Library', '/me/lists', '', None), ('Profile', profile_path, '', None), ('Stories', '/me/stories', '', None), ('Stats', '/me/stats', '', None), ) rows = ''.join( f'{label}' for label, href, path, current in links ) return f'''''' 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'''Write''' else: nav = 'WriteSign in' 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 = '''
Medium
''' elif "help-center-surface" in page_class: header = '''
MediumHelp Center
''' elif "status-surface" in page_class: header = '''
Medium
''' elif not account and "home-page" in page_class: nav = 'Our storyMembershipWriteSign inGet started' header = f'''''' else: sidebar_toggle = '''''' if sidebar_enabled else "" header = f'''''' 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 '''''' content = f'''''' if sidebar_enabled else f'''
{body}
''' shell_class = " account-layout" if sidebar_enabled else "" return f'''{e(title)}{header}{content}{footer}''' def notice(message: str, kind: str = "ok", *, ident: str = "") -> str: if not message: return "" attr = f' id="{e(ident)}"' if ident else "" return f'
{e(message)}
' def join_modal() -> str: """Anonymous-home registration dialog matching the observed Start reading state.""" return '''''' 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? Sign in' if signup else 'No account? Create one' envelope = '''''' 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 = '''''' if signup else "" primary = f'''
{email_label}{provider_options}
''' else: if signup: fields = '''
''' form_id = "register-form" else: fields = '''
''' form_id = "sign-in-form" primary = f'
{fields}
' verify = '''''' 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'Back to sign {"up" if signup else "in"} options' if email_step else "" submit = f'' if email_step else "" if write_intent: detail = '''

Already have an account? Sign in

By clicking “Sign up”, you accept Medium's Terms of Service and Privacy Policy.''' elif email_step and not signup: detail = f'''{submit}{back}

Forgot password?

''' elif email_step: detail = f'''{submit}{back}

{switch}

By clicking “Create Account”, you accept Medium's Terms of Service and Privacy Policy.
This site uses reCaptcha and the Google Privacy Policy and Terms of Service apply.
''' elif signup: detail = '''

Already have an account? Sign in

By clicking “Sign up”, you accept Medium's Terms of Service and Privacy Policy.''' else: detail = '''

No account? Create one

Forgot email or trouble signing in? Get help.

By clicking “Sign in”, you accept Medium's Terms of Service and Privacy Policy.''' 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'''
×{envelope if email_step else ''}

{heading}

{notice(message, "error", ident="auth-notice") if message else '
'}{primary}{verify}{detail}
''' if email_step: content = f'''{modal}''' page_class = f"auth-surface auth-{mode}" else: content = f'''

Humanstories & ideas

A place to read, write, and deepen your understanding

Start reading
{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 = '''
''' 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'{e(topic)}' for topic in story.get("topics", [])) actions = f'EditView' if manage else '4 min read' return f'''

{title}

{subtitle}

{topics}{actions}{e(status.title())}
''' 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'''
▧
{e(row['filename'])}{e(row['alt_text'])}
''' for row in media) revision_rows = "".join(f'
  • Version {e(row["revision"])} · {e(str(row["event"]).replace("-", " ").title())}
  • ' 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'''''' add_content = '''
    ''' body = f'''
    {e(story['status'].title())}Saved{more_menu}
    Formatting, links, embeds and metadata
    Story media

    Upload a local image and alternative text. Files never leave this clone.

    {media_rows or '

    No inline media yet.

    '}
    Version history
      {revision_rows}

    Story preview

    Preview only · unpublished edits remain private

    Publish your story

    Add up to five topics so readers know what your story is about.


    ''' body = body.replace( '
    ', f'
    {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'{e(topic)}' for topic in story.get("topics", [])) highlight_rows = "".join( f'
  • {e(row["quote"])}
  • ' 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'
    {e(site_data.display_name(str(child["actor_subject_id"])))}

    {e(child["body"])}

    ' for child in children) response_html += f'''
    {e(site_data.display_name(str(row['actor_subject_id'])))}

    {e(row['body'])}

    {child_html}
    ''' 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'''
    {state_note}
    {e(site_data.display_name(str(story['owner_subject_id']))[:1])}
    {e(site_data.display_name(str(story['owner_subject_id'])))}

    {e(str(story.get('published_at') or story['updated_at'])[:10])} · 4 min read

    {e(story['title'] or 'Untitled story')}

    {e(story['subtitle'])}

    {len(responses)}{'Edit story' if owner else ''}
    {f'

    {e(story["heading"])}

    ' if story.get('heading') else ''}

    {e(story['body'])}

    {f'

    {e(story["link_label"])}

    ' if story.get('link_url') else ''}{f'' if story.get('embed_url') else ''}
    {topic_rows}

    Saved highlights ({len(engagement.get('highlights', []))})

      {highlight_rows or '
    • No saved highlights yet.
    • '}

    Responses ({len(responses)})

    {response_html or '

    Be the first to respond.

    '}
    ''' 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'''

    PAGE NOT FOUND

    {e(heading)}

    Out of nothing, something.

    {e(message)}
    Maybe these stories will take you somewhere new?

    ''' return layout(title, body, account=account, page_class="error-surface")