{
  "id": 143,
  "slug": "floating-selection-toolbar",
  "name": "Contextual Floating Selection Toolbar",
  "kind": "ui",
  "family": "Editorial & Reading",
  "sourceSite": {
    "name": "Ghost",
    "url": "https://ghost.org/",
    "verifiedStatus": 200
  },
  "tagline": "Editorial article canvas with a live floating text-selection toolbar (Bold, Italic, Highlight, Quote, Note) and mobile action dock.",
  "whyUnique": "Keeps the writing canvas completely free of permanent formatting toolbars until text is selected, then floats a dark contextual popover right above the selection—with a bottom dock fallback for mobile OS selection handles.",
  "theme": "light",
  "mobileStrength": "high",
  "tags": [
    "selection-toolbar",
    "floating-ui",
    "rich-text",
    "editorial",
    "annotations",
    "publishing"
  ],
  "bestFor": [
    "Publishing platforms and blog editors",
    "Collaborative document commenting tools",
    "E-readers and web highlighters",
    "Research clippers and note-taking apps"
  ],
  "palette": [
    {
      "role": "canvas",
      "hex": "#FAF9F7",
      "name": "Alabaster"
    },
    {
      "role": "surface",
      "hex": "#FFFFFF",
      "name": "Editorial Sheet"
    },
    {
      "role": "ink",
      "hex": "#18181B",
      "name": "Press Ink"
    },
    {
      "role": "accent",
      "hex": "#D97706",
      "name": "Highlighter Amber"
    },
    {
      "role": "muted",
      "hex": "#71717A",
      "name": "Caption Gray"
    }
  ],
  "typography": {
    "display": "Newsreader",
    "body": "Newsreader",
    "mono": "JetBrains Mono",
    "googleFontsUrl": "https://fonts.googleapis.com/css2?family=Inter:wght@500;600&family=Newsreader:ital,wght@0,400;0,600;0,700;1,400&display=swap",
    "scaleNotes": "32px serif article headline, 18px/1.75 body text, 13px sans floating toolbar buttons, 12px annotation cards."
  },
  "layoutNotes": "Centered 700px editorial column paired with a subtle saved-annotations sidebar on desktop; fixed bottom contextual toolbar on mobile so it never collides with iOS/Android native selection callouts.",
  "interactionNotes": "Selecting any text range computes Range.getBoundingClientRect() to position the floating dark toolbar with Bold, Italic, Highlight, Pull-Quote, Add Note, and Copy Quote actions, plus one-click preset phrase selectors.",
  "mobileNotes": "Pins formatting actions to a bottom dock when text is selected on touchscreens and offers quick-select sentence chips so mobile visitors can test every tool effortlessly.",
  "agentGuardrails": {
    "do": [
      "Clamp floating toolbar coordinates inside the viewport bounds so it never clips off the left or right edge.",
      "Use a bottom-docked action bar on mobile so custom actions do not collide with native OS Copy/Paste menus.",
      "Preserve the active text selection (preventDefault on mousedown) when clicking toolbar buttons."
    ],
    "dont": [
      "Never let toolbar clicks blur the selection before the formatting command executes.",
      "Avoid cluttering the floating popover with more than 6 primary formatting/annotation actions."
    ]
  },
  "demoFile": "demos/floating-selection-toolbar.html",
  "thumbDesktop": "thumbs/floating-selection-toolbar-desktop.webp",
  "thumbMobile": "thumbs/floating-selection-toolbar-mobile.webp",
  "urls": {
    "page": "https://templates.michaelpitts.net/t/floating-selection-toolbar",
    "markdown": "https://templates.michaelpitts.net/t/floating-selection-toolbar.md",
    "api": "https://templates.michaelpitts.net/api/templates/floating-selection-toolbar",
    "demo": "https://templates.michaelpitts.net/demos/floating-selection-toolbar.html",
    "thumbDesktop": "https://templates.michaelpitts.net/thumbs/floating-selection-toolbar-desktop.webp",
    "thumbMobile": "https://templates.michaelpitts.net/thumbs/floating-selection-toolbar-mobile.webp"
  },
  "agentPrompt": "Design & build using template #143 \"Contextual Floating Selection Toolbar\" (ui / Editorial & Reading, light theme).\nFull AI blueprint & standalone starter code: https://templates.michaelpitts.net/t/floating-selection-toolbar.md\nLive demo: https://templates.michaelpitts.net/demos/floating-selection-toolbar.html\nReal-world inspiration: Ghost (https://ghost.org/)\n\nCore aesthetic: Keeps the writing canvas completely free of permanent formatting toolbars until text is selected, then floats a dark contextual popover right above the selection—with a bottom dock fallback for mobile OS selection handles.\nPalette: canvas: #FAF9F7 (Alabaster), surface: #FFFFFF (Editorial Sheet), ink: #18181B (Press Ink), accent: #D97706 (Highlighter Amber), muted: #71717A (Caption Gray)\nTypography: Display=\"Newsreader\", Body=\"Newsreader\", Mono=\"JetBrains Mono\"\nLayout: Centered 700px editorial column paired with a subtle saved-annotations sidebar on desktop; fixed bottom contextual toolbar on mobile so it never collides with iOS/Android native selection callouts.\nInteractions: Selecting any text range computes Range.getBoundingClientRect() to position the floating dark toolbar with Bold, Italic, Highlight, Pull-Quote, Add Note, and Copy Quote actions, plus one-click preset phrase selectors.\nMobile: Pins formatting actions to a bottom dock when text is selected on touchscreens and offers quick-select sentence chips so mobile visitors can test every tool effortlessly.\n\nGuardrails:\n- DO: Clamp floating toolbar coordinates inside the viewport bounds so it never clips off the left or right edge.\n- DO: Use a bottom-docked action bar on mobile so custom actions do not collide with native OS Copy/Paste menus.\n- DO: Preserve the active text selection (preventDefault on mousedown) when clicking toolbar buttons.\n- DON'T: Never let toolbar clicks blur the selection before the formatting command executes.\n- DON'T: Avoid cluttering the floating popover with more than 6 primary formatting/annotation actions.",
  "sourceCode": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Alabaster Press — Contextual Selection Toolbar</title>\n<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n<link href=\"https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400..600;1,6..72,400&family=Inter:wght@400;500;600&display=swap\" rel=\"stylesheet\">\n<style>\n  :root {\n    --bg: #faf8f4;\n    --surface: #ffffff;\n    --border: #e7e2d9;\n    --ink: #1b1b1a;\n    --muted: #6c6963;\n    --toolbar-bg: #18181b;\n    --toolbar-ink: #f8fafc;\n    --accent: #b45309;\n    --hl: #fef08a;\n  }\n  * { box-sizing: border-box; margin: 0; padding: 0; }\n  html, body { overflow-x: hidden; }\n  body {\n    font-family: 'Inter', system-ui, -apple-system, sans-serif;\n    background: var(--bg);\n    color: var(--ink);\n    min-height: 100vh;\n    padding-bottom: 90px;\n  }\n  .topbar {\n    position: sticky;\n    top: 0;\n    z-index: 20;\n    background: rgba(250, 248, 244, 0.92);\n    backdrop-filter: blur(8px);\n    border-bottom: 1px solid var(--border);\n    padding: 12px 20px;\n  }\n  .topbar-inner {\n    max-width: 1120px;\n    margin: 0 auto;\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    justify-content: space-between;\n    gap: 10px;\n  }\n  .pub {\n    display: flex;\n    align-items: center;\n    gap: 10px;\n  }\n  .pub-mark {\n    width: 34px;\n    height: 34px;\n    border-radius: 50%;\n    background: var(--ink);\n    color: #fff;\n    font-family: 'Newsreader', Georgia, serif;\n    font-size: 19px;\n    display: grid;\n    place-items: center;\n  }\n  .pub strong { font-size: 15px; letter-spacing: -0.01em; }\n  .pub span { font-size: 12px; color: var(--muted); display: block; }\n\n  .quick-bar {\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    gap: 7px;\n  }\n  .quick-label {\n    font-size: 12px;\n    color: var(--muted);\n    margin-right: 2px;\n  }\n  .preset-chip {\n    min-height: 38px;\n    padding: 0 12px;\n    border-radius: 99px;\n    border: 1px solid var(--border);\n    background: var(--surface);\n    color: var(--ink);\n    font: inherit;\n    font-size: 12.5px;\n    font-weight: 500;\n    cursor: pointer;\n    transition: all 0.15s;\n  }\n  .preset-chip:hover { border-color: var(--ink); background: #f3efe8; }\n\n  .layout {\n    max-width: 1120px;\n    margin: 26px auto 0;\n    padding: 0 20px;\n    display: grid;\n    grid-template-columns: minmax(0, 1fr) 310px;\n    gap: 28px;\n    align-items: start;\n  }\n\n  article.editor-sheet {\n    background: var(--surface);\n    border: 1px solid var(--border);\n    border-radius: 16px;\n    padding: 42px 48px;\n    box-shadow: 0 2px 16px rgba(27, 27, 26, 0.03);\n  }\n  .kicker {\n    font-size: 11.5px;\n    text-transform: uppercase;\n    letter-spacing: 0.1em;\n    color: var(--accent);\n    font-weight: 600;\n    margin-bottom: 10px;\n  }\n  .doc-title {\n    font-family: 'Newsreader', Georgia, serif;\n    font-size: 38px;\n    font-weight: 500;\n    line-height: 1.12;\n    letter-spacing: -0.02em;\n    margin-bottom: 12px;\n  }\n  .byline {\n    font-size: 13px;\n    color: var(--muted);\n    padding-bottom: 22px;\n    border-bottom: 1px solid var(--border);\n    margin-bottom: 26px;\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: space-between;\n    gap: 8px;\n  }\n\n  .prose {\n    font-family: 'Newsreader', Georgia, serif;\n    font-size: 20px;\n    line-height: 1.7;\n    color: #242321;\n    outline: none;\n  }\n  .prose p { margin-bottom: 20px; }\n  .prose p:last-child { margin-bottom: 0; }\n  .prose mark.hl {\n    background: var(--hl);\n    color: inherit;\n    padding: 1px 3px;\n    border-radius: 3px;\n  }\n  .prose .pull-quote-inline {\n    display: block;\n    margin: 22px 0;\n    padding: 14px 20px;\n    border-left: 3px solid var(--ink);\n    background: #f8f5ef;\n    font-style: italic;\n    font-size: 22px;\n    line-height: 1.45;\n    color: var(--ink);\n    border-radius: 0 10px 10px 0;\n  }\n  .prose span.annotated {\n    border-bottom: 2px dotted var(--accent);\n    background: rgba(180, 83, 9, 0.08);\n    padding-bottom: 1px;\n  }\n\n  /* Margin notes rail */\n  aside.rail {\n    position: sticky;\n    top: 78px;\n    display: flex;\n    flex-direction: column;\n    gap: 14px;\n  }\n  .rail-card {\n    background: var(--surface);\n    border: 1px solid var(--border);\n    border-radius: 14px;\n    padding: 16px;\n  }\n  .rail-card h2 {\n    font-size: 12px;\n    text-transform: uppercase;\n    letter-spacing: 0.08em;\n    color: var(--muted);\n    margin-bottom: 10px;\n    display: flex;\n    justify-content: space-between;\n  }\n  .note-list {\n    display: flex;\n    flex-direction: column;\n    gap: 10px;\n  }\n  .note-item {\n    background: #faf8f4;\n    border: 1px solid var(--border);\n    border-radius: 10px;\n    padding: 10px 12px;\n    font-size: 13px;\n  }\n  .note-quote {\n    font-family: 'Newsreader', Georgia, serif;\n    font-style: italic;\n    font-size: 14px;\n    color: var(--muted);\n    border-left: 2px solid var(--accent);\n    padding-left: 8px;\n    margin-bottom: 6px;\n  }\n  .note-body { color: var(--ink); line-height: 1.45; }\n  .note-meta {\n    margin-top: 6px;\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    font-size: 11px;\n    color: var(--muted);\n  }\n  .note-del {\n    border: none;\n    background: none;\n    color: var(--muted);\n    cursor: pointer;\n    font-size: 12px;\n    padding: 4px 6px;\n  }\n  .note-del:hover { color: #b91c1c; }\n\n  .stats-grid {\n    display: grid;\n    grid-template-columns: 1fr 1fr;\n    gap: 8px;\n  }\n  .stat-box {\n    background: #faf8f4;\n    border: 1px solid var(--border);\n    border-radius: 10px;\n    padding: 10px;\n  }\n  .stat-box span { font-size: 11px; color: var(--muted); display: block; }\n  .stat-box strong { font-size: 18px; font-weight: 600; }\n\n  /* Floating Desktop Toolbar */\n  .float-toolbar {\n    position: fixed;\n    z-index: 60;\n    background: var(--toolbar-bg);\n    color: var(--toolbar-ink);\n    border-radius: 12px;\n    padding: 5px;\n    display: flex;\n    align-items: center;\n    gap: 2px;\n    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.28);\n    opacity: 0;\n    transform: translate(-50%, -8px) scale(0.96);\n    pointer-events: none;\n    transition: opacity 0.14s ease, transform 0.14s ease;\n  }\n  .float-toolbar.visible {\n    opacity: 1;\n    transform: translate(-50%, 0) scale(1);\n    pointer-events: auto;\n  }\n  .float-toolbar::after {\n    content: \"\";\n    position: absolute;\n    left: 50%;\n    bottom: -6px;\n    transform: translateX(-50%);\n    border-left: 6px solid transparent;\n    border-right: 6px solid transparent;\n    border-top: 6px solid var(--toolbar-bg);\n  }\n  .tb-btn {\n    min-width: 38px;\n    min-height: 38px;\n    padding: 0 10px;\n    border: none;\n    background: transparent;\n    color: var(--toolbar-ink);\n    border-radius: 8px;\n    font: inherit;\n    font-size: 13px;\n    font-weight: 600;\n    cursor: pointer;\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    gap: 4px;\n    white-space: nowrap;\n  }\n  .tb-btn:hover { background: rgba(255, 255, 255, 0.14); }\n  .tb-sep {\n    width: 1px;\n    height: 20px;\n    background: rgba(255, 255, 255, 0.18);\n    margin: 0 2px;\n  }\n\n  /* Inline Note Composer Popover */\n  .note-modal {\n    position: fixed;\n    inset: 0;\n    background: rgba(24, 24, 27, 0.45);\n    display: none;\n    align-items: center;\n    justify-content: center;\n    padding: 16px;\n    z-index: 80;\n  }\n  .note-modal.open { display: flex; }\n  .note-dialog {\n    width: 100%;\n    max-width: 400px;\n    background: var(--surface);\n    border-radius: 16px;\n    padding: 20px;\n    border: 1px solid var(--border);\n    box-shadow: 0 20px 44px rgba(0, 0, 0, 0.2);\n    display: flex;\n    flex-direction: column;\n    gap: 12px;\n  }\n  .note-dialog textarea {\n    width: 100%;\n    min-height: 88px;\n    padding: 10px 12px;\n    border-radius: 10px;\n    border: 1px solid var(--border);\n    font: inherit;\n    font-size: 14px;\n    resize: vertical;\n  }\n  .dialog-actions {\n    display: flex;\n    justify-content: flex-end;\n    gap: 8px;\n  }\n  .btn {\n    min-height: 44px;\n    padding: 0 16px;\n    border-radius: 10px;\n    border: 1px solid var(--border);\n    background: var(--surface);\n    color: var(--ink);\n    font: inherit;\n    font-size: 13.5px;\n    font-weight: 600;\n    cursor: pointer;\n  }\n  .btn-dark { background: var(--ink); border-color: var(--ink); color: #fff; }\n\n  /* Mobile Bottom Action Bar */\n  .mobile-dock {\n    display: none;\n    position: fixed;\n    left: 0; right: 0; bottom: 0;\n    background: var(--toolbar-bg);\n    color: var(--toolbar-ink);\n    padding: 8px 10px;\n    z-index: 55;\n    justify-content: space-around;\n    gap: 4px;\n    border-top: 1px solid #2e2e35;\n  }\n  .mobile-dock .tb-btn { min-height: 44px; flex: 1; font-size: 12.5px; padding: 0 6px; }\n  .mobile-dock.inactive { opacity: 0.65; }\n\n  .toast {\n    position: fixed;\n    bottom: 72px;\n    left: 50%;\n    transform: translate(-50%, 10px);\n    background: var(--toolbar-bg);\n    color: #fff;\n    padding: 9px 16px;\n    border-radius: 99px;\n    font-size: 13px;\n    opacity: 0;\n    pointer-events: none;\n    transition: all 0.2s;\n    z-index: 90;\n  }\n  .toast.show { opacity: 1; transform: translate(-50%, 0); }\n\n  @media (max-width: 860px) {\n    .layout { grid-template-columns: 1fr; padding: 0 12px; margin-top: 16px; gap: 16px; }\n    article.editor-sheet { padding: 22px 18px; }\n    .doc-title { font-size: 28px; }\n    .prose { font-size: 18px; }\n    aside.rail { position: static; }\n    .float-toolbar { display: none !important; }\n    .mobile-dock { display: flex; }\n  }\n</style>\n</head>\n<body>\n<header class=\"topbar\">\n  <div class=\"topbar-inner\">\n    <div class=\"pub\">\n      <div class=\"pub-mark\">A</div>\n      <div>\n        <strong>Alabaster Press</strong>\n        <span>Draft · Select any text to format, quote, or annotate</span>\n      </div>\n    </div>\n    <div class=\"quick-bar\">\n      <span class=\"quick-label\">Quick select:</span>\n      <button type=\"button\" class=\"preset-chip\" data-phrase=\"quiet typography is an act of hospitality\">Opening thesis</button>\n      <button type=\"button\" class=\"preset-chip\" data-phrase=\"margins are not empty space; they are breathing room\">Margins quote</button>\n      <button type=\"button\" class=\"preset-chip\" data-phrase=\"every tool should stay invisible until your fingers ask for it\">Toolbar line</button>\n    </div>\n  </div>\n</header>\n\n<main class=\"layout\">\n  <article class=\"editor-sheet\">\n    <div class=\"kicker\">Essay Draft · Issue 19</div>\n    <h1 class=\"doc-title\">Why Quiet Interfaces Outlast Loud Ones</h1>\n    <div class=\"byline\">\n      <span>By Clara Lindholm · 4 min read</span>\n      <span id=\"selStatus\">No text selected</span>\n    </div>\n\n    <div class=\"prose\" id=\"prose\" contenteditable=\"true\" spellcheck=\"true\">\n      <p>Good editorial software behaves like a well-lit reading room. We often forget that quiet typography is an act of hospitality: when a page refuses to shout with badges, sidebars, and blinking chrome, the reader’s attention settles into the cadence of the argument.</p>\n      <p>In print studios of the 1960s, editors worked with nothing more than a soft graphite pencil and a generous page border. They understood that margins are not empty space; they are breathing room where a second thought can land without interrupting the first.</p>\n      <p>Digital writing tools inherited too many ribbons from spreadsheets. Instead of pinning forty buttons above the headline, every tool should stay invisible until your fingers ask for it—rising cleanly above a highlighted clause and vanishing the instant you resume typing.</p>\n      <p>Try dragging across any sentence in this draft, or tap one of the quick-select chips above, to test bold, italic, highlighter, pull-quote promotion, and margin notes directly in place.</p>\n    </div>\n  </article>\n\n  <aside class=\"rail\">\n    <section class=\"rail-card\">\n      <h2><span>Draft Telemetry</span></h2>\n      <div class=\"stats-grid\">\n        <div class=\"stat-box\"><span>Words</span><strong id=\"wordCount\">0</strong></div>\n        <div class=\"stat-box\"><span>Margin Notes</span><strong id=\"noteCount\">1</strong></div>\n      </div>\n    </section>\n\n    <section class=\"rail-card\">\n      <h2><span>Margin Notes</span><button type=\"button\" id=\"resetDocBtn\" style=\"border:none;background:none;color:var(--accent);font:inherit;font-size:11.5px;font-weight:600;cursor:pointer\">Reset Draft</button></h2>\n      <div class=\"note-list\" id=\"noteList\"></div>\n    </section>\n  </aside>\n</main>\n\n<!-- Floating Selection Toolbar (Desktop) -->\n<div class=\"float-toolbar\" id=\"floatToolbar\" role=\"toolbar\" aria-label=\"Text formatting toolbar\">\n  <button type=\"button\" class=\"tb-btn\" data-action=\"bold\" title=\"Bold\"><strong>B</strong></button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"italic\" title=\"Italic\"><em>I</em></button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"highlight\" title=\"Highlight\">Highlight</button>\n  <span class=\"tb-sep\"></span>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"quote\" title=\"Turn into pull-quote\">“Quote”</button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"note\" title=\"Attach margin note\">Note</button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"copy\" title=\"Copy selection\">Copy</button>\n</div>\n\n<!-- Mobile Bottom Action Bar -->\n<div class=\"mobile-dock inactive\" id=\"mobileDock\" role=\"toolbar\" aria-label=\"Mobile selection actions\">\n  <button type=\"button\" class=\"tb-btn\" data-action=\"bold\"><strong>B</strong></button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"italic\"><em>I</em></button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"highlight\">Mark</button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"quote\">Quote</button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"note\">Note</button>\n  <button type=\"button\" class=\"tb-btn\" data-action=\"copy\">Copy</button>\n</div>\n\n<!-- Add Note Dialog -->\n<div class=\"note-modal\" id=\"noteModal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"noteDlgTitle\">\n  <form class=\"note-dialog\" id=\"noteForm\">\n    <h3 id=\"noteDlgTitle\" style=\"font-size:17px\">Attach Margin Note</h3>\n    <div class=\"note-quote\" id=\"noteQuotePreview\"></div>\n    <textarea id=\"noteInput\" placeholder=\"Write an editorial note or revision cue...\" required></textarea>\n    <div class=\"dialog-actions\">\n      <button type=\"button\" class=\"btn\" id=\"cancelNoteBtn\">Cancel</button>\n      <button type=\"submit\" class=\"btn btn-dark\">Save Note</button>\n    </div>\n  </form>\n</div>\n\n<div class=\"toast\" id=\"toast\" role=\"status\" aria-live=\"polite\"></div>\n\n<script>\n(() => {\n  const prose = document.getElementById('prose');\n  const initialProseHTML = prose.innerHTML;\n  const floatToolbar = document.getElementById('floatToolbar');\n  const mobileDock = document.getElementById('mobileDock');\n  const selStatus = document.getElementById('selStatus');\n  const noteList = document.getElementById('noteList');\n  const noteModal = document.getElementById('noteModal');\n  const noteInput = document.getElementById('noteInput');\n  const noteQuotePreview = document.getElementById('noteQuotePreview');\n\n  let savedRange = null;\n  let savedText = '';\n  let notes = [\n    { id: 1, quote: 'well-lit reading room', body: 'Keep this opening metaphor — resonates with the print studio section below.', time: 'Just now' }\n  ];\n  let nextNoteId = 2;\n\n  function showToast(msg) {\n    const t = document.getElementById('toast');\n    t.textContent = msg;\n    t.classList.add('show');\n    setTimeout(() => t.classList.remove('show'), 2200);\n  }\n\n  function updateWordCount() {\n    const words = prose.innerText.trim().split(/\\s+/).filter(Boolean).length;\n    document.getElementById('wordCount').textContent = words;\n  }\n\n  function renderNotes() {\n    document.getElementById('noteCount').textContent = notes.length;\n    if (!notes.length) {\n      noteList.innerHTML = '<div style=\"font-size:13px;color:var(--muted)\">No margin notes yet. Select any phrase and click Note.</div>';\n      return;\n    }\n    noteList.innerHTML = notes.map(n => `\n      <div class=\"note-item\">\n        <div class=\"note-quote\">“${n.quote.replace(/</g, '&lt;')}”</div>\n        <div class=\"note-body\">${n.body.replace(/</g, '&lt;')}</div>\n        <div class=\"note-meta\">\n          <span>${n.time}</span>\n          <button type=\"button\" class=\"note-del\" data-id=\"${n.id}\">Remove</button>\n        </div>\n      </div>\n    `).join('');\n  }\n\n  function getValidSelection() {\n    const sel = window.getSelection();\n    if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return null;\n    const range = sel.getRangeAt(0);\n    if (!prose.contains(range.commonAncestorContainer)) return null;\n    const text = sel.toString().trim();\n    if (!text) return null;\n    return { sel, range, text };\n  }\n\n  function positionToolbar() {\n    const info = getValidSelection();\n    if (!info) {\n      floatToolbar.classList.remove('visible');\n      mobileDock.classList.add('inactive');\n      selStatus.textContent = 'No text selected';\n      return;\n    }\n    savedRange = info.range.cloneRange();\n    savedText = info.text;\n    selStatus.textContent = `${info.text.split(/\\s+/).length} word(s) selected`;\n    mobileDock.classList.remove('inactive');\n\n    const rect = info.range.getBoundingClientRect();\n    const tbW = floatToolbar.offsetWidth || 340;\n    const x = Math.max(tbW / 2 + 12, Math.min(window.innerWidth - tbW / 2 - 12, rect.left + rect.width / 2));\n    const y = Math.max(12, rect.top - 54);\n    floatToolbar.style.left = `${x}px`;\n    floatToolbar.style.top = `${y}px`;\n    floatToolbar.classList.add('visible');\n  }\n\n  function wrapRange(tagName, className) {\n    if (!savedRange) return;\n    const sel = window.getSelection();\n    sel.removeAllRanges();\n    sel.addRange(savedRange);\n    const el = document.createElement(tagName);\n    if (className) el.className = className;\n    try {\n      savedRange.surroundContents(el);\n    } catch {\n      const frag = savedRange.extractContents();\n      el.appendChild(frag);\n      savedRange.insertNode(el);\n    }\n    sel.removeAllRanges();\n    floatToolbar.classList.remove('visible');\n    mobileDock.classList.add('inactive');\n    updateWordCount();\n  }\n\n  function handleAction(action) {\n    if (!savedRange || !savedText) {\n      showToast('Select a phrase in the essay first');\n      return;\n    }\n    if (action === 'bold') {\n      wrapRange('strong');\n      showToast('Applied bold');\n    } else if (action === 'italic') {\n      wrapRange('em');\n      showToast('Applied italic');\n    } else if (action === 'highlight') {\n      wrapRange('mark', 'hl');\n      showToast('Highlighted selection');\n    } else if (action === 'quote') {\n      wrapRange('span', 'pull-quote-inline');\n      showToast('Promoted to pull-quote');\n    } else if (action === 'copy') {\n      if (navigator.clipboard) navigator.clipboard.writeText(savedText).catch(() => {});\n      showToast('Copied selection to clipboard');\n      floatToolbar.classList.remove('visible');\n    } else if (action === 'note') {\n      noteQuotePreview.textContent = `“${savedText.slice(0, 110)}${savedText.length > 110 ? '…' : ''}”`;\n      noteInput.value = '';\n      noteModal.classList.add('open');\n      setTimeout(() => noteInput.focus(), 40);\n    }\n  }\n\n  function bindToolbar(container) {\n    container.addEventListener('pointerdown', (e) => {\n      if (e.target.closest('.tb-btn')) e.preventDefault();\n    });\n    container.addEventListener('click', (e) => {\n      const btn = e.target.closest('.tb-btn');\n      if (btn) handleAction(btn.dataset.action);\n    });\n  }\n  bindToolbar(floatToolbar);\n  bindToolbar(mobileDock);\n\n  // Quick-select preset chips so desktop & mobile users can test in 1 tap\n  document.querySelectorAll('.preset-chip').forEach(chip => {\n    chip.addEventListener('click', () => {\n      const phrase = chip.dataset.phrase;\n      const walker = document.createTreeWalker(prose, NodeFilter.SHOW_TEXT);\n      let node;\n      while ((node = walker.nextNode())) {\n        const idx = node.nodeValue.toLowerCase().indexOf(phrase.toLowerCase());\n        if (idx !== -1) {\n          const range = document.createRange();\n          range.setStart(node, idx);\n          range.setEnd(node, idx + phrase.length);\n          const sel = window.getSelection();\n          sel.removeAllRanges();\n          sel.addRange(range);\n          node.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });\n          setTimeout(positionToolbar, 120);\n          return;\n        }\n      }\n      showToast('Phrase already edited — click Reset Draft to restore');\n    });\n  });\n\n  document.getElementById('noteForm').addEventListener('submit', (e) => {\n    e.preventDefault();\n    const body = noteInput.value.trim();\n    if (!body) return;\n    wrapRange('span', 'annotated');\n    notes.unshift({\n      id: ++nextNoteId,\n      quote: savedText.slice(0, 90),\n      body,\n      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n    });\n    renderNotes();\n    noteModal.classList.remove('open');\n    showToast('Margin note attached');\n  });\n\n  document.getElementById('cancelNoteBtn').addEventListener('click', () => noteModal.classList.remove('open'));\n  noteModal.addEventListener('click', (e) => { if (e.target === noteModal) noteModal.classList.remove('open'); });\n\n  noteList.addEventListener('click', (e) => {\n    const btn = e.target.closest('.note-del');\n    if (!btn) return;\n    const id = parseInt(btn.dataset.id, 10);\n    notes = notes.filter(n => n.id !== id);\n    renderNotes();\n  });\n\n  document.getElementById('resetDocBtn').addEventListener('click', () => {\n    prose.innerHTML = initialProseHTML;\n    savedRange = null;\n    savedText = '';\n    floatToolbar.classList.remove('visible');\n    updateWordCount();\n    showToast('Draft restored');\n  });\n\n  document.addEventListener('selectionchange', () => {\n    if (!noteModal.classList.contains('open')) positionToolbar();\n  });\n  prose.addEventListener('pointerup', () => setTimeout(positionToolbar, 10));\n  prose.addEventListener('input', updateWordCount);\n  window.addEventListener('scroll', () => { if (floatToolbar.classList.contains('visible')) positionToolbar(); }, { passive: true });\n\n  updateWordCount();\n  renderNotes();\n})();\n</script>\n</body>\n</html>\n"
}
