feat: add clickable URLs feature in CSV cells

- Implemented automatic detection and rendering of plain-text URLs as clickable links in CSV cells.
- Added functionality to toggle between display and edit modes for URL cells.
- Updated styles for URL display and interaction.
- Created utility functions for URL detection and parsing.
- Added tests for URL detection and parsing functionality.
This commit is contained in:
JayBridge 2026-02-01 13:53:34 +08:00
parent a23c224b9f
commit 672d162195
8 changed files with 494 additions and 1 deletions

View file

@ -28,6 +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 NonDestructively**: Autodetects 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.
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. <!-- For in-markdown edit, I recommend `anyblock` with a much more complex syntax. -->

View file

@ -23,6 +23,7 @@
- **编辑** 直接点击并输入即可编辑单元格
- **管理** 行和列(添加、删除、移动),只需右键点击表头
- **非破坏性分隔符切换**:自动检测文件原始分隔符(逗号、分号、制表符等)。在工具栏切换分隔符只会重新解析视图,不会改写文件;保存编辑时仍使用文件原始分隔符,避免产生大规模 diff。
- **可点击的 URL 链接**:单元格中的纯文本 URL 会自动识别并渲染为可点击的链接。点击链接在浏览器中打开,或点击单元格编辑 URL 文本。
我计划仅用 json 和 csv 设计自己的数据库。如果你有关于表格或 csv 的新想法,欢迎提 issue我会考虑加入 csv-lite 或新插件),或在社区中搜索。<!-- 对于 Markdown 内编辑,推荐 `anyblock`,但语法更复杂。 -->

100
docs/CLICKABLE_URLS.md Normal file
View file

