Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export function App() {
activeTabId,
switchTab,
closeTab,
reorderTabs,
rootPath,
setRootPath,
saveStatus,
Expand Down Expand Up @@ -177,12 +178,10 @@ export function App() {
if (activePath && isPathWithin(activePath, path)) {
startNewBuffer();
}
setFavorites((prev) => prev.filter((favorite) => !isPathWithin(favorite, path)));
}, [
activePath,
folders,
isPathWithin,
setFavorites,
setFolders,
setRootPath,
startNewBuffer,
Expand Down Expand Up @@ -307,15 +306,16 @@ export function App() {

const exportToPdf = useCallback(async () => {
try {
await exportPreviewToPdf({ source, activePath });
const documentName = tabs.find((tab) => tab.id === activeTabId)?.title;
await exportPreviewToPdf({ source, activePath, documentName });
} catch (err) {
const message = err instanceof PdfExportError
? err.message
: t("app.pdfFailed");
console.error("marka.md: pdf export failed", err);
setLoadError({ message });
}
}, [source, activePath, setLoadError, t]);
}, [source, activePath, tabs, activeTabId, setLoadError, t]);


const toggleFullscreen = useCallback(async () => {
Expand Down Expand Up @@ -435,6 +435,14 @@ export function App() {
setStagedPaths([]);
}, [rootPath]);

// Keep the webview document title in sync with the active file. On Windows the
// native Ctrl+P prints the app window, and the browser derives the save-as-PDF
// default name from document.title — so this drives the exported file name.
useEffect(() => {
const tabTitle = tabs.find((tab) => tab.id === activeTabId)?.title;
document.title = (tabTitle ?? "untitled").replace(/\.md$/i, "");
}, [tabs, activeTabId]);

useEffect(() => {
let cancelled = false;
void getVersion()
Expand Down Expand Up @@ -905,6 +913,7 @@ export function App() {
activeTabId={activeTabId}
onSelect={switchTab}
onClose={handleCloseTab}
onReorder={reorderTabs}
onContextMenu={(e, path) => handleContextMenu(e, { path, name: basename(path), isDir: false })}
/>
{editorOnly ? (
Expand Down
98 changes: 92 additions & 6 deletions src/components/editor/open-tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { useEffect, useRef, type WheelEvent, type MouseEvent as ReactMouseEvent } from "react";
import {
useEffect,
useRef,
useState,
type WheelEvent,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
import { X } from "lucide-react";
import { Icon } from "@/components/primitives";
import type { FileTab } from "@/hooks/use-file-session";
Expand All @@ -9,12 +16,23 @@ type OpenTabsProps = {
activeTabId: string;
onSelect: (id: string) => void;
onClose: (id: string) => void;
onReorder?: (from: number, to: number) => void;
onContextMenu?: (e: React.MouseEvent, path: string) => void;
};

export function OpenTabs({ tabs, activeTabId, onSelect, onClose, onContextMenu }: OpenTabsProps) {
// px the pointer must travel before a press becomes a reorder drag
const DRAG_THRESHOLD = 4;

export function OpenTabs({ tabs, activeTabId, onSelect, onClose, onReorder, onContextMenu }: OpenTabsProps) {
const { t } = useI18n();
const listRef = useRef<HTMLDivElement | null>(null);
// active drag gesture; null when idle. Pointer-event based (not HTML5 DnD)
// because Tauri's dragDropEnabled intercepts native drag on WebView2.
const dragRef = useRef<{ fromIndex: number; startX: number; pointerId: number; moved: boolean } | null>(null);
// when a drag just ended, swallow the synthetic click so it doesn't select
const suppressClickRef = useRef(false);
const [fromIndex, setFromIndex] = useState<number | null>(null);
const [overIndex, setOverIndex] = useState<number | null>(null);

useEffect(() => {
const active = listRef.current?.querySelector<HTMLElement>(".mdv-tab.is-active");
Expand All @@ -30,24 +48,85 @@ export function OpenTabs({ tabs, activeTabId, onSelect, onClose, onContextMenu }
el.scrollLeft += event.deltaY;
};

// which tab index the pointer X currently sits over (by element midpoints)
const indexAtX = (clientX: number): number | null => {
const el = listRef.current;
if (!el) return null;
const tabEls = Array.from(el.querySelectorAll<HTMLElement>(".mdv-tab"));
if (tabEls.length === 0) return null;
for (let i = 0; i < tabEls.length; i++) {
const rect = tabEls[i].getBoundingClientRect();
if (clientX < rect.left + rect.width / 2) return i;
}
return tabEls.length - 1;
};

const onTabPointerDown = (e: ReactPointerEvent<HTMLDivElement>, index: number) => {
if (!onReorder || e.button !== 0) return;
suppressClickRef.current = false;
dragRef.current = { fromIndex: index, startX: e.clientX, pointerId: e.pointerId, moved: false };
};

const onListPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (!drag) return;
if (!drag.moved) {
if (Math.abs(e.clientX - drag.startX) < DRAG_THRESHOLD) return;
drag.moved = true;
setFromIndex(drag.fromIndex);
try {
listRef.current?.setPointerCapture(drag.pointerId);
} catch {
// capture unavailable — drag still tracks via move events
}
}
setOverIndex(indexAtX(e.clientX));
};

const endDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (!drag) return;
if (drag.moved) {
suppressClickRef.current = true;
const target = indexAtX(e.clientX);
if (onReorder && target !== null && target !== drag.fromIndex) {
onReorder(drag.fromIndex, target);
}
}
try {
listRef.current?.releasePointerCapture(drag.pointerId);
} catch {
// already released
}
dragRef.current = null;
setFromIndex(null);
setOverIndex(null);
};

return (
<div
ref={listRef}
className="mdv-tabs"
className={`mdv-tabs${fromIndex !== null ? " is-reordering" : ""}`}
role="tablist"
aria-label={t("tabs.openFiles")}
onWheel={handleWheel}
onPointerMove={onListPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
{tabs.map((tab) => {
{tabs.map((tab, tabIndex) => {
const active = tab.id === activeTabId;
const dirty = tab.source !== tab.savedContent;
const dragging = fromIndex === tabIndex;
const isDragOver = overIndex === tabIndex && fromIndex !== null && fromIndex !== tabIndex;
return (
<div
key={tab.id}
role="tab"
aria-selected={active}
className={`mdv-tab${active ? " is-active" : ""}${dirty ? " is-dirty" : ""}`}
className={`mdv-tab${active ? " is-active" : ""}${dirty ? " is-dirty" : ""}${dragging ? " is-dragging" : ""}${isDragOver ? " is-drag-over" : ""}`}
title={tab.path ?? tab.title}
onPointerDown={(e) => onTabPointerDown(e, tabIndex)}
onContextMenu={tab.path && onContextMenu ? (e: ReactMouseEvent) => {
e.preventDefault();
onContextMenu(e, tab.path!);
Expand All @@ -56,7 +135,13 @@ export function OpenTabs({ tabs, activeTabId, onSelect, onClose, onContextMenu }
<button
type="button"
className="mdv-tab__select"
onClick={() => onSelect(tab.id)}
onClick={() => {
if (suppressClickRef.current) {
suppressClickRef.current = false;
return;
}
onSelect(tab.id);
}}
>
<span className="mdv-tab__dot" aria-hidden="true" />
<span className="mdv-tab__label">{tab.title}</span>
Expand All @@ -66,6 +151,7 @@ export function OpenTabs({ tabs, activeTabId, onSelect, onClose, onContextMenu }
className="mdv-tab__close"
aria-label={t("tabs.close", { name: tab.title })}
data-tooltip={t("tabs.close", { name: tab.title })}
onPointerDown={(e) => e.stopPropagation()}
onClick={() => onClose(tab.id)}
>
<Icon icon={X} size={13} strokeWidth={1.8} />
Expand Down
23 changes: 20 additions & 3 deletions src/hooks/use-file-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type UseFileSessionResult = {
activeTabId: string;
switchTab: (id: string) => void;
closeTab: (id: string) => void;
reorderTabs: (from: number, to: number) => void;
rootPath: string | null;
setRootPath: (v: string | null | ((p: string | null) => string | null)) => void;
saveStatus: SaveStatus;
Expand Down Expand Up @@ -170,6 +171,16 @@ export function useFileSession({ onLoadError }: UseFileSessionArgs = {}): UseFil
setSaveStatus(next.source === next.savedContent ? "idle" : "dirty");
}, [snapshotActiveTab, setActivePath, tabs]);

const reorderTabs = useCallback((from: number, to: number) => {
setTabs((prev) => {
if (from === to || from < 0 || to < 0 || from >= prev.length || to >= prev.length) return prev;
const next = [...prev];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved);
return next;
});
}, []);

const closeTab = useCallback((id: string) => {
const current = snapshotActiveTab(tabs);
const closingIndex = current.findIndex((tab) => tab.id === id);
Expand Down Expand Up @@ -207,8 +218,8 @@ export function useFileSession({ onLoadError }: UseFileSessionArgs = {}): UseFil
async (path: string) => {
const seq = ++loadSeq.current;
const existing = snapshotActiveTab(tabs).find((tab) => tab.path === path);
if (existing && activePathRef.current !== path) {
switchTab(existing.id);
if (existing) {
if (activePathRef.current !== path) switchTab(existing.id);
return;
}
const check = await validateSupportedTextFile(path);
Expand Down Expand Up @@ -315,6 +326,11 @@ export function useFileSession({ onLoadError }: UseFileSessionArgs = {}): UseFil

const loadPlainTextFile = useCallback(async (path: string) => {
const seq = ++loadSeq.current;
const existing = snapshotActiveTab(tabs).find((tab) => tab.path === path);
if (existing) {
if (activePathRef.current !== path) switchTab(existing.id);
return;
}
const check = await validatePlainTextFile(path);
if (seq !== loadSeq.current) return;
if (!check.ok) {
Expand Down Expand Up @@ -342,7 +358,7 @@ export function useFileSession({ onLoadError }: UseFileSessionArgs = {}): UseFil
console.error("marka.md: loadPlainTextFile failed", err);
onLoadError?.({ message: String(err), path });
}
}, [makeTabId, setActivePath, setRecentFiles, onLoadError, snapshotActiveTab, titleForPath]);
}, [makeTabId, setActivePath, setRecentFiles, onLoadError, snapshotActiveTab, switchTab, tabs, titleForPath]);

const saveAs = useCallback(async (): Promise<string | null> => {
const defaultPath = activePath
Expand Down Expand Up @@ -424,6 +440,7 @@ export function useFileSession({ onLoadError }: UseFileSessionArgs = {}): UseFil
activeTabId,
switchTab,
closeTab,
reorderTabs,
rootPath,
setRootPath,
saveStatus,
Expand Down
10 changes: 7 additions & 3 deletions src/lib/pdf-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,16 +141,20 @@ export class PdfExportError extends Error {
type ExportOpts = {
source: string;
activePath: string | null;
/** active tab title — drives the PDF document name (browser save-as default) */
documentName?: string;
};

/** Export markdown as self-contained print HTML and open in browser to save as PDF. */
export async function exportPreviewToPdf({ source, activePath }: ExportOpts): Promise<void> {
export async function exportPreviewToPdf({ source, activePath, documentName }: ExportOpts): Promise<void> {
if (!source.trim()) {
throw new PdfExportError("empty", "nothing to export. open or write some markdown first.");
}

const fileName = activePath ? basename(activePath) : undefined;
const title = "marka.md export";
// Prefer the file name; fall back to the tab title (e.g. "untitled") so the
// browser's save-as-PDF default is never the literal "marka.md export".
const fileName = activePath ? basename(activePath) : documentName;
const title = (fileName ?? "export").replace(/\.md$/i, "");

// Always render with latte for PDF — guarantees light, readable colors on
// white paper regardless of the user's current app theme. Lazy-loads the
Expand Down
14 changes: 14 additions & 0 deletions src/styles/editor/panes.css
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,20 @@
background: color-mix(in srgb, var(--fg) 8%, transparent);
}

.mdv-tabs.is-reordering {
user-select: none;
cursor: grabbing;
}

.mdv-tab.is-dragging {
opacity: 0.5;
}

.mdv-tab.is-drag-over {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, transparent);
}

/* editor-only mode (#28) — preview pane hidden, editor fills remaining width */
.mdv-shell__editor-solo {
flex: 1;
Expand Down
4 changes: 4 additions & 0 deletions src/styles/files/sidebar.css
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,10 @@
border-top: none;
}

.mdv-favorites .mdv-tree::before {
display: none;
}

.mdv-rootfolder__header {
display: flex;
align-items: center;
Expand Down
55 changes: 54 additions & 1 deletion src/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,59 @@ body.mdv-print .mdv-prose a {
}

@media print {
@page { margin: 16mm; }
@page {
margin: 16mm 16mm 20mm;
/* Clear browser-generated headers/footers (date, title, URL) */
@top-left { content: ''; }
@top-center { content: ''; }
@top-right { content: ''; }
@bottom-left { content: ''; }
@bottom-right { content: ''; }
/* Page number centered at bottom */
@bottom-center {
content: counter(page);
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 10px;
color: #888888;
}
}
body { background: #fff !important; }

.mdv-titlebar,
.mdv-breadcrumb,
.mdv-statusbar,
.mdv-sidebar,
.mdv-tabs,
.mdv-splitter__handle,
.mdv-splitter__pane:first-child,
.mdv-toast,
.mdv-overlay,
.mdv-overlay__backdrop,
.mdv-drop,
.mdv-tooltip,
.mdv-popover {
display: none !important;
}

.mdv-app,
.mdv-shell,
.mdv-splitter,
.mdv-splitter__pane:last-child,
.mdv-preview {
display: block !important;
height: auto !important;
width: 100% !important;
max-width: 100% !important;
overflow: visible !important;
background: #ffffff !important;
color: #000000 !important;
padding: 0 !important;
}

.mdv-prose {
max-width: 100% !important;
padding: 24px 32px !important;
color: #000000 !important;
background: #ffffff !important;
}
}