Complete Guide & Showcase · All Features · All Workflows · All Systems

A calm writing desk with warm lamplight — the FlowWrite atmosphere

Welcome to FlowWrite — the most intelligent, most elegant writing environment ever built for people who take their words seriously. This is not a word processor. This is a creative operating system: a pure writing canvas fused with a real-time AI partner, an intelligent save system, a powerful export engine, and a document library — all wrapped in a dark, luxurious interface.

This guide covers every feature, every workflow, every system in FlowWrite. It is divided into four parts — paste them one after the other inside FlowWrite to experience every feature as you read about it.

Part 1 · Editor & Workspace Part 2 · AI Systems Part 3 · Rich Content Part 4 · Export & Workflows
Part 1 of 4

The Editor, The Workspace & The Universe

The Editor Canvas — How It Actually Works

The FlowWrite editor looks deceptively simple. A dark screen. A blinking cursor. EB Garamond serif font at 24 pixels with generous 1.625 line-spacing — the same typeface used by serious book publishers for three centuries. And nothing else visible.

But underneath that simplicity is a remarkable engineering achievement: a four-layer rendering system that gives you the typing speed of a plain textarea and the visual richness of a full document editor simultaneously.

architecture
┌─────────────────────────────────────────────────────────────┐
│                    BROWSER WINDOW                           │
│                                                             │
│  ┌──────────────────────────────────────────────────────┐  │
│  │           LAYER 4 — AI SYSTEM (silent)               │  │
│  │   3s debounce → paragraph detection → API call       │  │
│  └──────────────────────────────────────────────────────┘  │
│                                                             │
│  ┌───────────┐  ┌────────────────────────────────────────┐ │
│  │  LAYER 3  │  │     LAYER 1 — TRANSPARENT TEXTAREA     │ │
│  │   GUTTER  │  │  (handles all keyboard input & cursor) │ │
│  │  Numbers  │  ├────────────────────────────────────────┤ │
│  │  ▸ Fold   │  │   LAYER 2 — RICH RENDERING OVERLAY     │ │
│  │  buttons  │  │  (bold, italic, color, code blocks)    │ │
│  └───────────┘  └────────────────────────────────────────┘ │
│                                                             │
│  ┌──────────────────────────────────────────────────────┐  │
│  │           FOOTER STATS BAR (fades in/out)            │  │
│  │    Title · Saved · 4m · 812w · 23p · 187L · 4391C   │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

Layer 1 — The Transparent Textarea: A native HTML textarea, visually invisible, at the very top of the stack. Every keystroke lands here. Zero lag between your fingers and the screen.

Layer 2 — The Rich Rendering Overlay: A mirrored div behind the textarea, re-rendering your document in real time with bold, italic, colors, highlights, and code block rendering.

Layer 3 — The Gutter System: Line Numbers gutter (sequential, toggleable) and Code Fold gutter (▸/▾ buttons to collapse/expand any code block).

Layer 4 — The Silent AI Watcher: Every 3 seconds after you pause typing, the AI checks your current paragraph. If Auto-fix is enabled, it silently improves it. A tiny amber dot pulses → turns green → disappears.


Your Complete Keyboard Shortcut Reference

Shortcut Action Category
Ctrl + K Open / Close the Panel drawer Navigation
Ctrl + S Force-save to server immediately Save
Ctrl + Z Undo — up to 150 steps back History
Ctrl + Shift + Z Redo the undone action History
Ctrl + B Bold the selected text Formatting
Ctrl + I Italic the selected text Formatting
Ctrl + U Underline the selected text Formatting
Tab Request AI ghost-text autocomplete for current line AI
Tab (again) Accept ghost-text and insert it into document AI
Escape Dismiss ghost text / Close panel / End search mode General

The Panel — Your Mission Control Center

Press Ctrl+K anywhere. A panel glides in from the left with a spring animation. This is your hub for everything outside the writing canvas.

① AI Model Selector

Switch Gemini / Groq / ChatGPT live. Status dot shows ChatGPT bridge health: green (ready), yellow (bridge running but not logged in), grey (bridge offline).

