prosemirror-suggestcat-plugin 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ /* eslint-disable no-console */
2
+ import { Fragment, Slice } from "prosemirror-model";
3
+ import { Plugin } from "prosemirror-state";
4
+ import { defaultCompleteOptions } from "./defaults";
5
+ import { completeRequest, makeShorterLonger } from "./makeTaksRequest";
6
+ import { OpenAiPromptsWithoutParam, OpenAiPromptsWithParam, Status, } from "./types";
7
+ import { completePluginKey, isCompleteMeta } from "./utils";
8
+ /*
9
+ * idle - initial state, waiting for task
10
+ * new - make request in view
11
+ * streaming - update state in apply method and wait for finished
12
+ * finished - update state in apply method and wait for accepted or rejected
13
+ * accepted - insert/replace text in view and set status to done, also used for clearing an error
14
+ * rejected - set status to done
15
+ * done - used for clearing pluginState, do not use, it is just for internal state management
16
+ * error - whenever an error occurs, this field gets populated so you can display it for the user, use `accepted`* meta to clear it
17
+ */
18
+ export const completePlugin = (apiKey, options = defaultCompleteOptions) => {
19
+ let streaming = false;
20
+ return new Plugin({
21
+ key: completePluginKey,
22
+ state: {
23
+ init() {
24
+ return { status: Status.idle };
25
+ },
26
+ apply(tr, pluginState, prevState, state) {
27
+ const meta = tr.getMeta(completePluginKey);
28
+ console.log("ASD META", { meta });
29
+ if (pluginState.status === Status.done ||
30
+ pluginState.status === Status.rejected) {
31
+ return { status: Status.idle };
32
+ }
33
+ if (meta && isCompleteMeta(meta)) {
34
+ if (pluginState.type && meta.type !== pluginState.type) {
35
+ return pluginState;
36
+ }
37
+ return Object.assign(Object.assign({}, pluginState), meta);
38
+ }
39
+ return pluginState;
40
+ },
41
+ },
42
+ view() {
43
+ return {
44
+ update(view, prevState) {
45
+ const pluginState = completePluginKey.getState(view.state);
46
+ /* eslint-disable prefer-destructuring */
47
+ let tr = view.state.tr;
48
+ if ((pluginState === null || pluginState === void 0 ? void 0 : pluginState.status) === Status.new && !streaming) {
49
+ switch (pluginState.type) {
50
+ case OpenAiPromptsWithoutParam.Complete:
51
+ streaming = true;
52
+ completeRequest(pluginState, view, apiKey);
53
+ console.log("complete");
54
+ break;
55
+ case OpenAiPromptsWithoutParam.MakeLonger:
56
+ case OpenAiPromptsWithoutParam.MakeShorter:
57
+ case OpenAiPromptsWithoutParam.Improve:
58
+ case OpenAiPromptsWithoutParam.Simplify:
59
+ case OpenAiPromptsWithoutParam.Explain:
60
+ case OpenAiPromptsWithoutParam.ActionItems:
61
+ case OpenAiPromptsWithParam.Translate:
62
+ case OpenAiPromptsWithParam.ChangeTone:
63
+ streaming = true;
64
+ makeShorterLonger(pluginState.type, pluginState, view, apiKey, options.maxSelection, pluginState.params);
65
+ console.log("improve selected text");
66
+ break;
67
+ default:
68
+ break;
69
+ }
70
+ }
71
+ if ((pluginState === null || pluginState === void 0 ? void 0 : pluginState.status) === Status.accepted) {
72
+ streaming = false;
73
+ if (pluginState.error) {
74
+ tr.setMeta(completePluginKey, {
75
+ type: pluginState.type,
76
+ status: Status.done,
77
+ });
78
+ view.dispatch(tr);
79
+ return;
80
+ }
81
+ switch (pluginState.type) {
82
+ case OpenAiPromptsWithoutParam.Complete:
83
+ tr = tr.insertText(pluginState.result || "", view.state.doc.nodeSize - 2);
84
+ tr.setMeta(completePluginKey, {
85
+ type: OpenAiPromptsWithoutParam.Complete,
86
+ status: Status.done,
87
+ });
88
+ view.dispatch(tr);
89
+ view.focus();
90
+ console.log("complete accepted V1");
91
+ break;
92
+ case OpenAiPromptsWithoutParam.MakeLonger:
93
+ case OpenAiPromptsWithoutParam.MakeShorter:
94
+ case OpenAiPromptsWithoutParam.Improve:
95
+ case OpenAiPromptsWithoutParam.Simplify:
96
+ case OpenAiPromptsWithoutParam.Explain:
97
+ case OpenAiPromptsWithoutParam.ActionItems:
98
+ if (pluginState.selection && pluginState.result) {
99
+ const content = pluginState.result;
100
+ const paragraphs = content.split("\n\n");
101
+ const paragraphNodes = paragraphs.map((paragraph) => view.state.schema.node("paragraph", null, view.state.schema.text(paragraph)));
102
+ const fragment = Fragment.fromArray(paragraphNodes);
103
+ tr.selection.replace(tr, new Slice(fragment, 0, 0));
104
+ }
105
+ tr.setMeta(completePluginKey, {
106
+ type: pluginState.type,
107
+ status: Status.done,
108
+ });
109
+ view.dispatch(tr);
110
+ view.focus();
111
+ console.log("makeShorterLonger acceptedV1");
112
+ break;
113
+ default:
114
+ break;
115
+ }
116
+ }
117
+ },
118
+ };
119
+ },
120
+ });
121
+ };
package/dist/index.es.js CHANGED
@@ -1 +1 @@
1
- import{PluginKey as e,Plugin as t}from"prosemirror-state";import{Decoration as n,DecorationSet as o}from"prosemirror-view";import r from"fast-diff";import{__awaiter as s}from"tslib";import i from"lodash.debounce";import{StepMap as a,Mapping as c}from"prosemirror-transform";import{Fragment as l,Slice as d}from"prosemirror-model";var p,g,u,m,h,f,x;!function(e){e.suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion"}(p||(p={})),function(e){e.grammarSuggestPopup="grammar-suggest-popup"}(g||(g={})),function(e){e.Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly"}(u||(u={})),function(e){e.English="English",e.Spanish="Spanish",e.French="French",e.German="German",e.Italian="Italian",e.Portuguese="Portuguese",e.Dutch="Dutch",e.Russian="Russian",e.Chinese="Chinese",e.Korean="Korean",e.Japanese="Japanese"}(m||(m={})),function(e){e.Complete="Complete",e.Improve="Improve",e.MakeLonger="MakeLonger",e.MakeShorter="MakeShorter",e.Simplify="Simplify",e.Explain="Explain",e.ActionItems="ActionItems"}(h||(h={})),function(e){e.ChangeTone="ChangeTone",e.Translate="Translate"}(f||(f={})),function(e){e.idle="idle",e.new="new",e.streaming="streaming",e.finished="finished",e.accepted="accepted",e.rejected="rejected",e.done="done",e.error="error"}(x||(x={}));const v=new e("completePlugin"),y=new e("grammarSuggestPlugin"),S=e=>{let t="";return e.descendants(((e,n)=>{e.isText&&(t+=`${e.text}\n`)})),t},w=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const n=r(e,t),o=n[0],s=o[0]===r.EQUAL?o[1].length-1:0,i=((e,t)=>{if(t[t.length-1][0]!==r.EQUAL)return e.length;const n=t.slice(0,t.length-1);let o=0;for(const e of n){const[t,n]=e;t===r.EQUAL&&(o+=n.length),t===r.DELETE&&(o+=n.length)}return o})(e,n),a=e.lastIndexOf("\n",s),c=e.indexOf("\n",i),l=-1===a?0:a+1,d=-1===c?e.length:c,p=e.slice(l,d),g=t.slice(l,t.length-(e.length-d));return{start:l,end:l+g.length,oldStart:l,oldEnd:d,oldText:p,newText:g}},j=[{docPos:1,textPos:0}],b=e=>{let t="";const n=[];return e.descendants(((e,o)=>{e.isText&&(n.push({docPos:o,textPos:t.length}),t+=`${e.text}\n`)})),{text:t,mapping:n.length?n:j}},T=(e,t)=>{for(let n=0;n<t.length;n++)if(e>=t[n].textPos&&(void 0===t[n+1]||e<t[n+1].textPos))return t[n].docPos+(e-t[n].textPos);throw new Error("textPositionToDocumentPosition: textPos not found in mapping")},C=(e,t)=>s(void 0,void 0,void 0,(function*(){const n=[...t.split("\n")];return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:n}})}).then((e=>e.ok?e.json():Promise.reject(e))).then((e=>e&&e.some((e=>(e=>{try{JSON.parse(e)}catch(e){return!1}return!0})(e)))?{result:e.map((e=>JSON.parse(e).result)).join("\n"),fixed:!0}:{fixed:!1,result:t})).catch((e=>(e.text().then((t=>{console.error({status:e.status,text:t})})),{fixed:!1,result:t})))})),O=e=>e.replacement===e.original,E=e=>e.reduce(((e,t)=>{const n=e[e.length-1],o=e.slice(0,e.length-1);if(!n)return[t];return[...o,...((e,t)=>{if(e.to!==t.from)throw new Error(`Replace pairs must be adjacent\n\n, ${JSON.stringify({leftReplace:e,rightReplace:t})}`);if(e.replacement.endsWith("\n"))return[e,t];if(O(e)&&O(t))return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}];if(O(e)){if(t.replacement.startsWith(" ")&&""===t.original||t.original.startsWith(" ")&&""===t.replacement)return[e,t];const n=e.original.split(" "),o=n.pop()||"",r=n.join(" ")+(n.length?" ":"");return[...r.length?[{from:e.from,to:e.from+r.length,original:r,replacement:r}]:[],{from:e.from+r.length,to:t.to,original:o+t.original,replacement:o+t.replacement}]}if(O(t)){if(e.replacement.endsWith(" ")&&""===e.original||e.original.endsWith(" ")&&""===e.replacement)return[e,t];const n=t.original.split(" "),o=n.shift()||"",r=(n.length?" ":"")+n.join(" ");return" "===r?[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]:[{from:e.from,to:e.to+o.length,original:e.original+o,replacement:e.replacement+o},...r.length?[{from:e.to+o.length,to:t.to,original:r,replacement:r}]:[]]}return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]})(n,t)]}),[]),M=(e,t)=>{const n=(e=>{let t=0;return e.map((([e,n])=>{switch(e){case r.EQUAL:const e=n.lastIndexOf("\n"),o={from:t,to:t+n.length,original:n,replacement:n};if(-1!==e&&"\n"!==n){const o=[{from:t,to:t+e+1,original:n.slice(0,e+1),replacement:n.slice(0,e+1)},{from:t+e+1,to:t+n.length,original:n.slice(e+1),replacement:n.slice(e+1)}];return t+=n.length,o}return t+=n.length,[o];case r.DELETE:const s={from:t,to:t+n.length,original:n,replacement:""};return t+=n.length,[s];case r.INSERT:return[{from:t,to:t,original:"",replacement:n}]}})).flat()})(r(e,t));return E(E(n))},P=(e,t)=>{var n;const o=null===(n=y.getState(e.state))||void 0===n?void 0:n.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===t.spec.id))[0];if(!o)return;const{text:r}=o.spec,{from:s,to:i}=o,a={type:p.acceptSuggestion,id:t.spec.id},c=e.state.tr.insertText(r,s,i).setMeta(y,a);e.dispatch(c)},L=(e,t)=>{const{spec:n}=t,o={type:p.discardSuggestion,id:n.id},r=e.state.tr.setMeta(y,o);e.dispatch(r)},k=(e,t)=>{const n=y.getState(e.state);if(!n)return!1;const{decorations:o}=n,r=o.find(t,t)[0];if(!r){const t={type:p.closeSuggestion};return e.dispatch(e.state.tr.setMeta(y,t)),!1}const s=n.popupDecoration.find()[0];if((null==s?void 0:s.spec.id)===r.spec.id)return!1;const i={type:p.openSuggestion,decoration:r};return e.dispatch(e.state.tr.setMeta(y,i)),!1},D={debounceMs:2e3,createUpdatePopup:(e,t,n,o,r)=>{const s=document.createElement("div");s.className="grammar-suggest-tooltip";const{spec:i}=t,a=e.dom.getBoundingClientRect();s.id=g.grammarSuggestPopup;const c=e.coordsAtPos(n);s.style.left=c.left-a.left+"px",s.style.top=c.bottom-a.top+5+"px";const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=i.text||i.originalText,i.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{o(e,t)},s.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{r(e,t)},s.appendChild(d),s},withYjs:!1},A={maxSelection:1e3},I=(e,r=D)=>{let s=!1;return new t({key:y,state:{init:()=>({lastText:"",decorations:o.empty,popupDecoration:o.empty}),apply(e,t,s,i){const l=e.getMeta(y);return(null==l?void 0:l.type)===p.suggestionUpdate?((e,t,o)=>{const{changedRegion:r,fix:s,mapping:i,text:a}=t,c=M(r.newText,s.result).filter((e=>!O(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:o,replacement:s})=>{const a=T(r.start+e,i),c=T(r.start+(s.endsWith("\n")?t-1:t),i),l={text:s.endsWith("\n")?s.slice(0,-1):s,originalText:o,id:{}};return n.inline(a,c,{class:"grammarSuggestion "+(""===s?"removalSuggestion":"")},l)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(o.doc,c),lastText:a})})(t,l,e):(null==l?void 0:l.type)===p.acceptSuggestion?((e,t,n)=>{const r=e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:S(n.doc),decorations:r.map(n.mapping,n.doc),popupDecoration:o.empty})})(t,l,e):(null==l?void 0:l.type)===p.openSuggestion?((e,t,r,s)=>{const{decoration:i}=t,a={id:i.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:o.create(r.doc,[n.widget(i.from,((e,t)=>{const n=t();return n?s.createUpdatePopup(e,i,n,P,L):document.createElement("div")}),Object.assign(Object.assign({},a),{stopEvent:()=>!0}))])})})(t,l,e,r):(null==l?void 0:l.type)===p.closeSuggestion?Object.assign(Object.assign({},t),{popupDecoration:o.empty}):(null==l?void 0:l.type)===p.discardSuggestion?((e,t,n)=>Object.assign(Object.assign({},e),{decorations:e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id))),popupDecoration:o.empty}))(t,l,e):e.docChanged?((e,t,n,o)=>{const r=b(n.doc).text,{text:s,mapping:i}=b(t.doc);if(s===r)return e;let l=t.mapping;if(o){const e=t.doc.content.findDiffStart(n.doc.content),o=n.doc.content.findDiffEnd(t.doc.content),r=new a(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);l=new c([r])}const d=w(r,s),p=e.decorations.map(l,t.doc),g=T(d.start,i),u=T(d.end,i),m=e.popupDecoration.map(l,t.doc);return Object.assign(Object.assign({},e),{decorations:p.remove(p.find(g,u)),popupDecoration:m.remove(m.find(g,u))})})(t,e,s,r.withYjs):t}},props:{handleClick:k,decorations:e=>{const t=y.getState(e);if(!t)return null;const n=v.getState(e);return(null==n?void 0:n.status)!==x.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const t=((e,t)=>i((e=>{var n;const o=b(e.state.doc),r=(null===(n=y.getState(e.state))||void 0===n?void 0:n.lastText)||"",s=w(r,o.text);C(t,s.newText).then((t=>{if(S(e.state.doc)!==o.text)return;const n={type:p.suggestionUpdate,fix:t,changedRegion:s,mapping:o.mapping,text:o.text};e.dispatch(e.state.tr.setMeta(y,n))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(r,e);return{update(e,n){const o=y.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===n.doc.textBetween(0,n.doc.nodeSize-2,"/n")&&s||!o||o.lastText===S(e.state.doc)||(s=!0,t(e))}}}})},R=(e,t,n,o,r,i,a)=>s(void 0,void 0,void 0,(function*(){var e;let n="";try{const c=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:r,params:a}})})).body)||void 0===e?void 0:e.getReader(),l=({done:e,value:t})=>s(void 0,void 0,void 0,(function*(){if(e)return;const s=(new TextDecoder).decode(t);try{n+=s,console.log({res:n,chunk:s}),o.dispatch(o.state.tr.setMeta(v,Object.assign({type:r,status:x.streaming,result:n},i&&{selection:i})))}catch(e){console.error("Could not parse stream message",s,e)}return null==c?void 0:c.read().then(l)}));yield null==c?void 0:c.read().then(l),o.dispatch(o.state.tr.setMeta(v,Object.assign({type:r,status:x.finished,result:n},i&&{selection:i})))}catch(e){console.error("Error:",e)}})),N=(e,n=A)=>new t({key:v,state:{init:()=>({status:x.idle}),apply(e,t,n,o){const r=e.getMeta(v);return t.status===x.done||t.status===x.rejected?{status:x.idle}:r&&(e=>Object.values(f).includes(e.type)||Object.values(h).includes(e.type))(r)?t.type&&r.type!==t.type?t:Object.assign(Object.assign({},t),r):t}},view:()=>({update(e,t){const o=v.getState(e.state);let r=e.state.tr;if((null==o?void 0:o.status)===x.new)switch(o.type){case h.Complete:((e,t,n)=>{s(void 0,void 0,void 0,(function*(){const{doc:e}=t.state,n=[];e.descendants((e=>{"paragraph"===e.type.name&&n.push(e.textContent)}));let o="";o=n.length>=2?n.slice(-2).join(" "):n.join(" "),R(0,o,0,t,h.Complete)}))})(0,e),console.log("complete");break;case h.MakeLonger:case h.MakeShorter:case h.Improve:case h.Simplify:case h.Explain:case h.ActionItems:case f.Translate:case f.ChangeTone:((e,t,n,o,r,s)=>{const i=n.state.selection;if(!i)return console.log("No selection"),void n.dispatch(n.state.tr.setMeta(v,{task:e,status:x.done}));const a=n.state.doc.textBetween(i.from,i.to);if(console.log({selectedText:a}),a.length>r)return void n.dispatch(n.state.tr.setMeta(v,{type:e,status:x.error,error:"Selection is too big"}));const c=n.state.doc.textBetween(i.from,i.to,"\n");R(0,c,0,n,e,i,s)})(o.type,0,e,0,n.maxSelection,o.params),console.log("improve selected text")}if((null==o?void 0:o.status)===x.accepted){if(o.error)return r.setMeta(v,{type:o.type,status:x.done}),void e.dispatch(r);switch(o.type){case h.Complete:r=r.insertText(o.result||"",e.state.doc.nodeSize-2),r.setMeta(v,{type:h.Complete,status:x.done}),e.dispatch(r),e.focus(),console.log("complete accepted V1");break;case h.MakeLonger:case h.MakeShorter:case h.Improve:case h.Simplify:case h.Explain:case h.ActionItems:if(o.selection&&o.result){const t=l.fromArray(Array.from(o.result).map((t=>e.state.schema.text(t))));r.selection.replace(r,new d(t,0,0))}r.setMeta(v,{type:o.type,status:x.done}),e.dispatch(r),e.focus(),console.log("makeShorterLonger acceptedV1")}}}})});export{u as MoodParamType,f as OpenAiPromptsWithParam,h as OpenAiPromptsWithoutParam,x as Status,m as TranslationTargetLanguage,N as completePlugin,v as completePluginKey,A as defaultCompleteOptions,D as defaultOptions,I as grammarSuggestPlugin};
1
+ import{PluginKey as e,Plugin as t}from"prosemirror-state";import{Decoration as n,DecorationSet as o}from"prosemirror-view";import r from"fast-diff";import{__awaiter as s}from"tslib";import i from"lodash.debounce";import{StepMap as a,Mapping as c}from"prosemirror-transform";import{Fragment as l,Slice as d}from"prosemirror-model";var p,g,u,m,h,f,x;!function(e){e.suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion"}(p||(p={})),function(e){e.grammarSuggestPopup="grammar-suggest-popup"}(g||(g={})),function(e){e.Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly"}(u||(u={})),function(e){e.English="English",e.Spanish="Spanish",e.French="French",e.German="German",e.Italian="Italian",e.Portuguese="Portuguese",e.Dutch="Dutch",e.Russian="Russian",e.Chinese="Chinese",e.Korean="Korean",e.Japanese="Japanese"}(m||(m={})),function(e){e.Complete="Complete",e.Improve="Improve",e.MakeLonger="MakeLonger",e.MakeShorter="MakeShorter",e.Simplify="Simplify",e.Explain="Explain",e.ActionItems="ActionItems"}(h||(h={})),function(e){e.ChangeTone="ChangeTone",e.Translate="Translate"}(f||(f={})),function(e){e.idle="idle",e.new="new",e.streaming="streaming",e.finished="finished",e.accepted="accepted",e.rejected="rejected",e.done="done",e.error="error"}(x||(x={}));const v=new e("completePlugin"),S=new e("grammarSuggestPlugin"),y=e=>{let t="";return e.descendants(((e,n)=>{e.isText&&(t+=`${e.text}\n`)})),t},w=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const n=r(e,t),o=n[0],s=o[0]===r.EQUAL?o[1].length-1:0,i=((e,t)=>{if(t[t.length-1][0]!==r.EQUAL)return e.length;const n=t.slice(0,t.length-1);let o=0;for(const e of n){const[t,n]=e;t===r.EQUAL&&(o+=n.length),t===r.DELETE&&(o+=n.length)}return o})(e,n),a=e.lastIndexOf("\n",s),c=e.indexOf("\n",i),l=-1===a?0:a+1,d=-1===c?e.length:c,p=e.slice(l,d),g=t.slice(l,t.length-(e.length-d));return{start:l,end:l+g.length,oldStart:l,oldEnd:d,oldText:p,newText:g}},j=[{docPos:1,textPos:0}],b=e=>{let t="";const n=[];return e.descendants(((e,o)=>{e.isText&&(n.push({docPos:o,textPos:t.length}),t+=`${e.text}\n`)})),{text:t,mapping:n.length?n:j}},T=(e,t)=>{for(let n=0;n<t.length;n++)if(e>=t[n].textPos&&(void 0===t[n+1]||e<t[n+1].textPos))return t[n].docPos+(e-t[n].textPos);throw new Error("textPositionToDocumentPosition: textPos not found in mapping")},C=(e,t)=>s(void 0,void 0,void 0,(function*(){const n=[...t.split("\n")];return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:n}})}).then((e=>e.ok?e.json():Promise.reject(e))).then((e=>e&&e.some((e=>(e=>{try{JSON.parse(e)}catch(e){return!1}return!0})(e)))?{result:e.map((e=>JSON.parse(e).result)).join("\n"),fixed:!0}:{fixed:!1,result:t})).catch((e=>(e.text().then((t=>{console.error({status:e.status,text:t})})),{fixed:!1,result:t})))})),O=e=>e.replacement===e.original,E=e=>e.reduce(((e,t)=>{const n=e[e.length-1],o=e.slice(0,e.length-1);if(!n)return[t];return[...o,...((e,t)=>{if(e.to!==t.from)throw new Error(`Replace pairs must be adjacent\n\n, ${JSON.stringify({leftReplace:e,rightReplace:t})}`);if(e.replacement.endsWith("\n"))return[e,t];if(O(e)&&O(t))return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}];if(O(e)){if(t.replacement.startsWith(" ")&&""===t.original||t.original.startsWith(" ")&&""===t.replacement)return[e,t];const n=e.original.split(" "),o=n.pop()||"",r=n.join(" ")+(n.length?" ":"");return[...r.length?[{from:e.from,to:e.from+r.length,original:r,replacement:r}]:[],{from:e.from+r.length,to:t.to,original:o+t.original,replacement:o+t.replacement}]}if(O(t)){if(e.replacement.endsWith(" ")&&""===e.original||e.original.endsWith(" ")&&""===e.replacement)return[e,t];const n=t.original.split(" "),o=n.shift()||"",r=(n.length?" ":"")+n.join(" ");return" "===r?[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]:[{from:e.from,to:e.to+o.length,original:e.original+o,replacement:e.replacement+o},...r.length?[{from:e.to+o.length,to:t.to,original:r,replacement:r}]:[]]}return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]})(n,t)]}),[]),M=(e,t)=>{const n=(e=>{let t=0;return e.map((([e,n])=>{switch(e){case r.EQUAL:const e=n.lastIndexOf("\n"),o={from:t,to:t+n.length,original:n,replacement:n};if(-1!==e&&"\n"!==n){const o=[{from:t,to:t+e+1,original:n.slice(0,e+1),replacement:n.slice(0,e+1)},{from:t+e+1,to:t+n.length,original:n.slice(e+1),replacement:n.slice(e+1)}];return t+=n.length,o}return t+=n.length,[o];case r.DELETE:const s={from:t,to:t+n.length,original:n,replacement:""};return t+=n.length,[s];case r.INSERT:return[{from:t,to:t,original:"",replacement:n}]}})).flat()})(r(e,t));return E(E(n))},P=(e,t)=>{var n;const o=null===(n=S.getState(e.state))||void 0===n?void 0:n.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===t.spec.id))[0];if(!o)return;const{text:r}=o.spec,{from:s,to:i}=o,a={type:p.acceptSuggestion,id:t.spec.id},c=e.state.tr.insertText(r,s,i).setMeta(S,a);e.dispatch(c)},L=(e,t)=>{const{spec:n}=t,o={type:p.discardSuggestion,id:n.id},r=e.state.tr.setMeta(S,o);e.dispatch(r)},k=(e,t)=>{const n=S.getState(e.state);if(!n)return!1;const{decorations:o}=n,r=o.find(t,t)[0];if(!r){const t={type:p.closeSuggestion};return e.dispatch(e.state.tr.setMeta(S,t)),!1}const s=n.popupDecoration.find()[0];if((null==s?void 0:s.spec.id)===r.spec.id)return!1;const i={type:p.openSuggestion,decoration:r};return e.dispatch(e.state.tr.setMeta(S,i)),!1},D={debounceMs:2e3,createUpdatePopup:(e,t,n,o,r)=>{const s=document.createElement("div");s.className="grammar-suggest-tooltip";const{spec:i}=t,a=e.dom.getBoundingClientRect();s.id=g.grammarSuggestPopup;const c=e.coordsAtPos(n);s.style.left=c.left-a.left+"px",s.style.top=c.bottom-a.top+5+"px";const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=i.text||i.originalText,i.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{o(e,t)},s.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{r(e,t)},s.appendChild(d),s},withYjs:!1},I={maxSelection:1e3},A=(e,r=D)=>{let s=!1;return new t({key:S,state:{init:()=>({lastText:"",decorations:o.empty,popupDecoration:o.empty}),apply(e,t,s,i){const l=e.getMeta(S);return(null==l?void 0:l.type)===p.suggestionUpdate?((e,t,o)=>{const{changedRegion:r,fix:s,mapping:i,text:a}=t,c=M(r.newText,s.result).filter((e=>!O(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:o,replacement:s})=>{const a=T(r.start+e,i),c=T(r.start+(s.endsWith("\n")?t-1:t),i),l={text:s.endsWith("\n")?s.slice(0,-1):s,originalText:o,id:{}};return n.inline(a,c,{class:"grammarSuggestion "+(""===s?"removalSuggestion":"")},l)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(o.doc,c),lastText:a})})(t,l,e):(null==l?void 0:l.type)===p.acceptSuggestion?((e,t,n)=>{const r=e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:y(n.doc),decorations:r.map(n.mapping,n.doc),popupDecoration:o.empty})})(t,l,e):(null==l?void 0:l.type)===p.openSuggestion?((e,t,r,s)=>{const{decoration:i}=t,a={id:i.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:o.create(r.doc,[n.widget(i.from,((e,t)=>{const n=t();return n?s.createUpdatePopup(e,i,n,P,L):document.createElement("div")}),Object.assign(Object.assign({},a),{stopEvent:()=>!0}))])})})(t,l,e,r):(null==l?void 0:l.type)===p.closeSuggestion?Object.assign(Object.assign({},t),{popupDecoration:o.empty}):(null==l?void 0:l.type)===p.discardSuggestion?((e,t,n)=>Object.assign(Object.assign({},e),{decorations:e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id))),popupDecoration:o.empty}))(t,l,e):e.docChanged?((e,t,n,o)=>{const r=b(n.doc).text,{text:s,mapping:i}=b(t.doc);if(s===r)return e;let l=t.mapping;if(o){const e=t.doc.content.findDiffStart(n.doc.content),o=n.doc.content.findDiffEnd(t.doc.content),r=new a(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);l=new c([r])}const d=w(r,s),p=e.decorations.map(l,t.doc),g=T(d.start,i),u=T(d.end,i),m=e.popupDecoration.map(l,t.doc);return Object.assign(Object.assign({},e),{decorations:p.remove(p.find(g,u)),popupDecoration:m.remove(m.find(g,u))})})(t,e,s,r.withYjs):t}},props:{handleClick:k,decorations:e=>{const t=S.getState(e);if(!t)return null;const n=v.getState(e);return(null==n?void 0:n.status)!==x.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const t=((e,t)=>i((e=>{var n;const o=b(e.state.doc),r=(null===(n=S.getState(e.state))||void 0===n?void 0:n.lastText)||"",s=w(r,o.text);C(t,s.newText).then((t=>{if(y(e.state.doc)!==o.text)return;const n={type:p.suggestionUpdate,fix:t,changedRegion:s,mapping:o.mapping,text:o.text};e.dispatch(e.state.tr.setMeta(S,n))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(r,e);return{update(e,n){const o=S.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===n.doc.textBetween(0,n.doc.nodeSize-2,"/n")&&s||!o||o.lastText===y(e.state.doc)||(s=!0,t(e))}}}})},R=(e,t,n,o,r,i,a)=>s(void 0,void 0,void 0,(function*(){var e;let n="";try{const c=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:r,params:a}})})).body)||void 0===e?void 0:e.getReader(),l=({done:e,value:t})=>s(void 0,void 0,void 0,(function*(){if(e)return;const s=(new TextDecoder).decode(t);try{n+=s,console.log({res:n,chunk:s}),o.dispatch(o.state.tr.setMeta(v,Object.assign({type:r,status:x.streaming,result:n},i&&{selection:i})))}catch(e){console.error("Could not parse stream message",s,e)}return null==c?void 0:c.read().then(l)}));yield null==c?void 0:c.read().then(l),o.dispatch(o.state.tr.setMeta(v,Object.assign({type:r,status:x.finished,result:n},i&&{selection:i})))}catch(e){console.error("Error:",e)}})),N=(e,n=I)=>{let o=!1;return new t({key:v,state:{init:()=>({status:x.idle}),apply(e,t,n,o){const r=e.getMeta(v);return t.status===x.done||t.status===x.rejected?{status:x.idle}:r&&(e=>Object.values(f).includes(e.type)||Object.values(h).includes(e.type))(r)?t.type&&r.type!==t.type?t:Object.assign(Object.assign({},t),r):t}},view:()=>({update(e,t){const r=v.getState(e.state);let i=e.state.tr;if((null==r?void 0:r.status)===x.new&&!o)switch(r.type){case h.Complete:o=!0,((e,t,n)=>{s(void 0,void 0,void 0,(function*(){const{doc:e}=t.state,n=[];e.descendants((e=>{"paragraph"===e.type.name&&n.push(e.textContent)}));let o="";o=n.length>=2?n.slice(-2).join(" "):n.join(" "),R(0,o,0,t,h.Complete)}))})(0,e),console.log("complete");break;case h.MakeLonger:case h.MakeShorter:case h.Improve:case h.Simplify:case h.Explain:case h.ActionItems:case f.Translate:case f.ChangeTone:o=!0,((e,t,n,o,r,s)=>{const i=n.state.selection;if(!i)return console.log("No selection"),void n.dispatch(n.state.tr.setMeta(v,{task:e,status:x.done}));const a=n.state.doc.textBetween(i.from,i.to);if(console.log({selectedText:a}),a.length>r)return void n.dispatch(n.state.tr.setMeta(v,{type:e,status:x.error,error:"Selection is too big"}));const c=n.state.doc.textBetween(i.from,i.to,"\n");R(0,c,0,n,e,i,s)})(r.type,0,e,0,n.maxSelection,r.params),console.log("improve selected text")}if((null==r?void 0:r.status)===x.accepted){if(o=!1,r.error)return i.setMeta(v,{type:r.type,status:x.done}),void e.dispatch(i);switch(r.type){case h.Complete:i=i.insertText(r.result||"",e.state.doc.nodeSize-2),i.setMeta(v,{type:h.Complete,status:x.done}),e.dispatch(i),e.focus(),console.log("complete accepted V1");break;case h.MakeLonger:case h.MakeShorter:case h.Improve:case h.Simplify:case h.Explain:case h.ActionItems:if(r.selection&&r.result){const t=r.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),n=l.fromArray(t);i.selection.replace(i,new d(n,0,0))}i.setMeta(v,{type:r.type,status:x.done}),e.dispatch(i),e.focus(),console.log("makeShorterLonger acceptedV1")}}}})})};export{u as MoodParamType,f as OpenAiPromptsWithParam,h as OpenAiPromptsWithoutParam,x as Status,m as TranslationTargetLanguage,N as completePlugin,v as completePluginKey,I as defaultCompleteOptions,D as defaultOptions,A as grammarSuggestPlugin};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e,o,n,r,s,a,i=require("prosemirror-state"),p=require("prosemirror-view"),c=require("fast-diff"),l=require("tslib"),d=require("lodash.debounce"),u=require("prosemirror-transform"),g=require("prosemirror-model");!function(t){t.suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion"}(t||(t={})),function(t){t.grammarSuggestPopup="grammar-suggest-popup"}(e||(e={})),exports.MoodParamType=void 0,(o=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",o.Confident="Confident",o.Straightforward="Straightforward",o.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(n=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",n.Spanish="Spanish",n.French="French",n.German="German",n.Italian="Italian",n.Portuguese="Portuguese",n.Dutch="Dutch",n.Russian="Russian",n.Chinese="Chinese",n.Korean="Korean",n.Japanese="Japanese",exports.OpenAiPromptsWithoutParam=void 0,(r=exports.OpenAiPromptsWithoutParam||(exports.OpenAiPromptsWithoutParam={})).Complete="Complete",r.Improve="Improve",r.MakeLonger="MakeLonger",r.MakeShorter="MakeShorter",r.Simplify="Simplify",r.Explain="Explain",r.ActionItems="ActionItems",exports.OpenAiPromptsWithParam=void 0,(s=exports.OpenAiPromptsWithParam||(exports.OpenAiPromptsWithParam={})).ChangeTone="ChangeTone",s.Translate="Translate",exports.Status=void 0,(a=exports.Status||(exports.Status={})).idle="idle",a.new="new",a.streaming="streaming",a.finished="finished",a.accepted="accepted",a.rejected="rejected",a.done="done",a.error="error";const m=new i.PluginKey("completePlugin"),h=new i.PluginKey("grammarSuggestPlugin"),x=t=>{let e="";return t.descendants(((t,o)=>{t.isText&&(e+=`${t.text}\n`)})),e},f=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const o=c(t,e),n=o[0],r=n[0]===c.EQUAL?n[1].length-1:0,s=((t,e)=>{if(e[e.length-1][0]!==c.EQUAL)return t.length;const o=e.slice(0,e.length-1);let n=0;for(const t of o){const[e,o]=t;e===c.EQUAL&&(n+=o.length),e===c.DELETE&&(n+=o.length)}return n})(t,o),a=t.lastIndexOf("\n",r),i=t.indexOf("\n",s),p=-1===a?0:a+1,l=-1===i?t.length:i,d=t.slice(p,l),u=e.slice(p,e.length-(t.length-l));return{start:p,end:p+u.length,oldStart:p,oldEnd:l,oldText:d,newText:u}},P=[{docPos:1,textPos:0}],S=t=>{let e="";const o=[];return t.descendants(((t,n)=>{t.isText&&(o.push({docPos:n,textPos:e.length}),e+=`${t.text}\n`)})),{text:e,mapping:o.length?o:P}},v=(t,e)=>{for(let o=0;o<e.length;o++)if(t>=e[o].textPos&&(void 0===e[o+1]||t<e[o+1].textPos))return e[o].docPos+(t-e[o].textPos);throw new Error("textPositionToDocumentPosition: textPos not found in mapping")},y=(t,e)=>l.__awaiter(void 0,void 0,void 0,(function*(){const o=[...e.split("\n")];return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:o}})}).then((t=>t.ok?t.json():Promise.reject(t))).then((t=>t&&t.some((t=>(t=>{try{JSON.parse(t)}catch(t){return!1}return!0})(t)))?{result:t.map((t=>JSON.parse(t).result)).join("\n"),fixed:!0}:{fixed:!1,result:e})).catch((t=>(t.text().then((e=>{console.error({status:t.status,text:e})})),{fixed:!1,result:e})))})),O=t=>t.replacement===t.original,w=t=>t.reduce(((t,e)=>{const o=t[t.length-1],n=t.slice(0,t.length-1);if(!o)return[e];return[...n,...((t,e)=>{if(t.to!==e.from)throw new Error(`Replace pairs must be adjacent\n\n, ${JSON.stringify({leftReplace:t,rightReplace:e})}`);if(t.replacement.endsWith("\n"))return[t,e];if(O(t)&&O(e))return[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}];if(O(t)){if(e.replacement.startsWith(" ")&&""===e.original||e.original.startsWith(" ")&&""===e.replacement)return[t,e];const o=t.original.split(" "),n=o.pop()||"",r=o.join(" ")+(o.length?" ":"");return[...r.length?[{from:t.from,to:t.from+r.length,original:r,replacement:r}]:[],{from:t.from+r.length,to:e.to,original:n+e.original,replacement:n+e.replacement}]}if(O(e)){if(t.replacement.endsWith(" ")&&""===t.original||t.original.endsWith(" ")&&""===t.replacement)return[t,e];const o=e.original.split(" "),n=o.shift()||"",r=(o.length?" ":"")+o.join(" ");return" "===r?[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}]:[{from:t.from,to:t.to+n.length,original:t.original+n,replacement:t.replacement+n},...r.length?[{from:t.to+n.length,to:e.to,original:r,replacement:r}]:[]]}return[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}]})(o,e)]}),[]),T=(t,e)=>{const o=(t=>{let e=0;return t.map((([t,o])=>{switch(t){case c.EQUAL:const t=o.lastIndexOf("\n"),n={from:e,to:e+o.length,original:o,replacement:o};if(-1!==t&&"\n"!==o){const n=[{from:e,to:e+t+1,original:o.slice(0,t+1),replacement:o.slice(0,t+1)},{from:e+t+1,to:e+o.length,original:o.slice(t+1),replacement:o.slice(t+1)}];return e+=o.length,n}return e+=o.length,[n];case c.DELETE:const r={from:e,to:e+o.length,original:o,replacement:""};return e+=o.length,[r];case c.INSERT:return[{from:e,to:e,original:"",replacement:o}]}})).flat()})(c(t,e));return w(w(o))},A=(e,o)=>{var n;const r=null===(n=h.getState(e.state))||void 0===n?void 0:n.decorations.find(0,e.state.doc.nodeSize,(t=>t.id===o.spec.id))[0];if(!r)return;const{text:s}=r.spec,{from:a,to:i}=r,p={type:t.acceptSuggestion,id:o.spec.id},c=e.state.tr.insertText(s,a,i).setMeta(h,p);e.dispatch(c)},j=(e,o)=>{const{spec:n}=o,r={type:t.discardSuggestion,id:n.id},s=e.state.tr.setMeta(h,r);e.dispatch(s)},b=(e,o)=>{const n=h.getState(e.state);if(!n)return!1;const{decorations:r}=n,s=r.find(o,o)[0];if(!s){const o={type:t.closeSuggestion};return e.dispatch(e.state.tr.setMeta(h,o)),!1}const a=n.popupDecoration.find()[0];if((null==a?void 0:a.spec.id)===s.spec.id)return!1;const i={type:t.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(h,i)),!1},M={debounceMs:2e3,createUpdatePopup:(t,o,n,r,s)=>{const a=document.createElement("div");a.className="grammar-suggest-tooltip";const{spec:i}=o,p=t.dom.getBoundingClientRect();a.id=e.grammarSuggestPopup;const c=t.coordsAtPos(n);a.style.left=c.left-p.left+"px",a.style.top=c.bottom-p.top+5+"px";const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=i.text||i.originalText,i.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{r(t,o)},a.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{s(t,o)},a.appendChild(d),a},withYjs:!1},C={maxSelection:1e3},W=(t,e,o,n,r,s,a)=>l.__awaiter(void 0,void 0,void 0,(function*(){var t;let o="";try{const i=null===(t=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[e],task:r,params:a}})})).body)||void 0===t?void 0:t.getReader(),p=({done:t,value:e})=>l.__awaiter(void 0,void 0,void 0,(function*(){if(t)return;const a=(new TextDecoder).decode(e);try{o+=a,console.log({res:o,chunk:a}),n.dispatch(n.state.tr.setMeta(m,Object.assign({type:r,status:exports.Status.streaming,result:o},s&&{selection:s})))}catch(t){console.error("Could not parse stream message",a,t)}return null==i?void 0:i.read().then(p)}));yield null==i?void 0:i.read().then(p),n.dispatch(n.state.tr.setMeta(m,Object.assign({type:r,status:exports.Status.finished,result:o},s&&{selection:s})))}catch(t){console.error("Error:",t)}}));exports.completePlugin=(t,e=C)=>new i.Plugin({key:m,state:{init:()=>({status:exports.Status.idle}),apply(t,e,o,n){const r=t.getMeta(m);return e.status===exports.Status.done||e.status===exports.Status.rejected?{status:exports.Status.idle}:r&&(t=>Object.values(exports.OpenAiPromptsWithParam).includes(t.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(t.type))(r)?e.type&&r.type!==e.type?e:Object.assign(Object.assign({},e),r):e}},view:()=>({update(t,o){const n=m.getState(t.state);let r=t.state.tr;if((null==n?void 0:n.status)===exports.Status.new)switch(n.type){case exports.OpenAiPromptsWithoutParam.Complete:((t,e,o)=>{l.__awaiter(void 0,void 0,void 0,(function*(){const{doc:t}=e.state,o=[];t.descendants((t=>{"paragraph"===t.type.name&&o.push(t.textContent)}));let n="";n=o.length>=2?o.slice(-2).join(" "):o.join(" "),W(0,n,0,e,exports.OpenAiPromptsWithoutParam.Complete)}))})(0,t),console.log("complete");break;case exports.OpenAiPromptsWithoutParam.MakeLonger:case exports.OpenAiPromptsWithoutParam.MakeShorter:case exports.OpenAiPromptsWithoutParam.Improve:case exports.OpenAiPromptsWithoutParam.Simplify:case exports.OpenAiPromptsWithoutParam.Explain:case exports.OpenAiPromptsWithoutParam.ActionItems:case exports.OpenAiPromptsWithParam.Translate:case exports.OpenAiPromptsWithParam.ChangeTone:((t,e,o,n,r,s)=>{const a=o.state.selection;if(!a)return console.log("No selection"),void o.dispatch(o.state.tr.setMeta(m,{task:t,status:exports.Status.done}));const i=o.state.doc.textBetween(a.from,a.to);if(console.log({selectedText:i}),i.length>r)return void o.dispatch(o.state.tr.setMeta(m,{type:t,status:exports.Status.error,error:"Selection is too big"}));const p=o.state.doc.textBetween(a.from,a.to,"\n");W(0,p,0,o,t,a,s)})(n.type,0,t,0,e.maxSelection,n.params),console.log("improve selected text")}if((null==n?void 0:n.status)===exports.Status.accepted){if(n.error)return r.setMeta(m,{type:n.type,status:exports.Status.done}),void t.dispatch(r);switch(n.type){case exports.OpenAiPromptsWithoutParam.Complete:r=r.insertText(n.result||"",t.state.doc.nodeSize-2),r.setMeta(m,{type:exports.OpenAiPromptsWithoutParam.Complete,status:exports.Status.done}),t.dispatch(r),t.focus(),console.log("complete accepted V1");break;case exports.OpenAiPromptsWithoutParam.MakeLonger:case exports.OpenAiPromptsWithoutParam.MakeShorter:case exports.OpenAiPromptsWithoutParam.Improve:case exports.OpenAiPromptsWithoutParam.Simplify:case exports.OpenAiPromptsWithoutParam.Explain:case exports.OpenAiPromptsWithoutParam.ActionItems:if(n.selection&&n.result){const e=g.Fragment.fromArray(Array.from(n.result).map((e=>t.state.schema.text(e))));r.selection.replace(r,new g.Slice(e,0,0))}r.setMeta(m,{type:n.type,status:exports.Status.done}),t.dispatch(r),t.focus(),console.log("makeShorterLonger acceptedV1")}}}})}),exports.completePluginKey=m,exports.defaultCompleteOptions=C,exports.defaultOptions=M,exports.grammarSuggestPlugin=(e,o=M)=>{let n=!1;return new i.Plugin({key:h,state:{init:()=>({lastText:"",decorations:p.DecorationSet.empty,popupDecoration:p.DecorationSet.empty}),apply(e,n,r,s){const a=e.getMeta(h);return(null==a?void 0:a.type)===t.suggestionUpdate?((t,e,o)=>{const{changedRegion:n,fix:r,mapping:s,text:a}=e,i=T(n.newText,r.result).filter((t=>!O(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((({from:t,to:e,original:o,replacement:r})=>{const a=v(n.start+t,s),i=v(n.start+(r.endsWith("\n")?e-1:e),s),c={text:r.endsWith("\n")?r.slice(0,-1):r,originalText:o,id:{}};return p.Decoration.inline(a,i,{class:"grammarSuggestion "+(""===r?"removalSuggestion":"")},c)}));return Object.assign(Object.assign({},t),{decorations:t.decorations.add(o.doc,i),lastText:a})})(n,a,e):(null==a?void 0:a.type)===t.acceptSuggestion?((t,e,o)=>{const n=t.decorations.remove(t.decorations.find(0,o.doc.nodeSize,(t=>t.id===e.id)));return Object.assign(Object.assign({},t),{lastText:x(o.doc),decorations:n.map(o.mapping,o.doc),popupDecoration:p.DecorationSet.empty})})(n,a,e):(null==a?void 0:a.type)===t.openSuggestion?((t,e,o,n)=>{const{decoration:r}=e,s={id:r.spec.id};return Object.assign(Object.assign({},t),{popupDecoration:p.DecorationSet.create(o.doc,[p.Decoration.widget(r.from,((t,e)=>{const o=e();return o?n.createUpdatePopup(t,r,o,A,j):document.createElement("div")}),Object.assign(Object.assign({},s),{stopEvent:()=>!0}))])})})(n,a,e,o):(null==a?void 0:a.type)===t.closeSuggestion?Object.assign(Object.assign({},n),{popupDecoration:p.DecorationSet.empty}):(null==a?void 0:a.type)===t.discardSuggestion?((t,e,o)=>Object.assign(Object.assign({},t),{decorations:t.decorations.remove(t.decorations.find(0,o.doc.nodeSize,(t=>t.id===e.id))),popupDecoration:p.DecorationSet.empty}))(n,a,e):e.docChanged?((t,e,o,n)=>{const r=S(o.doc).text,{text:s,mapping:a}=S(e.doc);if(s===r)return t;let i=e.mapping;if(n){const t=e.doc.content.findDiffStart(o.doc.content),n=o.doc.content.findDiffEnd(e.doc.content),r=n&&t?new u.StepMap([t,n.a-t,n.b-t]):new u.StepMap([0,0,0]);i=new u.Mapping([r])}const p=f(r,s),c=t.decorations.map(i,e.doc),l=v(p.start,a),d=v(p.end,a),g=t.popupDecoration.map(i,e.doc);return Object.assign(Object.assign({},t),{decorations:c.remove(c.find(l,d)),popupDecoration:g.remove(g.find(l,d))})})(n,e,r,o.withYjs):n}},props:{handleClick:b,decorations:t=>{const e=h.getState(t);if(!e)return null;const o=m.getState(t);return(null==o?void 0:o.status)!==exports.Status.idle?e.decorations:e.decorations.add(t.doc,e.popupDecoration.find())}},view(){const r=((e,o)=>d((e=>{var n;const r=S(e.state.doc),s=(null===(n=h.getState(e.state))||void 0===n?void 0:n.lastText)||"",a=f(s,r.text);y(o,a.newText).then((o=>{if(x(e.state.doc)!==r.text)return;const n={type:t.suggestionUpdate,fix:o,changedRegion:a,mapping:r.mapping,text:r.text};e.dispatch(e.state.tr.setMeta(h,n))})).catch((t=>{console.error("Grammar suggest API error",t)}))}),e.debounceMs))(o,e);return{update(t,e){const o=h.getState(t.state);t.state.doc.textBetween(0,t.state.doc.nodeSize-2,"/n")===e.doc.textBetween(0,e.doc.nodeSize-2,"/n")&&n||!o||o.lastText===x(t.state.doc)||(n=!0,r(t))}}}})};
1
+ "use strict";var t,e,o,n,r,s,a,i=require("prosemirror-state"),p=require("prosemirror-view"),c=require("fast-diff"),l=require("tslib"),d=require("lodash.debounce"),u=require("prosemirror-transform"),g=require("prosemirror-model");!function(t){t.suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion"}(t||(t={})),function(t){t.grammarSuggestPopup="grammar-suggest-popup"}(e||(e={})),exports.MoodParamType=void 0,(o=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",o.Confident="Confident",o.Straightforward="Straightforward",o.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(n=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",n.Spanish="Spanish",n.French="French",n.German="German",n.Italian="Italian",n.Portuguese="Portuguese",n.Dutch="Dutch",n.Russian="Russian",n.Chinese="Chinese",n.Korean="Korean",n.Japanese="Japanese",exports.OpenAiPromptsWithoutParam=void 0,(r=exports.OpenAiPromptsWithoutParam||(exports.OpenAiPromptsWithoutParam={})).Complete="Complete",r.Improve="Improve",r.MakeLonger="MakeLonger",r.MakeShorter="MakeShorter",r.Simplify="Simplify",r.Explain="Explain",r.ActionItems="ActionItems",exports.OpenAiPromptsWithParam=void 0,(s=exports.OpenAiPromptsWithParam||(exports.OpenAiPromptsWithParam={})).ChangeTone="ChangeTone",s.Translate="Translate",exports.Status=void 0,(a=exports.Status||(exports.Status={})).idle="idle",a.new="new",a.streaming="streaming",a.finished="finished",a.accepted="accepted",a.rejected="rejected",a.done="done",a.error="error";const m=new i.PluginKey("completePlugin"),h=new i.PluginKey("grammarSuggestPlugin"),x=t=>{let e="";return t.descendants(((t,o)=>{t.isText&&(e+=`${t.text}\n`)})),e},f=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const o=c(t,e),n=o[0],r=n[0]===c.EQUAL?n[1].length-1:0,s=((t,e)=>{if(e[e.length-1][0]!==c.EQUAL)return t.length;const o=e.slice(0,e.length-1);let n=0;for(const t of o){const[e,o]=t;e===c.EQUAL&&(n+=o.length),e===c.DELETE&&(n+=o.length)}return n})(t,o),a=t.lastIndexOf("\n",r),i=t.indexOf("\n",s),p=-1===a?0:a+1,l=-1===i?t.length:i,d=t.slice(p,l),u=e.slice(p,e.length-(t.length-l));return{start:p,end:p+u.length,oldStart:p,oldEnd:l,oldText:d,newText:u}},P=[{docPos:1,textPos:0}],S=t=>{let e="";const o=[];return t.descendants(((t,n)=>{t.isText&&(o.push({docPos:n,textPos:e.length}),e+=`${t.text}\n`)})),{text:e,mapping:o.length?o:P}},v=(t,e)=>{for(let o=0;o<e.length;o++)if(t>=e[o].textPos&&(void 0===e[o+1]||t<e[o+1].textPos))return e[o].docPos+(t-e[o].textPos);throw new Error("textPositionToDocumentPosition: textPos not found in mapping")},y=(t,e)=>l.__awaiter(void 0,void 0,void 0,(function*(){const o=[...e.split("\n")];return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:o}})}).then((t=>t.ok?t.json():Promise.reject(t))).then((t=>t&&t.some((t=>(t=>{try{JSON.parse(t)}catch(t){return!1}return!0})(t)))?{result:t.map((t=>JSON.parse(t).result)).join("\n"),fixed:!0}:{fixed:!1,result:e})).catch((t=>(t.text().then((e=>{console.error({status:t.status,text:e})})),{fixed:!1,result:e})))})),O=t=>t.replacement===t.original,w=t=>t.reduce(((t,e)=>{const o=t[t.length-1],n=t.slice(0,t.length-1);if(!o)return[e];return[...n,...((t,e)=>{if(t.to!==e.from)throw new Error(`Replace pairs must be adjacent\n\n, ${JSON.stringify({leftReplace:t,rightReplace:e})}`);if(t.replacement.endsWith("\n"))return[t,e];if(O(t)&&O(e))return[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}];if(O(t)){if(e.replacement.startsWith(" ")&&""===e.original||e.original.startsWith(" ")&&""===e.replacement)return[t,e];const o=t.original.split(" "),n=o.pop()||"",r=o.join(" ")+(o.length?" ":"");return[...r.length?[{from:t.from,to:t.from+r.length,original:r,replacement:r}]:[],{from:t.from+r.length,to:e.to,original:n+e.original,replacement:n+e.replacement}]}if(O(e)){if(t.replacement.endsWith(" ")&&""===t.original||t.original.endsWith(" ")&&""===t.replacement)return[t,e];const o=e.original.split(" "),n=o.shift()||"",r=(o.length?" ":"")+o.join(" ");return" "===r?[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}]:[{from:t.from,to:t.to+n.length,original:t.original+n,replacement:t.replacement+n},...r.length?[{from:t.to+n.length,to:e.to,original:r,replacement:r}]:[]]}return[{from:t.from,to:e.to,original:t.original+e.original,replacement:t.replacement+e.replacement}]})(o,e)]}),[]),T=(t,e)=>{const o=(t=>{let e=0;return t.map((([t,o])=>{switch(t){case c.EQUAL:const t=o.lastIndexOf("\n"),n={from:e,to:e+o.length,original:o,replacement:o};if(-1!==t&&"\n"!==o){const n=[{from:e,to:e+t+1,original:o.slice(0,t+1),replacement:o.slice(0,t+1)},{from:e+t+1,to:e+o.length,original:o.slice(t+1),replacement:o.slice(t+1)}];return e+=o.length,n}return e+=o.length,[n];case c.DELETE:const r={from:e,to:e+o.length,original:o,replacement:""};return e+=o.length,[r];case c.INSERT:return[{from:e,to:e,original:"",replacement:o}]}})).flat()})(c(t,e));return w(w(o))},A=(e,o)=>{var n;const r=null===(n=h.getState(e.state))||void 0===n?void 0:n.decorations.find(0,e.state.doc.nodeSize,(t=>t.id===o.spec.id))[0];if(!r)return;const{text:s}=r.spec,{from:a,to:i}=r,p={type:t.acceptSuggestion,id:o.spec.id},c=e.state.tr.insertText(s,a,i).setMeta(h,p);e.dispatch(c)},j=(e,o)=>{const{spec:n}=o,r={type:t.discardSuggestion,id:n.id},s=e.state.tr.setMeta(h,r);e.dispatch(s)},b=(e,o)=>{const n=h.getState(e.state);if(!n)return!1;const{decorations:r}=n,s=r.find(o,o)[0];if(!s){const o={type:t.closeSuggestion};return e.dispatch(e.state.tr.setMeta(h,o)),!1}const a=n.popupDecoration.find()[0];if((null==a?void 0:a.spec.id)===s.spec.id)return!1;const i={type:t.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(h,i)),!1},M={debounceMs:2e3,createUpdatePopup:(t,o,n,r,s)=>{const a=document.createElement("div");a.className="grammar-suggest-tooltip";const{spec:i}=o,p=t.dom.getBoundingClientRect();a.id=e.grammarSuggestPopup;const c=t.coordsAtPos(n);a.style.left=c.left-p.left+"px",a.style.top=c.bottom-p.top+5+"px";const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=i.text||i.originalText,i.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{r(t,o)},a.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{s(t,o)},a.appendChild(d),a},withYjs:!1},C={maxSelection:1e3},W=(t,e,o,n,r,s,a)=>l.__awaiter(void 0,void 0,void 0,(function*(){var t;let o="";try{const i=null===(t=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[e],task:r,params:a}})})).body)||void 0===t?void 0:t.getReader(),p=({done:t,value:e})=>l.__awaiter(void 0,void 0,void 0,(function*(){if(t)return;const a=(new TextDecoder).decode(e);try{o+=a,console.log({res:o,chunk:a}),n.dispatch(n.state.tr.setMeta(m,Object.assign({type:r,status:exports.Status.streaming,result:o},s&&{selection:s})))}catch(t){console.error("Could not parse stream message",a,t)}return null==i?void 0:i.read().then(p)}));yield null==i?void 0:i.read().then(p),n.dispatch(n.state.tr.setMeta(m,Object.assign({type:r,status:exports.Status.finished,result:o},s&&{selection:s})))}catch(t){console.error("Error:",t)}}));exports.completePlugin=(t,e=C)=>{let o=!1;return new i.Plugin({key:m,state:{init:()=>({status:exports.Status.idle}),apply(t,e,o,n){const r=t.getMeta(m);return e.status===exports.Status.done||e.status===exports.Status.rejected?{status:exports.Status.idle}:r&&(t=>Object.values(exports.OpenAiPromptsWithParam).includes(t.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(t.type))(r)?e.type&&r.type!==e.type?e:Object.assign(Object.assign({},e),r):e}},view:()=>({update(t,n){const r=m.getState(t.state);let s=t.state.tr;if((null==r?void 0:r.status)===exports.Status.new&&!o)switch(r.type){case exports.OpenAiPromptsWithoutParam.Complete:o=!0,((t,e,o)=>{l.__awaiter(void 0,void 0,void 0,(function*(){const{doc:t}=e.state,o=[];t.descendants((t=>{"paragraph"===t.type.name&&o.push(t.textContent)}));let n="";n=o.length>=2?o.slice(-2).join(" "):o.join(" "),W(0,n,0,e,exports.OpenAiPromptsWithoutParam.Complete)}))})(0,t),console.log("complete");break;case exports.OpenAiPromptsWithoutParam.MakeLonger:case exports.OpenAiPromptsWithoutParam.MakeShorter:case exports.OpenAiPromptsWithoutParam.Improve:case exports.OpenAiPromptsWithoutParam.Simplify:case exports.OpenAiPromptsWithoutParam.Explain:case exports.OpenAiPromptsWithoutParam.ActionItems:case exports.OpenAiPromptsWithParam.Translate:case exports.OpenAiPromptsWithParam.ChangeTone:o=!0,((t,e,o,n,r,s)=>{const a=o.state.selection;if(!a)return console.log("No selection"),void o.dispatch(o.state.tr.setMeta(m,{task:t,status:exports.Status.done}));const i=o.state.doc.textBetween(a.from,a.to);if(console.log({selectedText:i}),i.length>r)return void o.dispatch(o.state.tr.setMeta(m,{type:t,status:exports.Status.error,error:"Selection is too big"}));const p=o.state.doc.textBetween(a.from,a.to,"\n");W(0,p,0,o,t,a,s)})(r.type,0,t,0,e.maxSelection,r.params),console.log("improve selected text")}if((null==r?void 0:r.status)===exports.Status.accepted){if(o=!1,r.error)return s.setMeta(m,{type:r.type,status:exports.Status.done}),void t.dispatch(s);switch(r.type){case exports.OpenAiPromptsWithoutParam.Complete:s=s.insertText(r.result||"",t.state.doc.nodeSize-2),s.setMeta(m,{type:exports.OpenAiPromptsWithoutParam.Complete,status:exports.Status.done}),t.dispatch(s),t.focus(),console.log("complete accepted V1");break;case exports.OpenAiPromptsWithoutParam.MakeLonger:case exports.OpenAiPromptsWithoutParam.MakeShorter:case exports.OpenAiPromptsWithoutParam.Improve:case exports.OpenAiPromptsWithoutParam.Simplify:case exports.OpenAiPromptsWithoutParam.Explain:case exports.OpenAiPromptsWithoutParam.ActionItems:if(r.selection&&r.result){const e=r.result.split("\n\n").map((e=>t.state.schema.node("paragraph",null,t.state.schema.text(e)))),o=g.Fragment.fromArray(e);s.selection.replace(s,new g.Slice(o,0,0))}s.setMeta(m,{type:r.type,status:exports.Status.done}),t.dispatch(s),t.focus(),console.log("makeShorterLonger acceptedV1")}}}})})},exports.completePluginKey=m,exports.defaultCompleteOptions=C,exports.defaultOptions=M,exports.grammarSuggestPlugin=(e,o=M)=>{let n=!1;return new i.Plugin({key:h,state:{init:()=>({lastText:"",decorations:p.DecorationSet.empty,popupDecoration:p.DecorationSet.empty}),apply(e,n,r,s){const a=e.getMeta(h);return(null==a?void 0:a.type)===t.suggestionUpdate?((t,e,o)=>{const{changedRegion:n,fix:r,mapping:s,text:a}=e,i=T(n.newText,r.result).filter((t=>!O(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((({from:t,to:e,original:o,replacement:r})=>{const a=v(n.start+t,s),i=v(n.start+(r.endsWith("\n")?e-1:e),s),c={text:r.endsWith("\n")?r.slice(0,-1):r,originalText:o,id:{}};return p.Decoration.inline(a,i,{class:"grammarSuggestion "+(""===r?"removalSuggestion":"")},c)}));return Object.assign(Object.assign({},t),{decorations:t.decorations.add(o.doc,i),lastText:a})})(n,a,e):(null==a?void 0:a.type)===t.acceptSuggestion?((t,e,o)=>{const n=t.decorations.remove(t.decorations.find(0,o.doc.nodeSize,(t=>t.id===e.id)));return Object.assign(Object.assign({},t),{lastText:x(o.doc),decorations:n.map(o.mapping,o.doc),popupDecoration:p.DecorationSet.empty})})(n,a,e):(null==a?void 0:a.type)===t.openSuggestion?((t,e,o,n)=>{const{decoration:r}=e,s={id:r.spec.id};return Object.assign(Object.assign({},t),{popupDecoration:p.DecorationSet.create(o.doc,[p.Decoration.widget(r.from,((t,e)=>{const o=e();return o?n.createUpdatePopup(t,r,o,A,j):document.createElement("div")}),Object.assign(Object.assign({},s),{stopEvent:()=>!0}))])})})(n,a,e,o):(null==a?void 0:a.type)===t.closeSuggestion?Object.assign(Object.assign({},n),{popupDecoration:p.DecorationSet.empty}):(null==a?void 0:a.type)===t.discardSuggestion?((t,e,o)=>Object.assign(Object.assign({},t),{decorations:t.decorations.remove(t.decorations.find(0,o.doc.nodeSize,(t=>t.id===e.id))),popupDecoration:p.DecorationSet.empty}))(n,a,e):e.docChanged?((t,e,o,n)=>{const r=S(o.doc).text,{text:s,mapping:a}=S(e.doc);if(s===r)return t;let i=e.mapping;if(n){const t=e.doc.content.findDiffStart(o.doc.content),n=o.doc.content.findDiffEnd(e.doc.content),r=n&&t?new u.StepMap([t,n.a-t,n.b-t]):new u.StepMap([0,0,0]);i=new u.Mapping([r])}const p=f(r,s),c=t.decorations.map(i,e.doc),l=v(p.start,a),d=v(p.end,a),g=t.popupDecoration.map(i,e.doc);return Object.assign(Object.assign({},t),{decorations:c.remove(c.find(l,d)),popupDecoration:g.remove(g.find(l,d))})})(n,e,r,o.withYjs):n}},props:{handleClick:b,decorations:t=>{const e=h.getState(t);if(!e)return null;const o=m.getState(t);return(null==o?void 0:o.status)!==exports.Status.idle?e.decorations:e.decorations.add(t.doc,e.popupDecoration.find())}},view(){const r=((e,o)=>d((e=>{var n;const r=S(e.state.doc),s=(null===(n=h.getState(e.state))||void 0===n?void 0:n.lastText)||"",a=f(s,r.text);y(o,a.newText).then((o=>{if(x(e.state.doc)!==r.text)return;const n={type:t.suggestionUpdate,fix:o,changedRegion:a,mapping:r.mapping,text:r.text};e.dispatch(e.state.tr.setMeta(h,n))})).catch((t=>{console.error("Grammar suggest API error",t)}))}),e.debounceMs))(o,e);return{update(t,e){const o=h.getState(t.state);t.state.doc.textBetween(0,t.state.doc.nodeSize-2,"/n")===e.doc.textBetween(0,e.doc.nodeSize-2,"/n")&&n||!o||o.lastText===x(t.state.doc)||(n=!0,r(t))}}}})};
@@ -0,0 +1,101 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { OpenAiPromptsWithoutParam, Status, } from "./types";
11
+ import { completePluginKey } from "./utils";
12
+ const request = (apiKey, text, pluginState, view, task, selection, params) => __awaiter(void 0, void 0, void 0, function* () {
13
+ var _a;
14
+ console.log("request is starting res is string.empty");
15
+ let res = "";
16
+ try {
17
+ const response = yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app", {
18
+ method: "POST",
19
+ cache: "no-cache",
20
+ headers: {
21
+ "Content-Type": "application/json",
22
+ Authorization: "Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe",
23
+ },
24
+ body: JSON.stringify({
25
+ model: "gpt-3.5-turbo",
26
+ modelParams: {
27
+ input: [text],
28
+ task,
29
+ params,
30
+ },
31
+ }),
32
+ });
33
+ const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();
34
+ const processStream = ({ done, value }) => __awaiter(void 0, void 0, void 0, function* () {
35
+ if (done) {
36
+ return;
37
+ }
38
+ const chunk = new TextDecoder().decode(value);
39
+ try {
40
+ res += chunk;
41
+ console.log({ res, chunk });
42
+ view.dispatch(view.state.tr.setMeta(completePluginKey, Object.assign({ type: task, status: Status.streaming, result: res }, (selection && { selection }))));
43
+ }
44
+ catch (error) {
45
+ console.error("Could not parse stream message", chunk, error);
46
+ }
47
+ // Continue processing the stream
48
+ /* eslint-disable-next-line consistent-return */
49
+ return reader === null || reader === void 0 ? void 0 : reader.read().then(processStream);
50
+ });
51
+ yield (reader === null || reader === void 0 ? void 0 : reader.read().then(processStream));
52
+ view.dispatch(view.state.tr.setMeta(completePluginKey, Object.assign({ type: task, status: Status.finished, result: res }, (selection && { selection }))));
53
+ }
54
+ catch (error) {
55
+ console.error("Error:", error);
56
+ }
57
+ });
58
+ export const completeRequest = (pluginState, view, apiKey) => __awaiter(void 0, void 0, void 0, function* () {
59
+ console.log("completeRequest is starting");
60
+ // get last 2 paragraphs from state.doc
61
+ const { doc } = view.state;
62
+ const paragraphNodes = [];
63
+ doc.descendants((node) => {
64
+ if (node.type.name === "paragraph") {
65
+ paragraphNodes.push(node.textContent);
66
+ }
67
+ });
68
+ let text = "";
69
+ if (paragraphNodes.length >= 2) {
70
+ text = paragraphNodes.slice(-2).join(" ");
71
+ }
72
+ else {
73
+ text = paragraphNodes.join(" ");
74
+ }
75
+ request(apiKey, text, pluginState, view, OpenAiPromptsWithoutParam.Complete);
76
+ });
77
+ export const makeShorterLonger = (task, pluginState, view, apiKey, maxSelection, params) => {
78
+ console.log("makeShorterLonger is starting");
79
+ const selection = view.state.selection;
80
+ if (!selection) {
81
+ console.log("No selection");
82
+ view.dispatch(view.state.tr.setMeta(completePluginKey, {
83
+ task,
84
+ status: Status.done,
85
+ }));
86
+ return;
87
+ }
88
+ // if selection is too big
89
+ const selectedText = view.state.doc.textBetween(selection.from, selection.to);
90
+ console.log({ selectedText });
91
+ if (selectedText.length > maxSelection) {
92
+ view.dispatch(view.state.tr.setMeta(completePluginKey, {
93
+ type: task,
94
+ status: Status.error,
95
+ error: "Selection is too big",
96
+ }));
97
+ return;
98
+ }
99
+ const text = view.state.doc.textBetween(selection.from, selection.to, "\n");
100
+ request(apiKey, text, pluginState, view, task, selection, params);
101
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prosemirror-suggestcat-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",