fix: Strip unsupported markdown formatting from canned responses (#13028)
# Pull Request Template
## Description
This PR fixes,
1. **Issue with canned response insertion** - Canned responses with
formatting (bold, italic, code, lists, etc.) were not being inserted
into channels that don't support that formatting.
Now unsupported markdown syntax is automatically stripped based on the
channel's schema before insertion.
2. **Make image node optional** - Images are now stripped while paste.
9e269fca04
3. Enable **bold** and _italic_ for API channel
Fixes
https://linear.app/chatwoot/issue/CW-6091/editor-breaks-when-inserting-canned-response
## Type of change
- [x] Bug fix (non-breaking change which fixes an issue)
## How Has This Been Tested?
### Loom video
https://www.loom.com/share/9a5215dfef2949fcaa3871f51bdec4bb
## Checklist:
- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] Any dependent changes have been merged and published in downstream
modules
This commit is contained in:
@@ -33,9 +33,9 @@ export const FORMATTING = {
|
||||
],
|
||||
},
|
||||
'Channel::Api': {
|
||||
marks: [],
|
||||
marks: ['strong', 'em'],
|
||||
nodes: [],
|
||||
menu: [],
|
||||
menu: ['strong', 'em', 'undo', 'redo'],
|
||||
},
|
||||
'Channel::FacebookPage': {
|
||||
marks: ['strong', 'em', 'code', 'strike'],
|
||||
@@ -153,6 +153,80 @@ export const ARTICLE_EDITOR_MENU_OPTIONS = [
|
||||
'code',
|
||||
];
|
||||
|
||||
/**
|
||||
* Markdown formatting patterns for stripping unsupported formatting.
|
||||
*
|
||||
* Maps camelCase type names to ProseMirror snake_case schema names.
|
||||
* Order matters: codeBlock before code to avoid partial matches.
|
||||
*/
|
||||
export const MARKDOWN_PATTERNS = [
|
||||
// --- BLOCK NODES ---
|
||||
{
|
||||
type: 'codeBlock', // PM: code_block, eg: ```js\ncode\n```
|
||||
patterns: [
|
||||
{ pattern: /`{3}(?:\w+)?\n?([\s\S]*?)`{3}/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'blockquote', // PM: blockquote, eg: > quote
|
||||
patterns: [{ pattern: /^> ?/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'bulletList', // PM: bullet_list, eg: - item
|
||||
patterns: [{ pattern: /^[\t ]*[-*+]\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'orderedList', // PM: ordered_list, eg: 1. item
|
||||
patterns: [{ pattern: /^[\t ]*\d+\.\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'heading', // PM: heading, eg: ## Heading
|
||||
patterns: [{ pattern: /^#{1,6}\s+/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'horizontalRule', // PM: horizontal_rule, eg: ---
|
||||
patterns: [{ pattern: /^(?:---|___|\*\*\*)\s*$/gm, replacement: '' }],
|
||||
},
|
||||
{
|
||||
type: 'image', // PM: image, eg: 
|
||||
patterns: [{ pattern: /!\[([^\]]*)\]\([^)]+\)/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'hardBreak', // PM: hard_break, eg: line\\\n or line \n
|
||||
patterns: [
|
||||
{ pattern: /\\\n/g, replacement: '\n' },
|
||||
{ pattern: / {2,}\n/g, replacement: '\n' },
|
||||
],
|
||||
},
|
||||
// --- INLINE MARKS ---
|
||||
{
|
||||
type: 'strong', // PM: strong, eg: **bold** or __bold__
|
||||
patterns: [
|
||||
{ pattern: /\*\*(.+?)\*\*/g, replacement: '$1' },
|
||||
{ pattern: /__(.+?)__/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'em', // PM: em, eg: *italic* or _italic_
|
||||
patterns: [
|
||||
{ pattern: /(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, replacement: '$1' },
|
||||
{ pattern: /(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g, replacement: '$1' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'strike', // PM: strike, eg: ~~strikethrough~~
|
||||
patterns: [{ pattern: /~~(.+?)~~/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'code', // PM: code, eg: `inline code`
|
||||
patterns: [{ pattern: /`([^`]+)`/g, replacement: '$1' }],
|
||||
},
|
||||
{
|
||||
type: 'link', // PM: link, eg: [text](url)
|
||||
patterns: [{ pattern: /\[([^\]]+)\]\([^)]+\)/g, replacement: '$1' }],
|
||||
},
|
||||
];
|
||||
|
||||
// Editor image resize options for Message Editor
|
||||
export const MESSAGE_EDITOR_IMAGE_RESIZES = [
|
||||
{
|
||||
|
||||
@@ -5,7 +5,8 @@ import {
|
||||
} from '@chatwoot/prosemirror-schema';
|
||||
import { replaceVariablesInMessage } from '@chatwoot/utils';
|
||||
import * as Sentry from '@sentry/vue';
|
||||
import { FORMATTING } from 'dashboard/constants/editor';
|
||||
import { FORMATTING, MARKDOWN_PATTERNS } from 'dashboard/constants/editor';
|
||||
import camelcaseKeys from 'camelcase-keys';
|
||||
|
||||
/**
|
||||
* The delimiter used to separate the signature from the rest of the body.
|
||||
@@ -284,6 +285,47 @@ export function setURLWithQueryAndSize(selectedImageNode, size, editorView) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips unsupported markdown formatting from content based on the editor schema.
|
||||
* This ensures canned responses with rich formatting can be inserted into channels
|
||||
* that don't support certain formatting (e.g., API channels don't support bold).
|
||||
*
|
||||
* @param {string} content - The markdown content to sanitize
|
||||
* @param {Object} schema - The ProseMirror schema with supported marks and nodes
|
||||
* @returns {string} - Content with unsupported formatting stripped
|
||||
*/
|
||||
export function stripUnsupportedFormatting(content, schema) {
|
||||
if (!content || typeof content !== 'string') return content;
|
||||
if (!schema) return content;
|
||||
|
||||
let sanitizedContent = content;
|
||||
|
||||
// Get supported marks and nodes from the schema
|
||||
// Note: ProseMirror uses snake_case internally (code_block, bullet_list, etc.)
|
||||
// but our FORMATTING constant uses camelCase (codeBlock, bulletList, etc.)
|
||||
// We use camelcase-keys to normalize node names for comparison
|
||||
const supportedMarks = Object.keys(schema.marks || {});
|
||||
const nodeKeys = Object.keys(schema.nodes || {});
|
||||
const nodeKeysObj = Object.fromEntries(nodeKeys.map(k => [k, true]));
|
||||
const supportedNodes = Object.keys(camelcaseKeys(nodeKeysObj));
|
||||
|
||||
// Process each formatting type in order (codeBlock before code is important!)
|
||||
MARKDOWN_PATTERNS.forEach(({ type, patterns }) => {
|
||||
// Check if this format type is supported by the schema
|
||||
const isMarkSupported = supportedMarks.includes(type);
|
||||
const isNodeSupported = supportedNodes.includes(type);
|
||||
|
||||
// If not supported, strip the formatting
|
||||
if (!isMarkSupported && !isNodeSupported) {
|
||||
patterns.forEach(({ pattern, replacement }) => {
|
||||
sanitizedContent = sanitizedContent.replace(pattern, replacement);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return sanitizedContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Content Node Creation Helper Functions for
|
||||
* - mention
|
||||
@@ -314,8 +356,17 @@ const createNode = (editorView, nodeType, content) => {
|
||||
|
||||
return mentionNode;
|
||||
}
|
||||
case 'cannedResponse':
|
||||
return new MessageMarkdownTransformer(state.schema).parse(content);
|
||||
case 'cannedResponse': {
|
||||
// Strip unsupported formatting before parsing to ensure content can be inserted
|
||||
// into channels that don't support certain markdown features (e.g., API channels)
|
||||
const sanitizedContent = stripUnsupportedFormatting(
|
||||
content,
|
||||
state.schema
|
||||
);
|
||||
return new MessageMarkdownTransformer(state.schema).parse(
|
||||
sanitizedContent
|
||||
);
|
||||
}
|
||||
case 'variable':
|
||||
return state.schema.text(`{{${content}}}`);
|
||||
case 'emoji':
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
getSelectionCoords,
|
||||
getMenuAnchor,
|
||||
calculateMenuPosition,
|
||||
stripUnsupportedFormatting,
|
||||
} from '../editorHelper';
|
||||
import { FORMATTING } from 'dashboard/constants/editor';
|
||||
import { EditorState } from '@chatwoot/prosemirror-schema';
|
||||
@@ -745,6 +746,157 @@ describe('getFormattingForEditor', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripUnsupportedFormatting', () => {
|
||||
describe('when schema supports all formatting', () => {
|
||||
const fullSchema = {
|
||||
marks: { strong: {}, em: {}, code: {}, strike: {}, link: {} },
|
||||
nodes: { bulletList: {}, orderedList: {}, codeBlock: {}, blockquote: {} },
|
||||
};
|
||||
|
||||
it('preserves all formatting when schema supports it', () => {
|
||||
const content = '**bold** and *italic* and `code`';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
|
||||
it('preserves links when schema supports them', () => {
|
||||
const content = 'Check [this link](https://example.com)';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
|
||||
it('preserves lists when schema supports them', () => {
|
||||
const content = '- item 1\n- item 2\n1. first\n2. second';
|
||||
expect(stripUnsupportedFormatting(content, fullSchema)).toBe(content);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when schema has no formatting support (eg:SMS channel)', () => {
|
||||
const emptySchema = {
|
||||
marks: {},
|
||||
nodes: {},
|
||||
};
|
||||
|
||||
it('strips bold formatting', () => {
|
||||
expect(stripUnsupportedFormatting('**bold text**', emptySchema)).toBe(
|
||||
'bold text'
|
||||
);
|
||||
expect(stripUnsupportedFormatting('__bold text__', emptySchema)).toBe(
|
||||
'bold text'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips italic formatting', () => {
|
||||
expect(stripUnsupportedFormatting('*italic text*', emptySchema)).toBe(
|
||||
'italic text'
|
||||
);
|
||||
expect(stripUnsupportedFormatting('_italic text_', emptySchema)).toBe(
|
||||
'italic text'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips inline code formatting', () => {
|
||||
expect(stripUnsupportedFormatting('`inline code`', emptySchema)).toBe(
|
||||
'inline code'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips strikethrough formatting', () => {
|
||||
expect(stripUnsupportedFormatting('~~strikethrough~~', emptySchema)).toBe(
|
||||
'strikethrough'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips links but keeps text', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting(
|
||||
'Check [this link](https://example.com)',
|
||||
emptySchema
|
||||
)
|
||||
).toBe('Check this link');
|
||||
});
|
||||
|
||||
it('strips bullet list markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('- item 1\n- item 2', emptySchema)
|
||||
).toBe('item 1\nitem 2');
|
||||
expect(
|
||||
stripUnsupportedFormatting('* item 1\n* item 2', emptySchema)
|
||||
).toBe('item 1\nitem 2');
|
||||
});
|
||||
|
||||
it('strips ordered list markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('1. first\n2. second', emptySchema)
|
||||
).toBe('first\nsecond');
|
||||
});
|
||||
|
||||
it('strips code block markers', () => {
|
||||
expect(
|
||||
stripUnsupportedFormatting('```javascript\ncode here\n```', emptySchema)
|
||||
).toBe('code here\n');
|
||||
});
|
||||
|
||||
it('strips blockquote markers', () => {
|
||||
expect(stripUnsupportedFormatting('> quoted text', emptySchema)).toBe(
|
||||
'quoted text'
|
||||
);
|
||||
});
|
||||
|
||||
it('handles complex content with multiple formatting types', () => {
|
||||
const content =
|
||||
'**Bold** and *italic* with `code` and [link](url)\n- list item';
|
||||
const expected = 'Bold and italic with code and link\nlist item';
|
||||
expect(stripUnsupportedFormatting(content, emptySchema)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when schema has partial support', () => {
|
||||
const partialSchema = {
|
||||
marks: { strong: {}, em: {} },
|
||||
nodes: {},
|
||||
};
|
||||
|
||||
it('preserves supported marks and strips unsupported ones', () => {
|
||||
const content = '**bold** and `code`';
|
||||
expect(stripUnsupportedFormatting(content, partialSchema)).toBe(
|
||||
'**bold** and code'
|
||||
);
|
||||
});
|
||||
|
||||
it('strips unsupported nodes but keeps supported marks', () => {
|
||||
const content = '**bold** text\n- list item';
|
||||
expect(stripUnsupportedFormatting(content, partialSchema)).toBe(
|
||||
'**bold** text\nlist item'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('returns content unchanged if content is empty', () => {
|
||||
expect(stripUnsupportedFormatting('', {})).toBe('');
|
||||
});
|
||||
|
||||
it('returns content unchanged if content is null', () => {
|
||||
expect(stripUnsupportedFormatting(null, {})).toBe(null);
|
||||
});
|
||||
|
||||
it('returns content unchanged if content is undefined', () => {
|
||||
expect(stripUnsupportedFormatting(undefined, {})).toBe(undefined);
|
||||
});
|
||||
|
||||
it('returns content unchanged if schema is null', () => {
|
||||
expect(stripUnsupportedFormatting('**bold**', null)).toBe('**bold**');
|
||||
});
|
||||
|
||||
it('handles nested formatting correctly', () => {
|
||||
const emptySchema = { marks: {}, nodes: {} };
|
||||
// After stripping bold (**), the remaining *and italic* becomes italic and is stripped too
|
||||
expect(
|
||||
stripUnsupportedFormatting('**bold *and italic***', emptySchema)
|
||||
).toBe('bold and italic');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Menu positioning helpers', () => {
|
||||
const mockEditorView = {
|
||||
coordsAtPos: vi.fn((pos, bias) => {
|
||||
|
||||
@@ -110,6 +110,7 @@ export default {
|
||||
v-model="content"
|
||||
class="message-editor [&>div]:px-1"
|
||||
:class="{ editor_warning: v$.content.$error }"
|
||||
channel-type="Context::Default"
|
||||
enable-variables
|
||||
:enable-canned-responses="false"
|
||||
:placeholder="$t('CANNED_MGMT.ADD.FORM.CONTENT.PLACEHOLDER')"
|
||||
|
||||
@@ -114,6 +114,7 @@ export default {
|
||||
v-model="content"
|
||||
class="message-editor [&>div]:px-1"
|
||||
:class="{ editor_warning: v$.content.$error }"
|
||||
channel-type="Context::Default"
|
||||
enable-variables
|
||||
:enable-canned-responses="false"
|
||||
:placeholder="$t('CANNED_MGMT.EDIT.FORM.CONTENT.PLACEHOLDER')"
|
||||
|
||||
Reference in New Issue
Block a user