# #143 — Contextual Floating Selection Toolbar

> Editorial article canvas with a live floating text-selection toolbar (Bold, Italic, Highlight, Quote, Note) and mobile action dock.

## Metadata

- **Index**: #143
- **Slug**: `floating-selection-toolbar`
- **Kind**: `ui`
- **Family**: Editorial & Reading
- **Theme**: `light`
- **Mobile Strength**: `high`
- **Tags**: `selection-toolbar`, `floating-ui`, `rich-text`, `editorial`, `annotations`, `publishing`
- **Best For**: Publishing platforms and blog editors, Collaborative document commenting tools, E-readers and web highlighters, Research clippers and note-taking apps
- **Real-World Inspiration**: [Ghost](https://ghost.org/)
- **Detail Page**: https://templates.michaelpitts.net/t/floating-selection-toolbar
- **Live Demo**: https://templates.michaelpitts.net/demos/floating-selection-toolbar.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/floating-selection-toolbar

## Why This Aesthetic Is Unique

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.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Alabaster | `#FAF9F7` |
| `surface` | Editorial Sheet | `#FFFFFF` |
| `ink` | Press Ink | `#18181B` |
| `accent` | Highlighter Amber | `#D97706` |
| `muted` | Caption Gray | `#71717A` |

## Typography

- **Display**: `Newsreader`
- **Body**: `Newsreader`
- **Mono**: `JetBrains Mono`
- **Scale Notes**: 32px serif article headline, 18px/1.75 body text, 13px sans floating toolbar buttons, 12px annotation cards.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=Inter:wght@500;600&family=Newsreader:ital,wght@0,400;0,600;0,700;1,400&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@500;600&family=Newsreader:ital,wght@0,400;0,600;0,700;1,400&display=swap">
  ```

## Layout Architecture

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.

## Interaction & Micro-Motion Rules

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.

## Mobile & Responsive Rules

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.

## Agent Guardrails

### 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.

### DON'T
- 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.

## Complete Standalone Starter Code

File: `demos/floating-selection-toolbar.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alabaster Press — Contextual Selection Toolbar</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<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">
<style>
  :root {
    --bg: #faf8f4;
    --surface: #ffffff;
    --border: #e7e2d9;
    --ink: #1b1b1a;
    --muted: #6c6963;
    --toolbar-bg: #18181b;
    --toolbar-ink: #f8fafc;
    --accent: #b45309;
    --hl: #fef08a;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { overflow-x: hidden; }
  body {
    font-family: 'Inter', system-ui, -apple-system, sans-serif;
    background: var(--bg);
    color: var(--ink);
    min-height: 100vh;
    padding-bottom: 90px;
  }
  .topbar {
    position: sticky;
    top: 0;
    z-index: 20;
    background: rgba(250, 248, 244, 0.92);
    backdrop-filter: blur(8px);
    border-bottom: 1px solid var(--border);
    padding: 12px 20px;
  }
  .topbar-inner {
    max-width: 1120px;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }
  .pub {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .pub-mark {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    background: var(--ink);
    color: #fff;
    font-family: 'Newsreader', Georgia, serif;
    font-size: 19px;
    display: grid;
    place-items: center;
  }
  .pub strong { font-size: 15px; letter-spacing: -0.01em; }
  .pub span { font-size: 12px; color: var(--muted); display: block; }

  .quick-bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 7px;
  }
  .quick-label {
    font-size: 12px;
    color: var(--muted);
    margin-right: 2px;
  }
  .preset-chip {
    min-height: 38px;
    padding: 0 12px;
    border-radius: 99px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--ink);
    font: inherit;
    font-size: 12.5px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.15s;
  }
  .preset-chip:hover { border-color: var(--ink); background: #f3efe8; }

  .layout {
    max-width: 1120px;
    margin: 26px auto 0;
    padding: 0 20px;
    display: grid;
    grid-template-columns: minmax(0, 1fr) 310px;
    gap: 28px;
    align-items: start;
  }

  article.editor-sheet {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 42px 48px;
    box-shadow: 0 2px 16px rgba(27, 27, 26, 0.03);
  }
  .kicker {
    font-size: 11.5px;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: var(--accent);
    font-weight: 600;
    margin-bottom: 10px;
  }
  .doc-title {
    font-family: 'Newsreader', Georgia, serif;
    font-size: 38px;
    font-weight: 500;
    line-height: 1.12;
    letter-spacing: -0.02em;
    margin-bottom: 12px;
  }
  .byline {
    font-size: 13px;
    color: var(--muted);
    padding-bottom: 22px;
    border-bottom: 1px solid var(--border);
    margin-bottom: 26px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 8px;
  }

  .prose {
    font-family: 'Newsreader', Georgia, serif;
    font-size: 20px;
    line-height: 1.7;
    color: #242321;
    outline: none;
  }
  .prose p { margin-bottom: 20px; }
  .prose p:last-child { margin-bottom: 0; }
  .prose mark.hl {
    background: var(--hl);
    color: inherit;
    padding: 1px 3px;
    border-radius: 3px;
  }
  .prose .pull-quote-inline {
    display: block;
    margin: 22px 0;
    padding: 14px 20px;
    border-left: 3px solid var(--ink);
    background: #f8f5ef;
    font-style: italic;
    font-size: 22px;
    line-height: 1.45;
    color: var(--ink);
    border-radius: 0 10px 10px 0;
  }
  .prose span.annotated {
    border-bottom: 2px dotted var(--accent);
    background: rgba(180, 83, 9, 0.08);
    padding-bottom: 1px;
  }

  /* Margin notes rail */
  aside.rail {
    position: sticky;
    top: 78px;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  .rail-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 16px;
  }
  .rail-card h2 {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--muted);
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }
  .note-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .note-item {
    background: #faf8f4;
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px 12px;
    font-size: 13px;
  }
  .note-quote {
    font-family: 'Newsreader', Georgia, serif;
    font-style: italic;
    font-size: 14px;
    color: var(--muted);
    border-left: 2px solid var(--accent);
    padding-left: 8px;
    margin-bottom: 6px;
  }
  .note-body { color: var(--ink); line-height: 1.45; }
  .note-meta {
    margin-top: 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: var(--muted);
  }
  .note-del {
    border: none;
    background: none;
    color: var(--muted);
    cursor: pointer;
    font-size: 12px;
    padding: 4px 6px;
  }
  .note-del:hover { color: #b91c1c; }

  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
  .stat-box {
    background: #faf8f4;
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px;
  }
  .stat-box span { font-size: 11px; color: var(--muted); display: block; }
  .stat-box strong { font-size: 18px; font-weight: 600; }

  /* Floating Desktop Toolbar */
  .float-toolbar {
    position: fixed;
    z-index: 60;
    background: var(--toolbar-bg);
    color: var(--toolbar-ink);
    border-radius: 12px;
    padding: 5px;
    display: flex;
    align-items: center;
    gap: 2px;
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.28);
    opacity: 0;
    transform: translate(-50%, -8px) scale(0.96);
    pointer-events: none;
    transition: opacity 0.14s ease, transform 0.14s ease;
  }
  .float-toolbar.visible {
    opacity: 1;
    transform: translate(-50%, 0) scale(1);
    pointer-events: auto;
  }
  .float-toolbar::after {
    content: "";
    position: absolute;
    left: 50%;
    bottom: -6px;
    transform: translateX(-50%);
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-top: 6px solid var(--toolbar-bg);
  }
  .tb-btn {
    min-width: 38px;
    min-height: 38px;
    padding: 0 10px;
    border: none;
    background: transparent;
    color: var(--toolbar-ink);
    border-radius: 8px;
    font: inherit;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    white-space: nowrap;
  }
  .tb-btn:hover { background: rgba(255, 255, 255, 0.14); }
  .tb-sep {
    width: 1px;
    height: 20px;
    background: rgba(255, 255, 255, 0.18);
    margin: 0 2px;
  }

  /* Inline Note Composer Popover */
  .note-modal {
    position: fixed;
    inset: 0;
    background: rgba(24, 24, 27, 0.45);
    display: none;
    align-items: center;
    justify-content: center;
    padding: 16px;
    z-index: 80;
  }
  .note-modal.open { display: flex; }
  .note-dialog {
    width: 100%;
    max-width: 400px;
    background: var(--surface);
    border-radius: 16px;
    padding: 20px;
    border: 1px solid var(--border);
    box-shadow: 0 20px 44px rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  .note-dialog textarea {
    width: 100%;
    min-height: 88px;
    padding: 10px 12px;
    border-radius: 10px;
    border: 1px solid var(--border);
    font: inherit;
    font-size: 14px;
    resize: vertical;
  }
  .dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
  .btn {
    min-height: 44px;
    padding: 0 16px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--ink);
    font: inherit;
    font-size: 13.5px;
    font-weight: 600;
    cursor: pointer;
  }
  .btn-dark { background: var(--ink); border-color: var(--ink); color: #fff; }

  /* Mobile Bottom Action Bar */
  .mobile-dock {
    display: none;
    position: fixed;
    left: 0; right: 0; bottom: 0;
    background: var(--toolbar-bg);
    color: var(--toolbar-ink);
    padding: 8px 10px;
    z-index: 55;
    justify-content: space-around;
    gap: 4px;
    border-top: 1px solid #2e2e35;
  }
  .mobile-dock .tb-btn { min-height: 44px; flex: 1; font-size: 12.5px; padding: 0 6px; }
  .mobile-dock.inactive { opacity: 0.65; }

  .toast {
    position: fixed;
    bottom: 72px;
    left: 50%;
    transform: translate(-50%, 10px);
    background: var(--toolbar-bg);
    color: #fff;
    padding: 9px 16px;
    border-radius: 99px;
    font-size: 13px;
    opacity: 0;
    pointer-events: none;
    transition: all 0.2s;
    z-index: 90;
  }
  .toast.show { opacity: 1; transform: translate(-50%, 0); }

  @media (max-width: 860px) {
    .layout { grid-template-columns: 1fr; padding: 0 12px; margin-top: 16px; gap: 16px; }
    article.editor-sheet { padding: 22px 18px; }
    .doc-title { font-size: 28px; }
    .prose { font-size: 18px; }
    aside.rail { position: static; }
    .float-toolbar { display: none !important; }
    .mobile-dock { display: flex; }
  }
</style>
</head>
<body>
<header class="topbar">
  <div class="topbar-inner">
    <div class="pub">
      <div class="pub-mark">A</div>
      <div>
        <strong>Alabaster Press</strong>
        <span>Draft · Select any text to format, quote, or annotate</span>
      </div>
    </div>
    <div class="quick-bar">
      <span class="quick-label">Quick select:</span>
      <button type="button" class="preset-chip" data-phrase="quiet typography is an act of hospitality">Opening thesis</button>
      <button type="button" class="preset-chip" data-phrase="margins are not empty space; they are breathing room">Margins quote</button>
      <button type="button" class="preset-chip" data-phrase="every tool should stay invisible until your fingers ask for it">Toolbar line</button>
    </div>
  </div>
</header>

<main class="layout">
  <article class="editor-sheet">
    <div class="kicker">Essay Draft · Issue 19</div>
    <h1 class="doc-title">Why Quiet Interfaces Outlast Loud Ones</h1>
    <div class="byline">
      <span>By Clara Lindholm · 4 min read</span>
      <span id="selStatus">No text selected</span>
    </div>

    <div class="prose" id="prose" contenteditable="true" spellcheck="true">
      <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>
      <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>
      <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>
      <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>
    </div>
  </article>

  <aside class="rail">
    <section class="rail-card">
      <h2><span>Draft Telemetry</span></h2>
      <div class="stats-grid">
        <div class="stat-box"><span>Words</span><strong id="wordCount">0</strong></div>
        <div class="stat-box"><span>Margin Notes</span><strong id="noteCount">1</strong></div>
      </div>
    </section>

    <section class="rail-card">
      <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>
      <div class="note-list" id="noteList"></div>
    </section>
  </aside>
</main>

<!-- Floating Selection Toolbar (Desktop) -->
<div class="float-toolbar" id="floatToolbar" role="toolbar" aria-label="Text formatting toolbar">
  <button type="button" class="tb-btn" data-action="bold" title="Bold"><strong>B</strong></button>
  <button type="button" class="tb-btn" data-action="italic" title="Italic"><em>I</em></button>
  <button type="button" class="tb-btn" data-action="highlight" title="Highlight">Highlight</button>
  <span class="tb-sep"></span>
  <button type="button" class="tb-btn" data-action="quote" title="Turn into pull-quote">“Quote”</button>
  <button type="button" class="tb-btn" data-action="note" title="Attach margin note">Note</button>
  <button type="button" class="tb-btn" data-action="copy" title="Copy selection">Copy</button>
</div>

<!-- Mobile Bottom Action Bar -->
<div class="mobile-dock inactive" id="mobileDock" role="toolbar" aria-label="Mobile selection actions">
  <button type="button" class="tb-btn" data-action="bold"><strong>B</strong></button>
  <button type="button" class="tb-btn" data-action="italic"><em>I</em></button>
  <button type="button" class="tb-btn" data-action="highlight">Mark</button>
  <button type="button" class="tb-btn" data-action="quote">Quote</button>
  <button type="button" class="tb-btn" data-action="note">Note</button>
  <button type="button" class="tb-btn" data-action="copy">Copy</button>
</div>

<!-- Add Note Dialog -->
<div class="note-modal" id="noteModal" role="dialog" aria-modal="true" aria-labelledby="noteDlgTitle">
  <form class="note-dialog" id="noteForm">
    <h3 id="noteDlgTitle" style="font-size:17px">Attach Margin Note</h3>
    <div class="note-quote" id="noteQuotePreview"></div>
    <textarea id="noteInput" placeholder="Write an editorial note or revision cue..." required></textarea>
    <div class="dialog-actions">
      <button type="button" class="btn" id="cancelNoteBtn">Cancel</button>
      <button type="submit" class="btn btn-dark">Save Note</button>
    </div>
  </form>
</div>

<div class="toast" id="toast" role="status" aria-live="polite"></div>

<script>
(() => {
  const prose = document.getElementById('prose');
  const initialProseHTML = prose.innerHTML;
  const floatToolbar = document.getElementById('floatToolbar');
  const mobileDock = document.getElementById('mobileDock');
  const selStatus = document.getElementById('selStatus');
  const noteList = document.getElementById('noteList');
  const noteModal = document.getElementById('noteModal');
  const noteInput = document.getElementById('noteInput');
  const noteQuotePreview = document.getElementById('noteQuotePreview');

  let savedRange = null;
  let savedText = '';
  let notes = [
    { id: 1, quote: 'well-lit reading room', body: 'Keep this opening metaphor — resonates with the print studio section below.', time: 'Just now' }
  ];
  let nextNoteId = 2;

  function showToast(msg) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 2200);
  }

  function updateWordCount() {
    const words = prose.innerText.trim().split(/\s+/).filter(Boolean).length;
    document.getElementById('wordCount').textContent = words;
  }

  function renderNotes() {
    document.getElementById('noteCount').textContent = notes.length;
    if (!notes.length) {
      noteList.innerHTML = '<div style="font-size:13px;color:var(--muted)">No margin notes yet. Select any phrase and click Note.</div>';
      return;
    }
    noteList.innerHTML = notes.map(n => `
      <div class="note-item">
        <div class="note-quote">“${n.quote.replace(/</g, '&lt;')}”</div>
        <div class="note-body">${n.body.replace(/</g, '&lt;')}</div>
        <div class="note-meta">
          <span>${n.time}</span>
          <button type="button" class="note-del" data-id="${n.id}">Remove</button>
        </div>
      </div>
    `).join('');
  }

  function getValidSelection() {
    const sel = window.getSelection();
    if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return null;
    const range = sel.getRangeAt(0);
    if (!prose.contains(range.commonAncestorContainer)) return null;
    const text = sel.toString().trim();
    if (!text) return null;
    return { sel, range, text };
  }

  function positionToolbar() {
    const info = getValidSelection();
    if (!info) {
      floatToolbar.classList.remove('visible');
      mobileDock.classList.add('inactive');
      selStatus.textContent = 'No text selected';
      return;
    }
    savedRange = info.range.cloneRange();
    savedText = info.text;
    selStatus.textContent = `${info.text.split(/\s+/).length} word(s) selected`;
    mobileDock.classList.remove('inactive');

    const rect = info.range.getBoundingClientRect();
    const tbW = floatToolbar.offsetWidth || 340;
    const x = Math.max(tbW / 2 + 12, Math.min(window.innerWidth - tbW / 2 - 12, rect.left + rect.width / 2));
    const y = Math.max(12, rect.top - 54);
    floatToolbar.style.left = `${x}px`;
    floatToolbar.style.top = `${y}px`;
    floatToolbar.classList.add('visible');
  }

  function wrapRange(tagName, className) {
    if (!savedRange) return;
    const sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(savedRange);
    const el = document.createElement(tagName);
    if (className) el.className = className;
    try {
      savedRange.surroundContents(el);
    } catch {
      const frag = savedRange.extractContents();
      el.appendChild(frag);
      savedRange.insertNode(el);
    }
    sel.removeAllRanges();
    floatToolbar.classList.remove('visible');
    mobileDock.classList.add('inactive');
    updateWordCount();
  }

  function handleAction(action) {
    if (!savedRange || !savedText) {
      showToast('Select a phrase in the essay first');
      return;
    }
    if (action === 'bold') {
      wrapRange('strong');
      showToast('Applied bold');
    } else if (action === 'italic') {
      wrapRange('em');
      showToast('Applied italic');
    } else if (action === 'highlight') {
      wrapRange('mark', 'hl');
      showToast('Highlighted selection');
    } else if (action === 'quote') {
      wrapRange('span', 'pull-quote-inline');
      showToast('Promoted to pull-quote');
    } else if (action === 'copy') {
      if (navigator.clipboard) navigator.clipboard.writeText(savedText).catch(() => {});
      showToast('Copied selection to clipboard');
      floatToolbar.classList.remove('visible');
    } else if (action === 'note') {
      noteQuotePreview.textContent = `“${savedText.slice(0, 110)}${savedText.length > 110 ? '…' : ''}”`;
      noteInput.value = '';
      noteModal.classList.add('open');
      setTimeout(() => noteInput.focus(), 40);
    }
  }

  function bindToolbar(container) {
    container.addEventListener('pointerdown', (e) => {
      if (e.target.closest('.tb-btn')) e.preventDefault();
    });
    container.addEventListener('click', (e) => {
      const btn = e.target.closest('.tb-btn');
      if (btn) handleAction(btn.dataset.action);
    });
  }
  bindToolbar(floatToolbar);
  bindToolbar(mobileDock);

  // Quick-select preset chips so desktop & mobile users can test in 1 tap
  document.querySelectorAll('.preset-chip').forEach(chip => {
    chip.addEventListener('click', () => {
      const phrase = chip.dataset.phrase;
      const walker = document.createTreeWalker(prose, NodeFilter.SHOW_TEXT);
      let node;
      while ((node = walker.nextNode())) {
        const idx = node.nodeValue.toLowerCase().indexOf(phrase.toLowerCase());
        if (idx !== -1) {
          const range = document.createRange();
          range.setStart(node, idx);
          range.setEnd(node, idx + phrase.length);
          const sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
          node.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
          setTimeout(positionToolbar, 120);
          return;
        }
      }
      showToast('Phrase already edited — click Reset Draft to restore');
    });
  });

  document.getElementById('noteForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const body = noteInput.value.trim();
    if (!body) return;
    wrapRange('span', 'annotated');
    notes.unshift({
      id: ++nextNoteId,
      quote: savedText.slice(0, 90),
      body,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    });
    renderNotes();
    noteModal.classList.remove('open');
    showToast('Margin note attached');
  });

  document.getElementById('cancelNoteBtn').addEventListener('click', () => noteModal.classList.remove('open'));
  noteModal.addEventListener('click', (e) => { if (e.target === noteModal) noteModal.classList.remove('open'); });

  noteList.addEventListener('click', (e) => {
    const btn = e.target.closest('.note-del');
    if (!btn) return;
    const id = parseInt(btn.dataset.id, 10);
    notes = notes.filter(n => n.id !== id);
    renderNotes();
  });

  document.getElementById('resetDocBtn').addEventListener('click', () => {
    prose.innerHTML = initialProseHTML;
    savedRange = null;
    savedText = '';
    floatToolbar.classList.remove('visible');
    updateWordCount();
    showToast('Draft restored');
  });

  document.addEventListener('selectionchange', () => {
    if (!noteModal.classList.contains('open')) positionToolbar();
  });
  prose.addEventListener('pointerup', () => setTimeout(positionToolbar, 10));
  prose.addEventListener('input', updateWordCount);
  window.addEventListener('scroll', () => { if (floatToolbar.classList.contains('visible')) positionToolbar(); }, { passive: true });

  updateWordCount();
  renderNotes();
})();
</script>
</body>
</html>
```
