From 671e8a11c743bf9fea5f3c38b34ca5e931cebd7a Mon Sep 17 00:00:00 2001 From: Erich Schroeter Date: Fri, 31 Jul 2026 10:32:00 -0500 Subject: [PATCH] feat(new tool): Markdown Format Converter (#488) Fix #485 --------- Co-authored-by: Erich Schroeter --- locales/en.yml | 11 + src/tools/markdown-format-converter/index.ts | 25 ++ .../markdown-format-converter.e2e.spec.ts | 11 + .../markdown-format-converter.service.test.ts | 399 ++++++++++++++++++ .../markdown-format-converter.service.ts | 58 +++ .../markdown-format-converter.vue | 151 +++++++ .../strategies/ConverterStrategy.ts | 220 ++++++++++ .../strategies/DiscordStrategy.ts | 50 +++ .../strategies/GitHubStrategy.ts | 55 +++ .../strategies/JiraStrategy.ts | 175 ++++++++ .../strategies/LogseqStrategy.ts | 173 ++++++++ .../strategies/ObsidianStrategy.ts | 44 ++ .../strategies/SlackStrategy.ts | 128 ++++++ .../strategies/StackOverflowStrategy.ts | 40 ++ vite.config.ts | 3 + 15 files changed, 1543 insertions(+) create mode 100644 src/tools/markdown-format-converter/index.ts create mode 100644 src/tools/markdown-format-converter/markdown-format-converter.e2e.spec.ts create mode 100644 src/tools/markdown-format-converter/markdown-format-converter.service.test.ts create mode 100644 src/tools/markdown-format-converter/markdown-format-converter.service.ts create mode 100644 src/tools/markdown-format-converter/markdown-format-converter.vue create mode 100644 src/tools/markdown-format-converter/strategies/ConverterStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/DiscordStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/GitHubStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/JiraStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/LogseqStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/ObsidianStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/SlackStrategy.ts create mode 100644 src/tools/markdown-format-converter/strategies/StackOverflowStrategy.ts diff --git a/locales/en.yml b/locales/en.yml index a07c3a62..d7229a3b 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -2338,6 +2338,17 @@ tools: label-asterisk: Asterisk (*) label-underscore: Underscore (_) label-tilde: Tilde (~) + markdown-format-converter: + title: Format Converter + description: Convert between standard Markdown, Obsidian, Logseq, Slack, Jira, and other formats. + texts: + label-source-format: Source Format + label-target-format: Target Format + placeholder-input-markdown: Paste or type your standard, Obsidian, or Logseq Markdown here... + label-input-markdown: Input Markdown + label-converted-output: Converted Output + label-text: Text + label-preview: Preview ical-parser: title: ICAL File Parser description: Parse ICAL/ICS file to event display diff --git a/src/tools/markdown-format-converter/index.ts b/src/tools/markdown-format-converter/index.ts new file mode 100644 index 00000000..d9042b83 --- /dev/null +++ b/src/tools/markdown-format-converter/index.ts @@ -0,0 +1,25 @@ +import { defineAsyncComponent } from 'vue'; +import { defineTool } from '../tool'; +import { translate as t } from '@/plugins/i18n.plugin'; + +export const tool = defineTool({ + name: t('tools.markdown-format-converter.title'), + path: '/markdown-format-converter', + description: t('tools.markdown-format-converter.description'), + keywords: [ + 'markdown', + 'format', + 'converter', + 'slack', + 'discord', + 'jira', + 'github', + 'stackoverflow', + 'obsidian', + 'logseq', + ], + component: () => import('./markdown-format-converter.vue'), + icon: defineAsyncComponent(() => import('@vicons/tabler/es/Markdown')), + createdAt: new Date('2026-07-14'), + category: 'Markdown', +}); diff --git a/src/tools/markdown-format-converter/markdown-format-converter.e2e.spec.ts b/src/tools/markdown-format-converter/markdown-format-converter.e2e.spec.ts new file mode 100644 index 00000000..5ee42eb9 --- /dev/null +++ b/src/tools/markdown-format-converter/markdown-format-converter.e2e.spec.ts @@ -0,0 +1,11 @@ +import { test, expect } from '@playwright/test'; + +test.describe('Tool - Format Converter', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/markdown-format-converter'); + }); + + test('Has correct title', async ({ page }) => { + await expect(page).toHaveTitle('Format Converter - IT Tools'); + }); +}); diff --git a/src/tools/markdown-format-converter/markdown-format-converter.service.test.ts b/src/tools/markdown-format-converter/markdown-format-converter.service.test.ts new file mode 100644 index 00000000..1b03b954 --- /dev/null +++ b/src/tools/markdown-format-converter/markdown-format-converter.service.test.ts @@ -0,0 +1,399 @@ +import { describe, expect, it } from 'vitest'; +import { convertMarkdown } from './markdown-format-converter.service'; + +describe('markdown-format-converter', () => { + describe('Standard elements conversion (from GitHub/Standard Markdown)', () => { + const input = + '# Heading 1\nThis is **bold** and *italic* and ~~strikethrough~~.\nHere is `inline code`.\n\n[Google](https://google.com)'; + + it('should convert standard elements to Slack format', () => { + const output = convertMarkdown(input, 'github', 'slack'); + expect(output).toContain('*Heading 1*'); + expect(output).toContain('*bold*'); + expect(output).toContain('_italic_'); + expect(output).toContain('~strikethrough~'); + expect(output).toContain(''); + }); + + it('should convert standard elements to Discord format', () => { + const output = convertMarkdown(input, 'github', 'discord'); + expect(output).toContain('# Heading 1'); + expect(output).toContain('**bold**'); + expect(output).toContain('*italic*'); + expect(output).toContain('~~strikethrough~~'); + expect(output).toContain('[Google](https://google.com)'); + }); + + it('should convert standard elements to Jira format', () => { + const output = convertMarkdown(input, 'github', 'jira'); + expect(output).toContain('h1. Heading 1'); + expect(output).toContain('*bold*'); + expect(output).toContain('_italic_'); + expect(output).toContain('-strikethrough-'); + expect(output).toContain('[Google|https://google.com]'); + }); + + it('should convert standard elements to GitHub format', () => { + const output = convertMarkdown(input, 'github', 'github'); + expect(output).toContain('# Heading 1'); + expect(output).toContain('**bold**'); + expect(output).toContain('*italic*'); + expect(output).toContain('~~strikethrough~~'); + expect(output).toContain('[Google](https://google.com)'); + }); + }); + + describe('Wikilink conversion', () => { + const input1 = 'Check [[My Page]] for info.'; + const input2 = 'Check [[My Page|Alternate Text]] for info.'; + + it('should convert wikilink with Slack format', () => { + expect(convertMarkdown(input1, 'github', 'slack')).toContain('*My Page*'); + expect(convertMarkdown(input2, 'github', 'slack')).toContain('*Alternate Text*'); + }); + + it('should convert wikilink with Jira format', () => { + expect(convertMarkdown(input1, 'github', 'jira')).toContain('[My Page|My Page]'); + expect(convertMarkdown(input2, 'github', 'jira')).toContain('[Alternate Text|My Page]'); + }); + + it('should convert wikilink with GitHub format', () => { + expect(convertMarkdown(input1, 'github', 'github')).toContain('[My Page](my-page)'); + expect(convertMarkdown(input2, 'github', 'github')).toContain('[Alternate Text](my-page)'); + }); + + it('should convert wikilink with Obsidian format', () => { + expect(convertMarkdown(input1, 'github', 'obsidian')).toContain('[[My Page]]'); + expect(convertMarkdown(input2, 'github', 'obsidian')).toContain('[[My Page|Alternate Text]]'); + }); + }); + + describe('Callout conversion', () => { + const input = '> [!info] Tip of the day\n> This is some callout body content.\n> Line 2 of callout.'; + + it('should convert callout to Slack blockquotes', () => { + const output = convertMarkdown(input, 'github', 'slack'); + expect(output).toContain('> *[INFO] Tip of the day*'); + expect(output).toContain('> This is some callout body content.'); + }); + + it('should convert callout to Jira panel macro', () => { + const output = convertMarkdown(input, 'github', 'jira'); + expect(output).toContain( + '{panel:title=Tip of the day|borderStyle=solid|borderColor=#3572b0|titleBGColor=#cbe3ff|bgColor=#e0f0ff}', + ); + expect(output).toContain('This is some callout body content.'); + expect(output).toContain('{panel}'); + }); + + it('should convert callout to GitHub native alerts', () => { + const output = convertMarkdown(input, 'github', 'github'); + expect(output).toContain('> [!NOTE] > **Tip of the day**'); + expect(output).toContain('> This is some callout body content.'); + }); + + it('should preserve callout in Obsidian strategy', () => { + const output = convertMarkdown(input, 'github', 'obsidian'); + expect(output).toContain('> [!info] Tip of the day'); + expect(output).toContain('> This is some callout body content.'); + }); + }); + + describe('Lists conversion', () => { + it('should convert ordered lists correctly in standard formats', () => { + const input = '1. First item\n2. Second item\n3. Third item'; + + const githubOutput = convertMarkdown(input, 'github', 'github'); + expect(githubOutput).toContain('1. First item'); + expect(githubOutput).toContain('2. Second item'); + expect(githubOutput).toContain('3. Third item'); + + const jiraOutput = convertMarkdown(input, 'github', 'jira'); + expect(jiraOutput).toContain('# First item'); + expect(jiraOutput).toContain('# Second item'); + expect(jiraOutput).toContain('# Third item'); + }); + + it('should convert nested lists with correct indentation', () => { + const input = '- Parent item\n - Child item 1\n - Child item 2'; + const output = convertMarkdown(input, 'github', 'github'); + expect(output).toContain('- Parent item'); + expect(output).toContain(' - Child item 1'); + expect(output).toContain(' - Child item 2'); + }); + + it('should convert standard elements to Logseq outliner format', () => { + const input = '# Heading 1\nThis is a paragraph.\n1. Item 1\n2. Item 2'; + const output = convertMarkdown(input, 'github', 'logseq'); + expect(output).toContain('- # Heading 1'); + expect(output).toContain('- This is a paragraph.'); + expect(output).toContain('- 1. Item 1'); + expect(output).toContain('- 2. Item 2'); + }); + + it('should convert nested lists with correct separate line formatting in Logseq outliner format', () => { + const input = '- ordered list\n 1. item 1\n 2. item 2'; + const output = convertMarkdown(input, 'github', 'logseq'); + expect(output).toContain('- ordered list\n - 1. item 1\n - 2. item 2'); + }); + + it('should convert loose ordered lists correctly without shifting the content to the next line', () => { + const input = `1. **Item 1**\n - Detail 1\n\n2. **Item 2**\n - Detail 2`; + const output = convertMarkdown(input, 'github', 'github'); + expect(output).toContain('1. **Item 1**\n - Detail 1'); + expect(output).toContain('2. **Item 2**\n - Detail 2'); + }); + + it('should unescape special characters like single quotes in the final output', () => { + const input = "Jira's native prefix"; + const output = convertMarkdown(input, 'github', 'jira'); + expect(output).toContain("Jira's"); + }); + }); + + describe('Cross-format parsing and conversion', () => { + it('should convert Jira input to Slack output', () => { + const input = 'h1. Title\nThis is *bold* and _italic_ and {{inline code}}.\n{code:javascript}\nconst x = 5;\n{code}\n[Google|https://google.com]'; + const output = convertMarkdown(input, 'jira', 'slack'); + expect(output).toContain('*Title*'); + expect(output).toContain('*bold*'); + expect(output).toContain('_italic_'); + expect(output).toContain('`inline code`'); + expect(output).toContain('```\nconst x = 5;\n```'); + expect(output).toContain(''); + }); + + it('should convert Slack input to Jira output', () => { + const input = '*Title*\nThis is *bold* and _italic_ and ~strike~.\n'; + const output = convertMarkdown(input, 'slack', 'jira'); + expect(output).toContain('h1. Title'); + expect(output).toContain('*bold*'); + expect(output).toContain('_italic_'); + expect(output).toContain('-strike-'); + expect(output).toContain('[Google|https://google.com]'); + }); + + it('should convert Logseq outliner input to standard Markdown output', () => { + const input = '- # Heading 1\n- Normal paragraph.\n- Bullet parent\n - Bullet child\n- > blockquote'; + const output = convertMarkdown(input, 'logseq', 'github'); + expect(output).toContain('# Heading 1'); + expect(output).toContain('Normal paragraph.'); + expect(output).toContain('- Bullet parent\n - Bullet child'); + expect(output).toContain('> blockquote'); + }); + + it('should convert Logseq ordered lists properties correctly to standard GFM ordered list', () => { + const input = '- item 1\n logseq.order-list-type:: number\n- item 2\n logseq.order-list-type:: number'; + const output = convertMarkdown(input, 'logseq', 'github'); + expect(output).toContain('1. item 1'); + expect(output).toContain('2. item 2'); + }); + + it('should convert standard markdown lists and task lists correctly to Slack format with proper bullets, checkboxes, and 4-space nested indentation', () => { + const input = '- [x] implement feature\n- [ ] merge PR\n- ordered list\n 1. item 1\n 2. item 2'; + const output = convertMarkdown(input, 'github', 'slack'); + expect(output).toContain('✓ implement feature'); + expect(output).not.toContain('✓ [x]'); + expect(output).toContain('☐ merge PR'); + expect(output).not.toContain('☐ [ ]'); + expect(output).toContain('• ordered list\n 1. item 1\n 2. item 2'); + }); + }); + + describe('49-Combination Test Matrix for Standard Elements', () => { + const strategies = ['github', 'slack', 'discord', 'jira', 'stackoverflow', 'obsidian', 'logseq']; + + const fixtures: Record> = { + bold: { + github: { input: 'This is **bold text**.', output: 'This is **bold text**.' }, + slack: { input: 'This is *bold text*.', output: 'This is *bold text*.' }, + discord: { input: 'This is **bold text**.', output: 'This is **bold text**.' }, + jira: { input: 'This is *bold text*.', output: 'This is *bold text*.' }, + stackoverflow: { input: 'This is **bold text**.', output: 'This is **bold text**.' }, + obsidian: { input: 'This is **bold text**.', output: 'This is **bold text**.' }, + logseq: { input: '- This is **bold text**.', output: '- This is **bold text**.' }, + }, + italic: { + github: { input: 'This is *italic text*.', output: 'This is *italic text*.' }, + slack: { input: 'This is _italic text_.', output: 'This is _italic text_.' }, + discord: { input: 'This is *italic text*.', output: 'This is *italic text*.' }, + jira: { input: 'This is _italic text_.', output: 'This is _italic text_.' }, + stackoverflow: { input: 'This is *italic text*.', output: 'This is *italic text*.' }, + obsidian: { input: 'This is *italic text*.', output: 'This is *italic text*.' }, + logseq: { input: '- This is *italic text*.', output: '- This is *italic text*.' }, + }, + strikethrough: { + github: { input: 'This is ~~strikethrough text~~.', output: 'This is ~~strikethrough text~~.' }, + slack: { input: 'This is ~strikethrough text~.', output: 'This is ~strikethrough text~.' }, + discord: { input: 'This is ~~strikethrough text~~.', output: 'This is ~~strikethrough text~~.' }, + jira: { input: 'This is -strikethrough text-.', output: 'This is -strikethrough text-.' }, + stackoverflow: { input: 'This is ~~strikethrough text~~.', output: 'This is ~~strikethrough text~~.' }, + obsidian: { input: 'This is ~~strikethrough text~~.', output: 'This is ~~strikethrough text~~.' }, + logseq: { input: '- This is ~~strikethrough text~~.', output: '- This is ~~strikethrough text~~.' }, + }, + code: { + github: { input: 'This is `inline code`.', output: 'This is `inline code`.' }, + slack: { input: 'This is `inline code`.', output: 'This is `inline code`.' }, + discord: { input: 'This is `inline code`.', output: 'This is `inline code`.' }, + jira: { input: 'This is {{inline code}}.', output: 'This is {{inline code}}.' }, + stackoverflow: { input: 'This is `inline code`.', output: 'This is `inline code`.' }, + obsidian: { input: 'This is `inline code`.', output: 'This is `inline code`.' }, + logseq: { input: '- This is `inline code`.', output: '- This is `inline code`.' }, + }, + link: { + github: { input: 'Check [Google](https://google.com).', output: 'Check [Google](https://google.com).' }, + slack: { input: 'Check .', output: 'Check .' }, + discord: { input: 'Check [Google](https://google.com).', output: 'Check [Google](https://google.com).' }, + jira: { input: 'Check [Google|https://google.com].', output: 'Check [Google|https://google.com].' }, + stackoverflow: { input: 'Check [Google](https://google.com).', output: 'Check [Google](https://google.com).' }, + obsidian: { input: 'Check [Google](https://google.com).', output: 'Check [Google](https://google.com).' }, + logseq: { input: '- Check [Google](https://google.com).', output: '- Check [Google](https://google.com).' }, + }, + heading1: { + github: { input: '# Heading 1', output: '# Heading 1' }, + slack: { input: '*Heading 1*', output: '*Heading 1*' }, + discord: { input: '# Heading 1', output: '# Heading 1' }, + jira: { input: 'h1. Heading 1', output: 'h1. Heading 1' }, + stackoverflow: { input: '# Heading 1', output: '# Heading 1' }, + obsidian: { input: '# Heading 1', output: '# Heading 1' }, + logseq: { input: '- # Heading 1', output: '- # Heading 1' }, + }, + }; + + for (const source of strategies) { + for (const target of strategies) { + it(`should convert standard elements from ${source} to ${target}`, () => { + for (const [_elementName, elementMap] of Object.entries(fixtures)) { + const sourceFixture = elementMap[source]; + const targetFixture = elementMap[target]; + + const output = convertMarkdown(sourceFixture.input, source, target); + expect(output).toContain(targetFixture.output); + } + }); + } + } + }); + + describe('Targeted Strategy-Specific Edge Cases', () => { + describe('Discord Specifics', () => { + it('should map callout alerts to correct Discord emojis and bold titles', () => { + const input = '> [!tip] Check this out\n> Some useful tip content.'; + const output = convertMarkdown(input, 'github', 'discord'); + expect(output).toContain('> **💡 [TIP] Check this out**'); + expect(output).toContain('> Some useful tip content.'); + + const inputWarning = '> [!warning] Alert\n> Be careful.'; + const outputWarning = convertMarkdown(inputWarning, 'github', 'discord'); + expect(outputWarning).toContain('> **⚠️ [WARNING] Alert**'); + }); + + it('should format wikilinks as standard markdown links', () => { + const input = 'Check [[My Page]]'; + const output = convertMarkdown(input, 'github', 'discord'); + expect(output).toContain('[My Page](My Page)'); + }); + }); + + describe('StackOverflow Specifics', () => { + it('should fallback callouts to standard blockquotes with bold headers', () => { + const input = '> [!info] Some title\n> Info content here.'; + const output = convertMarkdown(input, 'github', 'stackoverflow'); + expect(output).toContain('> **[INFO] Some title**'); + expect(output).toContain('> Info content here.'); + }); + + it('should convert wikilinks to standard markdown links', () => { + const input = 'Check [[Page Name|Custom Label]]'; + const output = convertMarkdown(input, 'github', 'stackoverflow'); + expect(output).toContain('[Custom Label](Page Name)'); + }); + }); + + describe('Jira Specifics', () => { + it('should convert code blocks with languages between GFM and Jira formats', () => { + const gfmInput = '```javascript\nconst x = 42;\n```'; + const jiraOutput = convertMarkdown(gfmInput, 'github', 'jira'); + expect(jiraOutput).toContain('{code:javascript}\nconst x = 42;\n{code}'); + + const jiraInput = '{code:typescript}\nconst y = "test";\n{code}'; + const gfmOutput = convertMarkdown(jiraInput, 'jira', 'github'); + expect(gfmOutput).toContain('```typescript\nconst y = "test";\n```'); + }); + + it('should convert nested list structures correctly', () => { + const gfmInput = '- Item 1\n - Nested Item 1a\n - Nested Item 1a.1'; + const jiraOutput = convertMarkdown(gfmInput, 'github', 'jira'); + expect(jiraOutput).toContain('* Item 1\n* Nested Item 1a\n* Nested Item 1a.1'); + + const jiraInput = '# Ordered 1\n## Ordered 1.1\n### Ordered 1.1.1'; + const gfmOutput = convertMarkdown(jiraInput, 'jira', 'github'); + expect(gfmOutput).toContain('1. Ordered 1\n2. Ordered 1.1\n 1. Ordered 1.1.1'); + }); + + it('should convert images back and forth correctly', () => { + const gfmInput = '![Alt Text](https://example.com/image.png)'; + const jiraOutput = convertMarkdown(gfmInput, 'github', 'jira'); + expect(jiraOutput).toContain('!https://example.com/image.png!'); + + const jiraInput = '!https://example.com/test.png!'; + const gfmOutput = convertMarkdown(jiraInput, 'jira', 'github'); + expect(gfmOutput).toContain('![](https://example.com/test.png)'); + }); + }); + + describe('Slack Specifics', () => { + it('should auto-link bare links and Slack style link targets', () => { + const slackInput = ''; + const gfmOutput = convertMarkdown(slackInput, 'slack', 'github'); + expect(gfmOutput).toContain('[https://google.com](https://google.com)'); + }); + + it('should format standard markdown images into Slack link syntax with fallbacks', () => { + const gfmInput = '![An image](https://example.com/img.jpg)'; + const slackOutput = convertMarkdown(gfmInput, 'github', 'slack'); + expect(slackOutput).toContain(''); + }); + + it('should retain nested bullet formatting and proper Slack indentation', () => { + const gfmInput = '- Bullet A\n - Bullet B'; + const slackOutput = convertMarkdown(gfmInput, 'github', 'slack'); + expect(slackOutput).toContain('• Bullet A\n • Bullet B'); + }); + }); + + describe('Logseq Specifics', () => { + it('should strip Logseq block properties from parsed outputs', () => { + const logseqInput = '- Some block item\n id:: 65161c16-86d1-41fb-992a-fa1fef9013e8\n collapsed:: true'; + const gfmOutput = convertMarkdown(logseqInput, 'logseq', 'github'); + expect(gfmOutput).toEqual('Some block item'); + }); + + it('should wrap blockquotes inside a bullet point block natively', () => { + const gfmInput = '> This is a quote'; + const logseqOutput = convertMarkdown(gfmInput, 'github', 'logseq'); + expect(logseqOutput).toContain('- > - This is a quote'); + }); + }); + + describe('Obsidian Specifics', () => { + it('should parse and format multi-line custom Obsidian callouts', () => { + const obsidianInput = '> [!info] Tip of the day\n> This is line 1.\n> This is line 2.'; + const gfmOutput = convertMarkdown(obsidianInput, 'obsidian', 'github'); + expect(gfmOutput).toContain('> [!NOTE] > **Tip of the day**'); + expect(gfmOutput).toContain('> This is line 1.'); + expect(gfmOutput).toContain('> This is line 2.'); + }); + + it('should preserve and render internal Obsidian wikilinks with alias targets', () => { + const inputWithAlias = '[[Target Page|Alias Text]]'; + const obsidianOutput = convertMarkdown(inputWithAlias, 'github', 'obsidian'); + expect(obsidianOutput).toContain('[[Target Page|Alias Text]]'); + + const inputWithoutAlias = '[[Target Page]]'; + const obsidianOutputNoAlias = convertMarkdown(inputWithoutAlias, 'github', 'obsidian'); + expect(obsidianOutputNoAlias).toContain('[[Target Page]]'); + }); + }); + }); +}); diff --git a/src/tools/markdown-format-converter/markdown-format-converter.service.ts b/src/tools/markdown-format-converter/markdown-format-converter.service.ts new file mode 100644 index 00000000..35e4f6a0 --- /dev/null +++ b/src/tools/markdown-format-converter/markdown-format-converter.service.ts @@ -0,0 +1,58 @@ +import { Marked } from 'marked'; +import { getMarkdownExtensions, type ConverterStrategy } from './strategies/ConverterStrategy'; +import { SlackStrategy } from './strategies/SlackStrategy'; +import { DiscordStrategy } from './strategies/DiscordStrategy'; +import { JiraStrategy } from './strategies/JiraStrategy'; +import { GitHubStrategy } from './strategies/GitHubStrategy'; +import { StackOverflowStrategy } from './strategies/StackOverflowStrategy'; +import { ObsidianStrategy } from './strategies/ObsidianStrategy'; +import { LogseqStrategy } from './strategies/LogseqStrategy'; + +export const strategies: ConverterStrategy[] = [ + new SlackStrategy(), + new DiscordStrategy(), + new JiraStrategy(), + new GitHubStrategy(), + new StackOverflowStrategy(), + new ObsidianStrategy(), + new LogseqStrategy(), +]; + +function unescapeHtml(text: string): string { + return text + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&'); +} + +export function convertMarkdown(input: string, sourceStrategyId: string, targetStrategyId: string): string { + if (!input) { + return ''; + } + + const sourceStrategy = strategies.find((s) => s.id === sourceStrategyId) || strategies.find((s) => s.id === 'github') || strategies[0]; + const targetStrategy = strategies.find((s) => s.id === targetStrategyId) || strategies[0]; + const tokens = sourceStrategy.lex(input); + + const markedInstance = new Marked(); + + // Configure marked instance with target strategy and its extensions + markedInstance.use({ + extensions: getMarkdownExtensions(targetStrategy), + renderer: targetStrategy.getRenderer(), + // Standard option overrides + gfm: true, + breaks: true, + }); + + try { + const parsed = markedInstance.parser(tokens) as string; + // Post-process the result to trim any redundant multiple newlines from marked's parsing + return unescapeHtml(parsed.trim()); + } catch (err) { + console.error('Failed to parse and convert markdown:', err); + return input; + } +} diff --git a/src/tools/markdown-format-converter/markdown-format-converter.vue b/src/tools/markdown-format-converter/markdown-format-converter.vue new file mode 100644 index 00000000..fe43d912 --- /dev/null +++ b/src/tools/markdown-format-converter/markdown-format-converter.vue @@ -0,0 +1,151 @@ + + + + + diff --git a/src/tools/markdown-format-converter/strategies/ConverterStrategy.ts b/src/tools/markdown-format-converter/strategies/ConverterStrategy.ts new file mode 100644 index 00000000..8f5e2a11 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/ConverterStrategy.ts @@ -0,0 +1,220 @@ +import { Renderer, type Token } from 'marked'; + +export interface ConverterStrategy { + id: string; + name: string; + getRenderer(): Renderer; + lex(input: string): Token[]; + renderWikilink?(target: string, text: string): string; + renderCallout?(type: string, title: string, content: string): string; +} + +/** + * Global extensions to parse custom dialects (Obsidian/Logseq) + */ +export function getMarkdownExtensions(strategy: ConverterStrategy) { + return [ + { + name: 'wikilink', + level: 'inline' as const, + start(src: string) { return src.indexOf('[['); }, + tokenizer(src: string) { + const rule = /^\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/; + const match = rule.exec(src); + if (match) { + return { + type: 'wikilink', + raw: match[0], + target: match[1].trim(), + text: (match[2] || match[1]).trim(), + }; + } + }, + renderer(token: any) { + if (strategy.renderWikilink) { + return strategy.renderWikilink(token.target, token.text); + } + // Default standard markdown fallback (converts wikilink to standard markdown link) + return `[${token.text}](${token.target})`; + }, + }, + { + name: 'callout', + level: 'block' as const, + start(src: string) { return src.indexOf('>'); }, + tokenizer(src: string) { + const rule = /^> \[!([a-zA-Z-]+)\]([^\n]*)\n?((?:>.*\n?)*)/; + const match = rule.exec(src); + if (match) { + const calloutType = match[1].trim(); + const title = match[2].trim(); + const content = match[3] + .split('\n') + .map(line => line.replace(/^>\s?/, '')) + .join('\n'); + return { + type: 'callout', + raw: match[0], + calloutType, + title, + content, + }; + } + }, + renderer(token: any) { + if (strategy.renderCallout) { + return strategy.renderCallout(token.calloutType, token.title, token.content); + } + // Default fallback (renders as standard blockquote with type header) + const header = token.title + ? `**[${token.calloutType.toUpperCase()}] ${token.title}**\n` + : `**[${token.calloutType.toUpperCase()}]**\n`; + const text = `${header}${token.content}`; + const lines = text.trim().split('\n').map(line => `> ${line}`).join('\n'); + return `\n${lines}\n`; + }, + }, + ]; +} + +/** + * A Base Renderer that outputs standard Markdown instead of HTML. + * Other specific strategies (Slack, Jira, Discord, etc.) will extend this + * and override only the elements they need to format differently. + */ +export class PlainRenderer extends Renderer { + constructor() { + super(); + + // Walk the entire prototype chain and copy/bind methods to the instance as direct own properties. + // This is CRITICAL for marked.use() which uses Object.assign/spread, completely ignoring + // inherited prototype methods of classes. + let currentProto = Object.getPrototypeOf(this); + const boundKeys = new Set(); + + while (currentProto && currentProto !== Object.prototype) { + for (const key of Object.getOwnPropertyNames(currentProto)) { + if (key !== 'constructor' && !boundKeys.has(key)) { + const value = (this as any)[key]; + if (typeof value === 'function') { + (this as any)[key] = value.bind(this); + boundKeys.add(key); + } + } + } + currentProto = Object.getPrototypeOf(currentProto); + } + } + + override code(code: string, infostring: string | undefined, escaped: boolean): string { + const lang = (infostring || '').match(/^\S*/)?.[0] || ''; + return `\n\`\`\`${lang}\n${code}\n\`\`\`\n`; + } + + override blockquote(quote: string): string { + const lines = quote + .trim() + .split('\n') + .map(line => `> ${line}`) + .join('\n'); + return `\n${lines}\n`; + } + + override html(html: string, block?: boolean): string { + return html; + } + + override heading(text: string, level: number, raw: string): string { + return `\n${'#'.repeat(level)} ${text}\n`; + } + + override hr(): string { + return '\n---\n'; + } + + override list(body: string, ordered: boolean, start: number): string { + if (ordered) { + let index = start; + const lines = body.split('\n'); + const formattedLines = lines.map(line => { + // Only convert lines that start with our custom item bullet prefix directly + if (line.startsWith('- ')) { + return line.replace(/^- /, `${index++}. `); + } + return line; + }); + return `\n${formattedLines.join('\n')}`; + } + return `\n${body}`; + } + + override listitem(text: string, task: boolean, checked: boolean): string { + let prefix = '- '; + if (task) { + prefix = checked ? '- [x] ' : '- [ ] '; + } + + const lines = text.trim().split('\n').filter(line => line.trim() !== ''); + const firstLine = lines[0].trim(); + const otherLines = lines + .slice(1) + .map(line => ` ${line}`) + .join('\n'); + + const formatted = otherLines ? `${firstLine}\n${otherLines}` : firstLine; + return `${prefix}${formatted}\n`; + } + + override checkbox(checked: boolean): string { + return ''; + } + + override paragraph(text: string): string { + return `\n${text}\n`; + } + + override table(header: string, body: string): string { + return `\n${header}${body}\n`; + } + + override tablerow(content: string): string { + return `| ${content}\n`; + } + + override tablecell(content: string, flags: { header: boolean; align: 'center' | 'left' | 'right' | null }): string { + return `${content} |`; + } + + override strong(text: string): string { + return `**${text}**`; + } + + override em(text: string): string { + return `*${text}*`; + } + + override codespan(text: string): string { + return `\`${text}\``; + } + + override br(): string { + return '\n'; + } + + override del(text: string): string { + return `~~${text}~~`; + } + + override link(href: string, title: string | null | undefined, text: string): string { + return `[${text}](${href})`; + } + + override image(href: string, title: string | null | undefined, text: string): string { + const titleAttr = title ? ` "${title}"` : ''; + return `![${text}](${href}${titleAttr})`; + } + + override text(text: string): string { + return text; + } +} diff --git a/src/tools/markdown-format-converter/strategies/DiscordStrategy.ts b/src/tools/markdown-format-converter/strategies/DiscordStrategy.ts new file mode 100644 index 00000000..cea9e27d --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/DiscordStrategy.ts @@ -0,0 +1,50 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +class DiscordRenderer extends PlainRenderer { + // Discord supports standard markdown closely +} + +export class DiscordStrategy implements ConverterStrategy { + id = 'discord'; + name = 'Discord'; + + getRenderer() { + return new DiscordRenderer(); + } + + lex(input: string): Token[] { + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(input); + } + + renderWikilink(target: string, text: string): string { + // Discord supports links in some contexts, so standard markdown link is appropriate + return `[${text}](${target})`; + } + + renderCallout(type: string, title: string, content: string): string { + // Discord doesn't have callouts, we can render as a nice blockquote with emoji or type header + const emojiMap: Record = { + info: 'ℹ️', + note: '📝', + tip: '💡', + warning: '⚠️', + danger: '🔥', + todo: '✅', + }; + const emoji = emojiMap[type.toLowerCase()] || '📝'; + const header = title ? `**${emoji} [${type.toUpperCase()}] ${title}**\n` : `**${emoji} [${type.toUpperCase()}]**\n`; + const fullText = `${header}${content}`; + return `\n${fullText + .trim() + .split('\n') + .map((l) => `> ${l}`) + .join('\n')}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/GitHubStrategy.ts b/src/tools/markdown-format-converter/strategies/GitHubStrategy.ts new file mode 100644 index 00000000..5a9c7fd1 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/GitHubStrategy.ts @@ -0,0 +1,55 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +class GitHubRenderer extends PlainRenderer { + // Matches standard GitHub Flavored Markdown (GFM) +} + +export class GitHubStrategy implements ConverterStrategy { + id = 'github'; + name = 'GitHub'; + + getRenderer() { + return new GitHubRenderer(); + } + + lex(input: string): Token[] { + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(input); + } + + renderWikilink(target: string, text: string): string { + // Converts WikiLinks to standard GFM markdown links + // Sluggify target to be URL-friendly (e.g. "Some Page" -> "some-page" or "some-page.md") + const href = target.toLowerCase().replace(/\s+/g, '-'); + return `[${text}](${href})`; + } + + renderCallout(type: string, title: string, content: string): string { + // GitHub supports native alert blockquotes: > [!NOTE], > [!TIP], > [!IMPORTANT], > [!WARNING], > [!CAUTION] + const validTypes = ['NOTE', 'TIP', 'IMPORTANT', 'WARNING', 'CAUTION']; + let alertType = type.toUpperCase(); + if (!validTypes.includes(alertType)) { + if (alertType === 'DANGER') { + alertType = 'CAUTION'; + } else { + alertType = 'NOTE'; + } + } + + const headerLine = `> [!${alertType}]`; + const titleLine = title ? ` > **${title}**` : ''; + const bodyLines = content + .trim() + .split('\n') + .map((line) => `> ${line}`) + .join('\n'); + + return `\n${headerLine}${titleLine}\n${bodyLines}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/JiraStrategy.ts b/src/tools/markdown-format-converter/strategies/JiraStrategy.ts new file mode 100644 index 00000000..86ac4910 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/JiraStrategy.ts @@ -0,0 +1,175 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +function jiraToMarkdown(input: string): string { + let output = input; + + // Code blocks: {code:lang}content{code} or {code}content{code} + output = output.replace(/\{code(?::([a-zA-Z0-9+-]+))?\}([\s\S]*?)\{code\}/g, (_, lang, content) => { + const l = lang ? lang.trim() : ''; + return `\n\`\`\`${l}\n${content.trim()}\n\`\`\`\n`; + }); + + // Blockquotes: {quote}content{quote} + output = output.replace(/\{quote\}([\s\S]*?)\{quote\}/g, (_, content) => { + const lines = content.trim().split('\n').map((line: string) => `> ${line}`).join('\n'); + return `\n${lines}\n`; + }); + + // Jira Lists (Do this before Heading/Bold replacement so `#` list bullets aren't mistaken for markdown headings) + const lines = output.split('\n'); + const convertedLines = lines.map(line => { + // Unordered nested + const unorderedMatch = line.match(/^(\*+)\s+(.+)$/); + if (unorderedMatch) { + const depth = unorderedMatch[1].length; + return `${' '.repeat(depth - 1)}* ${unorderedMatch[2]}`; + } + + // Ordered nested + const orderedMatch = line.match(/^(#+)\s+(.+)$/); + if (orderedMatch) { + const depth = orderedMatch[1].length; + return `${' '.repeat(depth - 1)}1. ${orderedMatch[2]}`; + } + + return line; + }); + output = convertedLines.join('\n'); + + // Headings: h1. Text -> # Text + output = output.replace(/^(?:[ \t]*)h([1-6])\.\s*(.+)$/gm, (_, level, text) => { + return `${'#'.repeat(parseInt(level, 10))} ${text}`; + }); + + // Links: [Text|URL] -> [Text](URL) + output = output.replace(/\[([^\]|]+)\|([^\]|]+)\]/g, '[$1]($2)'); + // Links without text: [URL] (negative lookahead to ensure we don't match standard markdown links like [Text](URL)) + output = output.replace(/\[([^\]|]+)\](?!\()/g, '[$1]($1)'); + + // Images: !URL! -> ![](URL) + output = output.replace(/!([^!\s]+)!/g, '![]($1)'); + + // Bold: *bold* -> **bold** (excluding lines starting with asterisk list bullets) + output = output.replace(/(? *italic* + output = output.replace(/(?<=^|\s|[.,;:!?])_([^_]+)_(?=$|\s|[.,;:!?])/g, '*$1*'); + + // Strikethrough: -del- -> ~~del~~ + output = output.replace(/(?<=^|\s|[.,;:!?])-([^-]+)-(?=$|\s|[.,;:!?])/g, '~~$1~~'); + + // Inline code: {{code}} -> `code` + output = output.replace(/\{\{([^}]+)\}\}/g, '`$1`'); + + return output; +} + +class JiraRenderer extends PlainRenderer { + override strong(text: string): string { + return `*${text}*`; + } + + override em(text: string): string { + return `_${text}_`; + } + + override del(text: string): string { + return `-${text}-`; + } + + override codespan(text: string): string { + return `{{${text}}}`; + } + + override code(code: string, infostring: string | undefined): string { + const lang = (infostring || '').match(/^\S*/)?.[0] || ''; + const langOption = lang ? `:${lang}` : ''; + return `\n{code${langOption}}\n${code}\n{code}\n`; + } + + override blockquote(quote: string): string { + return `\n{quote}\n${quote.trim()}\n{quote}\n`; + } + + override heading(text: string, level: number): string { + // Jira uses h1., h2. etc. + const cappedLevel = Math.min(Math.max(level, 1), 6); + return `\nh${cappedLevel}. ${text}\n`; + } + + override hr(): string { + return '\n----\n'; + } + + override list(body: string, ordered: boolean, start: number): string { + if (ordered) { + const lines = body.split('\n'); + const formattedLines = lines.map(line => { + if (line.startsWith('* ')) { + return line.replace(/^\* /, '# '); + } + return line; + }); + return `\n${formattedLines.join('\n')}`; + } + return `\n${body}`; + } + + override listitem(text: string, task: boolean, checked: boolean): string { + // Jira list items use * or #. Nested is handles by ** or ##. + // For single level, return standard bullet: + const prefix = task ? (checked ? '(/) ' : '(x) ') : ''; + return `* ${prefix}${text.trim()}\n`; + } + + override link(href: string, title: string | null | undefined, text: string): string { + if (text && text !== href) { + return `[${text}|${href}]`; + } + return `[${href}]`; + } + + override image(href: string, title: string | null | undefined, text: string): string { + return `!${href}!`; + } +} + +export class JiraStrategy implements ConverterStrategy { + id = 'jira'; + name = 'Jira'; + + getRenderer() { + return new JiraRenderer(); + } + + lex(input: string): Token[] { + const markdown = jiraToMarkdown(input); + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(markdown); + } + + renderWikilink(target: string, text: string): string { + return `[${text}|${target}]`; + } + + renderCallout(type: string, title: string, content: string): string { + // Jira has panel macro for callout panel: + // {panel:title=Title|borderStyle=dashed|borderColor=#ccc|titleBGColor=#F7F7F7|bgColor=#FFF} + const colorMap: Record = { + info: { border: '#3572b0', bg: '#e0f0ff', titleBg: '#cbe3ff' }, + note: { border: '#cccccc', bg: '#f7f7f7', titleBg: '#eeeeee' }, + tip: { border: '#148214', bg: '#e0ffe0', titleBg: '#cbebc6' }, + warning: { border: '#d04437', bg: '#fff0f0', titleBg: '#ffd0d0' }, + danger: { border: '#d04437', bg: '#fff0f0', titleBg: '#ffd0d0' }, + }; + const colors = colorMap[type.toLowerCase()] || colorMap.note; + const titleAttr = title ? `title=${title}|` : `title=${type.toUpperCase()}|`; + return `\n{panel:${titleAttr}borderStyle=solid|borderColor=${colors.border}|titleBGColor=${colors.titleBg}|bgColor=${colors.bg}}\n${content.trim()}\n{panel}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/LogseqStrategy.ts b/src/tools/markdown-format-converter/strategies/LogseqStrategy.ts new file mode 100644 index 00000000..97bfeffe --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/LogseqStrategy.ts @@ -0,0 +1,173 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +function logseqToMarkdown(input: string): string { + const lines = input.split('\n'); + const processedLines: string[] = []; + + const blockMetadata = lines.map((line, index) => { + const match = line.match(/^(\s*)-\s+(.*)$/); + const isProperty = line.trim().includes('::'); + return { + line, + index, + isBlock: !!match && !isProperty, + indent: match ? match[1].length : 0, + content: match ? match[2] : line, + isProperty, + isOrdered: false, + }; + }); + + // Mark blocks as ordered if they are followed by logseq.order-list-type:: number + for (let i = 0; i < blockMetadata.length; i++) { + if (blockMetadata[i].isProperty && blockMetadata[i].line.includes('logseq.order-list-type:: number')) { + for (let j = i - 1; j >= 0; j--) { + if (blockMetadata[j].isBlock) { + blockMetadata[j].isOrdered = true; + break; + } + } + } + } + + const listCounters: Record = {}; + + for (let i = 0; i < blockMetadata.length; i++) { + const meta = blockMetadata[i]; + + if (meta.isProperty) { + continue; + } + + if (!meta.isBlock) { + processedLines.push(meta.line); + continue; + } + + let hasChildren = false; + for (let j = i + 1; j < blockMetadata.length; j++) { + const nextMeta = blockMetadata[j]; + if (nextMeta.isBlock) { + if (nextMeta.indent > meta.indent) { + hasChildren = true; + } + break; + } + } + + const indentStr = ' '.repeat(meta.indent); + + if (meta.isOrdered) { + if (!listCounters[meta.indent]) { + listCounters[meta.indent] = 1; + } + const num = listCounters[meta.indent]++; + processedLines.push(`${indentStr}${num}. ${meta.content}`); + } else { + listCounters[meta.indent] = 0; + + if (meta.indent > 0) { + processedLines.push(`${indentStr}- ${meta.content}`); + } else { + if (meta.content.trim().startsWith('#')) { + processedLines.push(meta.content); + } else if (meta.content.trim().startsWith('>')) { + processedLines.push(meta.content); + } else if (hasChildren) { + processedLines.push(`- ${meta.content}`); + } else { + processedLines.push(meta.content); + } + } + } + } + + return processedLines.join('\n'); +} + +class LogseqRenderer extends PlainRenderer { + override heading(text: string, level: number): string { + // Logseq headings must be prefixed with a bullet point + return `- ${'#'.repeat(level)} ${text}\n`; + } + + override paragraph(text: string): string { + // Every paragraph/block in Logseq is natively a bullet point + return `- ${text}\n`; + } + + override code(code: string, infostring: string | undefined): string { + const lang = (infostring || '').match(/^\S*/)?.[0] || ''; + return `- \`\`\`${lang}\n${code.trim()}\n\`\`\`\n`; + } + + override blockquote(quote: string): string { + // Render blockquote nested inside a bullet point + const lines = quote + .trim() + .split('\n') + .map(line => line.replace(/^>\s?/, '').trim()); + return `- > ${lines.join('\n> ')}\n`; + } + + override hr(): string { + return `- ---\n`; + } + + override list(body: string, ordered: boolean, start: number): string { + if (ordered) { + let index = start; + const lines = body.split('\n'); + const formattedLines = lines.map(line => { + // Convert the bullet list items to manual numbered list items nested in bullets + if (line.startsWith('- ')) { + return line.replace(/^- /, `- ${index++}. `); + } + return line; + }); + return `\n${formattedLines.join('\n')}`; + } + return `\n${body}`; + } +} + +export class LogseqStrategy implements ConverterStrategy { + id = 'logseq'; + name = 'Logseq'; + + getRenderer() { + return new LogseqRenderer(); + } + + lex(input: string): Token[] { + const markdown = logseqToMarkdown(input); + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(markdown); + } + + renderWikilink(target: string, text: string): string { + // Logseq uses double brackets for pages, but supports text links too + if (text === target) { + return `[[${target}]]`; + } + return `[${text}](${target})`; + } + + renderCallout(type: string, title: string, content: string): string { + // Logseq doesn't have callouts natively, we format as a bullet with a blockquote + const header = title ? `**[${type.toUpperCase()}] ${title}**\n` : `**[${type.toUpperCase()}]**\n`; + const fullText = `${header}${content}`; + const lines = fullText + .trim() + .split('\n') + .map(l => `> ${l}`) + .join('\n'); + return `- ${lines}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/ObsidianStrategy.ts b/src/tools/markdown-format-converter/strategies/ObsidianStrategy.ts new file mode 100644 index 00000000..549f3604 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/ObsidianStrategy.ts @@ -0,0 +1,44 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +class ObsidianRenderer extends PlainRenderer { + // Mostly standard GFM +} + +export class ObsidianStrategy implements ConverterStrategy { + id = 'obsidian'; + name = 'Obsidian'; + + getRenderer() { + return new ObsidianRenderer(); + } + + lex(input: string): Token[] { + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(input); + } + + renderWikilink(target: string, text: string): string { + if (text === target) { + return `[[${target}]]`; + } + return `[[${target}|${text}]]`; + } + + renderCallout(type: string, title: string, content: string): string { + const typeLabel = `[!${type.toLowerCase()}]`; + const titleText = title ? ` ${title}` : ''; + const bodyLines = content + .trim() + .split('\n') + .map((line) => `> ${line}`) + .join('\n'); + + return `\n> ${typeLabel}${titleText}\n${bodyLines}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/SlackStrategy.ts b/src/tools/markdown-format-converter/strategies/SlackStrategy.ts new file mode 100644 index 00000000..7666a542 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/SlackStrategy.ts @@ -0,0 +1,128 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +function slackToMarkdown(input: string): string { + let output = input; + + // Convert links: -> [Example](http://example.com) + output = output.replace(/<([^>|]+)\|([^>]+)>/g, '[$2]($1)'); + + // Convert links without text: -> [http://example.com](http://example.com) + output = output.replace(/<([^>]+)>/g, '[$1]($1)'); + + // Headings: Slack uses bold lines as headings + output = output.replace(/^(?:[ \t]*)\*([^*]+)\*(?:[ \t]*)$/gm, '# $1'); + + // Bold: Slack *bold* -> GFM **bold** + output = output.replace(/(?<=^|\s|[.,;:!?])\*([^*]+)\*(?=$|\s|[.,;:!?])/g, '**$1**'); + + // Strikethrough: Slack ~strike~ -> GFM ~~strike~~ + output = output.replace(/(?<=^|\s|[.,;:!?])~([^~]+)~(?=$|\s|[.,;:!?])/g, '~~$1~~'); + + // Italics: Slack _italic_ -> GFM *italic* + output = output.replace(/(?<=^|\s|[.,;:!?])_([^_]+)_(?=$|\s|[.,;:!?])/g, '*$1*'); + + return output; +} + +class SlackRenderer extends PlainRenderer { + override strong(text: string): string { + return `*${text}*`; + } + + override em(text: string): string { + return `_${text}_`; + } + + override del(text: string): string { + return `~${text}~`; + } + + override link(href: string, title: string | null | undefined, text: string): string { + return `<${href}|${text}>`; + } + + override image(href: string, title: string | null | undefined, text: string): string { + return `<${href}|${text || 'Image'}>`; + } + + override heading(text: string, level: number): string { + // Slack has no native headings, so we format as strong text with double newlines + return `\n*${text}*\n`; + } + + override code(code: string): string { + // Slack does not support language formatting on block backticks + return `\n\`\`\`\n${code}\n\`\`\`\n`; + } + + override list(body: string, ordered: boolean, start: number): string { + if (ordered) { + let index = start; + const lines = body.split('\n'); + const formattedLines = lines.map(line => { + if (line.startsWith('• ')) { + return line.replace(/^• /, `${index++}. `); + } + const match = line.match(/^(\s+)•\s+(.*)$/); + if (match) { + return `${match[1]}${index++}. ${match[2]}`; + } + return line; + }); + return `\n${formattedLines.join('\n')}`; + } + return `\n${body}`; + } + + override listitem(text: string, task: boolean, checked: boolean): string { + let prefix = '• '; + if (task) { + prefix = checked ? '✓ ' : '☐ '; + } + + const lines = text.trim().split('\n').filter(line => line.trim() !== ''); + const firstLine = lines[0].trim(); + const otherLines = lines + .slice(1) + .map(line => ` ${line}`) + .join('\n'); + + const formatted = otherLines ? `${firstLine}\n${otherLines}` : firstLine; + return `${prefix}${formatted}\n`; + } +} + +export class SlackStrategy implements ConverterStrategy { + id = 'slack'; + name = 'Slack'; + + getRenderer() { + return new SlackRenderer(); + } + + lex(input: string): Token[] { + const markdown = slackToMarkdown(input); + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(markdown); + } + + renderWikilink(target: string, text: string): string { + return `*${text}*`; + } + + renderCallout(type: string, title: string, content: string): string { + const header = title ? `*[${type.toUpperCase()}] ${title}*\n` : `*[${type.toUpperCase()}]*\n`; + const fullText = `${header}${content}`; + return `\n${fullText + .trim() + .split('\n') + .map((l) => `> ${l}`) + .join('\n')}\n`; + } +} diff --git a/src/tools/markdown-format-converter/strategies/StackOverflowStrategy.ts b/src/tools/markdown-format-converter/strategies/StackOverflowStrategy.ts new file mode 100644 index 00000000..3026e1c3 --- /dev/null +++ b/src/tools/markdown-format-converter/strategies/StackOverflowStrategy.ts @@ -0,0 +1,40 @@ +import { Marked, type Token } from 'marked'; +import { type ConverterStrategy, PlainRenderer, getMarkdownExtensions } from './ConverterStrategy'; + +class StackOverflowRenderer extends PlainRenderer { + // SO uses standard markdown close to GFM +} + +export class StackOverflowStrategy implements ConverterStrategy { + id = 'stackoverflow'; + name = 'StackOverflow'; + + getRenderer() { + return new StackOverflowRenderer(); + } + + lex(input: string): Token[] { + const markedInstance = new Marked(); + markedInstance.use({ + extensions: getMarkdownExtensions(this), + gfm: true, + breaks: true, + }); + return markedInstance.lexer(input); + } + + renderWikilink(target: string, text: string): string { + return `[${text}](${target})`; + } + + renderCallout(type: string, title: string, content: string): string { + // StackOverflow doesn't have alert styling, so format as standard blockquote with bold header + const header = title ? `**[${type.toUpperCase()}] ${title}**\n` : `**[${type.toUpperCase()}]**\n`; + const fullText = `${header}${content}`; + return `\n${fullText + .trim() + .split('\n') + .map((l) => `> ${l}`) + .join('\n')}\n`; + } +} diff --git a/vite.config.ts b/vite.config.ts index b481f7fd..aebd911c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -237,6 +237,9 @@ export default defineConfig({ ], // optionally specify dependency name }, server: { + watch: { + ignored: ['**/.pnpm-store/**'], + }, headers: { // 'Cross-Origin-Resource-Policy': 'same-site', 'Cross-Origin-Opener-Policy': 'same-origin',