② Quick Actions

Create new doc with today's date as title. Live search bar across all documents — 300ms debounce. Results show snippet + line number.

③ Recent Docs

Last 3 modified documents. Hover to reveal inline rename. Click to switch instantly, cursor position preserved.

④ Library

All documents with word counts. Rename, delete, upload .prash/.html/.txt files. Deduplicated titles auto-numbered.

⑤ AI Assistant

Grammar fix (full doc), Rewrite with instruction, Auto-fix toggle, Line Numbers toggle — all AI controls in one place.

⑥ Version History

Up to 100 snapshots per document. Triggered every 30s or on 5-word change. One-click restore — saves current state first.

⑦ Workspace Stats

Total words, total documents, total AI fixes applied — your complete writing lifetime in 3 numbers.

⑧ Export Suite

Preview (purple), .prash (gold), .html (green), .pdf (blue) — four export formats from the panel footer.


Formatting — Bold, Italic, Color & Highlight

Select any text — right-click for the context menu, or use keyboard shortcuts. Formatting is applied as invisible spans over the plain text, preserved through all export formats.

This sentence shows bold text right next to italic text and underlined text all together.

Color examples: Gold, Emerald, Sky Blue, Rose, Purple.

Highlights: Sunburst Mint Lavender Sky Rose.

And a strikethrough example for completeness.


The Footer Stats Bar — Your Live Writing Vitals

Move your mouse: the footer bar fades in. Stop for 2 seconds: it fades to 20% opacity. Every number updates on every single keystroke — no polling, no delay, pure live computation.

READ = words ÷ 200, rounded up. Code block content excluded.
W = prose word count only (code tags stripped).
P = paragraph count (blocks separated by 2+ newlines).
L = visual line count (entire code blocks = exactly 1 line).
C = character count excluding whitespace.


The Save System — 4 Layers of Protection

save timeline
T+0ms      You type: "The quick brown fox"
T+1ms      localStorage: draft saved instantly (browser storage)
T+700ms    Debounce timer fires — auto-save triggered
T+701ms    PATCH /api/documents/42 sent to server
T+850ms    Server: SQLite database updated
T+851ms    Server: data/backups/doc_42.json written (JSON backup)
T+852ms    Server: data/backups/markdown/My_Doc_42.md written
T+860ms    Footer: ✓ Saved (green check appears)
T+860ms    localStorage draft deleted (server save confirmed)

// Layer 1: localStorage (instant, every keystroke)
// Layer 2: 700ms debounce server auto-save
// Layer 3: Ctrl+S manual immediate save
// Layer 4: navigator.sendBeacon() on tab close (beforeunload)

// If DB is lost: server startup runs syncAndRestoreDiskBackups()
// Reads all JSON backups → re-inserts missing documents
// ZERO DATA LOSS — disk always mirrors the database

Version History — Time Travel for Your Writing

Snapshots are taken automatically when 30 seconds pass since the last snapshot OR the word count changes by 5+. Up to 100 snapshots per document. Before restoring any version, FlowWrite saves your current state first — so you can always go forward again. Full bidirectional time travel across sessions.


Search Across All Your Writing

search flow
User types: "consciousness"

Step 1: 300ms debounce fires
Step 2: GET /api/search?q=consciousness
Step 3: SQL LIKE query across title AND content of ALL documents
Step 4: Returns up to 10 results with:
        - documentTitle, matchIndex, lineNumber
        - matchCount (total occurrences in doc)
        - snippet (120 chars around the match)
        - relevance (1.0 title match, 0.7 content match)

Step 5: User clicks a result →
        Switch to that document
        Scroll to exact character position of match
        Highlight the matching text
        SearchNavHeader shows "1 of 14 matches"
        ← → arrows jump between all occurrences
        Escape closes the search navigation bar
Continuing to
Part 2 → AI Systems & All Workflows
Part 2 of 4

AI Systems, Models & Complete AI Workflows

Abstract neural network visualization — the AI mind of FlowWrite

