mirror of
https://github.com/baserow/baserow.git
synced 2026-12-04 00:08:25 +00:00
* feat(database): format AI field text output as rich text AI fields with text output can store rich text, reusing the rich long text editor without mentions or images. New AI fields default to it in the create form; existing fields, API clients and old imports stay plain. Rich fields add a one-line formatting instruction to the prompt. Also: - forward row-modal edits of AI fields, which were never saved - keep image markdown as literal text when images are off, instead of reducing it to its alt text and losing the URL on save - escape user file image references as `![alt]\[name]` so a reference nested in another's alt text can't stay live - return 400 instead of 500 when a PATCH would make a primary field rich text Closes #6220 * fix: preserve reference image URLs in rich text Defined Markdown image tokens carry their destination and title separately from the raw reference marker. Keep that data as self-contained literal inline text when image nodes are disabled, and align the preview behavior. Add parser, AI row persistence, and browser regressions while preserving internal file references and the existing inline-image path. * fix: handle AI field changes during generation
320 lines
9.5 KiB
JavaScript
320 lines
9.5 KiB
JavaScript
import { Extension } from '@tiptap/core'
|
|
import { Blockquote } from '@tiptap/extension-blockquote'
|
|
import { Bold } from '@tiptap/extension-bold'
|
|
import { BulletList as BaseBulletList } from '@tiptap/extension-bullet-list'
|
|
import { Code as BaseCode } from '@tiptap/extension-code'
|
|
import { CodeBlock as BaseCodeBlock } from '@tiptap/extension-code-block'
|
|
import { Document } from '@tiptap/extension-document'
|
|
import { Dropcursor } from '@tiptap/extension-dropcursor'
|
|
import { Gapcursor } from '@tiptap/extension-gapcursor'
|
|
import { HardBreak } from '@tiptap/extension-hard-break'
|
|
import { Heading as BaseHeading } from '@tiptap/extension-heading'
|
|
import { History } from '@tiptap/extension-history'
|
|
import { HorizontalRule } from '@tiptap/extension-horizontal-rule'
|
|
import { Italic } from '@tiptap/extension-italic'
|
|
import { isAllowedUri, Link as BaseLink } from '@tiptap/extension-link'
|
|
import { ListItem as BaseListItem } from '@tiptap/extension-list-item'
|
|
import { OrderedList } from '@tiptap/extension-ordered-list'
|
|
import { Paragraph } from '@tiptap/extension-paragraph'
|
|
import { Strike as BaseStrike } from '@tiptap/extension-strike'
|
|
import { Subscript } from '@tiptap/extension-subscript'
|
|
import { Superscript } from '@tiptap/extension-superscript'
|
|
import { TaskItem } from '@tiptap/extension-task-item'
|
|
import { TaskList } from '@tiptap/extension-task-list'
|
|
import { Text } from '@tiptap/extension-text'
|
|
import { Underline } from '@tiptap/extension-underline'
|
|
import { Markdown } from '@tiptap/markdown'
|
|
import { Slice } from '@tiptap/pm/model'
|
|
import { Plugin, PluginKey } from '@tiptap/pm/state'
|
|
import { Marked } from 'marked'
|
|
|
|
import { ScalableImage } from '@baserow/modules/core/editor/image'
|
|
import { rememberRichTextEditorClipboard } from '@baserow/modules/core/editor/richTextClipboard'
|
|
import {
|
|
decodeInlineCodeText,
|
|
LegacyNumericHtmlEntity,
|
|
LiteralInlineMarkdownHtml,
|
|
LiteralMarkdownHtml,
|
|
LiteralMarkdownImage,
|
|
MarkdownDocumentCompatibility,
|
|
MarkdownInputCapture,
|
|
} from '@baserow/modules/core/editor/markdownCompatibility'
|
|
|
|
export const MARKDOWN_OPTIONS = {
|
|
breaks: true,
|
|
gfm: true,
|
|
}
|
|
|
|
export const createMarkedInstance = () => new Marked()
|
|
|
|
const HEADING_LEVELS = [1, 2, 3]
|
|
const LINK_PROTOCOLS = [
|
|
{ scheme: 'ftp' },
|
|
{ scheme: 'mailto', optionalSlashes: true },
|
|
{ scheme: 'tel', optionalSlashes: true },
|
|
]
|
|
|
|
const Heading = BaseHeading.extend({
|
|
parseMarkdown(token, helpers) {
|
|
const content = helpers.parseInline(token.tokens ?? [])
|
|
return HEADING_LEVELS.includes(token.depth)
|
|
? helpers.createNode('heading', { level: token.depth }, content)
|
|
: helpers.createNode('paragraph', undefined, content)
|
|
},
|
|
renderMarkdown(node, helpers) {
|
|
const level = HEADING_LEVELS.includes(node.attrs?.level)
|
|
? node.attrs.level
|
|
: HEADING_LEVELS[0]
|
|
return `${'#'.repeat(level)} ${helpers.renderChildren(node.content ?? [])}`
|
|
},
|
|
})
|
|
|
|
const Strike = BaseStrike.extend({
|
|
parseMarkdown(token, helpers) {
|
|
return token.raw?.startsWith('~~')
|
|
? helpers.applyMark('strike', helpers.parseInline(token.tokens ?? []))
|
|
: helpers.createTextNode(token.raw ?? token.text ?? '')
|
|
},
|
|
})
|
|
|
|
const decodeMarkdownEscapes = (text) =>
|
|
text.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g, '$1')
|
|
|
|
// The Markdown manager puts a parsed mark on text nodes only.
|
|
const markImages = (content, mark) =>
|
|
content.map((node) =>
|
|
node.type === 'image'
|
|
? { ...node, marks: [...(node.marks ?? []), mark] }
|
|
: node
|
|
)
|
|
|
|
const MARKED_LINK_TEXT_UNESCAPE_REGEX = /\\([[\]])/g
|
|
|
|
/** Returns the text of a `[text](href)` link as written in `token.raw`, or `null`. */
|
|
function writtenLinkText(token) {
|
|
const raw = token.raw ?? ''
|
|
for (
|
|
let end = raw.indexOf('](');
|
|
end !== -1;
|
|
end = raw.indexOf('](', end + 1)
|
|
) {
|
|
const text = raw.slice(1, end)
|
|
// Comparing with marked's unescaped text finds the end without re-implementing its bracket grammar.
|
|
if (text.replace(MARKED_LINK_TEXT_UNESCAPE_REGEX, '$1') === token.text) {
|
|
return text
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
|
|
// Marked lexes link text without the backslash of `\[` and `\]`, which breaks an escaped image alt.
|
|
function linkTextTokens(token, helpers) {
|
|
const text = writtenLinkText(token)
|
|
return text === null || text === token.text
|
|
? (token.tokens ?? [])
|
|
: helpers.tokenizeInline(text)
|
|
}
|
|
|
|
const Link = BaseLink.extend({
|
|
parseMarkdown(token, helpers) {
|
|
const raw = token.raw ?? ''
|
|
const isExplicitLink = raw.startsWith('[') || raw.startsWith('<')
|
|
const isSafeLink = isAllowedUri(token.href, LINK_PROTOCOLS)
|
|
|
|
if (!isExplicitLink || !isSafeLink) {
|
|
return helpers.createTextNode(decodeMarkdownEscapes(raw))
|
|
}
|
|
|
|
const attrs = { href: token.href, title: token.title ?? null }
|
|
const content = helpers.parseInline(linkTextTokens(token, helpers))
|
|
return helpers.applyMark(
|
|
'link',
|
|
markImages(content, { type: 'link', attrs }),
|
|
attrs
|
|
)
|
|
},
|
|
})
|
|
|
|
const Code = BaseCode.extend({
|
|
parseMarkdown(token, helpers) {
|
|
return helpers.applyMark('code', [
|
|
helpers.createTextNode(decodeInlineCodeText(token.text ?? '')),
|
|
])
|
|
},
|
|
renderMarkdown(node, helpers) {
|
|
const content = helpers.renderChildren(node.content ?? [])
|
|
const delimiter = node.attrs?.markdownDelimiter ?? '`'
|
|
const padding = node.attrs?.markdownPadding ? ' ' : ''
|
|
return `${delimiter}${padding}${content}${padding}${delimiter}`
|
|
},
|
|
})
|
|
|
|
const CodeBlock = BaseCodeBlock.extend({
|
|
renderMarkdown(node, helpers) {
|
|
const content = helpers.renderChildren(node.content ?? [])
|
|
const longestBacktickRun = Math.max(
|
|
2,
|
|
...(content.match(/`+/g) ?? []).map(({ length }) => length)
|
|
)
|
|
const fence = '`'.repeat(longestBacktickRun + 1)
|
|
const language = node.attrs?.language ?? ''
|
|
return `${fence}${language}\n${content}\n${fence}`
|
|
},
|
|
})
|
|
|
|
const ListItem = BaseListItem.extend({
|
|
renderMarkdown(node, helpers, context) {
|
|
// Marked only recognizes an empty list item when it contains a visible Markdown
|
|
// placeholder. Replace the first sentinel only; later user text may contain it.
|
|
const emptyParagraphMarker = '\uE002'
|
|
const firstChild = node.content?.[0]
|
|
const normalizedNode =
|
|
firstChild?.type === 'paragraph' && !firstChild.content?.length
|
|
? {
|
|
...node,
|
|
content: [
|
|
{
|
|
...firstChild,
|
|
content: [{ type: 'text', text: emptyParagraphMarker }],
|
|
},
|
|
...node.content.slice(1),
|
|
],
|
|
}
|
|
: node
|
|
return BaseListItem.config
|
|
.renderMarkdown(normalizedNode, helpers, context)
|
|
.replace(emptyParagraphMarker, ' ')
|
|
},
|
|
})
|
|
|
|
const BulletList = BaseBulletList.extend({
|
|
renderMarkdown(node, helpers, context) {
|
|
const rendered = BaseBulletList.config.renderMarkdown(
|
|
node,
|
|
helpers,
|
|
context
|
|
)
|
|
// Marked merges adjacent same-marker lists; runs get alternating markers.
|
|
const marker = node.attrs?.markdownMarker ?? '-'
|
|
return marker === '-'
|
|
? rendered
|
|
: rendered.replace(/(^|\n)- /g, `$1${marker} `)
|
|
},
|
|
})
|
|
|
|
export function parseMarkdownClipboard(editor, text, plainText) {
|
|
if (plainText) {
|
|
return null
|
|
}
|
|
|
|
const document = editor.schema.nodeFromJSON(editor.markdown.parse(text))
|
|
return Slice.maxOpen(document.content)
|
|
}
|
|
|
|
export function serializeMarkdownClipboard(editor, slice) {
|
|
return editor.markdown.serialize({
|
|
type: 'doc',
|
|
content: slice.content.toJSON(),
|
|
})
|
|
}
|
|
|
|
const MarkdownClipboard = Extension.create({
|
|
name: 'markdownClipboard',
|
|
priority: 1000,
|
|
addProseMirrorPlugins() {
|
|
const rememberCopiedSelection = (view) => {
|
|
if (!view.state.selection.empty) {
|
|
rememberRichTextEditorClipboard(
|
|
serializeMarkdownClipboard(
|
|
this.editor,
|
|
view.state.selection.content()
|
|
)
|
|
)
|
|
}
|
|
return false
|
|
}
|
|
return [
|
|
new Plugin({
|
|
key: new PluginKey('markdownClipboard'),
|
|
props: {
|
|
handleDOMEvents: {
|
|
copy: rememberCopiedSelection,
|
|
cut: rememberCopiedSelection,
|
|
},
|
|
clipboardTextParser: (text, _context, plainText) =>
|
|
parseMarkdownClipboard(this.editor, text, plainText),
|
|
clipboardTextSerializer: (slice) =>
|
|
serializeMarkdownClipboard(this.editor, slice),
|
|
},
|
|
}),
|
|
]
|
|
},
|
|
})
|
|
|
|
export const createRichTextContentExtensions = ({
|
|
openLinksOnClick = false,
|
|
enableImages = false,
|
|
} = {}) => {
|
|
const extensions = [
|
|
Document,
|
|
Paragraph,
|
|
Text,
|
|
HardBreak,
|
|
Heading.configure({ levels: HEADING_LEVELS }),
|
|
ListItem,
|
|
OrderedList,
|
|
BulletList,
|
|
CodeBlock,
|
|
Blockquote,
|
|
HorizontalRule,
|
|
TaskItem,
|
|
TaskList,
|
|
Bold,
|
|
Italic,
|
|
Strike,
|
|
Code,
|
|
Underline,
|
|
Subscript,
|
|
Superscript,
|
|
Link.configure({
|
|
protocols: LINK_PROTOCOLS,
|
|
autolink: false,
|
|
openOnClick: openLinksOnClick,
|
|
}),
|
|
LiteralMarkdownHtml,
|
|
LiteralInlineMarkdownHtml,
|
|
LegacyNumericHtmlEntity,
|
|
]
|
|
|
|
extensions.push(enableImages ? ScalableImage : LiteralMarkdownImage)
|
|
|
|
return extensions
|
|
}
|
|
|
|
export const createRichTextEditorExtensions = (options = {}) => {
|
|
const extensions = [
|
|
...createRichTextContentExtensions(options),
|
|
MarkdownInputCapture,
|
|
Markdown.configure({
|
|
marked: createMarkedInstance(),
|
|
markedOptions: MARKDOWN_OPTIONS,
|
|
}),
|
|
MarkdownDocumentCompatibility,
|
|
MarkdownClipboard,
|
|
History,
|
|
]
|
|
|
|
if (options.enableImages) {
|
|
extensions.push(Dropcursor, Gapcursor)
|
|
}
|
|
|
|
return extensions
|
|
}
|
|
|
|
export const createPlainTextEditorExtensions = () => [
|
|
Document,
|
|
Paragraph,
|
|
Text,
|
|
HardBreak,
|
|
]
|