AutoCompletion.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 newNode = newState.doc.nodeAt(currentPos);
  124. const currentIsAtEnd =
  125. newState.selection.$head.pos === newState.selection.$head.end();
  126. // Check if the node still exists and is still a paragraph
  127. if (newNode && newNode.type.name === 'paragraph' && currentIsAtEnd) {
  128. const prompt = newNode.textContent;
  129. if (prompt.trim() !== '') {
  130. if (loading) return true;
  131. loading = true;
  132. this.options
  133. .generateCompletion(prompt)
  134. .then((suggestion) => {
  135. if (suggestion && suggestion.trim() !== '') {
  136. view.dispatch(
  137. newState.tr.setNodeMarkup(currentPos, null, {
  138. ...newNode.attrs,
  139. class: 'ai-autocompletion',
  140. 'data-prompt': prompt,
  141. 'data-suggestion': suggestion
  142. })
  143. );
  144. }
  145. })
  146. .finally(() => {
  147. loading = false;
  148. });
  149. }
  150. }
  151. }, this.options.debounceTime);
  152. }
  153. }
  154. }
  155. return false;
  156. },
  157. handleDOMEvents: {
  158. touchstart: (view, event) => {
  159. touchStartX = event.touches[0].clientX;
  160. touchStartY = event.touches[0].clientY;
  161. return false;
  162. },
  163. touchend: (view, event) => {
  164. const touchEndX = event.changedTouches[0].clientX;
  165. const touchEndY = event.changedTouches[0].clientY;
  166. const deltaX = touchEndX - touchStartX;
  167. const deltaY = touchEndY - touchStartY;
  168. // Check if the swipe was primarily horizontal and to the right
  169. if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 50) {
  170. const { state, dispatch } = view;
  171. const { selection } = state;
  172. const { $head } = selection;
  173. const node = $head.parent;
  174. if (node.type.name === 'paragraph' && node.attrs['data-suggestion']) {
  175. const suggestion = node.attrs['data-suggestion'];
  176. dispatch(
  177. state.tr.insertText(suggestion, $head.pos).setNodeMarkup($head.before(), null, {
  178. ...node.attrs,
  179. class: null,
  180. 'data-prompt': null,
  181. 'data-suggestion': null
  182. })
  183. );
  184. return true;
  185. }
  186. }
  187. return false;
  188. },
  189. mousedown: () => {
  190. // Reset debounce timer on mouse click
  191. clearTimeout(debounceTimer);
  192. return false;
  193. }
  194. }
  195. }
  196. })
  197. ];
  198. }
  199. });