Three AI Engines — Gemini, Groq, ChatGPT

Property ✦ Gemini ⚡ Groq 🤖 ChatGPT
Provider Google Groq Cloud OpenAI (Browser Automation)
Model gemini-2.5-flash llama-3.3-70b-versatile ChatGPT Web (latest)
Speed ~180 tok/s · Fast ~450 tok/s · Ultra-fast ~30 tok/s · Slow
Parallelism 4 chunks at once 4 chunks at once 1 chunk at a time (serial)
Fallback Chain 2.5 → 2.0 → 1.5-flash → 1.5-pro 3 retries, same model Requires main.py bridge
API Key GEMINI_API_KEY GROQ_API_KEY No key — uses browser session
Best For Default — reliable quality Speed-critical large docs No API key needed, free

The Smart Chunking System

FlowWrite's chunking pipeline splits long documents at paragraph boundaries, processes in parallel, then reassembles with perfect structural fidelity — zero blank-line changes, zero sentence splits.

chunking pipeline
Original document: 1,200 words · Max chunk size: 450 words

STEP 1: Split at paragraph boundaries (2+ newlines)
        Store exact separator strings for lossless reassembly

STEP 2: Group paragraphs into chunks ≤ 450 words each
        Never split mid-paragraph (would break sentence context)
        Result: 3 chunks of 440, 447, 313 words

STEP 3: Build overlap tails — last 30 words of each chunk
        Passed as context to the next chunk's AI prompt
        Prevents continuity breaks at chunk boundaries

STEP 4: Process in parallel (Gemini/Groq: 4 at a time)
        [Chunk 1 + Chunk 2] → sent simultaneously → ~800ms
        [Chunk 3] → sent after → ~400ms
        If a chunk fails: original text used as fallback

STEP 5: Reassemble with exact original separators
        chunk1_result + sep1 + chunk2_result + sep2 + chunk3_result
        Total time for 1,200 words: ~1.2 seconds

The AI Output Sanitizer — 5-Stage Cleaning

sanitizer stages
// RAW AI OUTPUT (before sanitizer):
"Here is the corrected version of your text:

The quick brown fox jumped over the lazy dog."

// STAGE 1: Strip ChatGPT <start>...<end> markers
// STAGE 2: Strip XML wrapper tags (<output>, <corrected_text>, etc.)
// STAGE 3: Strip markdown code fences (``` ... ```)
// STAGE 4: Strip conversational preambles
//          "Here is the corrected version:" → REMOVED
//          "Sure! Here's the improved text:" → REMOVED
//          "Certainly, here is the revised passage:" → REMOVED
// STAGE 5: Strip outer wrapping quotes ("..." or '...')

// CLEAN OUTPUT (after sanitizer):
The quick brown fox jumped over the lazy dog.

AI Workflow 1 — Auto-Fix on Pause (3 Seconds)

auto-fix logic
onContentChange() → debounce(3000ms) → runDeltaFix()

runDeltaFix():
  if (!autoCorrect) return                  // Auto-fix disabled
  if (normCurrent === normLast) return      // No meaningful change
  if (charDelta < 5) return                 // Change too tiny

  paragraph = getParagraphAtCursor()        // Only the current para
  result = await POST("/api/ai/grammar-fix", { text: paragraph })

  if (content !== contentAtCallStart) return  // User typed → discard

  fixed = content.slice(0, para.start)
        + result.corrected
        + content.slice(para.end)

  setContent(fixed)    // Silent update — cursor preserved

// EXAMPLE:
// You write: "She walkd into the room and it were quiet."
// 3 seconds pass...
// AI receives just that paragraph
// AI returns: "She walked into the room and it was quiet."
// Document silently updated. Amber dot → Green dot → Gone.

AI Workflow 2 — Tab Autocomplete (Ghost Text)

Press Tab at the end of any line. The AI receives your current line plus the last 800 characters of your document as context. It generates a 1–2 sentence natural continuation matching your exact tone, tense, and vocabulary.

The suggestion appears as dim grey text immediately after your cursor. Press Tab again to accept. Type any character to dismiss. Press Escape to clear.

