AI inline rewrite
Editable draft card with selection and paragraph triggers, inline AI instruction input, streaming del/ins diffs and retry variations.
pnpm dlx shadcn@latest add @haze/ai-inline-rewrite---
import { ArrowUp, Pencil } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Props {
id?: string;
title?: string;
badge?: string;
paragraphs?: string[];
class?: string;
}
const {
id = "haze-ai-inline-rewrite",
title = "Billing launch update",
badge = "Draft",
paragraphs = [
"We are ready to roll out the updated billing view next Tuesday. To keep the launch calm and predictable, workspace owners will get access in small waves first.",
"Due to the fact that metered compute charges are now tallied every hour, some finance teams might notice their mid-cycle totals look different then before.",
"Legacy payment webhooks stay active through quarter end while teams move to signed v3 payloads. Ping #billing if anything looks off.",
],
class: className,
} = Astro.props;
const presets = ["Shorter", "Clearer", "Friendlier", "Fix grammar"];
---
<section
aria-labelledby={`${id}-title`}
data-haze-ai-inline-rewrite
data-instance-id={id}
data-initial-paragraphs={JSON.stringify(paragraphs)}
class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
<div class="mx-auto max-w-md overflow-hidden rounded-2xl border border-border bg-card shadow-key">
<header class="flex items-center justify-between gap-3 border-b border-border px-5 py-3.5">
<div class="flex min-w-0 items-center gap-2">
<Pencil class="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
<h2 id={`${id}-title`} class="truncate text-sm/5 font-medium tracking-tight text-foreground">
{title}
</h2>
</div>
<span data-doc-badge class="shrink-0 text-xs/4 text-muted-foreground">
{badge}
</span>
</header>
<div data-doc-body class="space-y-4 p-5 text-[0.9375rem]/7 text-foreground">
{
paragraphs.map((text, idx) => (
<div data-para-wrap={idx} class="relative">
<button
type="button"
data-para-focus={idx}
class="sr-only rounded-md bg-muted px-2 py-1 text-xs font-medium text-foreground focus:not-sr-only focus:mb-1 focus:inline-block focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
Edit passage {idx + 1} with AI
</button>
<p
data-para-text={idx}
class="cursor-text break-words text-pretty select-text"
>
{idx === 1 ? (
<span class="box-decoration-clone rounded-xs bg-accent px-0.5 text-foreground">{text}</span>
) : (
text
)}
</p>
<div data-para-popover-slot={idx} class="mt-2.5" hidden={idx !== 1}>
{idx === 1 && (
<div
data-inline-popover
class="rounded-2xl border border-border bg-popover p-2.5 shadow-float"
>
<form data-popover-form class="flex items-center gap-2 border-b border-border pb-2.5">
<label for={`${id}-prompt`} class="sr-only">Ask AI to edit selected passage</label>
<input
id={`${id}-prompt`}
data-popover-input
type="text"
placeholder="Ask AI to edit..."
class="-m-px border border-frame-input min-w-0 flex-1 rounded-md bg-transparent px-1.5 py-1 text-sm text-popover-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
/>
<button
type="submit"
aria-label="Submit AI edit instruction"
class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-muted text-foreground transition-colors duration-150 ease-snappy hover:bg-primary hover:text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
>
<ArrowUp class="size-3.5" aria-hidden="true" />
</button>
</form>
<div class="flex flex-wrap items-center gap-1.5 pt-2.5">
{presets.map((preset) => (
<button
type="button"
data-preset={preset}
class="inline-flex h-7 cursor-pointer items-center rounded-full border border-frame bg-field px-2.5 text-xs font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
>
{preset}
</button>
))}
</div>
</div>
)}
</div>
</div>
))
}
</div>
<footer class="border-t border-border px-5 py-3 text-xs/4 text-muted-foreground">
Select any text to edit it with AI
</footer>
<p data-rewrite-status role="status" class="sr-only"></p>
</div>
<template data-rewrite-icons>
<span data-ic-up><ArrowUp class="size-3.5" aria-hidden="true" /></span>
</template>
</section>
<script>
interface DiffToken {
kind: "same" | "del" | "ins";
word: string;
}
function diffWords(oldText: string, newText: string): DiffToken[] {
const a = oldText.trim().split(/\s+/).filter(Boolean);
const b = newText.trim().split(/\s+/).filter(Boolean);
const m = a.length;
const n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => Array<number>(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (a[i] === b[j]) {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
}
const out: DiffToken[] = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (a[i] === b[j]) {
out.push({ kind: "same", word: a[i] });
i++;
j++;
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
out.push({ kind: "del", word: a[i] });
i++;
} else {
out.push({ kind: "ins", word: b[j] });
j++;
}
}
while (i < m) {
out.push({ kind: "del", word: a[i] });
i++;
}
while (j < n) {
out.push({ kind: "ins", word: b[j] });
j++;
}
return out;
}
function initAiInlineRewrite() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-inline-rewrite]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const instanceId = root.dataset.instanceId ?? "haze-ai-inline-rewrite";
const raw = root.dataset.initialParagraphs;
const badgeEl = root.querySelector<HTMLElement>("[data-doc-badge]");
const statusEl = root.querySelector<HTMLElement>("[data-rewrite-status]");
const iconTpl = root.querySelector<HTMLTemplateElement>("[data-rewrite-icons]");
if (!raw) return;
let paragraphs: string[] = [];
try {
paragraphs = JSON.parse(raw) as string[];
} catch {
return;
}
const presets = ["Shorter", "Clearer", "Friendlier", "Fix grammar"];
const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
let activeIndex = Math.min(1, Math.max(0, paragraphs.length - 1));
let activeInstruction = "";
let variationIdx = 0;
let candidateText = "";
let streamTimer: number | undefined;
const cloneUpIcon = (): Node | null => {
const el = iconTpl?.content.querySelector("[data-ic-up]")?.firstElementChild;
return el ? el.cloneNode(true) : null;
};
const clearStream = () => {
if (streamTimer !== undefined) {
window.clearInterval(streamTimer);
streamTimer = undefined;
}
};
const getVariations = (paraIdx: number, instruction: string, currentText: string): string[] => {
const lower = instruction.toLowerCase();
const safeIdx = paraIdx % 3;
const banks: Record<string, string[][]> = {
shorter: [
[
"The updated billing view launches Tuesday, rolling out in small waves to workspace owners.",
"New billing goes live Tuesday for a first wave of workspace owners.",
],
[
"Compute charges now update hourly, so mid-cycle totals may look different.",
"Hourly compute tallying means mid-cycle totals can differ from earlier estimates.",
],
[
"Legacy webhooks stay live through quarter end while teams move to signed v3. Ping #billing with questions.",
"Existing payment webhooks work through quarter close as teams adopt v3. Reach out in #billing.",
],
],
clearer: [
[
"We are shipping the new billing dashboard next Tuesday and enabling it in staged waves for workspace owners.",
"Starting Tuesday, workspace owners will receive the new billing dashboard in gradual rollout waves.",
],
[
"Because metered compute charges now update every hour, finance teams may see different mid-cycle totals than before.",
"Metered compute is now tallied hourly, so mid-cycle totals reflect live usage rather than end-of-month estimates.",
],
[
"Legacy payment webhooks remain supported until quarter end while teams migrate to signed v3 payloads. Post in #billing if you spot issues.",
"Current webhooks continue working through quarter end during the signed v3 migration. Message #billing with any issues.",
],
],
friendlier: [
[
"We are happy to share that the refreshed billing view ships Tuesday! We will enable it in small waves so every rollout feels smooth.",
"Good news — the updated billing view arrives Tuesday, starting with a few workspaces so we can support everyone closely.",
],
[
"Since compute charges now refresh hourly, finance teams may spot slightly different mid-cycle totals — everything is tallied accurately in real time.",
"Heads up for finance teams: hourly compute updates mean mid-cycle numbers can look a bit different than before.",
],
[
"No rush on migrations — legacy payment webhooks stay live all quarter while you switch to signed v3. Drop a note in #billing anytime.",
"Legacy payment webhooks will keep running through quarter end as you move to v3, and we are always happy to help in #billing.",
],
],
grammar: [
[
"We are ready to roll out the updated billing view next Tuesday. To keep the launch calm and predictable, workspace owners will receive access in small waves first.",
"We are ready to launch the updated billing view next Tuesday, giving workspace owners access in small waves first.",
],
[
"Because metered compute charges are now tallied every hour, some finance teams might notice that their mid-cycle totals look different than before.",
"Since metered compute charges are now tallied hourly, some finance teams may notice that mid-cycle totals look different than before.",
],
[
"Legacy payment webhooks will stay active through quarter end while teams migrate to signed v3 payloads. Reach out in #billing if anything looks off.",
"Legacy payment webhooks remain active through the end of the quarter while teams move to signed v3 payloads. Ping #billing if anything looks off.",
],
],
};
if (lower.includes("short") || lower.includes("brief") || lower.includes("concise")) return banks.shorter[safeIdx];
if (lower.includes("friend") || lower.includes("warm") || lower.includes("casual")) return banks.friendlier[safeIdx];
if (lower.includes("grammar") || lower.includes("fix") || lower.includes("typo")) return banks.grammar[safeIdx];
if (lower.includes("clear") || lower.includes("direct") || lower.includes("plain")) return banks.clearer[safeIdx];
const trimmed = instruction.trim();
if (!trimmed) return banks.shorter[safeIdx];
return [
banks.clearer[safeIdx][0],
banks.shorter[safeIdx][0],
`${currentText.replace(/\.$/, "")} (${trimmed}).`,
];
};
const renderParagraphText = (idx: number, highlighted: boolean) => {
const pEl = root.querySelector<HTMLElement>(`[data-para-text="${idx}"]`);
if (!pEl) return;
if (highlighted) {
const mark = document.createElement("span");
mark.className = "box-decoration-clone rounded-xs bg-accent px-0.5 text-foreground";
mark.textContent = paragraphs[idx];
pEl.replaceChildren(mark);
} else {
pEl.textContent = paragraphs[idx];
}
};
const hideAllPopovers = () => {
paragraphs.forEach((_, idx) => {
const slot = root.querySelector<HTMLElement>(`[data-para-popover-slot="${idx}"]`);
if (slot) {
slot.hidden = true;
slot.replaceChildren();
}
renderParagraphText(idx, false);
});
};
const showPromptPopover = (paraIdx: number, focusInput = false) => {
clearStream();
hideAllPopovers();
activeIndex = paraIdx;
variationIdx = 0;
candidateText = "";
renderParagraphText(paraIdx, true);
const slot = root.querySelector<HTMLElement>(`[data-para-popover-slot="${paraIdx}"]`);
if (!slot) return;
const popover = document.createElement("div");
popover.setAttribute("data-inline-popover", "");
popover.className = "rounded-2xl border border-border bg-popover p-2.5 shadow-float";
const form = document.createElement("form");
form.className = "flex items-center gap-2 border-b border-border pb-2.5";
const inputId = `${instanceId}-prompt-${paraIdx}`;
const label = document.createElement("label");
label.htmlFor = inputId;
label.className = "sr-only";
label.textContent = "Ask AI to edit selected passage";
const input = document.createElement("input");
input.id = inputId;
input.type = "text";
input.placeholder = "Ask AI to edit...";
input.className =
"-m-px border border-frame-input min-w-0 flex-1 rounded-md bg-transparent px-1.5 py-1 text-sm text-popover-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden";
const submitBtn = document.createElement("button");
submitBtn.type = "submit";
submitBtn.setAttribute("aria-label", "Submit AI edit instruction");
submitBtn.className =
"inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-muted text-foreground transition-colors duration-150 ease-snappy hover:bg-primary hover:text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95";
const upIc = cloneUpIcon();
if (upIc) submitBtn.append(upIc);
form.addEventListener("submit", (ev) => {
ev.preventDefault();
const prompt = input.value.trim() || "Shorter";
variationIdx = 0;
runRewrite(paraIdx, prompt);
});
form.append(label, input, submitBtn);
const presetRow = document.createElement("div");
presetRow.className = "flex flex-wrap items-center gap-1.5 pt-2.5";
presets.forEach((preset) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className =
"inline-flex h-7 cursor-pointer items-center rounded-full border border-frame bg-field px-2.5 text-xs font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95";
btn.textContent = preset;
btn.addEventListener("click", () => {
variationIdx = 0;
runRewrite(paraIdx, preset);
});
presetRow.append(btn);
});
popover.append(form, presetRow);
slot.replaceChildren(popover);
slot.hidden = false;
if (focusInput) {
window.requestAnimationFrame(() => input.focus());
}
};
const renderDiffPopover = (paraIdx: number, variationsCount: number) => {
const slot = root.querySelector<HTMLElement>(`[data-para-popover-slot="${paraIdx}"]`);
if (!slot) return;
const popover = document.createElement("div");
popover.className =
"flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-border bg-popover px-3 py-2 shadow-float";
const label = document.createElement("span");
label.className = "text-xs text-muted-foreground";
label.textContent = activeInstruction;
const actions = document.createElement("div");
actions.className = "flex flex-wrap items-center gap-1.5";
const acceptBtn = document.createElement("button");
acceptBtn.type = "button";
acceptBtn.className =
"inline-flex h-7 cursor-pointer items-center rounded-full bg-primary px-3 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 active:scale-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
acceptBtn.textContent = "Accept";
acceptBtn.addEventListener("click", () => {
paragraphs[paraIdx] = candidateText;
if (badgeEl) badgeEl.textContent = "Edited";
showPromptPopover(paraIdx, false);
if (statusEl) statusEl.textContent = `Accepted edit for passage ${paraIdx + 1}.`;
});
const retryBtn = document.createElement("button");
retryBtn.type = "button";
retryBtn.className =
"inline-flex h-7 cursor-pointer items-center rounded-full border border-frame bg-field px-2.5 text-xs font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
retryBtn.textContent = "Try again";
retryBtn.addEventListener("click", () => {
variationIdx = (variationIdx + 1) % variationsCount;
runRewrite(paraIdx, activeInstruction);
});
const discardBtn = document.createElement("button");
discardBtn.type = "button";
discardBtn.className =
"inline-flex h-7 cursor-pointer items-center rounded-full border border-frame bg-field px-2.5 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
discardBtn.textContent = "Discard";
discardBtn.addEventListener("click", () => {
showPromptPopover(paraIdx, false);
if (statusEl) statusEl.textContent = `Discarded edit for passage ${paraIdx + 1}.`;
});
actions.append(acceptBtn, retryBtn, discardBtn);
popover.append(label, actions);
slot.replaceChildren(popover);
slot.hidden = false;
};
const runRewrite = (paraIdx: number, instruction: string) => {
clearStream();
const pEl = root.querySelector<HTMLElement>(`[data-para-text="${paraIdx}"]`);
if (!pEl) return;
activeInstruction = instruction.trim() || "Shorter";
const original = paragraphs[paraIdx];
const variations = getVariations(paraIdx, activeInstruction, original);
candidateText = variations[variationIdx % variations.length];
const tokens = diffWords(original, candidateText);
if (statusEl) statusEl.textContent = `Streaming ${activeInstruction} rewrite for passage ${paraIdx + 1}.`;
const paintCount = (count: number) => {
const frag = document.createDocumentFragment();
for (let i = 0; i < count; i++) {
const tk = tokens[i];
if (i > 0) frag.append(document.createTextNode(" "));
if (tk.kind === "same") {
frag.append(document.createTextNode(tk.word));
} else if (tk.kind === "del") {
const del = document.createElement("del");
del.className = "rounded-xs bg-destructive/14 px-0.5 text-destructive line-through";
del.textContent = tk.word;
frag.append(del);
} else {
const ins = document.createElement("ins");
ins.className = "rounded-xs bg-success/14 px-0.5 text-success no-underline";
ins.textContent = tk.word;
frag.append(ins);
}
}
pEl.replaceChildren(frag);
};
renderDiffPopover(paraIdx, variations.length);
if (reducedMotion) {
paintCount(tokens.length);
if (statusEl) statusEl.textContent = "Diff ready. Choose Accept, Try again, or Discard.";
return;
}
let shown = 0;
streamTimer = window.setInterval(() => {
shown = Math.min(tokens.length, shown + 3);
paintCount(shown);
if (shown >= tokens.length) {
clearStream();
if (statusEl) statusEl.textContent = "Diff ready. Choose Accept, Try again, or Discard.";
}
}, 40);
};
root.querySelectorAll<HTMLElement>("[data-para-text]").forEach((paraEl) => {
const idx = Number(paraEl.dataset.paraText ?? "0");
paraEl.addEventListener("click", () => {
if (activeIndex !== idx) {
showPromptPopover(idx, false);
if (statusEl) statusEl.textContent = `Selected passage ${idx + 1} for AI edit.`;
}
});
paraEl.addEventListener("mouseup", () => {
const sel = window.getSelection();
if (!sel || sel.isCollapsed) return;
if (sel.toString().trim().length >= 3 && activeIndex !== idx) {
showPromptPopover(idx, false);
if (statusEl) statusEl.textContent = `Selected passage ${idx + 1} for AI edit.`;
}
});
});
root.querySelectorAll<HTMLButtonElement>("[data-para-focus]").forEach((btn) => {
btn.addEventListener("click", () => {
const idx = Number(btn.dataset.paraFocus ?? "0");
showPromptPopover(idx, true);
if (statusEl) statusEl.textContent = `Opened AI edit controls for passage ${idx + 1}.`;
});
});
showPromptPopover(activeIndex, false);
});
}
initAiInlineRewrite();
document.addEventListener("astro:page-load", initAiInlineRewrite);
</script>When to use
- Reviewing and refining draft prose inside a document without leaving the paragraph context
- Offering both text-selection and button-triggered AI rewrites with streaming del and ins previews
When not to use
- Reviewing large side-by-side code patches across multiple files; use ai-diff-review instead
- Offering single-line ghost text completion while typing; use ai-autocomplete
Installation
Add the Haze registry to components.json once, then install AI inline rewrite with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-inline-rewritenpx shadcn@latest add @haze/ai-inline-rewriteyarn dlx shadcn@latest add @haze/ai-inline-rewritebunx --bun shadcn@latest add @haze/ai-inline-rewriteFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | "haze-ai-inline-rewrite" | Unique prefix for headings and inline prompt inputs. |
| title | string | "Billing launch update" | Document title shown in the card header. |
| badge | string | "Draft" | Initial status badge shown next to the document title. |
| paragraphs | string[] | 3 demo paragraphs | Editable prose passages shown inside the draft. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across Rewrite paragraph buttons, preset prompt chips, custom instruction input and diff actions
- EnterSpace
- Open the inline prompt bar, apply a preset rewrite, or accept, retry or discard the diff
Accessibility
- Every paragraph exposes an explicit Rewrite paragraph button so keyboard and touch users never rely solely on pointer selection.
- Inline diffs use semantic del and ins elements and announce streaming, accept, discard and retry states in a polite role="status" region.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI block "AI inline rewrite" with `npx shadcn@latest add @haze/ai-inline-rewrite`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiInlineRewrite from "@/components/haze/blocks/ai-inline-rewrite.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/blocks/ai-inline-rewrite.md
Customize with real content
Adapt the Haze ai-inline-rewrite block for our product. Replace the demo values of these props with our real content: id, title, badge, paragraphs, class. Keep the layout, the heading level rules and these accessibility details: Every paragraph exposes an explicit Rewrite paragraph button so keyboard and touch users never rely solely on pointer selection. Inline diffs use semantic del and ins elements and announce streaming, accept, discard and retry states in a polite role="status" region. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-inline-rewrite, check it fits: use it when reviewing and refining draft prose inside a document without leaving the paragraph context; offering both text-selection and button-triggered ai rewrites with streaming del and ins previews. Avoid it when reviewing large side-by-side code patches across multiple files; use ai-diff-review instead; offering single-line ghost text completion while typing; use ai-autocomplete. Alternatives: @haze/ai-inline-edit, @haze/ai-autocomplete, @haze/ai-diff-review.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.