@ -0,0 +1,100 @@
# Clickable URLs Feature
## 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.
## How It Works
### URL Detection
The plugin uses a regex pattern to detect URLs in the format:
- `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`
### Display Modes
Each cell with a URL has two modes:
1. **Display Mode** (default)
- URLs are rendered as clickable links
- Links open in a new browser tab
- Click the cell (not the link) to enter edit mode
2. **Edit Mode**
- Shows the plain text input field
- Allows editing the URL text
- Automatically switches back to display mode on blur
### Implementation Details
#### Files Created/Modified
1. **`src/utils/url-utils.ts`** (new)
- `containsUrl()`: Detects if text contains URLs
- `parseTextWithUrls()`: Parses text into segments (URL and non-URL)
- `createUrlDisplay()`: Creates DOM elements with clickable links
2. **`src/view/table-render.ts`** (modified)
- Integrated URL display layer
- Toggle between display and edit modes
- Dynamic URL detection on input changes
3. **`styles.css`** (modified)
- Added styles for `.csv-cell-display`
- Added styles for `.csv-cell-link` with hover effects
#### Architecture
```
Cell Structure:
├── <td>
├── <div class="csv-cell-display"> (shown when not editing)
│ ├── <span>Plain text</span>
│ ├── <a href="..." class="csv-cell-link">URL</a>
│ └── <span>More text</span>
└── <input class="csv-cell-input"> (shown when editing)
```
### User Experience
1. **Viewing**: URLs appear as underlined, colored links
2. **Clicking a link**: Opens in new browser tab (Ctrl/Cmd + Click for background tab)
3. **Editing**: Click anywhere in the cell (including the display area, but not on the link itself) to enter edit mode
4. **Saving**: Changes are saved automatically when you blur the input
### Click Behavior
- **Click on link**: Opens URL in new tab
- **Click on cell (anywhere except link)**: Enters edit mode and focuses the input
- **Hover over cell**: Shows background highlight to indicate it's editable
- **Hover over link**: Shows link-specific hover effect
### Styling
The links use CSS variables for theming:
- `--link-color`: Link color
- `--link-color-hover`: Hover state color
- Transitions for smooth hover effects
### Testing
Unit tests are provided in `test/url-utils.test.ts`:
- URL detection accuracy
- Text parsing with single/multiple URLs
- Edge cases (URLs at start/end, with special characters)
### Demo
A sample CSV file with URLs is provided in `test/url-test-sample.csv` for testing the feature.
## Future Enhancements
Possible improvements:
- Support for other URL formats (ftp://, file://, etc.)
- URL validation and error indicators
- Custom link styling per column
- Option to disable auto-linking for specific columns

124
src/utils/url-utils.ts Normal file
View file

@ -0,0 +1,124 @@
/**
* Utility functions for URL detection and rendering
*/
// 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;
/**
* Detect if text contains URLs
*/
export function containsUrl(text: string): boolean {
const urlRegex = new RegExp(URL_PATTERN);
return urlRegex.test(text);
}
/**
* Parse text and return segments with URL information
*/
export interface TextSegment {
text: string;
isUrl: boolean;
url?: string;
}
export function parseTextWithUrls(text: string): TextSegment[] {
const segments: TextSegment[] = [];
let lastIndex = 0;
// Reset regex lastIndex
const urlRegex = new RegExp(URL_PATTERN);
let match;
while ((match = urlRegex.exec(text)) !== null) {
// Add text before URL
if (match.index > lastIndex) {
segments.push({
text: text.substring(lastIndex, match.index),
isUrl: false
});
}
// Add URL segment
segments.push({
text: match[0],
isUrl: true,
url: match[0]
});
lastIndex = urlRegex.lastIndex;
}
// Add remaining text
if (lastIndex < text.length) {
segments.push({
text: text.substring(lastIndex),
isUrl: false
});
}
// If no URLs found, return the whole text as one segment
if (segments.length === 0) {
segments.push({
text: text,
isUrl: false
});
}
return segments;
}
/**
* Create a display element with clickable URLs
*/
export function createUrlDisplay(text: string, onClick?: () => void): HTMLElement {
const display = document.createElement('div');
display.className = 'csv-cell-display';
const segments = parseTextWithUrls(text);
for (const segment of segments) {
if (segment.isUrl && segment.url) {
const link = document.createElement('a');
link.href = segment.url;
link.textContent = segment.text;
link.className = 'csv-cell-link';
link.target = '_blank';
link.rel = 'noopener noreferrer';
// Prevent link click from triggering cell edit
link.onclick = (e) => {
e.stopPropagation();
};
display.appendChild(link);
} else {
const span = document.createElement('span');
span.textContent = segment.text;
display.appendChild(span);
}
}
// Add an edit button for cells that are entirely URLs (no other clickable area)
if (onClick) {
const editBtn = document.createElement('span');
editBtn.className = 'csv-cell-edit-btn';
editBtn.textContent = '✎';
editBtn.title = 'Click to edit';
editBtn.onclick = (e) => {
e.stopPropagation();
onClick();
};
display.appendChild(editBtn);
// Also make display clickable (for areas that aren't links)
display.onclick = (e) => {
// Only trigger if not clicking on a link
if ((e.target as HTMLElement).tagName !== 'A') {
onClick();
}
};
}
return display;
}

View file

@ -2,6 +2,7 @@ import { TableUtils } from "../utils/table-utils";
import { CSVUtils } from "../utils/csv-utils";
import { i18n } from "../i18n";
import { setIcon } from "obsidian";
import { containsUrl, createUrlDisplay } from "../utils/url-utils";
export interface TableRenderOptions {
tableData: string[][];
@ -270,11 +271,39 @@ export function renderTable(options: TableRenderOptions) {
const td = tableRow.createEl("td", {
attr: { style: `width: ${columnWidths[j] || 100}px` },
});
const input = td.createEl("input", {
cls: "csv-cell-input",
attr: { value: cell },
});
// Create display layer for URL rendering
const hasUrl = containsUrl(cell);
let displayEl: HTMLElement | null = null;
// Function to enter edit mode
const enterEditMode = () => {
const display = td.querySelector('.csv-cell-display') as HTMLElement;
if (display) {
display.style.display = 'none';
}
input.style.display = 'block';
input.focus();
};
if (hasUrl) {
displayEl = createUrlDisplay(cell, enterEditMode);
td.insertBefore(displayEl, input);
}
setupAutoResize(input);
// Hide input initially if URL display is shown
if (hasUrl && displayEl) {
input.style.display = 'none';
displayEl.style.display = 'block';
}
input.oninput = (ev) => {
if (ev.currentTarget instanceof HTMLInputElement) {
saveSnapshot();
@ -290,10 +319,63 @@ export function renderTable(options: TableRenderOptions) {
if (autoResize) {
adjustInputHeight(ev.currentTarget);
}
// Update display on input change
const newHasUrl = containsUrl(ev.currentTarget.value);
const tdEl = ev.currentTarget.parentElement;
if (tdEl) {
const existingDisplay = tdEl.querySelector('.csv-cell-display');
if (newHasUrl) {
// Create or update display
if (existingDisplay) {
existingDisplay.remove();
}
const inputEl = ev.currentTarget;
const newDisplay = createUrlDisplay(ev.currentTarget.value, () => {
// Enter edit mode: show input first, then focus
const disp = tdEl.querySelector('.csv-cell-display') as HTMLElement;
if (disp) {
disp.style.display = 'none';
}
inputEl.style.display = 'block';
inputEl.focus();
});
tdEl.insertBefore(newDisplay, ev.currentTarget);
} else if (existingDisplay) {
// Remove display if no URLs
existingDisplay.remove();
}
}
}
};
input.onfocus = (ev) => {
setActiveCell(i, j, ev.currentTarget as HTMLInputElement);
if (ev.currentTarget instanceof HTMLInputElement) {
setActiveCell(i, j, ev.currentTarget);
// Hide display and show input when focused
const tdEl = ev.currentTarget.parentElement;
if (tdEl) {
const display = tdEl.querySelector('.csv-cell-display') as HTMLElement;
if (display) {
display.style.display = 'none';
ev.currentTarget.style.display = 'block';
}
}
}
};
input.onblur = (ev) => {
if (ev.currentTarget instanceof HTMLInputElement) {
// Show display and hide input when blurred (if contains URL)
const tdEl = ev.currentTarget.parentElement;
if (tdEl) {
const display = tdEl.querySelector('.csv-cell-display') as HTMLElement;
if (display && containsUrl(ev.currentTarget.value)) {
display.style.display = 'block';
ev.currentTarget.style.display = 'none';
}
}
}
};
});
}

View file

@ -53,6 +53,74 @@ If your plugin does not need CSS, delete this file.
line-height: 1.4;
}
/* URL display layer */
.csv-cell-display {
padding: 2px 4px;
min-height: 24px;
cursor: text;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.4;
user-select: text;
transition: background-color 0.15s ease;
position: relative;
padding-right: 24px; /* Space for edit button */
}
/* Hover effect on cell to show it's editable */
.csv-cell-display:hover {
background-color: var(--background-modifier-hover);
border-radius: 3px;
}
/* Edit button for URL cells */
.csv-cell-edit-btn {
cursor: pointer;
color: var(--text-muted);
font-size: 12px;
padding: 2px 4px;
border-radius: 3px;
opacity: 0;
transition: opacity 0.15s ease, background-color 0.15s ease;
position: absolute;
right: 2px;
top: 50%;
transform: translateY(-50%);
}
.csv-cell-display:hover .csv-cell-edit-btn {
opacity: 1;
}
.csv-cell-edit-btn:hover {
background-color: var(--interactive-accent);
color: var(--text-on-accent);
}
/* Clickable URL links */
.csv-cell-link {
color: var(--link-color);
text-decoration: none;
cursor: pointer;
border-bottom: 1px solid var(--link-color);
transition: all 0.2s ease;
position: relative;
z-index: 1;
}
.csv-cell-link:hover {
color: var(--link-color-hover);
border-bottom-color: var(--link-color-hover);
text-decoration: none;
background-color: rgba(var(--interactive-accent-rgb), 0.1);
padding: 0 2px;
border-radius: 2px;
}
.csv-cell-link:active {
opacity: 0.7;
}
/* csv-cell-input 特有样式(宽度由 JS 控制) */
.csv-cell-input {
width: 100%;

12
test/url-test-sample.csv Normal file
View file

@ -0,0 +1,12 @@
name,website,documentation,description
GitHub,https://github.com,https://docs.github.com,Popular code hosting platform
Stack Overflow,https://stackoverflow.com,https://stackoverflow.com/help,Q&A site for developers
MDN,https://developer.mozilla.org,https://developer.mozilla.org/en-US/docs/Web,Web technology documentation
Obsidian,https://obsidian.md,https://help.obsidian.md,Note-taking and knowledge base app
TypeScript,https://www.typescriptlang.org,https://www.typescriptlang.org/docs/,JavaScript with types
React,https://react.dev,https://react.dev/learn,UI library for web
Vue,https://vuejs.org,https://vuejs.org/guide/,Progressive framework
Node.js,https://nodejs.org,https://nodejs.org/docs/latest/api/,JavaScript runtime
NPM,https://www.npmjs.com,https://docs.npmjs.com/,Package manager
Python,https://www.python.org,https://docs.python.org/3/,General-purpose programming
Mixed Content,https://example.com,Check https://docs.example.com for details,Text with inline URLs
1 name website documentation description
2 GitHub https://github.com https://docs.github.com Popular code hosting platform
3 Stack Overflow https://stackoverflow.com https://stackoverflow.com/help Q&A site for developers
4 MDN https://developer.mozilla.org https://developer.mozilla.org/en-US/docs/Web Web technology documentation
5 Obsidian https://obsidian.md https://help.obsidian.md Note-taking and knowledge base app
6 TypeScript https://www.typescriptlang.org https://www.typescriptlang.org/docs/ JavaScript with types
7 React https://react.dev https://react.dev/learn UI library for web
8 Vue https://vuejs.org https://vuejs.org/guide/ Progressive framework
9 Node.js https://nodejs.org https://nodejs.org/docs/latest/api/ JavaScript runtime
10 NPM https://www.npmjs.com https://docs.npmjs.com/ Package manager
11 Python https://www.python.org https://docs.python.org/3/ General-purpose programming
12 Mixed Content https://example.com Check https://docs.example.com for details Text with inline URLs

105
test/url-utils.test.ts Normal file
View file

@ -0,0 +1,105 @@
import { containsUrl, parseTextWithUrls, createUrlDisplay } from '../src/utils/url-utils';
describe('URL Utils', () => {
describe('containsUrl', () => {
it('should detect HTTP URLs', () => {
expect(containsUrl('http://example.com')).toBe(true);
expect(containsUrl('Visit http://example.com for more')).toBe(true);
});
it('should detect HTTPS URLs', () => {
expect(containsUrl('https://example.com')).toBe(true);
expect(containsUrl('Check out https://github.com')).toBe(true);
});
it('should detect URLs with paths', () => {
expect(containsUrl('https://example.com/path/to/page')).toBe(true);
expect(containsUrl('http://site.com/docs?q=test')).toBe(true);
});
it('should detect URLs with query parameters', () => {
expect(containsUrl('https://example.com?foo=bar&baz=qux')).toBe(true);
});
it('should detect URLs with fragments', () => {
expect(containsUrl('https://example.com#section')).toBe(true);
expect(containsUrl('https://example.com/page#top')).toBe(true);
});
it('should return false for non-URLs', () => {
expect(containsUrl('Just plain text')).toBe(false);
expect(containsUrl('example.com')).toBe(false); // No protocol
expect(containsUrl('www.example.com')).toBe(false); // No protocol
expect(containsUrl('')).toBe(false);
});
it('should handle multiple URLs in text', () => {
expect(containsUrl('Visit https://site1.com and https://site2.com')).toBe(true);
});
});
describe('parseTextWithUrls', () => {
it('should parse text with no URLs', () => {
const result = parseTextWithUrls('Just plain text');
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
text: 'Just plain text',
isUrl: false
});
});
it('should parse text with single URL', () => {
const result = parseTextWithUrls('Visit https://example.com today');
expect(result).toHaveLength(3);
expect(result[0]).toEqual({
text: 'Visit ',
isUrl: false
});
expect(result[1]).toEqual({
text: 'https://example.com',
isUrl: true,
url: 'https://example.com'
});
expect(result[2]).toEqual({
text: ' today',
isUrl: false
});
});
it('should parse text with multiple URLs', () => {
const result = parseTextWithUrls('Check https://site1.com and https://site2.com out');
expect(result).toHaveLength(5);
expect(result[1].isUrl).toBe(true);
expect(result[3].isUrl).toBe(true);
});
it('should parse URL at start of text', () => {
const result = parseTextWithUrls('https://example.com is great');
expect(result[0]).toEqual({
text: 'https://example.com',
isUrl: true,
url: 'https://example.com'
});
});
it('should parse URL at end of text', () => {
const result = parseTextWithUrls('Visit https://example.com');
expect(result[result.length - 1]).toEqual({
text: 'https://example.com',
isUrl: true,
url: 'https://example.com'
});
});
it('should parse URL with complex path', () => {
const url = 'https://example.com/path/to/page?param=value&other=123#section';
const result = parseTextWithUrls(url);
expect(result).toHaveLength(1);
expect(result[0].isUrl).toBe(true);
expect(result[0].url).toBe(url);
});
});
// Note: createUrlDisplay tests are skipped as they require DOM environment
// The function is tested through integration tests in the actual plugin
});