autocomplete prompt
// AUTOCOMPLETE PROMPT (actual prompt used in FlowWrite)

Task: Write a natural 1-2 sentence continuation.

Background context (style reference):
[Last 600 characters of document for tone/topic context]

Rules:
1. Continue DIRECTLY from the last word — no gap
2. Match tone, tense, vocabulary, writing style seamlessly
3. Do NOT repeat any text from the current writing
4. Return ONLY the continuation text — no wrappers

Current writing:
"The algorithm processes each node in the tree by visiting
 its left subtree first,"

// AI returns:
" then the root node, and finally the right subtree —
  following the standard in-order traversal pattern."

AI Workflow 3 — Selection Fix / Rewrite / Format

Select any text → the Selection Action Bar appears at the bottom of the screen:

selection ai modes
MODE A — FIX
  Sends selection to grammar pipeline
  Rules: fix errors, preserve every word's meaning
  Before: "She don't know what happen. Everyone confuse."
  After:  "She doesn't know what happened. Everyone was confused."

MODE B — REWRITE  (prompts for instruction)
  Instruction examples that work:
  · "make it more concise"       → tightens sentences
  · "formal academic tone"       → elevates vocabulary
  · "simplify for a 12-year-old" → removes jargon
  · "more dramatic and emotional"→ heightens tension
  · "convert to bullet points"   → restructures as list

  Before: "The implementation of the aforementioned algorithmic
           solution necessitates comprehensive understanding..."
  Instruction: "make it simple and direct"
  After:  "To implement this algorithm, you need to understand
           how it works."

MODE C — FORMAT
  Structural cleanup ONLY — zero word changes
  Fixes: irregular spacing, inconsistent indentation,
         excessive blank lines, mis-aligned lists
  Temperature: 0.0 (completely deterministic)

AI Activity Badge — What the Colors Mean

AI Syncing (amber, pulsing)
→
AI Fixed (green, steady)
→
(disappears after 1.5s)

The badge is position: fixed, top-right, pointer-events: none — it literally cannot be clicked. It never blocks your writing flow.


Math & Technical Writing — AI Handles Everything

FlowWrite is built for technical documents. Code blocks are explicitly preserved by all AI prompts — your formulas, equations, and algorithms are never touched by grammar fix or rewrite operations.

mathematics
═══ FUNDAMENTAL THEOREM OF CALCULUS ════════════════════════

If F is the antiderivative of f on [a, b]:

  ∫[a to b] f(x) dx = F(b) - F(a)

Connects differentiation and integration as inverse operations.

═══ QUADRATIC FORMULA ══════════════════════════════════════

For ax² + bx + c = 0:

        -b ± √(b² - 4ac)
  x  =  ─────────────────
                2a

Discriminant:
  b² - 4ac > 0  →  Two distinct real roots
  b² - 4ac = 0  →  One repeated real root
  b² - 4ac < 0  →  Two complex conjugate roots

═══ EULER'S IDENTITY ═══════════════════════════════════════

  e^(iπ) + 1 = 0

Five fundamental constants in one equation:
  e = Euler's number ≈ 2.71828...
  i = imaginary unit (√-1)
  π = pi ≈ 3.14159...
statistics
═══ NORMAL DISTRIBUTION (Gaussian) ═════════════════════════

Probability density function:

         1              (x - μ)²
f(x) = ─────── · exp(- ─────────)
       σ√(2π)            2σ²

68-95-99.7 Rule:
  ±1σ covers 68.27% of all values
  ±2σ covers 95.45% of all values
  ±3σ covers 99.73% of all values

═══ BAYES' THEOREM ════════════════════════════════════════

        P(B|A) × P(A)
P(A|B) = ─────────────────
               P(B)

Real example: A medical test with 99% accuracy for a disease
with 1% prevalence. If you test positive → P(disease) ≈ 50%.
This is why Bayes matters in medicine — the prior matters.

═══ BIG-O NOTATION ════════════════════════════════════════

