RichTextInput.svelte 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <script lang="ts">
  2. import { marked } from 'marked';
  3. import TurndownService from 'turndown';
  4. const turndownService = new TurndownService({
  5. codeBlockStyle: 'fenced',
  6. headingStyle: 'atx'
  7. });
  8. turndownService.escape = (string) => string;
  9. import { onMount, onDestroy } from 'svelte';
  10. import { createEventDispatcher } from 'svelte';
  11. const eventDispatch = createEventDispatcher();
  12. import { EditorState, Plugin, PluginKey, TextSelection } from 'prosemirror-state';
  13. import { Decoration, DecorationSet } from 'prosemirror-view';
  14. import { Editor } from '@tiptap/core';
  15. import { AIAutocompletion } from './RichTextInput/AutoCompletion.js';
  16. import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
  17. import Placeholder from '@tiptap/extension-placeholder';
  18. import Highlight from '@tiptap/extension-highlight';
  19. import Typography from '@tiptap/extension-typography';
  20. import StarterKit from '@tiptap/starter-kit';
  21. import { all, createLowlight } from 'lowlight';
  22. import { PASTED_TEXT_CHARACTER_LIMIT } from '$lib/constants';
  23. // create a lowlight instance with all languages loaded
  24. const lowlight = createLowlight(all);
  25. export let className = 'input-prose';
  26. export let placeholder = 'Type here...';
  27. export let value = '';
  28. export let id = '';
  29. export let raw = false;
  30. export let preserveBreaks = false;
  31. export let generateAutoCompletion: Function = async () => null;
  32. export let autocomplete = false;
  33. export let messageInput = false;
  34. export let shiftEnter = false;
  35. export let largeTextAsFile = false;
  36. let element;
  37. let editor;
  38. const options = {
  39. throwOnError: false
  40. };
  41. // Function to find the next template in the document
  42. function findNextTemplate(doc, from = 0) {
  43. const patterns = [
  44. { start: '[', end: ']' },
  45. { start: '{{', end: '}}' }
  46. ];
  47. let result = null;
  48. doc.nodesBetween(from, doc.content.size, (node, pos) => {
  49. if (result) return false; // Stop if we've found a match
  50. if (node.isText) {
  51. const text = node.text;
  52. let index = Math.max(0, from - pos);
  53. while (index < text.length) {
  54. for (const pattern of patterns) {
  55. if (text.startsWith(pattern.start, index)) {
  56. const endIndex = text.indexOf(pattern.end, index + pattern.start.length);
  57. if (endIndex !== -1) {
  58. result = {
  59. from: pos + index,
  60. to: pos + endIndex + pattern.end.length
  61. };
  62. return false; // Stop searching
  63. }
  64. }
  65. }
  66. index++;
  67. }
  68. }
  69. });
  70. return result;
  71. }
  72. // Function to select the next template in the document
  73. function selectNextTemplate(state, dispatch) {
  74. const { doc, selection } = state;
  75. const from = selection.to;
  76. let template = findNextTemplate(doc, from);
  77. if (!template) {
  78. // If not found, search from the beginning
  79. template = findNextTemplate(doc, 0);
  80. }
  81. if (template) {
  82. if (dispatch) {
  83. const tr = state.tr.setSelection(TextSelection.create(doc, template.from, template.to));
  84. dispatch(tr);
  85. }
  86. return true;
  87. }
  88. return false;
  89. }
  90. export const setContent = (content) => {
  91. editor.commands.setContent(content);
  92. };
  93. const selectTemplate = () => {
  94. if (value !== '') {
  95. // After updating the state, try to find and select the next template
  96. setTimeout(() => {
  97. const templateFound = selectNextTemplate(editor.view.state, editor.view.dispatch);
  98. if (!templateFound) {
  99. // If no template found, set cursor at the end
  100. const endPos = editor.view.state.doc.content.size;
  101. editor.view.dispatch(
  102. editor.view.state.tr.setSelection(TextSelection.create(editor.view.state.doc, endPos))
  103. );
  104. }
  105. }, 0);
  106. }
  107. };
  108. onMount(async () => {
  109. console.log(value);
  110. if (preserveBreaks) {
  111. turndownService.addRule('preserveBreaks', {
  112. filter: 'br', // Target <br> elements
  113. replacement: function (content) {
  114. return '<br/>';
  115. }
  116. });
  117. }
  118. let content = value;
  119. if (!raw) {
  120. async function tryParse(value, attempts = 3, interval = 100) {
  121. try {
  122. // Try parsing the value
  123. return marked.parse(value.replaceAll(`\n<br/>`, `<br/>`), {
  124. breaks: false
  125. });
  126. } catch (error) {
  127. // If no attempts remain, fallback to plain text
  128. if (attempts <= 1) {
  129. return value;
  130. }
  131. // Wait for the interval, then retry
  132. await new Promise((resolve) => setTimeout(resolve, interval));
  133. return tryParse(value, attempts - 1, interval); // Recursive call
  134. }
  135. }
  136. // Usage example
  137. content = await tryParse(value);
  138. }
  139. editor = new Editor({
  140. element: element,
  141. extensions: [
  142. StarterKit,
  143. CodeBlockLowlight.configure({
  144. lowlight
  145. }),
  146. Highlight,
  147. Typography,
  148. Placeholder.configure({ placeholder }),
  149. ...(autocomplete
  150. ? [
  151. AIAutocompletion.configure({
  152. generateCompletion: async (text) => {
  153. if (text.trim().length === 0) {
  154. return null;
  155. }
  156. const suggestion = await generateAutoCompletion(text).catch(() => null);
  157. if (!suggestion || suggestion.trim().length === 0) {
  158. return null;
  159. }
  160. return suggestion;
  161. }
  162. })
  163. ]
  164. : [])
  165. ],
  166. content: content,
  167. autofocus: messageInput ? true : false,
  168. onTransaction: () => {
  169. // force re-render so `editor.isActive` works as expected
  170. editor = editor;
  171. if (!raw) {
  172. let newValue = turndownService
  173. .turndown(
  174. editor
  175. .getHTML()
  176. .replace(/<p><\/p>/g, '<br/>')
  177. .replace(/ {2,}/g, (m) => m.replace(/ /g, '\u00a0'))
  178. )
  179. .replace(/\u00a0/g, ' ');
  180. if (!preserveBreaks) {
  181. newValue = newValue.replace(/<br\/>/g, '');
  182. }
  183. if (value !== newValue) {
  184. value = newValue;
  185. // check if the node is paragraph as well
  186. if (editor.isActive('paragraph')) {
  187. if (value === '') {
  188. editor.commands.clearContent();
  189. }
  190. }
  191. }
  192. } else {
  193. value = editor.getHTML();
  194. }
  195. },
  196. editorProps: {
  197. attributes: { id },
  198. handleDOMEvents: {
  199. focus: (view, event) => {
  200. eventDispatch('focus', { event });
  201. return false;
  202. },
  203. keyup: (view, event) => {
  204. eventDispatch('keyup', { event });
  205. return false;
  206. },
  207. keydown: (view, event) => {
  208. if (messageInput) {
  209. // Handle Tab Key
  210. if (event.key === 'Tab') {
  211. const handled = selectNextTemplate(view.state, view.dispatch);
  212. if (handled) {
  213. event.preventDefault();
  214. return true;
  215. }
  216. }
  217. if (event.key === 'Enter') {
  218. // Check if the current selection is inside a structured block (like codeBlock or list)
  219. const { state } = view;
  220. const { $head } = state.selection;
  221. // Recursive function to check ancestors for specific node types
  222. function isInside(nodeTypes: string[]): boolean {
  223. let currentNode = $head;
  224. while (currentNode) {
  225. if (nodeTypes.includes(currentNode.parent.type.name)) {
  226. return true;
  227. }
  228. if (!currentNode.depth) break; // Stop if we reach the top
  229. currentNode = state.doc.resolve(currentNode.before()); // Move to the parent node
  230. }
  231. return false;
  232. }
  233. const isInCodeBlock = isInside(['codeBlock']);
  234. const isInList = isInside(['listItem', 'bulletList', 'orderedList']);
  235. const isInHeading = isInside(['heading']);
  236. if (isInCodeBlock || isInList || isInHeading) {
  237. // Let ProseMirror handle the normal Enter behavior
  238. return false;
  239. }
  240. }
  241. // Handle shift + Enter for a line break
  242. if (shiftEnter) {
  243. if (event.key === 'Enter' && event.shiftKey && !event.ctrlKey && !event.metaKey) {
  244. editor.commands.setHardBreak(); // Insert a hard break
  245. view.dispatch(view.state.tr.scrollIntoView()); // Move viewport to the cursor
  246. event.preventDefault();
  247. return true;
  248. }
  249. }
  250. }
  251. eventDispatch('keydown', { event });
  252. return false;
  253. },
  254. paste: (view, event) => {
  255. if (event.clipboardData) {
  256. // Extract plain text from clipboard and paste it without formatting
  257. const plainText = event.clipboardData.getData('text/plain');
  258. if (plainText) {
  259. if (largeTextAsFile) {
  260. if (plainText.length > PASTED_TEXT_CHARACTER_LIMIT) {
  261. // Dispatch paste event to parent component
  262. eventDispatch('paste', { event });
  263. event.preventDefault();
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. // Check if the pasted content contains image files
  270. const hasImageFile = Array.from(event.clipboardData.files).some((file) =>
  271. file.type.startsWith('image/')
  272. );
  273. // Check for image in dataTransfer items (for cases where files are not available)
  274. const hasImageItem = Array.from(event.clipboardData.items).some((item) =>
  275. item.type.startsWith('image/')
  276. );
  277. if (hasImageFile) {
  278. // If there's an image, dispatch the event to the parent
  279. eventDispatch('paste', { event });
  280. event.preventDefault();
  281. return true;
  282. }
  283. if (hasImageItem) {
  284. // If there's an image item, dispatch the event to the parent
  285. eventDispatch('paste', { event });
  286. event.preventDefault();
  287. return true;
  288. }
  289. }
  290. // For all other cases (text, formatted text, etc.), let ProseMirror handle it
  291. view.dispatch(view.state.tr.scrollIntoView()); // Move viewport to the cursor after pasting
  292. return false;
  293. }
  294. }
  295. }
  296. });
  297. if (messageInput) {
  298. selectTemplate();
  299. }
  300. });
  301. onDestroy(() => {
  302. if (editor) {
  303. editor.destroy();
  304. }
  305. });
  306. // Update the editor content if the external `value` changes
  307. $: if (
  308. editor &&
  309. (raw
  310. ? value !== editor.getHTML()
  311. : value !==
  312. turndownService
  313. .turndown(
  314. (preserveBreaks
  315. ? editor.getHTML().replace(/<p><\/p>/g, '<br/>')
  316. : editor.getHTML()
  317. ).replace(/ {2,}/g, (m) => m.replace(/ /g, '\u00a0'))
  318. )
  319. .replace(/\u00a0/g, ' '))
  320. ) {
  321. if (raw) {
  322. editor.commands.setContent(value);
  323. } else {
  324. preserveBreaks
  325. ? editor.commands.setContent(value)
  326. : editor.commands.setContent(
  327. marked.parse(value.replaceAll(`\n<br/>`, `<br/>`), {
  328. breaks: false
  329. })
  330. ); // Update editor content
  331. }
  332. selectTemplate();
  333. }
  334. </script>
  335. <div bind:this={element} class="relative w-full min-w-full h-full min-h-fit {className}" />