Save a fragment without losing your draft

Changing a checkbox or calling a save method does not confirm persistence. This guide makes the save boundary explicit with browser fetch, the documented selector GET, and conditional PUT. It does not depend on the Pagelove client helpers or assume they throw for every HTTP error.

Establish the source and acceptance boundary

Use a test host with harmless data. Through trusted authoring, create /notes.html containing this existing source fragment:

<p id="shopping-note">Remember the reusable bags.</p>

The host author owns the application definitions; permitted visitors edit this one shared note. Its stable identity is the resource /notes.html plus selector #shopping-note, independent of list position. Its value is plain text; this example preserves no additional attributes, markup, or fields. Keep this source separate from the editor page so publishing editor changes does not replace the live note.

Before using the editor, configure and check visitor read/write authorization and server validation for the actual target. Permit only the intended paragraph structure and apply appropriate server-side text/request limits; value validation is separate from a markup shape. The editor's 500-character limit is convenience, not server enforcement. A WebDAV upload deliberately bypasses application validation and does not establish that these checks work. Use the deployment checklist to record actual results.

This baseline requires an ordinary, uncomposed fragment, a strong ETag from its selector GET, and conditional PUT support on the intended host. Do not configure handlers or transformations on this example's target: they can change its representation, response, or side effects and require their own acceptance/reconciliation contract. No create, delete, cross-resource transaction, live subscription, or automatic retry is implemented. A platform version or capability that the host does not expose stays unverified.

Give the draft and pending request separate places

Put this editor on another HTML page on the same host. The server paragraph is authoritative. The confirmed display is a projection; the native form holds the editable draft, and the read-only pending fields retain one frozen submission. Temporary controls and notices are outside the persisted source.

<section aria-labelledby="note-heading">
  <h1 id="note-heading">Shopping note</h1>
  <h2>Last server copy</h2>
  <p id="confirmed-note">Not loaded.</p>
  <form id="note-editor">
    <label for="draft-note">Your draft (up to 500 characters)</label>
    <textarea id="draft-note" maxlength="500" required disabled></textarea>
    <button id="save-note" type="submit" disabled>Save draft</button>
  </form>
  <p itemscope itemtype="https://schema.org/Thing">
    <output id="save-status" itemprop="description" role="status" aria-live="polite">
      JavaScript and a successful server read are needed before editing.
    </output>
  </p>
  <h2>Pending request to review</h2>
  <label for="pending-note">Frozen PUT body (copy before leaving)</label>
  <textarea id="pending-note" readonly rows="4"></textarea>
  <p>Submitted validator: <output id="pending-validator">None</output></p>
  <button id="read-note" type="button">Read server copy; keep draft</button>
  <button id="use-server-note" type="button" disabled>Replace draft with server copy</button>
  <button id="finish-note-review" type="button" disabled>Finish review of pending attempt</button>
</section>

Add this module after the editor. All DOM lookups are scoped to these fixed IDs. The HTTP selector is sent in a Range header; a URL #fragment would not send it to the server.