O(1)      Constant     Array index access
O(log n)  Logarithmic  Binary search
O(n)      Linear       Linear scan, array sum
O(n log n) Linearithmic Merge sort, heap sort
O(n²)     Quadratic    Bubble sort, naive nested loops
O(2ⁿ)     Exponential  Recursive Fibonacci (naive)
O(n!)     Factorial    Brute-force travelling salesman
linear algebra
═══ MATRIX MULTIPLICATION (2×2) ════════════════════════════

  [a  b]   [e  f]   [ae+bg  af+bh]
  [c  d] × [g  h] = [ce+dg  cf+dh]

Determinant:  |a  b|  =  ad - bc
              |c  d|

Inverse (2×2):
       1    [ d  -b]
  A⁻¹ = ─── [-c   a]    (only if det ≠ 0)
           ad-bc

═══ EIGENVALUES ════════════════════════════════════════════

  A·v = λ·v  where v ≠ 0

Find λ: det(A - λI) = 0

Example: A = [3  1]
             [0  2]

det([3-λ  1 ]) = (3-λ)(2-λ) = 0
    [0   2-λ])

Eigenvalues: λ = 3 or λ = 2

═══ DOT AND CROSS PRODUCT ══════════════════════════════════

Dot: u·v = |u||v|cos(θ) = a₁b₁ + a₂b₂ + a₃b₃
Cross: u × v = [u_y·v_z - u_z·v_y,
                u_z·v_x - u_x·v_z,
                u_x·v_y - u_y·v_x]
Continuing to
Part 3 → Code Blocks, HTML, Tables, Images & Rich Content
Part 3 of 4

Code Blocks, HTML, Tables, Images & Rich Content

Developer screen showing beautiful code and design

The Code Block — How FlowWrite Renders It

Wrap anything in <code>...</code> tags. The FlowWrite renderer inspects the content and decides how to display it:

· Content is HTML (tables, divs, images) → renders as live HTML
· Content is multi-line plain code → styled code block with language label + copy button
· Content is single-line → inline code element

typescript
interface Document {
  id: number;
  title: string;
  content: string;
  wordCount: number;
  createdAt: string;
  updatedAt: string;
}

async function fetchDocument(id: number): Promise<Document> {
  const response = await fetch(`/api/documents/${id}`);
  if (!response.ok) {
    throw new Error(`Failed: ${response.statusText}`);
  }
  return response.json();
}

const doc = await fetchDocument(42);
console.log(`Loaded: ${doc.title} (${doc.wordCount} words)`);
python
def chunk_text(text: str, max_words: int = 450) -> list[str]:
    """Split text at paragraph boundaries into chunks."""
    paragraphs = text.split('\n\n')
    chunks = []
    current_chunk = []
    current_word_count = 0

    for paragraph in paragraphs:
        words = len(paragraph.split())
        if current_word_count + words > max_words and current_chunk:
            chunks.append('\n\n'.join(current_chunk))
            current_chunk = [paragraph]
            current_word_count = words
        else:
            current_chunk.append(paragraph)
            current_word_count += words

    if current_chunk:
        chunks.append('\n\n'.join(current_chunk))
    return chunks
sql
-- Get all documents with version count and last snapshot time
SELECT
    d.id,
    d.title,
    d.word_count,
    d.updated_at,
    COUNT(v.id) AS version_count,
    MAX(v.created_at) AS last_snapshot_at
FROM documents d
LEFT JOIN document_versions v ON v.document_id = d.id
GROUP BY d.id, d.title, d.word_count, d.updated_at
ORDER BY d.updated_at DESC
LIMIT 20;
css
:root {
  --bg: #080808;
  --surface: #111111;
  --accent: #d4a853;
  --text: #e6e6e6;
}

.editor-canvas {
  font-family: 'EB Garamond', Georgia, serif;
  font-size: 24px;
  line-height: 1.625;
  color: var(--text);
  background: transparent;
  border: none;
  outline: none;
  caret-color: var(--accent);
}

.fw-code-block {
  font-family: 'JetBrains Mono', monospace;
  background: var(--surface);
  border-radius: 12px;
  overflow: hidden;
}

