From 0c6cf1e9061feee3b74fed1a8415f38c76d99f4f Mon Sep 17 00:00:00 2001 From: Ryan Maleki Date: Sun, 15 Nov 2026 19:17:47 -0800 Subject: [PATCH] Add render markdown tool --- README.md | 6 +- client/src/App.tsx | 2 + client/src/data/tools.ts | 61 ++++ client/src/lib/markdown-to-html.ts | 94 ++++++ client/src/pages/tools/markdown-to-html.tsx | 323 ++++++++++++++++++++ package-lock.json | 13 + package.json | 3 +- tests/e2e/tools/markdown-to-html.spec.ts | 46 +++ tests/lib/markdown-to-html.test.ts | 76 +++++ 9 files changed, 620 insertions(+), 4 deletions(-) create mode 100644 client/src/lib/markdown-to-html.ts create mode 100644 client/src/pages/tools/markdown-to-html.tsx create mode 100644 tests/e2e/tools/markdown-to-html.spec.ts create mode 100644 tests/lib/markdown-to-html.test.ts diff --git a/README.md b/README.md index c5dc26be..d68e94e5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [FreeDevTool.App](https://FreeDevTool.App) -**A comprehensive collection of 49+ open source developer tools with offline functionality** +**A comprehensive collection of 50+ open source developer tools with offline functionality** ## Overview @@ -44,7 +44,7 @@ The client-side is a React with TypeScript application, built on a component-bas - **Routing**: Uses wouter for lightweight client-side routing. - **State Management**: Leverages React's built-in state management with hooks. -- **UI/UX Decisions**: Features collapsible header/sidebar menus with state persistence, responsive sidebar modes, a unified text editor with line numbers, and a searchable tool directory with keyboard shortcut navigation. All 49 tools now use simple React state (no session persistence) for optimal reliability and performance, and UI uniformity is achieved through shared components like `ToolButton` and `ToolTextArea`. Regex Tester uses Ctrl+E shortcut (Ctrl+R reserved for browser refresh). Session management has been completely removed from all tools for enhanced stability. +- **UI/UX Decisions**: Features collapsible header/sidebar menus with state persistence, responsive sidebar modes, a unified text editor with line numbers, and a searchable tool directory with keyboard shortcut navigation. All 50 tools now use simple React state (no session persistence) for optimal reliability and performance, and UI uniformity is achieved through shared components like `ToolButton` and `ToolTextArea`. Regex Tester uses Ctrl+E shortcut (Ctrl+R reserved for browser refresh). Session management has been completely removed from all tools for enhanced stability. ### Backend Architecture @@ -60,7 +60,7 @@ Not implemented ### Technical Implementations & Feature Specifications -- **Tool Suite**: Comprehensive conversion tools (URL/CSV to JSON, Number Base, Date, Timezone, Unit), image metadata extraction with local C2PA Content Credentials validation, advanced text tools (password generator, UUID v1/v4), and hardware tests (Camera, Microphone, Keyboard) with Web Audio API integration for alerts. SynthID watermark verification is not included. Added Metronome with multi-tone functionality. All 49 tools converted to simple React state management for enhanced reliability. +- **Tool Suite**: Comprehensive conversion tools (URL/CSV to JSON, Markdown to HTML, Number Base, Date, Timezone, Unit), image metadata extraction with local C2PA Content Credentials validation, advanced text tools (password generator, UUID v1/v4), and hardware tests (Camera, Microphone, Keyboard) with Web Audio API integration for alerts. SynthID watermark verification is not included. Added Metronome with multi-tone functionality. All 50 tools converted to simple React state management for enhanced reliability. - **Demo System**: Automated tour functionality with customizable speed controls (Slow 8s, Normal 5s, Fast 3s, Very Fast 1.5s), persistent state management, skip/stop controls, and speed preference persistence via localStorage. - **Offline Functionality**: All external dependencies for tools like QR and Barcode generators have been replaced with local JavaScript libraries to ensure 100% offline functionality. - **URL Sharing**: Implemented across all major tools, including timing tools, for state persistence and sharing. diff --git a/client/src/App.tsx b/client/src/App.tsx index 09c2e356..7e9cba6d 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -36,6 +36,7 @@ const GraphQLFormatter = lazy(() => import("@/pages/tools/graphql-formatter")); const TimeFormatter = lazy(() => import("@/pages/tools/time-formatter")); const Base64Encoder = lazy(() => import("@/pages/tools/base64-encoder")); const CborEncoder = lazy(() => import("@/pages/tools/cbor-encoder")); +const MarkdownToHtml = lazy(() => import("@/pages/tools/markdown-to-html")); const ImageMetadata = lazy(() => import("@/pages/tools/image-metadata")); const UrlEncoder = lazy(() => import("@/pages/tools/url-encoder")); const JwtDecoder = lazy(() => import("@/pages/tools/jwt-decoder")); @@ -111,6 +112,7 @@ function Router() { path="/tools/number-base-converter" component={NumberBaseConverter} /> + {/* Formatters */} diff --git a/client/src/data/tools.ts b/client/src/data/tools.ts index 87b1a903..b37deb1c 100644 --- a/client/src/data/tools.ts +++ b/client/src/data/tools.ts @@ -16,6 +16,7 @@ import { Link2, Table, Binary, + FileCode, // Formatters FileJson, @@ -1229,6 +1230,66 @@ export const toolsData: ToolData = { ], }, }, + { + name: "Markdown to HTML", + path: "/tools/markdown-to-html", + icon: FileCode, + shortcut: "Ctrl+Shift+Alt+M", + metadata: { + title: "Markdown to HTML Converter - Preview and Download HTML", + description: + "Convert Markdown to HTML with a live rendered preview. Supports GitHub Flavored Markdown and downloads a standalone HTML file.", + keywords: [ + "markdown to html", + "markdown converter", + "markdown preview", + "md to html", + "GitHub Flavored Markdown", + "markdown renderer", + ], + }, + explanations: { + notice: { + type: "privacy", + title: "Private, Local Conversion", + items: [ + "Markdown is converted locally in your browser and is never uploaded.", + "The preview runs in a sandboxed frame, so scripts embedded in the Markdown never execute.", + ], + }, + sections: [ + { + title: "Supported Markdown", + items: [ + "Headings, emphasis, links, images, lists, and blockquotes", + "GitHub Flavored Markdown: tables, task lists, strikethrough, and autolinks", + "Fenced and indented code blocks, plus inline HTML", + ], + }, + { + title: "Output Options", + items: [ + { + label: "Full HTML Document:", + text: "a standalone page with , title, and readable styles (light and dark)", + }, + { + label: "Body only:", + text: "just the converted HTML, ready to paste into an existing page or CMS", + }, + { + label: "Download:", + text: "saves the HTML using the first heading as the filename", + }, + { + label: "Remote images:", + text: "are kept in the HTML but may not appear in the in-page preview", + }, + ], + }, + ], + }, + }, ], }, Formatters: { diff --git a/client/src/lib/markdown-to-html.ts b/client/src/lib/markdown-to-html.ts new file mode 100644 index 00000000..0174684b --- /dev/null +++ b/client/src/lib/markdown-to-html.ts @@ -0,0 +1,94 @@ +import { marked } from "marked"; + +/** + * Stylesheet embedded in both the live preview and downloaded full HTML + * documents, so the downloaded file renders the same as the preview. + */ +const MARKDOWN_HTML_STYLES = ` +:root { color-scheme: light dark; --fg: #1e293b; --bg: #ffffff; --muted: #64748b; --border: #e2e8f0; --code-bg: #f1f5f9; --link: #2563eb; } +@media (prefers-color-scheme: dark) { + :root { --fg: #e2e8f0; --bg: #0f172a; --muted: #94a3b8; --border: #334155; --code-bg: #1e293b; --link: #60a5fa; } +} +:root[data-theme="light"] { --fg: #1e293b; --bg: #ffffff; --muted: #64748b; --border: #e2e8f0; --code-bg: #f1f5f9; --link: #2563eb; color-scheme: light; } +:root[data-theme="dark"] { --fg: #e2e8f0; --bg: #0f172a; --muted: #94a3b8; --border: #334155; --code-bg: #1e293b; --link: #60a5fa; color-scheme: dark; } +* { box-sizing: border-box; } +body { margin: 0 auto; max-width: 48rem; padding: 1.5rem 1rem; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: var(--fg); background: var(--bg); overflow-wrap: break-word; } +h1, h2, h3, h4, h5, h6 { line-height: 1.25; margin: 1.5em 0 0.5em; } +h1 { font-size: 2em; border-bottom: 1px solid var(--border); padding-bottom: 0.3em; } +h2 { font-size: 1.5em; border-bottom: 1px solid var(--border); padding-bottom: 0.3em; } +h1:first-child, h2:first-child { margin-top: 0; } +a { color: var(--link); } +img { max-width: 100%; } +code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.9em; background: var(--code-bg); padding: 0.15em 0.35em; border-radius: 4px; } +pre { background: var(--code-bg); padding: 1rem; border-radius: 6px; overflow-x: auto; } +pre code { background: none; padding: 0; } +blockquote { margin: 1em 0; padding: 0 1em; color: var(--muted); border-left: 4px solid var(--border); } +table { border-collapse: collapse; display: block; overflow-x: auto; margin: 1em 0; } +th, td { border: 1px solid var(--border); padding: 0.4em 0.8em; } +th { background: var(--code-bg); } +hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; } +li > input[type="checkbox"] { margin-right: 0.4em; } +`.trim(); + +/** Convert Markdown (GitHub Flavored) to an HTML fragment. */ +export function convertMarkdownToHtml(markdown: string): string { + return marked.parse(markdown, { + gfm: true, + breaks: false, + async: false, + }) as string; +} + +function escapeHtml(text: string): string { + return text + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +/** Title from the first level-1 heading, or "Document". */ +export function extractTitle(markdown: string): string { + const match = markdown.match(/^#[ \t]+(.+?)[ \t#]*$/m); + const title = match?.[1] + ?.replace(/[*_`~[\]]/g, "") + .replace(/\(([^)]*)\)/g, "") + .trim(); + return title || "Document"; +} + +/** Filesystem-friendly slug for a download filename. */ +export function slugifyFilename(title: string): string { + const slug = title + .toLowerCase() + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 80); + return slug || "document"; +} + +/** Wrap an HTML fragment in a standalone, styled HTML document. */ +export function wrapHtmlDocument( + body: string, + title: string, + theme?: "light" | "dark" +): string { + const themeAttr = theme ? ` data-theme="${theme}"` : ""; + return ` + + + + +${escapeHtml(title)} + + + +${body.trim()} + + +`; +} diff --git a/client/src/pages/tools/markdown-to-html.tsx b/client/src/pages/tools/markdown-to-html.tsx new file mode 100644 index 00000000..0b9e797b --- /dev/null +++ b/client/src/pages/tools/markdown-to-html.tsx @@ -0,0 +1,323 @@ +import { useShareTool } from "@/hooks/use-share-tool"; +import { useToast } from "@/hooks/use-toast"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { TextArea } from "@/components/ui/textarea"; +import { useTheme } from "@/providers/theme-provider"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + ToolButton, + ResetButton, + ClearButton, + ToolButtonGroup, + ActionButtonGroup, + DataButtonGroup, +} from "@/components/ui/tool-button"; +import { SecurityBanner } from "@/components/ui/security-banner"; +import { DEFAULT_MARKDOWN } from "@/data/defaults"; +import { getToolByPath } from "@/data/tools"; +import { ToolExplanations } from "@/components/tool-explanations"; +import { ShortcutBadge } from "@/components/ui/shortcut-badge"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { + convertMarkdownToHtml, + extractTitle, + slugifyFilename, + wrapHtmlDocument, +} from "@/lib/markdown-to-html"; +import { formatHTML } from "@/lib/formatters"; + +export default function MarkdownToHtml() { + const { handleShare } = useShareTool(); + const { toast } = useToast(); + const tool = getToolByPath("/tools/markdown-to-html"); + const [input, setInput] = useState(DEFAULT_MARKDOWN); + const [fullDocument, setFullDocument] = useState(true); + const { theme } = useTheme(); + + const { fragment, error } = useMemo(() => { + try { + return { fragment: convertMarkdownToHtml(input), error: null }; + } catch (err) { + return { + fragment: "", + error: `Conversion error: ${err instanceof Error ? err.message : "Unknown error"}`, + }; + } + }, [input]); + + const title = useMemo(() => extractTitle(input), [input]); + + const rawOutput = useMemo(() => { + if (!fragment) return ""; + return fullDocument ? wrapHtmlDocument(fragment, title) : fragment; + }, [fragment, fullDocument, title]); + + // Pretty-print with the same Prettier-based formatter as the HTML Formatter + // tool. Validation messages are ignored: they target hand-written HTML. + const [formatted, setFormatted] = useState<{ + source: string; + html: string; + } | null>(null); + useEffect(() => { + let cancelled = false; + if (!rawOutput) return undefined; + // The shared formatter can drop the doctype, so format without it and + // add it back to keep the downloaded file in standards mode. + const doctype = rawOutput.match(/^\s*/i)?.[0] ?? ""; + formatHTML(rawOutput.slice(doctype.length)) + .then(result => { + if (!cancelled) { + const html = doctype + ? `\n${result.formatted.trimStart()}` + : result.formatted; + setFormatted({ source: rawOutput, html }); + } + }) + .catch(() => { + // Keep showing the unformatted HTML if formatting fails. + }); + return () => { + cancelled = true; + }; + }, [rawOutput]); + const output = formatted?.source === rawOutput ? formatted.html : rawOutput; + + // Preview always renders as a full document, themed to match the app, with + // links opening in a new tab so the preview frame is never navigated away. + const previewDoc = useMemo( + () => + wrapHtmlDocument(fragment, title, theme) + .replace("", '\n') + // The preview card already frames the content, so drop the reading-width + // cap used by downloaded pages and keep only a small inset. + .replace( + "", + "\n" + ), + [fragment, title, theme] + ); + + // Grow the preview frame to fit its content so it never scrolls internally. + const previewRef = useRef(null); + const [previewHeight, setPreviewHeight] = useState(500); + const resizePreview = useCallback(() => { + const doc = previewRef.current?.contentDocument; + if (doc?.documentElement) { + // getBoundingClientRect reports content height; scrollHeight would never + // shrink below the current frame height. + setPreviewHeight( + Math.ceil(doc.documentElement.getBoundingClientRect().height) + 2 + ); + } + }, []); + + useEffect(() => { + window.addEventListener("resize", resizePreview); + return () => window.removeEventListener("resize", resizePreview); + }, [resizePreview]); + + const handleDownload = () => { + if (!output.trim()) { + toast({ + title: "Nothing to download", + description: "Enter some Markdown first.", + variant: "destructive", + duration: 2500, + }); + return; + } + const filename = `${slugifyFilename(title)}.html`; + try { + const blob = new Blob([output], { type: "text/html;charset=utf-8" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + toast({ + title: "Download started", + description: `Saved as ${filename}`, + duration: 2000, + }); + } catch { + toast({ + title: "Download failed", + description: "Could not create or save the file.", + variant: "destructive", + duration: 2500, + }); + } + }; + + const handleReset = () => setInput(DEFAULT_MARKDOWN); + const handleClear = () => setInput(""); + + const hasModifiedData = input !== DEFAULT_MARKDOWN && input.trim() !== ""; + const isAtDefault = input === DEFAULT_MARKDOWN; + + return ( +
+
+
+
+

+ Markdown to HTML + {tool?.shortcut ? ( + + ) : null} +

+

+ Convert Markdown to HTML, preview the rendered result, and + download it as an HTML file +

+
+ +
+
+ + {error ? ( + + + {error} + + + ) : null} + + + + + Download HTML + + + + + +
+ + +
+
+ +

+ On: standalone page with <head> and styles. Off: body + HTML only. +

+
+
+
+
+ + + + +
+ +
+ + + Markdown Input + + +