<script type="module">
  const byId = (id) => document.getElementById(id);
  const source = new URL('/notes.html', location.origin);
  const selector = '#shopping-note';
  const confirmed = byId('confirmed-note');
  const draft = byId('draft-note');
  const pending = byId('pending-note');
  const pendingValidator = byId('pending-validator');
  const status = byId('save-status');
  const save = byId('save-note');
  const read = byId('read-note');
  const useServer = byId('use-server-note');
  const finish = byId('finish-note-review');
  let etag;
  let loaded = false;
  let busy = false;
  let readAfterAttempt = false;

  function controls() {
    draft.disabled = !loaded;
    save.disabled = busy || !loaded || Boolean(pending.value);
    read.disabled = busy;
    useServer.disabled = busy || !loaded;
    finish.disabled = busy || !pending.value || !readAfterAttempt;
  }

  async function readServer() {
    if (busy) return;
    busy = true;
    controls();
    status.textContent = 'Reading the server copy; keeping your draft.';
    try {
      const response = await fetch(source, {
        credentials: 'same-origin', cache: 'no-store', redirect: 'error',
        headers: { Accept: 'text/html', Range: `selector=${selector}` },
      });
      if (response.status !== 206) throw new Error('Expected a fragment.');
      const nextETag = response.headers.get('ETag');
      if (!nextETag || !/^"[^"]*"$/.test(nextETag)) {
        throw new Error('A strong validator is required.');
      }
      const template = document.createElement('template');
      template.innerHTML = await response.text();
      const nodes = [...template.content.childNodes].filter((node) =>
        node.nodeType !== Node.TEXT_NODE || node.textContent.trim() !== '');
      const paragraph = nodes[0];
      if (nodes.length !== 1 || paragraph.nodeType !== Node.ELEMENT_NODE ||
          paragraph.localName !== 'p' || paragraph.id !== 'shopping-note' ||
          [...paragraph.attributes].some((attr) => attr.name !== 'id') ||
          [...paragraph.childNodes].some((node) => node.nodeType !== Node.TEXT_NODE)) {
        throw new Error('Unexpected source structure.');
      }
      confirmed.textContent = paragraph.textContent;
      etag = nextETag;
      if (!loaded) draft.value = confirmed.textContent;
      loaded = true;
      readAfterAttempt = Boolean(pending.value);
      status.textContent = pending.value
        ? 'Server copy loaded. Draft and pending request kept. Compare them before finishing review.'
        : 'Server copy loaded. Later reads keep your draft.';
    } catch {
      status.textContent = 'Could not load a supported server copy. Your draft and pending request are unchanged.';
    } finally {
      busy = false;
      controls();
    }
  }

  byId('note-editor').addEventListener('submit', async (event) => {
    event.preventDefault();
    if (busy || !loaded || pending.value) return;
    const paragraph = document.createElement('p');
    paragraph.id = 'shopping-note';
    paragraph.textContent = draft.value;
    const body = paragraph.outerHTML;
    const validator = etag;
    pending.value = body;
    pendingValidator.textContent = validator;
    readAfterAttempt = false;
    busy = true;
    controls();
    status.textContent = 'Saving the frozen request. You can continue typing a newer draft.';
    try {
      const response = await fetch(source, {
        method: 'PUT', credentials: 'same-origin', redirect: 'error',
        headers: {
          Accept: 'text/html', 'Content-Type': 'text/html; charset=utf-8',
          Range: `selector=${selector}`, 'If-Match': validator,
        },
        body,
      });
      if (response.status === 206) {
        status.textContent = 'PUT accepted. Read the latest server copy; your newer draft is still here.';
      } else if (response.status === 412 || response.status === 409) {
        status.textContent = 'Conflict. Request and draft kept. Read the server copy and reconcile; nothing will retry automatically.';
      } else {
        status.textContent = `Response ${response.status}; save not confirmed here. Request and draft kept. Read and review before another change.`;
      }
    } catch {
      status.textContent = 'Outcome unknown: the response was lost or the request failed. Request and draft kept. Do not blindly resend.';
    } finally {
      busy = false;
      controls();
    }
  });

  read.addEventListener('click', readServer);
  useServer.addEventListener('click', () => {
    if (busy || !loaded) return;
    if (draft.value !== confirmed.textContent &&
        !confirm('Replace this draft? Copy any text you want to keep first.')) return;
    draft.value = confirmed.textContent;
    status.textContent = 'Draft replaced by your choice. Any pending request still needs review.';
  });
  finish.addEventListener('click', () => {
    if (busy || !pending.value || !readAfterAttempt) return;
    pending.value = '';
    pendingValidator.textContent = 'None';
    readAfterAttempt = false;
    status.textContent = 'Review finished. Draft kept. The next Save is a new conditional request.';
    controls();
  });
  controls();
  await readServer();
</script>

Only a documented 206 marks this baseline PUT as accepted. That does not make text typed afterward saved. A fresh read establishes a new server copy, which may already include someone else's later change. Matching text alone is not a receipt identifying your earlier request.

After any attempt, read and compare the server copy, pending payload, and draft. Copy pending information you still need before choosing Finish review; that button records a deliberate review decision in this editor, not proof that an uncertain write committed. Resolve differences in the draft before making a new conditional request. Keep the prior frozen payload if you need to investigate independent effects; do not extend this example to POST retries without an operation-specific contract.

Check the recovery paths

On the test host, record these outcomes rather than inferring them from the code:

Scenario Expected client behavior
Valid accepted save Reports the operation's result; retains the frozen request until review; a fresh read establishes current server state.
Typing during a save Changes the draft only; the submitted HTML and validator stay fixed.
Another writer saves first A stale conditional write is refused; the draft and pending payload remain available for comparison.
Authorization or validation refusal Displays the non-success response without claiming persistence; retains the work.
Connection or response lost Marks the outcome unknown; performs no automatic retry.
Read while a draft is dirty Updates the server projection and validator without replacing the draft.
Explicitly replace the draft Requires confirmation when it differs, then adopts the server copy by the reader's choice.

This example keeps drafts in the open page only. Copy the draft and pending payload before reloading, navigating away, changing accounts, or closing the tab. Durable/offline draft storage, subscription lifecycle, full browser/accessibility checks, server policy and bounds, and actual hosted acceptance remain separate work. Passing the documentation build does not execute these scenarios or establish production readiness.