HTML Tables — Live Rendering in the Editor

Feature FlowWrite Google Docs Notion
AI Grammar Fix (Auto, 3s pause) ✓ – –
Ghost Text Autocomplete ✓ – –
Code Block Fold/Expand ✓ – ~
3-Format Export (.prash/.html/.pdf) ✓ ~ ~
100-Version History per Document ✓ ✓ –
4-Layer Save System ✓ ~ ~
Live HTML Rendering in Document ✓ – –
Disk Backup with Auto-Restore ✓ – –

Images — Inline with Full Styling Support

A creative team working around laptops — collaboration and writing
An open book with warm light
The written word endures
A beautiful notebook
Writing is the clearest form of thinking.
Before an idea can be shared, it must be made clear in the mind of its creator. The act of writing forces clarity — it reveals gaps in logic and moments of beauty that would otherwise remain unformed.

Image Grids — Responsive Visual Layouts

Mountain landscape
Mountain
Ocean shore
Ocean
Forest path
Forest

Styled Cards, Quotes & Process Lists

"Writing is the only art form where the material is the meaning. A sculptor uses stone to express something beyond stone. A writer uses words to express something made entirely of words."

— Anonymous

1
Open FlowWrite
Dark canvas. Cursor blinks. If a localStorage draft exists → auto-restored. Or: New Document → today's date becomes the title.
2
Write freely
No toolbar noise. Just your ideas. LocalStorage saves every keystroke. Server auto-saves every 700ms.
3
AI refines silently
3 seconds after each pause, Auto-fix checks the current paragraph. Amber dot → Green dot. Done.
4
Add rich content
Right-click → Insert → Table / Image / Grid. Or write <code> tags directly. Everything renders live.
5
Export beautifully
Panel → .pdf → new tab opens → auto-print dialog → Save as PDF. Or .prash / .html for archives and sharing.
Continuing to
Part 4 → Export System, Import, Full Workflows & Design
Part 4 of 4

Export System, Import, Full Workflows & Design

A beautifully printed document on a clean desk — the final output of FlowWrite

Three Export Formats — One Engine

✦
.prash
FlowWrite native format. Full HTML with embedded JSON data inside a script tag. Perfect round-trip import — zero data loss.
text/html · embedded JSON
⬡
.html
Standard HTML file. Opens in any browser — Chrome, Firefox, Safari, Edge. Share with anyone, host on any server.
text/html · universal
⬜
.pdf
Opens in new tab with A4 page settings. Browser's native PDF engine. Dark theme preserved exactly.
A4 · @page CSS · auto-print

Inside a .prash File — What It Contains

A .prash file is a complete standalone HTML document that renders beautifully in any browser. Inside is embedded JSON that allows FlowWrite to reimport with perfect fidelity:

.prash file anatomy
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="format" content="prash/1.0">
  <title>My Document – FlowWrite</title>
  <!-- Google Fonts: EB Garamond + Inter + JetBrains Mono -->
  <style>
    /* Full dark luxury CSS: 200+ lines */
    /* Variables, layout, typography, tables, code blocks */
  </style>

  <!-- ★ THE KEY: Embedded JSON for perfect re-import ★ -->
  <script type="application/json" id="prash-data">
  {
    "flowwrite": true,
    "version": "1.0.0",
    "metadata": {
      "title": "My Document",
      "wordCount": 3421,
      "exportedAt": "2024-01-15T14:32:00Z",
      "format": "prash/1.0"
    },
    "content": "Full raw document text here...",
    "formattingMap": [
      { "start": 0, "end": 18, "bold": true, "color": "#fbbf24" },
      { "start": 120, "end": 180, "italic": true }
    ]
  }
  </script>
</head>
<body>
  <header> sticky header: brand + stats + export date </header>
  <main>
    <h1 class="doc-title">My Document</h1>
    <div class="doc-body">
      <!-- Plain text → div.line elements -->
      <!-- Code blocks → div.fw-code-block -->
      <!-- HTML blocks → div.fw-html-block -->
      <!-- Tables → div.fw-table-container -->
    </div>
  </main>
  <footer> title · FlowWrite badge </footer>
  <script> fwCopyCode() function </script>
