diff --git a/README.md b/README.md index f51b75c..70db03c 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ A plugin designed to view and edit `CSV files` directly within Obsidian. - **Edit** cells directly by clicking and typing. - **Manage** rows and columns (add, delete, move) with a simple right-click on the header. - **Switch Delimiter Non‑Destructively**: Auto‑detects the file delimiter (comma, semicolon, tab, etc.). Changing the delimiter in the toolbar only re-parses the view; it does NOT rewrite your file. Your original delimiter is preserved when saving edits. -- **Clickable URLs**: Plain-text URLs in cells are automatically detected and rendered as clickable links. Click a link to open it in your browser, or click the cell to edit the URL text. +- **Clickable URLs**: Plain-text URLs and Markdown-style links (`[text](url)`) in cells are automatically detected and rendered as clickable links. Click a link to open it in your browser, or click the edit button (✎) to edit the cell content. I have a plan to design my own database using json and csv only. If you have fancy idea about tables or csv, please feel free to issue (I will consider it in csv-lite or my new plugin) or search it in community. diff --git a/README_zh.md b/README_zh.md index 5777650..f6d423b 100644 --- a/README_zh.md +++ b/README_zh.md @@ -23,7 +23,7 @@ - **编辑** 直接点击并输入即可编辑单元格 - **管理** 行和列(添加、删除、移动),只需右键点击表头 - **非破坏性分隔符切换**:自动检测文件原始分隔符(逗号、分号、制表符等)。在工具栏切换分隔符只会重新解析视图,不会改写文件;保存编辑时仍使用文件原始分隔符,避免产生大规模 diff。 -- **可点击的 URL 链接**:单元格中的纯文本 URL 会自动识别并渲染为可点击的链接。点击链接在浏览器中打开,或点击单元格编辑 URL 文本。 +- **可点击的 URL 链接**:单元格中的纯文本 URL 和 Markdown 风格链接(`[文本](url)`)会自动识别并渲染为可点击的链接。点击链接在浏览器中打开,或点击编辑按钮(✎)编辑单元格内容。 我计划仅用 json 和 csv 设计自己的数据库。如果你有关于表格或 csv 的新想法,欢迎提 issue(我会考虑加入 csv-lite 或新插件),或在社区中搜索。 diff --git a/docs/CLICKABLE_URLS.md b/docs/CLICKABLE_URLS.md index efc9dc1..265e708 100644 --- a/docs/CLICKABLE_URLS.md +++ b/docs/CLICKABLE_URLS.md @@ -2,19 +2,26 @@ ## Overview -The Clickable URLs feature automatically detects and renders plain-text URLs in CSV cells as clickable links. This makes it easy to navigate to external resources directly from your CSV data. +The Clickable URLs feature automatically detects and renders plain-text URLs and Markdown-style links in CSV cells as clickable links. This makes it easy to navigate to external resources directly from your CSV data while keeping your tables clean and readable. ## How It Works ### URL Detection -The plugin uses a regex pattern to detect URLs in the format: +The plugin detects two types of links: + +**1. Plain URLs:** - `http://example.com` - `https://example.com` - URLs with paths: `https://example.com/path/to/page` - URLs with query parameters: `https://example.com?param=value` - URLs with fragments: `https://example.com#section` +**2. Markdown-style Links:** +- `[GitHub](https://github.com)` - Displays as "GitHub" but links to the URL +- `[Documentation](https://docs.example.com)` - Clean, readable link text +- Mixed content: `Visit [our site](https://example.com) for more` - Text with embedded Markdown links + ### Display Modes Each cell with a URL has two modes: @@ -89,7 +96,32 @@ Unit tests are provided in `test/url-utils.test.ts`: ### Demo -A sample CSV file with URLs is provided in `test/url-test-sample.csv` for testing the feature. +Sample CSV files are provided for testing: +- `test/url-test-sample.csv` - Plain URLs +- `test/markdown-links-sample.csv` - Markdown-style links + +### Examples + +**Plain URLs:** +```csv +name,website +GitHub,https://github.com +``` +Displays: GitHub | https://github.com (as clickable link) + +**Markdown Links:** +```csv +name,website +GitHub,[Visit GitHub](https://github.com) +``` +Displays: GitHub | Visit GitHub (as clickable link, cleaner!) + +**Mixed Content:** +```csv +description +Check [our docs](https://docs.example.com) and https://example.com +``` +Both links are clickable, with Markdown link showing as "our docs" ## Future Enhancements @@ -98,3 +130,5 @@ Possible improvements: - URL validation and error indicators - Custom link styling per column - Option to disable auto-linking for specific columns +- Support for Obsidian internal links (`[[note]]`) +- Support for Wiki-style links diff --git a/src/utils/url-utils.ts b/src/utils/url-utils.ts index cda969c..6da2e55 100644 --- a/src/utils/url-utils.ts +++ b/src/utils/url-utils.ts @@ -5,12 +5,16 @@ // URL regex pattern that matches common URL formats const URL_PATTERN = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; +// Markdown link pattern: [text](url) +const MARKDOWN_LINK_PATTERN = /\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g; + /** - * Detect if text contains URLs + * Detect if text contains URLs or Markdown links */ export function containsUrl(text: string): boolean { const urlRegex = new RegExp(URL_PATTERN); - return urlRegex.test(text); + const markdownRegex = new RegExp(MARKDOWN_LINK_PATTERN); + return urlRegex.test(text) || markdownRegex.test(text); } /** @@ -20,18 +24,60 @@ export interface TextSegment { text: string; isUrl: boolean; url?: string; + displayText?: string; // For Markdown links } export function parseTextWithUrls(text: string): TextSegment[] { const segments: TextSegment[] = []; - let lastIndex = 0; - // Reset regex lastIndex + // Find all matches (both URLs and Markdown links) with their positions + interface Match { + index: number; + length: number; + displayText: string; + url: string; + } + + const matches: Match[] = []; + + // Find Markdown links first (they take precedence) + const markdownRegex = new RegExp(MARKDOWN_LINK_PATTERN); + let mdMatch: RegExpExecArray | null; + while ((mdMatch = markdownRegex.exec(text)) !== null) { + matches.push({ + index: mdMatch.index, + length: mdMatch[0].length, + displayText: mdMatch[1], // The text inside [...] + url: mdMatch[2] // The URL inside (...) + }); + } + + // Find plain URLs (but skip those inside Markdown links) const urlRegex = new RegExp(URL_PATTERN); - let match; + let urlMatch: RegExpExecArray | null; + while ((urlMatch = urlRegex.exec(text)) !== null) { + // Check if this URL is already part of a Markdown link + const isPartOfMarkdown = matches.some(m => + urlMatch!.index >= m.index && urlMatch!.index < m.index + m.length + ); + + if (!isPartOfMarkdown) { + matches.push({ + index: urlMatch.index, + length: urlMatch[0].length, + displayText: urlMatch[0], + url: urlMatch[0] + }); + } + } - while ((match = urlRegex.exec(text)) !== null) { - // Add text before URL + // Sort matches by position + matches.sort((a, b) => a.index - b.index); + + // Build segments + let lastIndex = 0; + for (const match of matches) { + // Add text before this match if (match.index > lastIndex) { segments.push({ text: text.substring(lastIndex, match.index), @@ -39,14 +85,15 @@ export function parseTextWithUrls(text: string): TextSegment[] { }); } - // Add URL segment + // Add URL/link segment segments.push({ - text: match[0], + text: match.displayText, isUrl: true, - url: match[0] + url: match.url, + displayText: match.displayText }); - lastIndex = urlRegex.lastIndex; + lastIndex = match.index + match.length; } // Add remaining text @@ -81,7 +128,8 @@ export function createUrlDisplay(text: string, onClick?: () => void): HTMLElemen if (segment.isUrl && segment.url) { const link = document.createElement('a'); link.href = segment.url; - link.textContent = segment.text; + // Use displayText if available (for Markdown links), otherwise use text + link.textContent = segment.displayText || segment.text; link.className = 'csv-cell-link'; link.target = '_blank'; link.rel = 'noopener noreferrer'; diff --git a/test/markdown-links-sample.csv b/test/markdown-links-sample.csv new file mode 100644 index 0000000..df19883 --- /dev/null +++ b/test/markdown-links-sample.csv @@ -0,0 +1,7 @@ +name,website,documentation,description +GitHub,[Visit GitHub](https://github.com),[Docs](https://docs.github.com),Code hosting with Markdown links +Stack Overflow,[SO Community](https://stackoverflow.com),[Help Center](https://stackoverflow.com/help),Q&A for developers - compact display +MDN,[MDN Docs](https://developer.mozilla.org),https://developer.mozilla.org/en-US/docs/Web,Mixed: Markdown and plain URL +Obsidian,https://obsidian.md,[Help](https://help.obsidian.md),Mixed: Plain URL and Markdown +TypeScript,[TS Lang](https://www.typescriptlang.org),[Documentation](https://www.typescriptlang.org/docs/),"Cleaner tables with [TS](https://www.typescriptlang.org)" +Multiple Links,[GitHub](https://github.com) and [GitLab](https://gitlab.com),[Docs1](https://docs.github.com) | [Docs2](https://docs.gitlab.com),Multiple Markdown links in one cell diff --git a/test/url-utils.test.ts b/test/url-utils.test.ts index 8c240d7..a628cd0 100644 --- a/test/url-utils.test.ts +++ b/test/url-utils.test.ts @@ -36,6 +36,15 @@ describe('URL Utils', () => { it('should handle multiple URLs in text', () => { expect(containsUrl('Visit https://site1.com and https://site2.com')).toBe(true); }); + + it('should detect Markdown-style links', () => { + expect(containsUrl('[GitHub](https://github.com)')).toBe(true); + expect(containsUrl('Check [this link](https://example.com) out')).toBe(true); + }); + + it('should detect mixed URLs and Markdown links', () => { + expect(containsUrl('[GitHub](https://github.com) and https://example.com')).toBe(true); + }); }); describe('parseTextWithUrls', () => { @@ -58,7 +67,8 @@ describe('URL Utils', () => { expect(result[1]).toEqual({ text: 'https://example.com', isUrl: true, - url: 'https://example.com' + url: 'https://example.com', + displayText: 'https://example.com' }); expect(result[2]).toEqual({ text: ' today', @@ -78,7 +88,8 @@ describe('URL Utils', () => { expect(result[0]).toEqual({ text: 'https://example.com', isUrl: true, - url: 'https://example.com' + url: 'https://example.com', + displayText: 'https://example.com' }); }); @@ -87,7 +98,8 @@ describe('URL Utils', () => { expect(result[result.length - 1]).toEqual({ text: 'https://example.com', isUrl: true, - url: 'https://example.com' + url: 'https://example.com', + displayText: 'https://example.com' }); }); @@ -98,6 +110,40 @@ describe('URL Utils', () => { expect(result[0].isUrl).toBe(true); expect(result[0].url).toBe(url); }); + + it('should parse Markdown-style link', () => { + const result = parseTextWithUrls('[GitHub](https://github.com)'); + expect(result).toHaveLength(1); + expect(result[0].isUrl).toBe(true); + expect(result[0].url).toBe('https://github.com'); + expect(result[0].displayText).toBe('GitHub'); + }); + + it('should parse text with Markdown link and plain text', () => { + const result = parseTextWithUrls('Visit [GitHub](https://github.com) now'); + expect(result).toHaveLength(3); + expect(result[0]).toEqual({ + text: 'Visit ', + isUrl: false + }); + expect(result[1].isUrl).toBe(true); + expect(result[1].url).toBe('https://github.com'); + expect(result[1].displayText).toBe('GitHub'); + expect(result[2]).toEqual({ + text: ' now', + isUrl: false + }); + }); + + it('should parse mixed Markdown links and plain URLs', () => { + const result = parseTextWithUrls('[GitHub](https://github.com) and https://example.com'); + expect(result).toHaveLength(3); + expect(result[0].isUrl).toBe(true); + expect(result[0].displayText).toBe('GitHub'); + expect(result[1].text).toBe(' and '); + expect(result[2].isUrl).toBe(true); + expect(result[2].url).toBe('https://example.com'); + }); }); // Note: createUrlDisplay tests are skipped as they require DOM environment