AutoCompletion.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. Here we initialize the plugin with keyword mapping.
  3. Intended to handle user interactions seamlessly.
  4. Observe the keydown events for proactive suggestions.
  5. Provide a mechanism for accepting AI suggestions.
  6. Evaluate each input change with debounce logic.
  7. Next, we implement touch and mouse interactions.
  8. Anchor the user experience to intuitive behavior.
  9. Intelligently reset suggestions on new input.
  10. */
  11. import { Extension } from '@tiptap/core';
  12. import { Plugin, PluginKey } from 'prosemirror-state';
  13. export const AIAutocompletion = Extension.create({
  14. name: 'aiAutocompletion',
  15. addOptions() {
  16. return {
  17. generateCompletion: () => Promise.resolve(''),
  18. debounceTime: 1000
  19. };
  20. },
  21. addGlobalAttributes() {
  22. return [
  23. {
  24. types: ['paragraph'],
  25. attributes: {
  26. class: {
  27. default: null,
  28. parseHTML: (element) => element.getAttribute('class'),
  29. renderHTML: (attributes) => {
  30. if (!attributes.class) return {};
  31. return { class: attributes.class };
  32. }
  33. },
  34. 'data-prompt': {
  35. default: null,
  36. parseHTML: (element) => element.getAttribute('data-prompt'),
  37. renderHTML: (attributes) => {
  38. if (!attributes['data-prompt']) return {};
  39. return { 'data-prompt': attributes['data-prompt'] };
  40. }
  41. },
  42. 'data-suggestion': {
  43. default: null,
  44. parseHTML: (element) => element.getAttribute('data-suggestion'),
  45. renderHTML: (attributes) => {
  46. if (!attributes['data-suggestion']) return {};
  47. return { 'data-suggestion': attributes['data-suggestion'] };
  48. }
  49. }
  50. }
  51. }
  52. ];
  53. },
  54. addProseMirrorPlugins() {
  55. let debounceTimer = null;
  56. let loading = false;
  57. let touchStartX = 0;
  58. let touchStartY = 0;
  59. return [
  60. new Plugin({
  61. key: new PluginKey('aiAutocompletion'),
  62. props: {
  63. handleKeyDown: (view, event) => {
  64. const { state, dispatch } = view;
  65. const { selection } = state;
  66. const { $head } = selection;
  67. if ($head.parent.type.name !== 'paragraph') return false;
  68. const node = $head.parent;
  69. if (event.key === 'Tab') {
  70. // if (!node.attrs['data-suggestion']) {
  71. // // Generate completion
  72. // if (loading) return true
  73. // loading = true
  74. // const prompt = node.textContent
  75. // this.options.generateCompletion(prompt).then(suggestion => {
  76. // if (suggestion && suggestion.trim() !== '') {
  77. // dispatch(state.tr.setNodeMarkup($head.before(), null, {
  78. // ...node.attrs,
  79. // class: 'ai-autocompletion',
  80. // 'data-prompt': prompt,
  81. // 'data-suggestion': suggestion,
  82. // }))
  83. // }
  84. // // If suggestion is empty or null, do nothing
  85. // }).finally(() => {
  86. // loading = false
  87. // })
  88. // }
  89. if (node.attrs['data-suggestion']) {
  90. // Accept suggestion
  91. const suggestion = node.attrs['data-suggestion'];
  92. dispatch(
  93. state.tr.insertText(suggestion, $head.pos).setNodeMarkup($head.before(), null, {
  94. ...node.attrs,
  95. class: null,
  96. 'data-prompt': null,
  97. 'data-suggestion': null
  98. })
  99. );
  100. return true;
  101. }
  102. } else {
  103. if (node.attrs['data-suggestion']) {
  104. // Reset suggestion on any other key press
  105. dispatch(
  106. state.tr.setNodeMarkup($head.before(), null, {
  107. ...node.attrs,
  108. class: null,
  109. 'data-prompt': null,
  110. 'data-suggestion': null
  111. })
  112. );
  113. }
  114. // Start debounce logic for AI generation only if the cursor is at the end of the paragraph
  115. if (selection.empty && $head.pos === $head.end()) {
  116. // Set up debounce for AI generation
  117. if (this.options.debounceTime !== null) {
  118. clearTimeout(debounceTimer);
  119. // Capture current position
  120. const currentPos = $head.before();
  121. debounceTimer = setTimeout(() => {
  122. const newState = view.state;
  123. const newSelection = newState.selection;
  124. const newNode = newState.doc.nodeAt(currentPos);
  125. // Check if the node still exists and is still a paragraph
  126. if (
  127. newNode &&
  128. newNode.type.name === 'paragraph' &&
  129. newSelection.$head.pos === newSelection.$head.end() &&
  130. newSelection.$head.pos === currentPos + newNode.nodeSize - 1
  131. ) {
  132. const prompt = newNode.textContent;
  133. if (prompt.trim() !== '') {
  134. if (loading) return true;
  135. loading = true;
  136. this.options
  137. .generateCompletion(prompt)
  138. .then((suggestion) => {
  139. if (suggestion && suggestion.trim() !== '') {
  140. if (
  141. view.state.selection.$head.pos === view.state.selection.$head.end()
  142. ) {
  143. if (view.state === newState) {
  144. view.dispatch(
  145. newState.tr.setNodeMarkup(currentPos, null, {
  146. ...newNode.attrs,
  147. class: 'ai-autocompletion',
  148. 'data-prompt': prompt,
  149. 'data-suggestion': suggestion
  150. })
  151. );
  152. }
  153. }
  154. }
  155. })
  156. .finally(() => {
  157. loading = false;
  158. });
  159. }
  160. }
  161. }, this.options.debounceTime);
  162. }
  163. }
  164. }
  165. return false;
  166. },
  167. handleDOMEvents: {
  168. touchstart: (view, event) => {
  169. touchStartX = event.touches[0].clientX;
  170. touchStartY = event.touches[0].clientY;
  171. return false;
  172. },
  173. touchend: (view, event) => {
  174. const touchEndX = event.changedTouches[0].clientX;
  175. const touchEndY = event.changedTouches[0].clientY;
  176. const deltaX = touchEndX - touchStartX;
  177. const deltaY = touchEndY - touchStartY;
  178. // Check if the swipe was primarily horizontal and to the right
  179. if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 50) {
  180. const { state, dispatch } = view;
  181. const { selection } = state;
  182. const { $head } = selection;
  183. const node = $head.parent;
  184. if (node.type.name === 'paragraph' && node.attrs['data-suggestion']) {
  185. const suggestion = node.attrs['data-suggestion'];
  186. dispatch(
  187. state.tr.insertText(suggestion, $head.pos).setNodeMarkup($head.before(), null, {
  188. ...node.attrs,
  189. class: null,
  190. 'data-prompt': null,
  191. 'data-suggestion': null
  192. })
  193. );
  194. return true;
  195. }
  196. }
  197. return false;
  198. },
  199. // Add mousedown behavior
  200. // mouseup: (view, event) => {
  201. // const { state, dispatch } = view;
  202. // const { selection } = state;
  203. // const { $head } = selection;
  204. // const node = $head.parent;
  205. // // Reset debounce timer on mouse click
  206. // clearTimeout(debounceTimer);
  207. // // If a suggestion exists and the cursor moves, remove the suggestion
  208. // if (
  209. // node.type.name === 'paragraph' &&
  210. // node.attrs['data-suggestion'] &&
  211. // view.state.selection.$head.pos !== view.state.selection.$head.end()
  212. // ) {
  213. // dispatch(
  214. // state.tr.setNodeMarkup($head.before(), null, {
  215. // ...node.attrs,
  216. // class: null,
  217. // 'data-prompt': null,
  218. // 'data-suggestion': null
  219. // })
  220. // );
  221. // }
  222. // return false;
  223. // }
  224. mouseup: (view, event) => {
  225. const { state, dispatch } = view;
  226. // Reset debounce timer on mouse click
  227. clearTimeout(debounceTimer);
  228. // Iterate over all nodes in the document
  229. const tr = state.tr;
  230. state.doc.descendants((node, pos) => {
  231. if (node.type.name === 'paragraph' && node.attrs['data-suggestion']) {
  232. // Remove suggestion from this paragraph
  233. tr.setNodeMarkup(pos, null, {
  234. ...node.attrs,
  235. class: null,
  236. 'data-prompt': null,
  237. 'data-suggestion': null
  238. });
  239. }
  240. });
  241. // Apply the transaction if any changes were made
  242. if (tr.docChanged) {
  243. dispatch(tr);
  244. }
  245. return false;
  246. }
  247. }
  248. }
  249. })
  250. ];
  251. }
  252. });