</body>
</html>

PDF Export — The Complete Pipeline

pdf export pipeline
function exportAsPdf(title, content, formattingMap, foldStorage) {

  // Step 1: Expand all collapsed code blocks
  const expanded = expandFoldPlaceholders(content, foldStorage);

  // Step 2: Generate exact same HTML as .html export
  let html = generateDocumentHtml(title, expanded, formattingMap);

  // Step 3: Inject A4 print CSS before </style>
  const printCss = `
    @page { size: A4; margin: 18mm 22mm }
    * { print-color-adjust: exact !important }
    @media print {
      body { background: var(--bg) !important }  /* Keep dark! */
      .doc-body .line { page-break-inside: avoid }
      .fw-code-block { page-break-inside: avoid }
      thead { display: table-header-group }       /* Repeat on pages */
      img, figure { page-break-inside: avoid }
    }
  `;
  html = html.replace('</style>', printCss + '\n</style>');

  // Step 4: Inject PDF bar (screen-only) before </body>
  // [✦ FlowWrite — PDF Preview] [? How to save] [⬇ Download] [⌘ Print]

  // Step 5: Build Blob + open in new tab
  const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
  const win = window.open(URL.createObjecturl(blob), '_blank');

  // Step 6: Auto-trigger window.print() after fonts load
  // document.fonts.ready.then(() => setTimeout(window.print, 700))

  // Step 7: If popup blocked → direct .html file download fallback
  if (!win || win.closed) { /* trigger <a> download instead */ }
}

Import System — Round-Trip Fidelity

import parser
function parseUploadedFile(rawText, filename) {
  const fallbackTitle = filename.replace(/\.(prash|txt|html)$/i, '');

  // Step 1: Find embedded JSON in .prash / .html
  const match = rawText.match(
    /<script[^>]+id="prash-data"[^>]*>([\s\S]*?)<\/script>/i
  );

  if (match) {
    const data = JSON.parse(match[1].trim());
    if (data?.flowwrite && data.content !== undefined) {
      return {
        title:         data.metadata?.title || fallbackTitle,
        content:       data.content,      // ← full raw document text
        formattingMap: data.formattingMap  // ← all formatting spans
      };
      // ROUND-TRIP FIDELITY: content + formattingMap preserved
      // Export → Import = byte-for-byte identical to original
    }
  }

  // Step 2: Legacy raw JSON format
  // Step 3: Plain text fallback (no formattingMap)
  return { title: fallbackTitle, content: rawText, formattingMap: [] };
}

Complete API Reference — Every Endpoint

Method Endpoint Description
GET /documents List all docs, sorted by updatedAt desc
POST /documents Create new doc — auto-deduplicates title
GET /documents/stats Workspace totals: docs, words, chars, AI fixes
GET /documents/recent Last 5 modified documents
GET /documents/:id Get single document by ID
PATCH /documents/:id Update content/title + version snapshot + disk backup
DELETE /documents/:id Delete document + remove disk backup files
GET /documents/:id/versions List up to 100 snapshots for this document
POST /documents/:id/versions/:v/restore Restore version — saves current state first
GET /search?q=query Full-text search, up to 10 results with snippets
GET /ai/mode Current AI model + ChatGPT bridge status
POST /ai/mode Switch model: { model: "gemini"|"groq"|"chatgpt" }
POST /ai/grammar-fix Grammar fix — chunked, parallel for long docs
POST /ai/fix-selection Fix / rewrite / format a specific text selection
POST /ai/autocomplete Ghost-text continuation for current line
POST /ai/rewrite Full document rewrite with custom instruction

The Design System — Full Specification

