Note editor sidebar, full-doc assist, persistent drafts, version history

NoteEditorView: two-column sidebar layout (project/milestone/tags/assist
always visible), removed assist toggle button, InlineAssistPanel removed.

Writing assist: whole_doc mode rewrites entire document; DiffView.vue
replaces editor during review showing full-document diff. Scope dropdown
in sidebar switches between whole-document and section modes.

Persistent drafts: migration 0022 adds note_drafts (UNIQUE per note+user)
and note_versions (max 20, auto-pruned) tables. Draft saved after generation
completes, restored on editor mount, cleared on accept/reject. Version
snapshot created automatically whenever note body changes on save.

HistoryPanel.vue: version list + DiffView modal, restore button writes
body back to editor.

Config: OLLAMA_NUM_CTX default raised to 65536; assist num_predict now
tracks Config.OLLAMA_NUM_CTX instead of a hardcoded 4096.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-05 17:10:55 -05:00
parent b11a92f32d
commit 9036dfd931
17 changed files with 1275 additions and 278 deletions
+118
View File
@@ -0,0 +1,118 @@
<script setup lang="ts">
import { computed } from "vue";
import type { DiffLine } from "@/composables/useAssist";
const props = defineProps<{
diff: DiffLine[];
}>();
const insertions = computed(() => props.diff.filter(l => l.type === 'insert').length);
const deletions = computed(() => props.diff.filter(l => l.type === 'delete').length);
function markerFor(type: DiffLine['type']): string {
if (type === 'insert') return '+';
if (type === 'delete') return '';
return ' ';
}
</script>
<template>
<div class="diff-view-full">
<div class="diff-summary-bar">
<span class="diff-summary-ins">+{{ insertions }} insertion{{ insertions !== 1 ? 's' : '' }}</span>
<span class="diff-summary-del">{{ deletions }} deletion{{ deletions !== 1 ? 's' : '' }}</span>
</div>
<div class="diff-scroll">
<div v-if="!diff.length" class="diff-empty">No changes.</div>
<div
v-for="(line, i) in diff"
:key="i"
:class="['diff-line', `diff-${line.type}`]"
>
<span class="diff-marker">{{ markerFor(line.type) }}</span>
<span class="diff-text">{{ line.text }}</span>
</div>
</div>
</div>
</template>
<style scoped>
.diff-view-full {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
background: var(--color-bg);
overflow: hidden;
}
.diff-summary-bar {
position: sticky;
top: 0;
flex-shrink: 0;
display: flex;
gap: 1rem;
padding: 0.4rem 0.75rem;
background: var(--color-bg-secondary);
border-bottom: 1px solid var(--color-border);
font-size: 0.78rem;
font-family: monospace;
font-weight: 600;
}
.diff-summary-ins { color: var(--color-success, #2ecc71); }
.diff-summary-del { color: var(--color-danger, #e74c3c); }
.diff-scroll {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 0.3rem 0;
}
.diff-empty {
padding: 0.75rem;
font-size: 0.85rem;
color: var(--color-text-muted);
font-style: italic;
}
.diff-line {
display: flex;
align-items: baseline;
padding: 0.04rem 0.5rem;
line-height: 1.55;
font-family: monospace;
font-size: 0.82rem;
}
.diff-delete {
background: color-mix(in srgb, var(--color-danger, #e74c3c) 12%, transparent);
color: var(--color-danger, #e74c3c);
}
.diff-insert {
background: color-mix(in srgb, var(--color-success, #2ecc71) 12%, transparent);
color: var(--color-success, #2ecc71);
}
.diff-equal {
color: var(--color-text-muted);
}
.diff-marker {
flex-shrink: 0;
width: 1rem;
text-align: center;
user-select: none;
font-weight: 700;
}
.diff-text {
flex: 1;
white-space: pre-wrap;
word-break: break-word;
}
</style>
+271
View File
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { apiGet } from "@/api/client";
import DiffView from "@/components/DiffView.vue";
import type { DiffLine } from "@/composables/useAssist";
interface NoteVersion {
id: number;
note_id: number;
title: string;
body?: string;
created_at: string;
}
const props = defineProps<{
noteId: number;
currentBody: string;
}>();
const emit = defineEmits<{
(e: 'restore', body: string): void;
(e: 'close'): void;
}>();
const versions = ref<NoteVersion[]>([]);
const selectedVersion = ref<NoteVersion | null>(null);
const loading = ref(false);
const loadingDetail = ref(false);
const diff = computed<DiffLine[]>(() => {
if (!selectedVersion.value?.body) return [];
const a = props.currentBody;
const b = selectedVersion.value.body;
const aLines = a.split('\n');
const bLines = b.split('\n');
const m = aLines.length, n = bLines.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--)
for (let j = n - 1; j >= 0; j--)
dp[i][j] = aLines[i] === bLines[j]
? dp[i+1][j+1] + 1
: Math.max(dp[i+1][j], dp[i][j+1]);
const result: DiffLine[] = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (aLines[i] === bLines[j]) { result.push({ type: 'equal', text: aLines[i++] }); j++; }
else if (dp[i+1][j] >= dp[i][j+1]) result.push({ type: 'delete', text: aLines[i++] });
else result.push({ type: 'insert', text: bLines[j++] });
}
while (i < m) result.push({ type: 'delete', text: aLines[i++] });
while (j < n) result.push({ type: 'insert', text: bLines[j++] });
return result;
});
function formatDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleString(undefined, {
month: 'short', day: 'numeric', year: 'numeric',
hour: '2-digit', minute: '2-digit',
});
}
async function loadVersions() {
loading.value = true;
try {
const data = await apiGet<{ versions: NoteVersion[] }>(
`/api/notes/${props.noteId}/versions`
);
versions.value = data.versions;
if (versions.value.length > 0) {
await selectVersionItem(versions.value[0]);
}
} catch {
// silent
} finally {
loading.value = false;
}
}
async function selectVersionItem(v: NoteVersion) {
if (v.body !== undefined) {
selectedVersion.value = v;
return;
}
loadingDetail.value = true;
try {
const full = await apiGet<NoteVersion>(
`/api/notes/${props.noteId}/versions/${v.id}`
);
// Cache body back onto list item
const listItem = versions.value.find(x => x.id === v.id);
if (listItem) listItem.body = full.body;
selectedVersion.value = full;
} catch {
// silent
} finally {
loadingDetail.value = false;
}
}
function restore() {
if (!selectedVersion.value?.body) return;
emit('restore', selectedVersion.value.body);
}
onMounted(loadVersions);
</script>
<template>
<teleport to="body">
<div class="modal-overlay" @click.self="emit('close')">
<div class="modal-card history-modal">
<div class="history-header">
<h3 class="history-title">Version History</h3>
<button class="history-close" @click="emit('close')">&times;</button>
</div>
<div class="history-body">
<!-- Left: version list -->
<div class="history-list">
<div v-if="loading" class="history-empty">Loading...</div>
<div v-else-if="!versions.length" class="history-empty">No versions yet.</div>
<div
v-for="v in versions"
:key="v.id"
:class="['history-item', { selected: selectedVersion?.id === v.id }]"
@click="selectVersionItem(v)"
>
<div class="history-item-title">{{ v.title || 'Untitled' }}</div>
<div class="history-item-date">{{ formatDate(v.created_at) }}</div>
</div>
</div>
<!-- Right: diff -->
<div class="history-diff">
<div v-if="loadingDetail" class="history-empty">Loading version...</div>
<div v-else-if="!selectedVersion" class="history-empty">Select a version to compare.</div>
<DiffView v-else :diff="diff" />
</div>
</div>
<div class="history-footer">
<button
class="btn-restore"
:disabled="!selectedVersion?.body"
@click="restore"
>Restore this version</button>
<button class="modal-btn" @click="emit('close')">Close</button>
</div>
</div>
</div>
</teleport>
</template>
<style scoped>
.history-modal {
max-width: 900px;
width: 95%;
height: 80vh;
max-height: 700px;
display: flex;
flex-direction: column;
padding: 0;
}
.history-header {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.9rem 1.25rem;
border-bottom: 1px solid var(--color-border);
}
.history-title {
margin: 0;
font-size: 1rem;
}
.history-close {
background: none;
border: none;
font-size: 1.25rem;
cursor: pointer;
color: var(--color-text-muted);
line-height: 1;
padding: 0.1rem 0.3rem;
}
.history-close:hover { color: var(--color-text); }
.history-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
}
.history-list {
width: 220px;
flex-shrink: 0;
border-right: 1px solid var(--color-border);
overflow-y: auto;
}
.history-item {
padding: 0.6rem 0.9rem;
cursor: pointer;
border-left: 3px solid transparent;
border-bottom: 1px solid var(--color-border);
}
.history-item:hover { background: var(--color-bg-secondary); }
.history-item.selected {
border-left-color: var(--color-primary);
background: var(--color-bg-secondary);
}
.history-item-title {
font-size: 0.85rem;
font-weight: 500;
color: var(--color-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-item-date {
font-size: 0.75rem;
color: var(--color-text-muted);
margin-top: 0.15rem;
}
.history-diff {
flex: 1;
min-width: 0;
overflow: hidden;
display: flex;
flex-direction: column;
padding: 0.5rem;
}
.history-empty {
padding: 1rem;
font-size: 0.85rem;
color: var(--color-text-muted);
font-style: italic;
}
.history-footer {
flex-shrink: 0;
display: flex;
gap: 0.5rem;
justify-content: flex-end;
padding: 0.75rem 1.25rem;
border-top: 1px solid var(--color-border);
}
.btn-restore {
padding: 0.45rem 1rem;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.9rem;
}
.btn-restore:disabled {
opacity: 0.5;
cursor: default;
}
</style>
+119 -49
View File
@@ -1,5 +1,5 @@
import { ref, computed, watch, type Ref } from "vue";
import { apiPost, apiSSEStream, type SSEStreamHandle } from "@/api/client";
import { apiPost, apiPut, apiDelete, apiSSEStream, type SSEStreamHandle } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import {
parseMarkdownSections,
@@ -7,6 +7,7 @@ import {
} from "@/utils/sectionParser";
export type AssistState = "idle" | "streaming" | "review";
export type ScopeMode = "document" | "section";
export interface AssistTarget {
text: string;
@@ -19,6 +20,17 @@ export interface DiffLine {
text: string;
}
export interface NoteDraft {
id: number;
note_id: number;
proposed_body: string;
original_body: string;
instruction: string;
scope: string;
created_at: string;
updated_at: string;
}
function computeDiff(a: string, b: string): DiffLine[] {
const aLines = a.split('\n');
const bLines = b.split('\n');
@@ -41,24 +53,28 @@ function computeDiff(a: string, b: string): DiffLine[] {
return result;
}
export function useAssist(body: Ref<string>) {
export function useAssist(body: Ref<string>, noteId?: Ref<number | null>) {
const toast = useToastStore();
const state = ref<AssistState>("idle");
const scopeMode = ref<ScopeMode>("document");
const sections = ref<MarkdownSection[]>([]);
const selectedSection = ref<MarkdownSection | null>(null);
const customSelection = ref<{ start: number; end: number; text: string } | null>(null);
const instruction = ref("");
const streamingText = ref("");
const proposedText = ref("");
// Full proposed document body (for section mode: body with section replaced)
const proposedFullBody = ref("");
const error = ref("");
const isProofreading = ref(false);
// Snapshot of body at the time a section/selection was chosen
// Snapshot of body at the time generation was started
let bodySnapshot = "";
let streamHandle: SSEStreamHandle | null = null;
const target = computed<AssistTarget | null>(() => {
if (scopeMode.value === 'document') return null;
if (customSelection.value) {
return {
text: customSelection.value.text,
@@ -76,16 +92,16 @@ export function useAssist(body: Ref<string>) {
return null;
});
const canSubmit = computed(
() =>
target.value !== null &&
instruction.value.trim().length > 0 &&
state.value !== "streaming"
const canSubmit = computed(() =>
instruction.value.trim().length > 0 &&
state.value !== "streaming" &&
(scopeMode.value === 'document' || target.value !== null)
);
// Diff always compares full document: original snapshot → proposed
const diff = computed<DiffLine[]>(() => {
if (state.value !== 'review' || !target.value || !proposedText.value) return [];
return computeDiff(target.value.text, proposedText.value);
if (state.value !== 'review' || !proposedFullBody.value) return [];
return computeDiff(bodySnapshot, proposedFullBody.value);
});
function refreshSections() {
@@ -93,21 +109,21 @@ export function useAssist(body: Ref<string>) {
}
function selectSection(section: MarkdownSection) {
scopeMode.value = 'section';
customSelection.value = null;
selectedSection.value = section;
bodySnapshot = body.value;
error.value = "";
}
function selectTextRange(start: number, end: number) {
if (start === end) return;
scopeMode.value = 'section';
selectedSection.value = null;
customSelection.value = {
start,
end,
text: body.value.slice(start, end),
};
bodySnapshot = body.value;
error.value = "";
}
@@ -121,35 +137,84 @@ export function useAssist(body: Ref<string>) {
instruction.value = "";
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
}
async function _saveDraft() {
if (!noteId?.value) return;
try {
await apiPut(`/api/notes/${noteId.value}/draft`, {
proposed_body: proposedFullBody.value,
original_body: bodySnapshot,
instruction: instruction.value,
scope: scopeMode.value,
});
} catch {
// Non-critical — ignore draft save errors
}
}
async function _deleteDraft() {
if (!noteId?.value) return;
try {
await apiDelete(`/api/notes/${noteId.value}/draft`);
} catch {
// Ignore — draft may not exist
}
}
async function submit() {
if (!canSubmit.value || !target.value) return;
if (!canSubmit.value) return;
bodySnapshot = body.value;
state.value = "streaming";
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
const wholeDoc = scopeMode.value === 'document';
const targetSection = wholeDoc ? body.value : (target.value?.text ?? "");
try {
// Step 1: Launch background generation
await apiPost("/api/notes/assist", {
body: body.value,
target_section: target.value.text,
target_section: targetSection,
instruction: instruction.value,
whole_doc: wholeDoc,
});
// Step 2: Tail the SSE buffer
streamHandle = apiSSEStream("/api/notes/assist/stream", (evt) => {
streamHandle = apiSSEStream("/api/notes/assist/stream", async (evt) => {
if (evt.event === "chunk") {
streamingText.value += evt.data.chunk as string;
}
if (evt.event === "done") {
proposedText.value = (evt.data.full_text as string) || streamingText.value;
const fullText = (evt.data.full_text as string) || streamingText.value;
proposedText.value = fullText;
if (wholeDoc) {
proposedFullBody.value = fullText;
} else {
// Reconstruct full body with section replaced
const t = target.value;
if (t) {
let text = fullText;
if (!text.endsWith("\n")) text += "\n";
proposedFullBody.value =
bodySnapshot.slice(0, t.startOffset) +
text +
bodySnapshot.slice(t.endOffset);
} else {
proposedFullBody.value = fullText;
}
}
state.value = "review";
streamHandle = null;
await _saveDraft();
}
if (evt.event === "error") {
error.value = evt.data.error as string;
@@ -161,11 +226,26 @@ export function useAssist(body: Ref<string>) {
await streamHandle.done;
// Fallback: if stream ended without done/error, use accumulated text
if (state.value === "streaming") {
if (streamingText.value) {
proposedText.value = streamingText.value;
if (wholeDoc) {
proposedFullBody.value = streamingText.value;
} else {
const t = target.value;
if (t) {
let text = streamingText.value;
if (!text.endsWith("\n")) text += "\n";
proposedFullBody.value =
bodySnapshot.slice(0, t.startOffset) +
text +
bodySnapshot.slice(t.endOffset);
} else {
proposedFullBody.value = streamingText.value;
}
}
state.value = "review";
await _saveDraft();
} else {
state.value = "idle";
}
@@ -182,9 +262,9 @@ export function useAssist(body: Ref<string>) {
async function proofread() {
if (state.value === 'streaming') return;
isProofreading.value = true;
scopeMode.value = 'document';
selectedSection.value = null;
customSelection.value = { start: 0, end: body.value.length, text: body.value };
bodySnapshot = body.value;
customSelection.value = null;
error.value = '';
instruction.value =
"Proofread for clarity, grammar, spelling, and flow. " +
@@ -194,60 +274,48 @@ export function useAssist(body: Ref<string>) {
}
function accept(): string {
if (!target.value || !proposedText.value) return body.value;
const result = proposedFullBody.value || body.value;
const t = target.value;
// Validate that the body hasn't changed at the target offsets
if (body.value !== bodySnapshot) {
const currentSlice = body.value.slice(t.startOffset, t.endOffset);
if (currentSlice !== t.text) {
error.value = "The document changed since this suggestion was made. Please clear and try again.";
toast.show(error.value, "error");
state.value = "idle";
return body.value;
}
}
// Ensure proposed text ends with a newline for clean separation
let text = proposedText.value;
if (!text.endsWith("\n")) {
text += "\n";
}
const newBody =
body.value.slice(0, t.startOffset) +
text +
body.value.slice(t.endOffset);
// Reset state
selectedSection.value = null;
customSelection.value = null;
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
return newBody;
_deleteDraft();
return result;
}
function reject() {
proposedText.value = "";
proposedFullBody.value = "";
streamingText.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
_deleteDraft();
// Keep selection + instruction for retry
}
// Keep sections in sync with body automatically
function loadDraft(draft: NoteDraft) {
bodySnapshot = draft.original_body;
proposedText.value = draft.proposed_body;
proposedFullBody.value = draft.proposed_body;
instruction.value = draft.instruction;
scopeMode.value = draft.scope as ScopeMode;
state.value = "review";
}
watch(body, () => {
refreshSections();
}, { immediate: true });
return {
state,
scopeMode,
sections,
selectedSection,
customSelection,
@@ -255,6 +323,7 @@ export function useAssist(body: Ref<string>) {
instruction,
streamingText,
proposedText,
proposedFullBody,
error,
canSubmit,
diff,
@@ -267,5 +336,6 @@ export function useAssist(body: Ref<string>) {
proofread,
accept,
reject,
loadDraft,
};
}
+19
View File
@@ -13,3 +13,22 @@ export interface TaskLog {
created_at: string;
updated_at: string;
}
export interface NoteDraft {
id: number;
note_id: number;
proposed_body: string;
original_body: string;
instruction: string;
scope: string;
created_at: string;
updated_at: string;
}
export interface NoteVersion {
id: number;
note_id: number;
title: string;
body?: string;
created_at: string;
}
+376 -196
View File
@@ -4,15 +4,16 @@ import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import { useAssist } from "@/composables/useAssist";
import { apiPost } from "@/api/client";
import { useAssist, type NoteDraft } from "@/composables/useAssist";
import { apiPost, apiGet } from "@/api/client";
import type { Editor } from "@tiptap/vue-3";
import MarkdownToolbar from "@/components/MarkdownToolbar.vue";
import TiptapEditor from "@/components/TiptapEditor.vue";
import TagInput from "@/components/TagInput.vue";
import ProjectSelector from "@/components/ProjectSelector.vue";
import MilestoneSelector from "@/components/MilestoneSelector.vue";
import InlineAssistPanel from "@/components/InlineAssistPanel.vue";
import DiffView from "@/components/DiffView.vue";
import HistoryPanel from "@/components/HistoryPanel.vue";
const route = useRoute();
const router = useRouter();
@@ -27,6 +28,8 @@ const milestoneId = ref<number | null>(null);
const dirty = ref(false);
const saving = ref(false);
const showPreview = ref(false);
const sidebarOpen = ref(true);
const showHistory = ref(false);
const editorRef = ref<InstanceType<typeof TiptapEditor> | null>(null);
const tiptapEditor = computed<Editor | null>(() => {
return (editorRef.value?.editor as Editor | undefined) ?? null;
@@ -39,24 +42,46 @@ const isEditing = computed(() => noteId.value !== null);
const renderedPreview = computed(() => renderMarkdown(body.value));
// AI Assist
const assist = useAssist(body);
// AI Assist — pass noteId for draft persistence
const assist = useAssist(body, noteId);
const assistLabel = computed(() => {
if (assist.isProofreading.value) return "Proofreading document...";
const t = assist.target.value;
if (!t) return "Generating...";
const heading = t.text.split("\n")[0];
return `Revising: "${heading.length > 50 ? heading.slice(0, 50) + "..." : heading}"`;
// Scope selector options: "Whole document" + one per section
const scopeOptions = computed(() => {
const opts: Array<{ value: string; label: string }> = [
{ value: '__document__', label: 'Whole document' },
];
for (const section of assist.sections.value) {
opts.push({
value: String(assist.sections.value.indexOf(section)),
label: section.heading || '(preamble)',
});
}
return opts;
});
// Assist panel toggle (persisted)
const ASSIST_KEY = 'fa-assist-open';
const assistOpen = ref(localStorage.getItem(ASSIST_KEY) !== 'false');
function toggleAssist() {
assistOpen.value = !assistOpen.value;
localStorage.setItem(ASSIST_KEY, String(assistOpen.value));
}
const scopeSelectValue = computed({
get() {
if (assist.scopeMode.value === 'document') return '__document__';
if (assist.selectedSection.value) {
const idx = assist.sections.value.indexOf(assist.selectedSection.value);
return idx >= 0 ? String(idx) : '__document__';
}
return '__document__';
},
set(val: string) {
if (val === '__document__') {
assist.scopeMode.value = 'document';
assist.selectedSection.value = null;
} else {
const idx = Number(val);
const section = assist.sections.value[idx];
if (section) {
assist.scopeMode.value = 'section';
assist.selectSection(section);
}
}
},
});
// Floating inline assist button
const floatingAssist = ref({ show: false, top: 0, left: 0 });
@@ -79,25 +104,17 @@ function onSelectionChange(payload: { text: string; start: number; end: number }
function handleInlineAssist() {
if (!pendingSelection.value) return;
assist.scopeMode.value = 'section';
assist.selectTextRange(pendingSelection.value.start, pendingSelection.value.end);
assistOpen.value = true;
localStorage.setItem(ASSIST_KEY, 'true');
floatingAssist.value.show = false;
nextTick(() => instructionRef.value?.focus());
}
function handleAssistAccept() {
const newBody = assist.accept();
if (newBody !== body.value) {
body.value = newBody;
markDirty();
toast.show("Section updated");
}
}
function truncateTarget(text: string, max = 60): string {
const first = text.split("\n")[0];
return first.length > max ? first.slice(0, max) + "..." : first;
body.value = newBody;
markDirty();
toast.show("Document updated");
}
// Tag suggestions
@@ -174,6 +191,14 @@ onMounted(async () => {
savedProjectId = projectId.value;
savedMilestoneId = milestoneId.value;
}
// Restore pending draft if any
try {
const draft = await apiGet<NoteDraft>(`/api/notes/${noteId.value}/draft`);
if (draft) assist.loadDraft(draft);
} catch {
// No draft — normal
}
}
});
@@ -218,9 +243,7 @@ async function save() {
const showDeleteConfirm = ref(false);
function remove() {
if (noteId.value) {
showDeleteConfirm.value = true;
}
if (noteId.value) showDeleteConfirm.value = true;
}
async function confirmDelete() {
@@ -236,14 +259,17 @@ async function confirmDelete() {
}
}
// Auto-save every 5 minutes when editing an existing note
// Auto-save every 5 minutes
let autoSaveTimer: ReturnType<typeof setInterval> | null = null;
async function autoSave() {
if (!isEditing.value || !dirty.value || saving.value) return;
saving.value = true;
try {
await store.updateNote(noteId.value!, { title: title.value, body: body.value, tags: tags.value, project_id: projectId.value, milestone_id: milestoneId.value } as Record<string, unknown>);
await store.updateNote(noteId.value!, {
title: title.value, body: body.value, tags: tags.value,
project_id: projectId.value, milestone_id: milestoneId.value,
} as Record<string, unknown>);
savedTitle = title.value;
savedBody = body.value;
savedTags = [...tags.value];
@@ -252,7 +278,7 @@ async function autoSave() {
dirty.value = false;
toast.show("Auto-saved");
} catch {
// Silent — user can still save manually
// Silent
} finally {
saving.value = false;
}
@@ -261,7 +287,6 @@ async function autoSave() {
onMounted(() => { autoSaveTimer = setInterval(autoSave, 5 * 60 * 1000); });
onUnmounted(() => { if (autoSaveTimer !== null) clearInterval(autoSaveTimer); });
// Ctrl+S handler
function onKeydown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
@@ -272,37 +297,27 @@ function onKeydown(e: KeyboardEvent) {
onMounted(() => document.addEventListener("keydown", onKeydown));
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
// Unsaved changes guard — in-app navigation
onBeforeRouteLeave(() => {
if (dirty.value) {
return confirm("You have unsaved changes. Leave anyway?");
}
if (dirty.value) return confirm("You have unsaved changes. Leave anyway?");
});
// Unsaved changes guard — browser close/reload
function onBeforeUnload(e: BeforeUnloadEvent) {
if (dirty.value) {
e.preventDefault();
}
if (dirty.value) e.preventDefault();
}
onMounted(() => window.addEventListener("beforeunload", onBeforeUnload));
onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
</script>
<template>
<main class="editor-page">
<main class="editor-page note-editor-page">
<div class="editor-header">
<div class="toolbar">
<router-link to="/notes" class="btn-back">Back</router-link>
<button class="btn-save" @click="save" :disabled="saving">
{{ saving ? "Saving..." : "Save" }}
</button>
<button v-if="isEditing" class="btn-delete" @click="remove">
Delete
</button>
<button class="btn-assist-toggle" :class="{ active: assistOpen }" @click="toggleAssist">
Assist
</button>
<button v-if="isEditing" class="btn-delete" @click="remove">Delete</button>
<button v-if="isEditing" class="btn-history" @click="showHistory = true">History</button>
</div>
<input
v-model="title"
@@ -311,133 +326,129 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
class="title-input"
@input="markDirty"
/>
<div class="field-row-meta">
<div class="meta-field">
<label class="meta-label">Project</label>
<ProjectSelector v-model="projectId" @update:modelValue="milestoneId = null; markDirty()" />
</div>
<div class="meta-field">
<label class="meta-label">Milestone</label>
<MilestoneSelector :projectId="projectId" v-model="milestoneId" @update:modelValue="markDirty" />
</div>
</div>
<TagInput
v-model="tags"
:fetchTags="(q: string) => store.fetchAllTags(q)"
@update:modelValue="markDirty"
/>
<div class="tag-suggest-row">
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
</button>
<template v-if="suggestedTags.length > 0">
<button
v-for="tag in suggestedTags"
:key="tag"
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
:disabled="appliedTags.has(tag)"
@click="applyTagSuggestion(tag)"
>
#{{ tag }}
<span v-if="appliedTags.has(tag)" class="tag-check">&#10003;</span>
</button>
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">&times;</button>
</template>
</div>
<div class="editor-tabs">
<button
:class="['tab', { active: !showPreview }]"
@click="showPreview = false"
>
Write
</button>
<button
:class="['tab', { active: showPreview }]"
@click="showPreview = true"
>
Preview
</button>
</div>
<MarkdownToolbar v-show="!showPreview" :editor="tiptapEditor" />
</div>
<div class="editor-body">
<div class="editor-main">
<!-- Inline assist output: streaming preview + review diff -->
<InlineAssistPanel
v-if="assist.state.value !== 'idle'"
:phase="assist.state.value as 'streaming' | 'review'"
:label="assistLabel"
:streaming-text="assist.streamingText.value"
:diff="assist.diff.value"
:proposed-text="assist.proposedText.value"
@accept="handleAssistAccept"
@reject="assist.reject()"
@cancel="assist.clearSelection()"
/>
<!-- Two-column body: main | sidebar -->
<div class="note-body">
<!-- Editor hidden during review so diff takes full column -->
<div v-show="!showPreview && assist.state.value !== 'review'">
<TiptapEditor
ref="editorRef"
:modelValue="body"
placeholder="Write your note in Markdown..."
@update:modelValue="onBodyUpdate"
@selectionChange="onSelectionChange"
/>
<!-- Main column -->
<div class="note-main">
<div class="body-tabs-row">
<div class="editor-tabs">
<button :class="['tab', { active: !showPreview }]" @click="showPreview = false">Write</button>
<button :class="['tab', { active: showPreview }]" @click="showPreview = true">Preview</button>
</div>
<MarkdownToolbar v-show="!showPreview && assist.state.value === 'idle'" :editor="tiptapEditor" />
</div>
<div
v-show="showPreview && assist.state.value !== 'review'"
class="preview-pane prose"
v-html="renderedPreview"
></div>
<!-- Streaming preview -->
<template v-if="assist.state.value === 'streaming'">
<div class="stream-label">Generating...</div>
<div class="stream-preview prose" v-html="renderMarkdown(assist.streamingText.value)" />
</template>
<!-- Review: full-document diff -->
<template v-else-if="assist.state.value === 'review'">
<DiffView :diff="assist.diff.value" class="main-diff" />
</template>
<!-- Normal editor -->
<template v-else>
<div v-show="!showPreview" class="body-editor-wrap">
<TiptapEditor
ref="editorRef"
:modelValue="body"
placeholder="Write your note in Markdown..."
@update:modelValue="onBodyUpdate"
@selectionChange="onSelectionChange"
/>
</div>
<div
v-show="showPreview"
class="preview-pane prose"
v-html="renderedPreview"
/>
</template>
<!-- Error from assist -->
<div v-if="assist.error.value" class="assist-error">{{ assist.error.value }}</div>
</div>
<aside v-if="assistOpen" class="assist-panel">
<!-- Panel header -->
<div class="assist-panel-header">
<span class="assist-panel-title"> AI Assist</span>
<button
class="btn-proofread"
@click="assist.proofread()"
:disabled="assist.state.value === 'streaming'"
>Proofread</button>
<button class="btn-close-assist" @click="toggleAssist">×</button>
</div>
<!-- Sidebar -->
<aside class="note-sidebar">
<button class="sidebar-toggle" @click="sidebarOpen = !sidebarOpen">
Details {{ sidebarOpen ? '' : '' }}
</button>
<!-- Panel body -->
<div class="assist-panel-body">
<div :class="['sidebar-content', { 'sidebar-open': sidebarOpen }]">
<!-- IDLE -->
<div v-if="assist.state.value === 'idle'" class="assist-idle">
<div class="assist-sections-label">Sections</div>
<div class="assist-sections">
<div
v-for="(section, i) in assist.sections.value"
:key="i"
:class="['assist-section-item', { selected: assist.selectedSection.value === section }]"
@click="assist.selectSection(section)"
<!-- Project / Milestone / Tags -->
<div class="sb-field">
<label class="sb-label">Project</label>
<ProjectSelector
v-model="projectId"
@update:modelValue="milestoneId = null; markDirty()"
/>
</div>
<div v-if="projectId" class="sb-field">
<label class="sb-label">Milestone</label>
<MilestoneSelector
:projectId="projectId"
v-model="milestoneId"
@update:modelValue="markDirty"
/>
</div>
<div class="sb-field">
<label class="sb-label">Tags</label>
<TagInput
v-model="tags"
:fetchTags="(q: string) => store.fetchAllTags(q)"
@update:modelValue="markDirty"
/>
</div>
<div class="tag-suggest-row">
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
</button>
<template v-if="suggestedTags.length > 0">
<button
v-for="tag in suggestedTags"
:key="tag"
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
:disabled="appliedTags.has(tag)"
@click="applyTagSuggestion(tag)"
>
{{ section.heading || '(preamble)' }}
</div>
<div v-if="!assist.sections.value.length" class="assist-empty">
Write some content to get started.
</div>
#{{ tag }}
<span v-if="appliedTags.has(tag)" class="tag-check">&#10003;</span>
</button>
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">&times;</button>
</template>
</div>
<div class="sb-divider"></div>
<!-- Writing Assistant (always visible) -->
<div class="assist-section">
<div class="assist-section-title"> Writing Assistant</div>
<!-- Scope selector -->
<div class="sb-field">
<label class="sb-label">Scope</label>
<select v-model="scopeSelectValue" class="sb-select" :disabled="assist.state.value === 'streaming'">
<option
v-for="opt in scopeOptions"
:key="opt.value"
:value="opt.value"
>{{ opt.label }}</option>
</select>
</div>
<template v-if="assist.target.value">
<div class="assist-target-preview">
Editing: <em>{{ truncateTarget(assist.target.value.text) }}</em>
</div>
<!-- Idle: instruction + buttons -->
<template v-if="assist.state.value === 'idle'">
<textarea
ref="instructionRef"
v-model="assist.instruction.value"
placeholder="What should I do with this section?"
placeholder="What should I do?"
class="assist-instruction"
rows="3"
></textarea>
@@ -447,38 +458,52 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
@click="assist.submit()"
:disabled="!assist.canSubmit.value"
>Generate</button>
<button class="btn-clear" @click="assist.clearSelection()">Clear</button>
<button
class="btn-proofread"
@click="assist.proofread()"
>Proofread</button>
</div>
</template>
<!-- Streaming: cancel -->
<template v-else-if="assist.state.value === 'streaming'">
<div class="assist-active-hint">Generating see main area</div>
<button class="btn-clear" @click="assist.clearSelection()">Cancel</button>
</template>
<!-- Review: accept / reject -->
<template v-else-if="assist.state.value === 'review'">
<div class="assist-active-hint">Review the diff in the main area</div>
<div class="assist-actions">
<button class="btn-accept" @click="handleAssistAccept">Accept</button>
<button class="btn-reject" @click="assist.reject()">Reject</button>
</div>
</template>
<div v-else class="assist-hint">
Select a section above or highlight text in the editor.
</div>
</div>
<!-- ERROR -->
<div v-if="assist.error.value" class="assist-error">{{ assist.error.value }}</div>
<!-- Hint when active (output shown inline in editor area) -->
<div v-if="assist.state.value !== 'idle'" class="assist-active-hint">
{{ assist.state.value === 'streaming' ? 'Generating in editor' : 'Review diff in editor ' }}
</div>
</div>
</div><!-- /sidebar-content -->
</aside>
</div>
</div><!-- /note-body -->
<!-- Floating inline assist button (teleported to body) -->
<!-- Floating inline assist button -->
<teleport to="body">
<button
v-if="floatingAssist.show"
class="inline-assist-btn"
:style="{ top: floatingAssist.top + 'px', left: floatingAssist.left + 'px' }"
@mousedown.prevent="handleInlineAssist"
>
Assist
</button>
> Assist</button>
</teleport>
<!-- History panel -->
<HistoryPanel
v-if="showHistory && noteId"
:note-id="noteId"
:current-body="body"
@restore="body = $event; markDirty()"
@close="showHistory = false"
/>
<!-- Delete confirmation -->
<teleport to="body">
<div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
@@ -497,23 +522,178 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
<style src="@/assets/editor-shared.css" />
<style scoped>
.field-row-meta {
display: flex;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 0.25rem;
/* ── Two-column note layout ──────────────────────────────────── */
.note-editor-page {
max-width: 1600px;
}
.meta-field {
.note-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
position: relative;
}
/* Main column */
.note-main {
flex: 1;
min-width: 0;
overflow-y: auto;
padding: 0.75rem 1.25rem 2rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.body-tabs-row {
display: flex;
flex-direction: column;
gap: 0.25rem;
min-width: 180px;
flex: 1;
max-width: 300px;
}
.meta-label {
.body-editor-wrap {
min-height: 200px;
}
.stream-label {
font-size: 0.8rem;
color: var(--color-text-secondary);
font-weight: 500;
color: var(--color-text-muted);
font-style: italic;
}
</style>
.stream-preview {
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
padding: 0.75rem;
background: var(--color-bg-card);
min-height: 200px;
}
.main-diff {
flex: 1;
min-height: 0;
}
/* Right sidebar */
.note-sidebar {
width: 280px;
flex-shrink: 0;
border-left: 1px solid var(--color-border);
overflow-y: auto;
display: flex;
flex-direction: column;
}
/* Mobile accordion toggle (hidden on desktop) */
.sidebar-toggle {
display: none;
width: 100%;
padding: 0.6rem 1rem;
background: var(--color-bg-secondary);
border: none;
border-bottom: 1px solid var(--color-border);
font-size: 0.85rem;
font-weight: 600;
color: var(--color-text-secondary);
cursor: pointer;
text-align: left;
font-family: inherit;
}
.sidebar-content {
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.65rem;
}
/* Sidebar field layout */
.sb-field {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.sb-label {
font-size: 0.78rem;
font-weight: 600;
color: var(--color-text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.sb-select {
width: 100%;
padding: 0.35rem 0.5rem;
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
background: var(--color-bg-card);
color: var(--color-text);
font-size: 0.875rem;
font-family: inherit;
box-sizing: border-box;
}
.sb-select:focus { outline: none; border-color: var(--color-primary); }
.sb-divider {
height: 1px;
background: var(--color-border);
margin: 0.15rem 0;
}
/* Tag suggest row inside sidebar */
.tag-suggest-row {
display: flex;
flex-wrap: wrap;
gap: 0.3rem;
align-items: center;
}
/* Writing Assistant section */
.assist-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.assist-section-title {
font-size: 0.78rem;
font-weight: 700;
color: var(--color-text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
}
/* History button */
.btn-history {
padding: 0.45rem 1rem;
background: none;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.875rem;
color: var(--color-text-secondary);
font-family: inherit;
}
.btn-history:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
/* Narrow screen: sidebar collapses */
@media (max-width: 720px) {
.note-body { flex-direction: column; overflow-y: auto; overflow-x: hidden; }
.note-main { padding: 0.75rem 1rem 1rem; overflow-y: visible; }
.note-sidebar {
width: 100%;
border-left: none;
border-top: 1px solid var(--color-border);
overflow-y: visible;
}
.sidebar-toggle { display: block; }
.sidebar-content {
display: none;
padding: 0.75rem 1rem;
}
.sidebar-content.sidebar-open { display: flex; }
}
</style>