design system
/* ── COLOR PALETTE ─────────────────────────────────── */
--bg:         #080808   /* near-black, not pure black */
--surface:    #111111   /* panels, code block backgrounds */
--surface-2:  #161616   /* table headers, code headers */
--border:     #1e1e1e   /* primary — very subtle */
--border-2:   #2c2c2c   /* secondary — slightly visible */
--text:       #e6e6e6   /* warm off-white (not harsh white) */
--text-muted: #888888   /* secondary text */
--accent:     #d4a853   /* gold — the FlowWrite signature */
--green:      #4ade80   /* success, saved, AI fixed */

/* ── TYPOGRAPHY ────────────────────────────────────── */
Body font:    EB Garamond, 24px, line-height 1.625 (editor)
              EB Garamond, 22px, line-height 1.9   (export)
Title font:   EB Garamond, 2.8rem, weight 500
UI font:      Inter, 10-14px, weight 400/500/600/700
Mono font:    JetBrains Mono — code, stats, labels

/* ── LAYOUT ────────────────────────────────────────── */
Editor content:  max-width 760px, centered
Export content:  max-width 820px, padding 72px 40px
Panel:           width 340px, slides from left
Line length:     ~65-70 chars (optimal for reading)

/* ── ANIMATIONS ────────────────────────────────────── */
Panel slide-in:     Spring, damping 28, stiffness 240
Selection bar:      Spring, damping 24, stiffness 300
AI badge pulse:     keyframes, 1.4s ease-in-out infinite
Footer fade:        opacity 1.0 ↔ 0.2 based on mouse idle
Transition speed:   400ms ease (most UI transitions)

Everything in One View — The Master Overview

✦ Editor
Transparent textarea + rich overlay
EB Garamond 24px serif canvas
Custom undo/redo (150 steps)
Scroll lock (cursor stays top 70%)
Auto-resize to content height
Line numbers gutter (toggleable)
Code fold gutter (▸/▾ per block)
Ghost text autocomplete overlay
Ambient gold radial glow
⚡ AI System
3 engines: Gemini / Groq / ChatGPT
Gemini fallback (4 models × 3 retries)
Smart chunking (450 words, para-aligned)
Parallel processing (4 concurrent)
5-stage output sanitizer
Auto-fix on pause (3s, paragraph-level)
Manual grammar fix (full document)
Tab ghost-text autocomplete
Selection fix / rewrite / format
Full doc rewrite (custom instruction)
💾 Save System
Layer 1: localStorage instant draft
Layer 2: 700ms debounce server save
Layer 3: Ctrl+S manual force save
Layer 4: beforeunload beacon save
Draft recovery on reload
JSON disk backup on every save
Markdown disk backup on every save
Startup auto-restore from disk
📦 Export & Import
.prash (HTML + embedded JSON)
.html (standard browser file)
.pdf (A4, dark theme, auto-print)
Import .prash (round-trip fidelity)
Import .html (full fidelity)
Import .txt (plain text)
PDF bar: Print / Download / Guide
Full-screen preview modal
📄 Rich Content
Code blocks (auto-language detection)
Copy button on every code block
Fold/expand (▸/▾ per block)
Live HTML rendering in <code> tags
Tables (styled, responsive)
Images (inline, captioned, grids)
CSS grid layouts
Cards, quotes, callout panels
Inline code (monospace)
🗂 Management
Unlimited documents
Auto-dated default titles
Case-insensitive title deduplication
Inline rename in panel
100-version history per document
One-click version restore
Full-text search (all documents)
Search nav bar (prev/next arrows)
Workspace stats (lifetime totals)

Final Showcase — A Complete Sample Document

✦ FLOWWRITE
2,847 words September 4, 2026
The Architecture of Intelligence
September 4, 2026 ——————————————

Intelligence is not a single thing. It is a collection of capabilities that work together so seamlessly, so invisibly, that we perceive them as one.

The same is true of FlowWrite. What feels like a simple writing tool is, underneath, a layered system: a rendering engine, an AI pipeline, a save architecture, an export framework — each component doing its part, each invisible until you need it.

That is the highest form of design: power that disappears into simplicity.

A vast mountain range at golden hour — the scale of FlowWrite's ambition
✦
FlowWrite
The Intelligent Writing Studio · Built by Prashant Pandey