prosemirror-suggestcat-plugin 0.1.14 → 1.1.0
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.
- package/dist/index.es.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +6 -5
- package/dist/completePlugin.js +0 -125
- package/dist/createUpdatePopup.js +0 -34
- package/dist/eventHandlers.js +0 -131
- package/dist/getDiff.d.ts +0 -2
- package/dist/getDiff.js +0 -17
- package/dist/makeRequest.js +0 -95
- package/dist/makeTaksRequest.js +0 -102
- package/dist/mapping.d.ts +0 -7
- package/dist/mapping.test.d.ts +0 -1
- package/dist/mapping.test.js +0 -24
- package/dist/mergeDiffs.d.ts +0 -11
- package/dist/mergeDiffs.test.d.ts +0 -1
- package/dist/plugin.js +0 -77
- package/dist/utils.js +0 -84
package/dist/index.es.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PluginKey as e,TextSelection as t,Plugin as n}from"prosemirror-state";import{Decoration as o,DecorationSet as s}from"prosemirror-view";import a from"fast-diff";import{__awaiter as i}from"tslib";import r from"lodash.debounce";import{docToTextWithMapping as c,textPosToDocPos as d}from"@emergence-engineering/prosemirror-text-map";import{StepMap as p,Mapping as l}from"prosemirror-transform";import{Fragment as g,Slice as u}from"prosemirror-model";import{getDiff as m,isIdentity as f}from"@emergence-engineering/fast-diff-merge";export{getDiff}from"@emergence-engineering/fast-diff-merge";var h,v,y,S,x,b,w;!function(e){e.suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion"}(h||(h={})),function(e){e.grammarSuggestPopup="grammar-suggest-popup"}(v||(v={})),function(e){e.Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly"}(y||(y={})),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"}(S||(S={})),function(e){e.Complete="Complete",e.Improve="Improve",e.MakeLonger="MakeLonger",e.MakeShorter="MakeShorter",e.Simplify="Simplify",e.Explain="Explain",e.ActionItems="ActionItems"}(x||(x={})),function(e){e.ChangeTone="ChangeTone",e.Translate="Translate"}(b||(b={})),function(e){e.idle="idle",e.new="new",e.streaming="streaming",e.finished="finished",e.accepted="accepted",e.cancelled="cancelled",e.rejected="rejected",e.done="done",e.error="error"}(w||(w={}));const j=new e("completePlugin"),C=new e("grammarSuggestPlugin"),T=e=>{let t="",n="",o=!1;return e.descendants(((e,s)=>{if(console.log({node:e}),e.type.isBlock){if(!o)return void(o=!0);t+=`${n}\n`,n=""}else e.isText&&(n+=`${e.text}`)})),t+=n,t},O=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const n=a(e,t),o=n[0],s=o[0]===a.EQUAL?o[1].length-1:0,i=((e,t)=>{if(t[t.length-1][0]!==a.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===a.EQUAL&&(o+=n.length),t===a.DELETE&&(o+=n.length)}return o})(e,n),r=e.lastIndexOf("\n",s),c=e.indexOf("\n",i),d=-1===r?0:r+1,p=-1===c?e.length:c,l=e.slice(d,p),g=t.slice(d,t.length-(e.length-p));return{start:d,end:d+g.length,oldStart:d,oldEnd:p,oldText:l,newText:g}},M=(e,t)=>i(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!0}return!1})(e)))?{fixed:!1,result:t}:{result:e.map((e=>JSON.parse(e).result)).join("\n"),fixed:!0})).catch((e=>(e.text().then((t=>{console.error({status:e.status,text:t})})),{fixed:!1,result:t})))})),L=(e,n)=>{var o;const s=null===(o=C.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===n.spec.id))[0];if(!s)return;const{text:a}=s.spec,{from:i,to:r}=s,c={type:h.acceptSuggestion,id:n.spec.id},d=a.split("\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),p=g.fromArray(d);let{tr:l}=e.state;l=l.setSelection(t.create(e.state.doc,i,r)),l.selection.replace(l,new u(p,1,1)),l.setMeta(C,c),e.dispatch(l)},E=(e,t)=>{const{spec:n}=t,o={type:h.discardSuggestion,id:n.id},s=e.state.tr.setMeta(C,o);e.dispatch(s)},k=(e,t)=>{const n=C.getState(e.state);if(!n)return!1;const{decorations:o}=n,s=o.find(t,t)[0];if(!s){const t={type:h.closeSuggestion};return e.dispatch(e.state.tr.setMeta(C,t)),!1}const a=n.popupDecoration.find()[0];if((null==a?void 0:a.spec.id)===s.spec.id)return!1;const i={type:h.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(C,i)),!1},D={debounceMs:2e3,createUpdatePopup:(e,t,n,o,s)=>{const a=document.createElement("div");a.className="grammar-suggest-tooltip";const{spec:i}=t,r=e.dom.getBoundingClientRect();a.id=v.grammarSuggestPopup;const c=e.coordsAtPos(n),d=e.dom.scrollTop||0,p=e.dom.scrollLeft||0;a.style.left=`${c.left-r.left+p}px`,a.style.top=`${c.bottom-r.top+d+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)},a.appendChild(l);const g=document.createElement("div");return g.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>",g.className="grammar-suggest-tooltip-discard",g.onclick=()=>{s(e,t)},a.appendChild(g),a},withYjs:!1},P={maxSelection:1e3},A=(e,t=D)=>{let a=!1;return new n({key:C,state:{init:()=>({lastText:"",decorations:s.empty,popupDecoration:s.empty}),apply(e,n,a,i){const r=e.getMeta(C);return(null==r?void 0:r.type)===h.suggestionUpdate?((e,t,n)=>{const{changedRegion:s,fix:a,mapping:i,text:r}=t,c=m(s.newText,a.result).filter((e=>!f(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:n,replacement:a})=>{const r=d(s.start+e,i),c=d(s.start+(a.endsWith("\n")?t-1:t),i),p={text:a.endsWith("\n")?a.slice(0,-1):a,originalText:n,id:{}};return o.inline(r,c,{class:"grammarSuggestion "+(""===a?"removalSuggestion":"")},p)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(n.doc,c),lastText:r})})(n,r,e):(null==r?void 0:r.type)===h.acceptSuggestion?((e,t,n)=>{const o=e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:T(n.doc),decorations:o.map(n.mapping,n.doc),popupDecoration:s.empty})})(n,r,e):(null==r?void 0:r.type)===h.openSuggestion?((e,t,n,a)=>{const{decoration:i}=t,r={id:i.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:s.create(n.doc,[o.widget(i.from,((e,t)=>{const n=t();return n?a.createUpdatePopup(e,i,n,L,E):document.createElement("div")}),Object.assign(Object.assign({},r),{stopEvent:()=>!0}))])})})(n,r,e,t):(null==r?void 0:r.type)===h.closeSuggestion?Object.assign(Object.assign({},n),{popupDecoration:s.empty}):(null==r?void 0:r.type)===h.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:s.empty}))(n,r,e):e.docChanged?((e,t,n,o)=>{const s=c(n.doc).text,{text:a,mapping:i}=c(t.doc);if(a===s)return e;let r=t.mapping;if(o){const e=t.doc.content.findDiffStart(n.doc.content),o=n.doc.content.findDiffEnd(t.doc.content),s=new p(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);r=new l([s])}const g=O(s,a),u=e.decorations.map(r,t.doc),m=d(g.start,i),f=d(g.end,i),h=e.popupDecoration.map(r,t.doc);return Object.assign(Object.assign({},e),{decorations:u.remove(u.find(m,f)),popupDecoration:h.remove(h.find(m,f))})})(n,e,a,t.withYjs):n}},props:{handleClick:k,decorations:e=>{const t=C.getState(e);if(!t)return null;const n=j.getState(e);return(null==n?void 0:n.status)!==w.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const n=((e,t)=>r((e=>{var n;const o=c(e.state.doc),s=(null===(n=C.getState(e.state))||void 0===n?void 0:n.lastText)||"",a=O(s,o.text);M(t,a.newText).then((t=>{if(T(e.state.doc)!==o.text)return;const n={type:h.suggestionUpdate,fix:t,changedRegion:a,mapping:o.mapping,text:o.text};e.dispatch(e.state.tr.setMeta(C,n))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(t,e);return{update(e,t){const o=C.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&a||!o||o.lastText===T(e.state.doc)||(a=!0,n(e))}}}})},I=(e,t,n,o,s,a,r)=>i(void 0,void 0,void 0,(function*(){var e;let n="";const c=new AbortController;try{const d=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},signal:c.signal,body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:s,params:r}})})).body)||void 0===e?void 0:e.getReader(),p=({done:e,value:t})=>i(void 0,void 0,void 0,(function*(){var i;if(e)return;if(null===(i=j.getState(o.state))||void 0===i?void 0:i.isCancelled)return void(yield c.abort());const r=(new TextDecoder).decode(t);try{n+=r,o.dispatch(o.state.tr.setMeta(j,Object.assign({type:s,status:w.streaming,result:n},a&&{selection:a})))}catch(e){console.error("Could not parse stream message",r,e)}return null==d?void 0:d.read().then(p)}));yield null==d?void 0:d.read().then(p),o.dispatch(o.state.tr.setMeta(j,Object.assign({type:s,status:w.finished,result:n},a&&{selection:a})))}catch(e){console.error("Error:",e)}})),B=(e,t=P)=>{let o=!1;return new n({key:j,state:{init:()=>({status:w.idle}),apply(e,t,n,s){const a=e.getMeta(j);return t.status===w.done||t.status===w.rejected?(o=!1,{status:w.idle}):(null==a?void 0:a.status)===w.cancelled?Object.assign(Object.assign(Object.assign({},t),a),{isCancelled:!0}):a&&(e=>Object.values(b).includes(e.type)||Object.values(x).includes(e.type))(a)?t.type&&a.type!==t.type?t:Object.assign(Object.assign({},t),a):t}},view:()=>({update(e,n){const s=j.getState(e.state);let a=e.state.tr;if((null==s?void 0:s.status)===w.new&&!o)switch(s.type){case x.Complete:o=!0,((e,t,n)=>{i(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(" "),I(0,o,0,t,x.Complete)}))})(0,e);break;case x.MakeLonger:case x.MakeShorter:case x.Improve:case x.Simplify:case x.Explain:case x.ActionItems:case b.Translate:case b.ChangeTone:o=!0,((e,t,n,o,s,a)=>{const i=n.state.selection;if(!i)return void n.dispatch(n.state.tr.setMeta(j,{task:e,status:w.done}));if(n.state.doc.textBetween(i.from,i.to).length>s)return void n.dispatch(n.state.tr.setMeta(j,{type:e,status:w.error,error:"Selection is too big"}));const r=n.state.doc.textBetween(i.from,i.to,"\n");I(0,r,0,n,e,i,a)})(s.type,0,e,0,t.maxSelection,s.params)}if((null==s?void 0:s.status)===w.accepted){if(s.error)return a.setMeta(j,{type:s.type,status:w.done}),void e.dispatch(a);switch(s.type){case x.Complete:a=a.insertText(s.result||"",e.state.doc.nodeSize-2),a.setMeta(j,{type:x.Complete,status:w.done}),e.dispatch(a),e.focus();break;case x.MakeLonger:case x.MakeShorter:case x.Improve:case x.Simplify:case x.Explain:case x.ActionItems:case b.Translate:case b.ChangeTone:if(s.selection&&s.result){const t=s.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),n=g.fromArray(t);a.selection.replace(a,new u(n,0,0))}a.setMeta(j,{type:s.type,status:w.done}),e.dispatch(a),e.focus()}}}})})};export{v as GrammarSuggestElementClass,h as GrammarSuggestMetaType,y as MoodParamType,b as OpenAiPromptsWithParam,x as OpenAiPromptsWithoutParam,w as Status,S as TranslationTargetLanguage,B as completePlugin,j as completePluginKey,I as completeRequest,P as defaultCompleteOptions,D as defaultOptions,O as getChangedRegions,A as grammarSuggestPlugin,M as suggescatRequest};
|
|
1
|
+
import{PluginKey as e,TextSelection as t,Plugin as n}from"prosemirror-state";import{Decoration as o,DecorationSet as s}from"prosemirror-view";import a from"fast-diff";import{__awaiter as i}from"tslib";import r from"lodash.debounce";import{docToTextWithMapping as c,textPosToDocPos as d}from"@emergence-engineering/prosemirror-text-map";import{StepMap as l,Mapping as p}from"prosemirror-transform";import{Fragment as g,Slice as u}from"prosemirror-model";import{getDiff as m,isIdentity as f}from"@emergence-engineering/fast-diff-merge";export{getDiff}from"@emergence-engineering/fast-diff-merge";var h,v,y,x,S,b,w;!function(e){e.suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion"}(h||(h={})),function(e){e.grammarSuggestPopup="grammar-suggest-popup"}(v||(v={})),function(e){e.Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly"}(y||(y={})),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"}(x||(x={})),function(e){e.Complete="Complete",e.Improve="Improve",e.MakeLonger="MakeLonger",e.MakeShorter="MakeShorter",e.Simplify="Simplify",e.Explain="Explain",e.ActionItems="ActionItems"}(S||(S={})),function(e){e.ChangeTone="ChangeTone",e.Translate="Translate"}(b||(b={})),function(e){e.idle="idle",e.new="new",e.streaming="streaming",e.finished="finished",e.accepted="accepted",e.cancelled="cancelled",e.rejected="rejected",e.done="done",e.error="error"}(w||(w={}));const j=new e("completePlugin"),C=new e("grammarSuggestPlugin"),T=e=>{let t="",n="",o=!1;return e.descendants(((e,s)=>{if(e.type.isBlock){if(!o)return void(o=!0);t+=`${n}\n`,n=""}else e.isText&&(n+=`${e.text}`)})),t+=n,t},M=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const n=a(e,t),o=n[0],s=o[0]===a.EQUAL?o[1].length-1:0,i=((e,t)=>{if(t[t.length-1][0]!==a.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===a.EQUAL&&(o+=n.length),t===a.DELETE&&(o+=n.length)}return o})(e,n),r=e.lastIndexOf("\n",s),c=e.indexOf("\n",i),d=-1===r?0:r+1,l=-1===c?e.length:c,p=e.slice(d,l),g=t.slice(d,t.length-(e.length-l));return{start:d,end:d+g.length,oldStart:d,oldEnd:l,oldText:p,newText:g}},O=(e,t)=>i(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=>(null==e?void 0:e.length)?{result:e.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})))})),L=(e,n)=>{var o;const s=null===(o=C.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===n.spec.id))[0];if(!s)return;const{text:a}=s.spec,{from:i,to:r}=s,c={type:h.acceptSuggestion,id:n.spec.id},d=a.split("\n").map((t=>t?e.state.schema.node("paragraph",null,e.state.schema.text(t||"")):e.state.schema.node("paragraph"))),l=g.fromArray(d);let{tr:p}=e.state;p=p.setSelection(t.create(e.state.doc,i,r)),p.selection.replace(p,new u(l,1,1)),p.setMeta(C,c),e.dispatch(p)},E=(e,t)=>{const{spec:n}=t,o={type:h.discardSuggestion,id:n.id},s=e.state.tr.setMeta(C,o);e.dispatch(s)},k=(e,t)=>{const n=C.getState(e.state);if(!n)return!1;const{decorations:o}=n,s=o.find(t,t)[0];if(!s){const t={type:h.closeSuggestion};return e.dispatch(e.state.tr.setMeta(C,t)),!1}const a=n.popupDecoration.find()[0];if((null==a?void 0:a.spec.id)===s.spec.id)return!1;const i={type:h.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(C,i)),!1},D={debounceMs:2e3,createUpdatePopup:(e,t,n,o,s)=>{const a=document.createElement("div");a.className="grammar-suggest-tooltip";const{spec:i}=t,r=e.dom.getBoundingClientRect();a.id=v.grammarSuggestPopup;const c=e.coordsAtPos(n),d=e.dom.scrollTop||0,l=e.dom.scrollLeft||0;a.style.left=`${c.left-r.left+l}px`,a.style.top=`${c.bottom-r.top+d+5}px`;const p=document.createElement("div");p.className="grammar-suggest-tooltip-apply",p.innerText=i.text||i.originalText,i.text||(p.style.textDecoration="line-through",p.style.color="red"),p.onclick=()=>{o(e,t)},a.appendChild(p);const g=document.createElement("div");return g.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>",g.className="grammar-suggest-tooltip-discard",g.onclick=()=>{s(e,t)},a.appendChild(g),a},withYjs:!1},P={maxSelection:1e3},A=(e,t=D)=>{let a=!1;return new n({key:C,state:{init:()=>({lastText:"",decorations:s.empty,popupDecoration:s.empty}),apply(e,n,a,i){const r=e.getMeta(C);return(null==r?void 0:r.type)===h.suggestionUpdate?((e,t,n)=>{const{changedRegion:s,fix:a,mapping:i,text:r}=t,c=m(s.newText,a.result).filter((e=>!f(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:n,replacement:a})=>{const r=d(s.start+e,i),c=d(s.start+(a.endsWith("\n")?t-1:t),i),l={text:a.endsWith("\n")?a.slice(0,-1):a,originalText:n,id:{}};return o.inline(r,c,{class:"grammarSuggestion "+(""===a?"removalSuggestion":"")},l)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(n.doc,c),lastText:r})})(n,r,e):(null==r?void 0:r.type)===h.acceptSuggestion?((e,t,n)=>{const o=e.decorations.remove(e.decorations.find(0,n.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:T(n.doc),decorations:o.map(n.mapping,n.doc),popupDecoration:s.empty})})(n,r,e):(null==r?void 0:r.type)===h.openSuggestion?((e,t,n,a)=>{const{decoration:i}=t,r={id:i.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:s.create(n.doc,[o.widget(i.from,((e,t)=>{const n=t();return n?a.createUpdatePopup(e,i,n,L,E):document.createElement("div")}),Object.assign(Object.assign({},r),{stopEvent:()=>!0}))])})})(n,r,e,t):(null==r?void 0:r.type)===h.closeSuggestion?Object.assign(Object.assign({},n),{popupDecoration:s.empty}):(null==r?void 0:r.type)===h.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:s.empty}))(n,r,e):e.docChanged?((e,t,n,o)=>{const s=c(n.doc).text,{text:a,mapping:i}=c(t.doc);if(a===s)return e;let r=t.mapping;if(o){const e=t.doc.content.findDiffStart(n.doc.content),o=n.doc.content.findDiffEnd(t.doc.content),s=new l(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);r=new p([s])}const g=M(s,a),u=e.decorations.map(r,t.doc),m=d(g.start,i),f=d(g.end,i),h=e.popupDecoration.map(r,t.doc);return Object.assign(Object.assign({},e),{decorations:u.remove(u.find(m,f)),popupDecoration:h.remove(h.find(m,f))})})(n,e,a,t.withYjs):n}},props:{handleClick:k,decorations:e=>{const t=C.getState(e);if(!t)return null;const n=j.getState(e);return(null==n?void 0:n.status)!==w.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const n=((e,t)=>r((e=>{var n;const o=c(e.state.doc),s=(null===(n=C.getState(e.state))||void 0===n?void 0:n.lastText)||"",a=M(s,o.text);O(t,a.newText).then((t=>{if(T(e.state.doc)!==o.text)return;const n={type:h.suggestionUpdate,fix:t,changedRegion:a,mapping:o.mapping,text:o.text};e.dispatch(e.state.tr.setMeta(C,n))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(t,e);return{update(e,t){const o=C.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&a||!o||o.lastText===T(e.state.doc)||(a=!0,n(e))}}}})},I=(e,t,n,o,s,a,r)=>i(void 0,void 0,void 0,(function*(){var e;let n="";const c=new AbortController;try{const d=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},signal:c.signal,body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:s,params:r}})})).body)||void 0===e?void 0:e.getReader(),l=({done:e,value:t})=>i(void 0,void 0,void 0,(function*(){var i;if(e)return;if(null===(i=j.getState(o.state))||void 0===i?void 0:i.isCancelled)return void(yield c.abort());const r=(new TextDecoder).decode(t);try{n+=r,o.dispatch(o.state.tr.setMeta(j,Object.assign({type:s,status:w.streaming,result:n},a&&{selection:a})))}catch(e){console.error("Could not parse stream message",r,e)}return null==d?void 0:d.read().then(l)}));yield null==d?void 0:d.read().then(l),o.dispatch(o.state.tr.setMeta(j,Object.assign({type:s,status:w.finished,result:n},a&&{selection:a})))}catch(e){console.error("Error:",e)}})),B=(e,t=P)=>{let o=!1;return new n({key:j,state:{init:()=>({status:w.idle}),apply(e,t,n,s){const a=e.getMeta(j);return t.status===w.done||t.status===w.rejected?(o=!1,{status:w.idle}):(null==a?void 0:a.status)===w.cancelled?Object.assign(Object.assign(Object.assign({},t),a),{isCancelled:!0}):a&&(e=>Object.values(b).includes(e.type)||Object.values(S).includes(e.type))(a)?t.type&&a.type!==t.type?t:Object.assign(Object.assign({},t),a):t}},view:()=>({update(e,n){const s=j.getState(e.state);let a=e.state.tr;if((null==s?void 0:s.status)===w.new&&!o)switch(s.type){case S.Complete:o=!0,((e,t,n)=>{i(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(" "),I(0,o,0,t,S.Complete)}))})(0,e);break;case S.MakeLonger:case S.MakeShorter:case S.Improve:case S.Simplify:case S.Explain:case S.ActionItems:case b.Translate:case b.ChangeTone:o=!0,((e,t,n,o,s,a)=>{const i=n.state.selection;if(!i)return void n.dispatch(n.state.tr.setMeta(j,{task:e,status:w.done}));if(n.state.doc.textBetween(i.from,i.to).length>s)return void n.dispatch(n.state.tr.setMeta(j,{type:e,status:w.error,error:"Selection is too big"}));const r=n.state.doc.textBetween(i.from,i.to,"\n");I(0,r,0,n,e,i,a)})(s.type,0,e,0,t.maxSelection,s.params)}if((null==s?void 0:s.status)===w.accepted){if(s.error)return a.setMeta(j,{type:s.type,status:w.done}),void e.dispatch(a);switch(s.type){case S.Complete:a=a.insertText(s.result||"",e.state.doc.nodeSize-2),a.setMeta(j,{type:S.Complete,status:w.done}),e.dispatch(a),e.focus();break;case S.MakeLonger:case S.MakeShorter:case S.Improve:case S.Simplify:case S.Explain:case S.ActionItems:case b.Translate:case b.ChangeTone:if(s.selection&&s.result){const t=s.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),n=g.fromArray(t);a.selection.replace(a,new u(n,0,0))}a.setMeta(j,{type:s.type,status:w.done}),e.dispatch(a),e.focus()}}}})})};export{v as GrammarSuggestElementClass,h as GrammarSuggestMetaType,y as MoodParamType,b as OpenAiPromptsWithParam,S as OpenAiPromptsWithoutParam,w as Status,x as TranslationTargetLanguage,B as completePlugin,j as completePluginKey,I as completeRequest,P as defaultCompleteOptions,D as defaultOptions,M as getChangedRegions,A as grammarSuggestPlugin,O as suggescatRequest};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t,o,s,a,r,n=require("prosemirror-state"),i=require("prosemirror-view"),p=require("fast-diff"),c=require("tslib"),d=require("lodash.debounce"),l=require("@emergence-engineering/prosemirror-text-map"),u=require("prosemirror-transform"),g=require("prosemirror-model"),m=require("@emergence-engineering/fast-diff-merge");exports.GrammarSuggestMetaType=void 0,(e=exports.GrammarSuggestMetaType||(exports.GrammarSuggestMetaType={})).suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion",exports.GrammarSuggestElementClass=void 0,(exports.GrammarSuggestElementClass||(exports.GrammarSuggestElementClass={})).grammarSuggestPopup="grammar-suggest-popup",exports.MoodParamType=void 0,(t=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",t.Confident="Confident",t.Straightforward="Straightforward",t.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(o=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",o.Spanish="Spanish",o.French="French",o.German="German",o.Italian="Italian",o.Portuguese="Portuguese",o.Dutch="Dutch",o.Russian="Russian",o.Chinese="Chinese",o.Korean="Korean",o.Japanese="Japanese",exports.OpenAiPromptsWithoutParam=void 0,(s=exports.OpenAiPromptsWithoutParam||(exports.OpenAiPromptsWithoutParam={})).Complete="Complete",s.Improve="Improve",s.MakeLonger="MakeLonger",s.MakeShorter="MakeShorter",s.Simplify="Simplify",s.Explain="Explain",s.ActionItems="ActionItems",exports.OpenAiPromptsWithParam=void 0,(a=exports.OpenAiPromptsWithParam||(exports.OpenAiPromptsWithParam={})).ChangeTone="ChangeTone",a.Translate="Translate",exports.Status=void 0,(r=exports.Status||(exports.Status={})).idle="idle",r.new="new",r.streaming="streaming",r.finished="finished",r.accepted="accepted",r.cancelled="cancelled",r.rejected="rejected",r.done="done",r.error="error";const x=new n.PluginKey("completePlugin"),h=new n.PluginKey("grammarSuggestPlugin"),S=e=>{let t="",o="",s=!1;return e.descendants(((e,a)=>{if(console.log({node:e}),e.type.isBlock){if(!s)return void(s=!0);t+=`${o}\n`,o=""}else e.isText&&(o+=`${e.text}`)})),t+=o,t},f=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const o=p(e,t),s=o[0],a=s[0]===p.EQUAL?s[1].length-1:0,r=((e,t)=>{if(t[t.length-1][0]!==p.EQUAL)return e.length;const o=t.slice(0,t.length-1);let s=0;for(const e of o){const[t,o]=e;t===p.EQUAL&&(s+=o.length),t===p.DELETE&&(s+=o.length)}return s})(e,o),n=e.lastIndexOf("\n",a),i=e.indexOf("\n",r),c=-1===n?0:n+1,d=-1===i?e.length:i,l=e.slice(c,d),u=t.slice(c,t.length-(e.length-d));return{start:c,end:c+u.length,oldStart:c,oldEnd:d,oldText:l,newText:u}},P=(e,t)=>c.__awaiter(void 0,void 0,void 0,(function*(){const o=[...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:o}})}).then((e=>e.ok?e.json():Promise.reject(e))).then((e=>!e||e.some((e=>(e=>{try{JSON.parse(e)}catch(e){return!0}return!1})(e)))?{fixed:!1,result:t}:{result:e.map((e=>JSON.parse(e).result)).join("\n"),fixed:!0})).catch((e=>(e.text().then((t=>{console.error({status:e.status,text:t})})),{fixed:!1,result:t})))})),y=(e,t)=>{var o;const s=null===(o=h.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===t.spec.id))[0];if(!s)return;const{text:a}=s.spec,{from:r,to:i}=s,p={type:exports.GrammarSuggestMetaType.acceptSuggestion,id:t.spec.id},c=a.split("\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),d=g.Fragment.fromArray(c);let{tr:l}=e.state;l=l.setSelection(n.TextSelection.create(e.state.doc,r,i)),l.selection.replace(l,new g.Slice(d,1,1)),l.setMeta(h,p),e.dispatch(l)},v=(e,t)=>{const{spec:o}=t,s={type:exports.GrammarSuggestMetaType.discardSuggestion,id:o.id},a=e.state.tr.setMeta(h,s);e.dispatch(a)},T=(e,t)=>{const o=h.getState(e.state);if(!o)return!1;const{decorations:s}=o,a=s.find(t,t)[0];if(!a){const t={type:exports.GrammarSuggestMetaType.closeSuggestion};return e.dispatch(e.state.tr.setMeta(h,t)),!1}const r=o.popupDecoration.find()[0];if((null==r?void 0:r.spec.id)===a.spec.id)return!1;const n={type:exports.GrammarSuggestMetaType.openSuggestion,decoration:a};return e.dispatch(e.state.tr.setMeta(h,n)),!1},O={debounceMs:2e3,createUpdatePopup:(e,t,o,s,a)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:n}=t,i=e.dom.getBoundingClientRect();r.id=exports.GrammarSuggestElementClass.grammarSuggestPopup;const p=e.coordsAtPos(o),c=e.dom.scrollTop||0,d=e.dom.scrollLeft||0;r.style.left=`${p.left-i.left+d}px`,r.style.top=`${p.bottom-i.top+c+5}px`;const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=n.text||n.originalText,n.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{s(e,t)},r.appendChild(l);const u=document.createElement("div");return u.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>",u.className="grammar-suggest-tooltip-discard",u.onclick=()=>{a(e,t)},r.appendChild(u),r},withYjs:!1},M={maxSelection:1e3},w=(e,t,o,s,a,r,n)=>c.__awaiter(void 0,void 0,void 0,(function*(){var e;let o="";const i=new AbortController;try{const p=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},signal:i.signal,body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:a,params:n}})})).body)||void 0===e?void 0:e.getReader(),d=({done:e,value:t})=>c.__awaiter(void 0,void 0,void 0,(function*(){var n;if(e)return;if(null===(n=x.getState(s.state))||void 0===n?void 0:n.isCancelled)return void(yield i.abort());const c=(new TextDecoder).decode(t);try{o+=c,s.dispatch(s.state.tr.setMeta(x,Object.assign({type:a,status:exports.Status.streaming,result:o},r&&{selection:r})))}catch(e){console.error("Could not parse stream message",c,e)}return null==p?void 0:p.read().then(d)}));yield null==p?void 0:p.read().then(d),s.dispatch(s.state.tr.setMeta(x,Object.assign({type:a,status:exports.Status.finished,result:o},r&&{selection:r})))}catch(e){console.error("Error:",e)}}));Object.defineProperty(exports,"getDiff",{enumerable:!0,get:function(){return m.getDiff}}),exports.completePlugin=(e,t=M)=>{let o=!1;return new n.Plugin({key:x,state:{init:()=>({status:exports.Status.idle}),apply(e,t,s,a){const r=e.getMeta(x);return t.status===exports.Status.done||t.status===exports.Status.rejected?(o=!1,{status:exports.Status.idle}):(null==r?void 0:r.status)===exports.Status.cancelled?Object.assign(Object.assign(Object.assign({},t),r),{isCancelled:!0}):r&&(e=>Object.values(exports.OpenAiPromptsWithParam).includes(e.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(e.type))(r)?t.type&&r.type!==t.type?t:Object.assign(Object.assign({},t),r):t}},view:()=>({update(e,s){const a=x.getState(e.state);let r=e.state.tr;if((null==a?void 0:a.status)===exports.Status.new&&!o)switch(a.type){case exports.OpenAiPromptsWithoutParam.Complete:o=!0,((e,t,o)=>{c.__awaiter(void 0,void 0,void 0,(function*(){const{doc:e}=t.state,o=[];e.descendants((e=>{"paragraph"===e.type.name&&o.push(e.textContent)}));let s="";s=o.length>=2?o.slice(-2).join(" "):o.join(" "),w(0,s,0,t,exports.OpenAiPromptsWithoutParam.Complete)}))})(0,e);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,((e,t,o,s,a,r)=>{const n=o.state.selection;if(!n)return void o.dispatch(o.state.tr.setMeta(x,{task:e,status:exports.Status.done}));if(o.state.doc.textBetween(n.from,n.to).length>a)return void o.dispatch(o.state.tr.setMeta(x,{type:e,status:exports.Status.error,error:"Selection is too big"}));const i=o.state.doc.textBetween(n.from,n.to,"\n");w(0,i,0,o,e,n,r)})(a.type,0,e,0,t.maxSelection,a.params)}if((null==a?void 0:a.status)===exports.Status.accepted){if(a.error)return r.setMeta(x,{type:a.type,status:exports.Status.done}),void e.dispatch(r);switch(a.type){case exports.OpenAiPromptsWithoutParam.Complete:r=r.insertText(a.result||"",e.state.doc.nodeSize-2),r.setMeta(x,{type:exports.OpenAiPromptsWithoutParam.Complete,status:exports.Status.done}),e.dispatch(r),e.focus();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:if(a.selection&&a.result){const t=a.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),o=g.Fragment.fromArray(t);r.selection.replace(r,new g.Slice(o,0,0))}r.setMeta(x,{type:a.type,status:exports.Status.done}),e.dispatch(r),e.focus()}}}})})},exports.completePluginKey=x,exports.completeRequest=w,exports.defaultCompleteOptions=M,exports.defaultOptions=O,exports.getChangedRegions=f,exports.grammarSuggestPlugin=(e,t=O)=>{let o=!1;return new n.Plugin({key:h,state:{init:()=>({lastText:"",decorations:i.DecorationSet.empty,popupDecoration:i.DecorationSet.empty}),apply(e,o,s,a){const r=e.getMeta(h);return(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.suggestionUpdate?((e,t,o)=>{const{changedRegion:s,fix:a,mapping:r,text:n}=t,p=m.getDiff(s.newText,a.result).filter((e=>!m.isIdentity(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:o,replacement:a})=>{const n=l.textPosToDocPos(s.start+e,r),p=l.textPosToDocPos(s.start+(a.endsWith("\n")?t-1:t),r),c={text:a.endsWith("\n")?a.slice(0,-1):a,originalText:o,id:{}};return i.Decoration.inline(n,p,{class:"grammarSuggestion "+(""===a?"removalSuggestion":"")},c)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(o.doc,p),lastText:n})})(o,r,e):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.acceptSuggestion?((e,t,o)=>{const s=e.decorations.remove(e.decorations.find(0,o.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:S(o.doc),decorations:s.map(o.mapping,o.doc),popupDecoration:i.DecorationSet.empty})})(o,r,e):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.openSuggestion?((e,t,o,s)=>{const{decoration:a}=t,r={id:a.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:i.DecorationSet.create(o.doc,[i.Decoration.widget(a.from,((e,t)=>{const o=t();return o?s.createUpdatePopup(e,a,o,y,v):document.createElement("div")}),Object.assign(Object.assign({},r),{stopEvent:()=>!0}))])})})(o,r,e,t):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.closeSuggestion?Object.assign(Object.assign({},o),{popupDecoration:i.DecorationSet.empty}):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.discardSuggestion?((e,t,o)=>Object.assign(Object.assign({},e),{decorations:e.decorations.remove(e.decorations.find(0,o.doc.nodeSize,(e=>e.id===t.id))),popupDecoration:i.DecorationSet.empty}))(o,r,e):e.docChanged?((e,t,o,s)=>{const a=l.docToTextWithMapping(o.doc).text,{text:r,mapping:n}=l.docToTextWithMapping(t.doc);if(r===a)return e;let i=t.mapping;if(s){const e=t.doc.content.findDiffStart(o.doc.content),s=o.doc.content.findDiffEnd(t.doc.content),a=s&&e?new u.StepMap([e,s.a-e,s.b-e]):new u.StepMap([0,0,0]);i=new u.Mapping([a])}const p=f(a,r),c=e.decorations.map(i,t.doc),d=l.textPosToDocPos(p.start,n),g=l.textPosToDocPos(p.end,n),m=e.popupDecoration.map(i,t.doc);return Object.assign(Object.assign({},e),{decorations:c.remove(c.find(d,g)),popupDecoration:m.remove(m.find(d,g))})})(o,e,s,t.withYjs):o}},props:{handleClick:T,decorations:e=>{const t=h.getState(e);if(!t)return null;const o=x.getState(e);return(null==o?void 0:o.status)!==exports.Status.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const s=((e,t)=>d((e=>{var o;const s=l.docToTextWithMapping(e.state.doc),a=(null===(o=h.getState(e.state))||void 0===o?void 0:o.lastText)||"",r=f(a,s.text);P(t,r.newText).then((t=>{if(S(e.state.doc)!==s.text)return;const o={type:exports.GrammarSuggestMetaType.suggestionUpdate,fix:t,changedRegion:r,mapping:s.mapping,text:s.text};e.dispatch(e.state.tr.setMeta(h,o))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(t,e);return{update(e,t){const a=h.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&o||!a||a.lastText===S(e.state.doc)||(o=!0,s(e))}}}})},exports.suggescatRequest=P;
|
|
1
|
+
"use strict";var e,t,o,s,a,r,n=require("prosemirror-state"),i=require("prosemirror-view"),p=require("fast-diff"),c=require("tslib"),d=require("lodash.debounce"),l=require("@emergence-engineering/prosemirror-text-map"),u=require("prosemirror-transform"),g=require("prosemirror-model"),m=require("@emergence-engineering/fast-diff-merge");exports.GrammarSuggestMetaType=void 0,(e=exports.GrammarSuggestMetaType||(exports.GrammarSuggestMetaType={})).suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion",exports.GrammarSuggestElementClass=void 0,(exports.GrammarSuggestElementClass||(exports.GrammarSuggestElementClass={})).grammarSuggestPopup="grammar-suggest-popup",exports.MoodParamType=void 0,(t=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",t.Confident="Confident",t.Straightforward="Straightforward",t.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(o=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",o.Spanish="Spanish",o.French="French",o.German="German",o.Italian="Italian",o.Portuguese="Portuguese",o.Dutch="Dutch",o.Russian="Russian",o.Chinese="Chinese",o.Korean="Korean",o.Japanese="Japanese",exports.OpenAiPromptsWithoutParam=void 0,(s=exports.OpenAiPromptsWithoutParam||(exports.OpenAiPromptsWithoutParam={})).Complete="Complete",s.Improve="Improve",s.MakeLonger="MakeLonger",s.MakeShorter="MakeShorter",s.Simplify="Simplify",s.Explain="Explain",s.ActionItems="ActionItems",exports.OpenAiPromptsWithParam=void 0,(a=exports.OpenAiPromptsWithParam||(exports.OpenAiPromptsWithParam={})).ChangeTone="ChangeTone",a.Translate="Translate",exports.Status=void 0,(r=exports.Status||(exports.Status={})).idle="idle",r.new="new",r.streaming="streaming",r.finished="finished",r.accepted="accepted",r.cancelled="cancelled",r.rejected="rejected",r.done="done",r.error="error";const x=new n.PluginKey("completePlugin"),h=new n.PluginKey("grammarSuggestPlugin"),S=e=>{let t="",o="",s=!1;return e.descendants(((e,a)=>{if(e.type.isBlock){if(!s)return void(s=!0);t+=`${o}\n`,o=""}else e.isText&&(o+=`${e.text}`)})),t+=o,t},f=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const o=p(e,t),s=o[0],a=s[0]===p.EQUAL?s[1].length-1:0,r=((e,t)=>{if(t[t.length-1][0]!==p.EQUAL)return e.length;const o=t.slice(0,t.length-1);let s=0;for(const e of o){const[t,o]=e;t===p.EQUAL&&(s+=o.length),t===p.DELETE&&(s+=o.length)}return s})(e,o),n=e.lastIndexOf("\n",a),i=e.indexOf("\n",r),c=-1===n?0:n+1,d=-1===i?e.length:i,l=e.slice(c,d),u=t.slice(c,t.length-(e.length-d));return{start:c,end:c+u.length,oldStart:c,oldEnd:d,oldText:l,newText:u}},P=(e,t)=>c.__awaiter(void 0,void 0,void 0,(function*(){const o=[...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:o}})}).then((e=>e.ok?e.json():Promise.reject(e))).then((e=>(null==e?void 0:e.length)?{result:e.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})))})),y=(e,t)=>{var o;const s=null===(o=h.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===t.spec.id))[0];if(!s)return;const{text:a}=s.spec,{from:r,to:i}=s,p={type:exports.GrammarSuggestMetaType.acceptSuggestion,id:t.spec.id},c=a.split("\n").map((t=>t?e.state.schema.node("paragraph",null,e.state.schema.text(t||"")):e.state.schema.node("paragraph"))),d=g.Fragment.fromArray(c);let{tr:l}=e.state;l=l.setSelection(n.TextSelection.create(e.state.doc,r,i)),l.selection.replace(l,new g.Slice(d,1,1)),l.setMeta(h,p),e.dispatch(l)},v=(e,t)=>{const{spec:o}=t,s={type:exports.GrammarSuggestMetaType.discardSuggestion,id:o.id},a=e.state.tr.setMeta(h,s);e.dispatch(a)},T=(e,t)=>{const o=h.getState(e.state);if(!o)return!1;const{decorations:s}=o,a=s.find(t,t)[0];if(!a){const t={type:exports.GrammarSuggestMetaType.closeSuggestion};return e.dispatch(e.state.tr.setMeta(h,t)),!1}const r=o.popupDecoration.find()[0];if((null==r?void 0:r.spec.id)===a.spec.id)return!1;const n={type:exports.GrammarSuggestMetaType.openSuggestion,decoration:a};return e.dispatch(e.state.tr.setMeta(h,n)),!1},O={debounceMs:2e3,createUpdatePopup:(e,t,o,s,a)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:n}=t,i=e.dom.getBoundingClientRect();r.id=exports.GrammarSuggestElementClass.grammarSuggestPopup;const p=e.coordsAtPos(o),c=e.dom.scrollTop||0,d=e.dom.scrollLeft||0;r.style.left=`${p.left-i.left+d}px`,r.style.top=`${p.bottom-i.top+c+5}px`;const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=n.text||n.originalText,n.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{s(e,t)},r.appendChild(l);const u=document.createElement("div");return u.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>",u.className="grammar-suggest-tooltip-discard",u.onclick=()=>{a(e,t)},r.appendChild(u),r},withYjs:!1},M={maxSelection:1e3},w=(e,t,o,s,a,r,n)=>c.__awaiter(void 0,void 0,void 0,(function*(){var e;let o="";const i=new AbortController;try{const p=null===(e=(yield fetch("https://suggestion-gw5lxik4dq-uc.a.run.app",{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:"Bearer -qKivjCv6MfQSmgF438PjEY7RnLfqoVe"},signal:i.signal,body:JSON.stringify({model:"gpt-3.5-turbo",modelParams:{input:[t],task:a,params:n}})})).body)||void 0===e?void 0:e.getReader(),d=({done:e,value:t})=>c.__awaiter(void 0,void 0,void 0,(function*(){var n;if(e)return;if(null===(n=x.getState(s.state))||void 0===n?void 0:n.isCancelled)return void(yield i.abort());const c=(new TextDecoder).decode(t);try{o+=c,s.dispatch(s.state.tr.setMeta(x,Object.assign({type:a,status:exports.Status.streaming,result:o},r&&{selection:r})))}catch(e){console.error("Could not parse stream message",c,e)}return null==p?void 0:p.read().then(d)}));yield null==p?void 0:p.read().then(d),s.dispatch(s.state.tr.setMeta(x,Object.assign({type:a,status:exports.Status.finished,result:o},r&&{selection:r})))}catch(e){console.error("Error:",e)}}));Object.defineProperty(exports,"getDiff",{enumerable:!0,get:function(){return m.getDiff}}),exports.completePlugin=(e,t=M)=>{let o=!1;return new n.Plugin({key:x,state:{init:()=>({status:exports.Status.idle}),apply(e,t,s,a){const r=e.getMeta(x);return t.status===exports.Status.done||t.status===exports.Status.rejected?(o=!1,{status:exports.Status.idle}):(null==r?void 0:r.status)===exports.Status.cancelled?Object.assign(Object.assign(Object.assign({},t),r),{isCancelled:!0}):r&&(e=>Object.values(exports.OpenAiPromptsWithParam).includes(e.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(e.type))(r)?t.type&&r.type!==t.type?t:Object.assign(Object.assign({},t),r):t}},view:()=>({update(e,s){const a=x.getState(e.state);let r=e.state.tr;if((null==a?void 0:a.status)===exports.Status.new&&!o)switch(a.type){case exports.OpenAiPromptsWithoutParam.Complete:o=!0,((e,t,o)=>{c.__awaiter(void 0,void 0,void 0,(function*(){const{doc:e}=t.state,o=[];e.descendants((e=>{"paragraph"===e.type.name&&o.push(e.textContent)}));let s="";s=o.length>=2?o.slice(-2).join(" "):o.join(" "),w(0,s,0,t,exports.OpenAiPromptsWithoutParam.Complete)}))})(0,e);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,((e,t,o,s,a,r)=>{const n=o.state.selection;if(!n)return void o.dispatch(o.state.tr.setMeta(x,{task:e,status:exports.Status.done}));if(o.state.doc.textBetween(n.from,n.to).length>a)return void o.dispatch(o.state.tr.setMeta(x,{type:e,status:exports.Status.error,error:"Selection is too big"}));const i=o.state.doc.textBetween(n.from,n.to,"\n");w(0,i,0,o,e,n,r)})(a.type,0,e,0,t.maxSelection,a.params)}if((null==a?void 0:a.status)===exports.Status.accepted){if(a.error)return r.setMeta(x,{type:a.type,status:exports.Status.done}),void e.dispatch(r);switch(a.type){case exports.OpenAiPromptsWithoutParam.Complete:r=r.insertText(a.result||"",e.state.doc.nodeSize-2),r.setMeta(x,{type:exports.OpenAiPromptsWithoutParam.Complete,status:exports.Status.done}),e.dispatch(r),e.focus();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:if(a.selection&&a.result){const t=a.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),o=g.Fragment.fromArray(t);r.selection.replace(r,new g.Slice(o,0,0))}r.setMeta(x,{type:a.type,status:exports.Status.done}),e.dispatch(r),e.focus()}}}})})},exports.completePluginKey=x,exports.completeRequest=w,exports.defaultCompleteOptions=M,exports.defaultOptions=O,exports.getChangedRegions=f,exports.grammarSuggestPlugin=(e,t=O)=>{let o=!1;return new n.Plugin({key:h,state:{init:()=>({lastText:"",decorations:i.DecorationSet.empty,popupDecoration:i.DecorationSet.empty}),apply(e,o,s,a){const r=e.getMeta(h);return(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.suggestionUpdate?((e,t,o)=>{const{changedRegion:s,fix:a,mapping:r,text:n}=t,p=m.getDiff(s.newText,a.result).filter((e=>!m.isIdentity(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:o,replacement:a})=>{const n=l.textPosToDocPos(s.start+e,r),p=l.textPosToDocPos(s.start+(a.endsWith("\n")?t-1:t),r),c={text:a.endsWith("\n")?a.slice(0,-1):a,originalText:o,id:{}};return i.Decoration.inline(n,p,{class:"grammarSuggestion "+(""===a?"removalSuggestion":"")},c)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(o.doc,p),lastText:n})})(o,r,e):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.acceptSuggestion?((e,t,o)=>{const s=e.decorations.remove(e.decorations.find(0,o.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:S(o.doc),decorations:s.map(o.mapping,o.doc),popupDecoration:i.DecorationSet.empty})})(o,r,e):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.openSuggestion?((e,t,o,s)=>{const{decoration:a}=t,r={id:a.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:i.DecorationSet.create(o.doc,[i.Decoration.widget(a.from,((e,t)=>{const o=t();return o?s.createUpdatePopup(e,a,o,y,v):document.createElement("div")}),Object.assign(Object.assign({},r),{stopEvent:()=>!0}))])})})(o,r,e,t):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.closeSuggestion?Object.assign(Object.assign({},o),{popupDecoration:i.DecorationSet.empty}):(null==r?void 0:r.type)===exports.GrammarSuggestMetaType.discardSuggestion?((e,t,o)=>Object.assign(Object.assign({},e),{decorations:e.decorations.remove(e.decorations.find(0,o.doc.nodeSize,(e=>e.id===t.id))),popupDecoration:i.DecorationSet.empty}))(o,r,e):e.docChanged?((e,t,o,s)=>{const a=l.docToTextWithMapping(o.doc).text,{text:r,mapping:n}=l.docToTextWithMapping(t.doc);if(r===a)return e;let i=t.mapping;if(s){const e=t.doc.content.findDiffStart(o.doc.content),s=o.doc.content.findDiffEnd(t.doc.content),a=s&&e?new u.StepMap([e,s.a-e,s.b-e]):new u.StepMap([0,0,0]);i=new u.Mapping([a])}const p=f(a,r),c=e.decorations.map(i,t.doc),d=l.textPosToDocPos(p.start,n),g=l.textPosToDocPos(p.end,n),m=e.popupDecoration.map(i,t.doc);return Object.assign(Object.assign({},e),{decorations:c.remove(c.find(d,g)),popupDecoration:m.remove(m.find(d,g))})})(o,e,s,t.withYjs):o}},props:{handleClick:T,decorations:e=>{const t=h.getState(e);if(!t)return null;const o=x.getState(e);return(null==o?void 0:o.status)!==exports.Status.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const s=((e,t)=>d((e=>{var o;const s=l.docToTextWithMapping(e.state.doc),a=(null===(o=h.getState(e.state))||void 0===o?void 0:o.lastText)||"",r=f(a,s.text);P(t,r.newText).then((t=>{if(S(e.state.doc)!==s.text)return;const o={type:exports.GrammarSuggestMetaType.suggestionUpdate,fix:t,changedRegion:r,mapping:s.mapping,text:s.text};e.dispatch(e.state.tr.setMeta(h,o))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(t,e);return{update(e,t){const a=h.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&o||!a||a.lastText===S(e.state.doc)||(o=!0,s(e))}}}})},exports.suggescatRequest=P;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prosemirror-suggestcat-plugin",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
},
|
|
20
20
|
"homepage": "https://github.com/emergence-engineering/prosemirror-suggestcat-plugin#readme",
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@emergence-engineering/fast-diff-merge": "^0.0.
|
|
22
|
+
"@emergence-engineering/fast-diff-merge": "^0.0.5",
|
|
23
23
|
"@emergence-engineering/prosemirror-text-map": "^0.0.3",
|
|
24
24
|
"eslint": "^8.29.0",
|
|
25
25
|
"eslint-config-airbnb": "^19.0.4",
|
|
26
|
-
"eslint-config-prettier": "^8.
|
|
26
|
+
"eslint-config-prettier": "^8.8.0",
|
|
27
27
|
"eslint-plugin-import": "^2.26.0",
|
|
28
28
|
"eslint-plugin-jest": "^27.1.6",
|
|
29
|
-
"eslint-plugin-prettier": "^
|
|
29
|
+
"eslint-plugin-prettier": "^5.0.0",
|
|
30
30
|
"fast-diff": "^1.3.0",
|
|
31
31
|
"lodash.debounce": "^4.0.8",
|
|
32
32
|
"prosemirror-model": "^1.19.3",
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
"prosemirror-test-builder": "^1.1.1",
|
|
35
35
|
"prosemirror-transform": "^1.7.3",
|
|
36
36
|
"prosemirror-view": "^1.31.4",
|
|
37
|
+
"rimraf": "^6.0.1",
|
|
37
38
|
"tslib": "^2.6.1"
|
|
38
39
|
},
|
|
39
40
|
"devDependencies": {
|
|
@@ -43,7 +44,7 @@
|
|
|
43
44
|
"jest": "^29.5.0",
|
|
44
45
|
"np": "^7.6.2",
|
|
45
46
|
"npm-check": "^6.0.1",
|
|
46
|
-
"prettier": "^
|
|
47
|
+
"prettier": "^3.0.0",
|
|
47
48
|
"rollup": "^3.7.4",
|
|
48
49
|
"rollup-plugin-copy": "^3.4.0",
|
|
49
50
|
"rollup-plugin-minification": "^0.2.0",
|
package/dist/completePlugin.js
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
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
|
-
if (pluginState.status === Status.done ||
|
|
29
|
-
pluginState.status === Status.rejected) {
|
|
30
|
-
streaming = false;
|
|
31
|
-
return { status: Status.idle };
|
|
32
|
-
}
|
|
33
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.status) === Status.cancelled) {
|
|
34
|
-
return Object.assign(Object.assign(Object.assign({}, pluginState), meta), { isCancelled: true });
|
|
35
|
-
}
|
|
36
|
-
if (meta && isCompleteMeta(meta)) {
|
|
37
|
-
if (pluginState.type && meta.type !== pluginState.type) {
|
|
38
|
-
return pluginState;
|
|
39
|
-
}
|
|
40
|
-
return Object.assign(Object.assign({}, pluginState), meta);
|
|
41
|
-
}
|
|
42
|
-
return pluginState;
|
|
43
|
-
},
|
|
44
|
-
},
|
|
45
|
-
view() {
|
|
46
|
-
return {
|
|
47
|
-
update(view, prevState) {
|
|
48
|
-
const pluginState = completePluginKey.getState(view.state);
|
|
49
|
-
/* eslint-disable prefer-destructuring */
|
|
50
|
-
let tr = view.state.tr;
|
|
51
|
-
if ((pluginState === null || pluginState === void 0 ? void 0 : pluginState.status) === Status.new && !streaming) {
|
|
52
|
-
switch (pluginState.type) {
|
|
53
|
-
case OpenAiPromptsWithoutParam.Complete:
|
|
54
|
-
streaming = true;
|
|
55
|
-
completeRequest(pluginState, view, apiKey);
|
|
56
|
-
console.log("complete");
|
|
57
|
-
break;
|
|
58
|
-
case OpenAiPromptsWithoutParam.MakeLonger:
|
|
59
|
-
case OpenAiPromptsWithoutParam.MakeShorter:
|
|
60
|
-
case OpenAiPromptsWithoutParam.Improve:
|
|
61
|
-
case OpenAiPromptsWithoutParam.Simplify:
|
|
62
|
-
case OpenAiPromptsWithoutParam.Explain:
|
|
63
|
-
case OpenAiPromptsWithoutParam.ActionItems:
|
|
64
|
-
case OpenAiPromptsWithParam.Translate:
|
|
65
|
-
case OpenAiPromptsWithParam.ChangeTone:
|
|
66
|
-
streaming = true;
|
|
67
|
-
makeShorterLonger(pluginState.type, pluginState, view, apiKey, options.maxSelection, pluginState.params);
|
|
68
|
-
console.log("improve selected text");
|
|
69
|
-
break;
|
|
70
|
-
default:
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
if ((pluginState === null || pluginState === void 0 ? void 0 : pluginState.status) === Status.accepted) {
|
|
75
|
-
if (pluginState.error) {
|
|
76
|
-
tr.setMeta(completePluginKey, {
|
|
77
|
-
type: pluginState.type,
|
|
78
|
-
status: Status.done,
|
|
79
|
-
});
|
|
80
|
-
view.dispatch(tr);
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
switch (pluginState.type) {
|
|
84
|
-
case OpenAiPromptsWithoutParam.Complete:
|
|
85
|
-
tr = tr.insertText(pluginState.result || "", view.state.doc.nodeSize - 2);
|
|
86
|
-
tr.setMeta(completePluginKey, {
|
|
87
|
-
type: OpenAiPromptsWithoutParam.Complete,
|
|
88
|
-
status: Status.done,
|
|
89
|
-
});
|
|
90
|
-
view.dispatch(tr);
|
|
91
|
-
view.focus();
|
|
92
|
-
console.log("complete accepted V1");
|
|
93
|
-
break;
|
|
94
|
-
case OpenAiPromptsWithoutParam.MakeLonger:
|
|
95
|
-
case OpenAiPromptsWithoutParam.MakeShorter:
|
|
96
|
-
case OpenAiPromptsWithoutParam.Improve:
|
|
97
|
-
case OpenAiPromptsWithoutParam.Simplify:
|
|
98
|
-
case OpenAiPromptsWithoutParam.Explain:
|
|
99
|
-
case OpenAiPromptsWithoutParam.ActionItems:
|
|
100
|
-
case OpenAiPromptsWithParam.Translate:
|
|
101
|
-
case OpenAiPromptsWithParam.ChangeTone:
|
|
102
|
-
if (pluginState.selection && pluginState.result) {
|
|
103
|
-
const content = pluginState.result;
|
|
104
|
-
const paragraphs = content.split("\n\n");
|
|
105
|
-
const paragraphNodes = paragraphs.map((paragraph) => view.state.schema.node("paragraph", null, view.state.schema.text(paragraph)));
|
|
106
|
-
const fragment = Fragment.fromArray(paragraphNodes);
|
|
107
|
-
tr.selection.replace(tr, new Slice(fragment, 0, 0));
|
|
108
|
-
}
|
|
109
|
-
tr.setMeta(completePluginKey, {
|
|
110
|
-
type: pluginState.type,
|
|
111
|
-
status: Status.done,
|
|
112
|
-
});
|
|
113
|
-
view.dispatch(tr);
|
|
114
|
-
view.focus();
|
|
115
|
-
console.log("makeShorterLonger acceptedV1");
|
|
116
|
-
break;
|
|
117
|
-
default:
|
|
118
|
-
break;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
},
|
|
122
|
-
};
|
|
123
|
-
},
|
|
124
|
-
});
|
|
125
|
-
};
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { GrammarSuggestElementClass } from "./types";
|
|
2
|
-
export const createUpdatePopup = (view, decoration, pos, applySuggestion, discardSuggestion) => {
|
|
3
|
-
const root = document.createElement("div");
|
|
4
|
-
root.className = "grammar-suggest-tooltip";
|
|
5
|
-
const { spec } = decoration;
|
|
6
|
-
const boundingRect = view.dom.getBoundingClientRect();
|
|
7
|
-
root.id = GrammarSuggestElementClass.grammarSuggestPopup;
|
|
8
|
-
const coords = view.coordsAtPos(pos);
|
|
9
|
-
const editorTopScroll = view.dom.scrollTop || 0;
|
|
10
|
-
const editorLeftScroll = view.dom.scrollLeft || 0;
|
|
11
|
-
root.style.left = `${coords.left - boundingRect.left + editorLeftScroll}px`;
|
|
12
|
-
root.style.top = `${coords.bottom - boundingRect.top + editorTopScroll + 5}px`;
|
|
13
|
-
const applyButton = document.createElement("div");
|
|
14
|
-
applyButton.className = "grammar-suggest-tooltip-apply";
|
|
15
|
-
applyButton.innerText = spec.text || spec.originalText;
|
|
16
|
-
console.log({ spec });
|
|
17
|
-
if (!spec.text) {
|
|
18
|
-
applyButton.style.textDecoration = "line-through";
|
|
19
|
-
applyButton.style.color = "red";
|
|
20
|
-
}
|
|
21
|
-
applyButton.onclick = () => {
|
|
22
|
-
applySuggestion(view, decoration);
|
|
23
|
-
};
|
|
24
|
-
root.appendChild(applyButton);
|
|
25
|
-
const discardButton = document.createElement("div");
|
|
26
|
-
discardButton.innerHTML =
|
|
27
|
-
"<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>";
|
|
28
|
-
discardButton.className = "grammar-suggest-tooltip-discard";
|
|
29
|
-
discardButton.onclick = () => {
|
|
30
|
-
discardSuggestion(view, decoration);
|
|
31
|
-
};
|
|
32
|
-
root.appendChild(discardButton);
|
|
33
|
-
return root;
|
|
34
|
-
};
|
package/dist/eventHandlers.js
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
import { Decoration, DecorationSet } from "prosemirror-view";
|
|
2
|
-
import { TextSelection } from "prosemirror-state";
|
|
3
|
-
import { Mapping, StepMap } from "prosemirror-transform";
|
|
4
|
-
import { Fragment, Slice } from "prosemirror-model";
|
|
5
|
-
import { isIdentity } from "@emergence-engineering/fast-diff-merge";
|
|
6
|
-
import { textPosToDocPos } from "@emergence-engineering/prosemirror-text-map";
|
|
7
|
-
import { GrammarSuggestMetaType, } from "./types";
|
|
8
|
-
import { getChangedRegions, getTextWithNewlines, grammarSuggestPluginKey, } from "./utils";
|
|
9
|
-
import { getDiff } from "./getDiff";
|
|
10
|
-
import { docToTextWithMapping } from "./makeRequest";
|
|
11
|
-
console.log("wtf");
|
|
12
|
-
export const handleUpdate = (pluginState, meta, tr) => {
|
|
13
|
-
// Add decorations
|
|
14
|
-
console.log("another here");
|
|
15
|
-
const { changedRegion, fix, mapping, text } = meta;
|
|
16
|
-
const newDecorations = getDiff(changedRegion.newText, fix.result)
|
|
17
|
-
.filter((i) => !isIdentity(i))
|
|
18
|
-
.filter((i) => i.original !== `${i.replacement}\n`)
|
|
19
|
-
.map(({ from, to, original, replacement }) => {
|
|
20
|
-
const decorationFrom = textPosToDocPos(changedRegion.start + from, mapping);
|
|
21
|
-
const decorationTo = textPosToDocPos(changedRegion.start + (replacement.endsWith("\n") ? to - 1 : to), mapping);
|
|
22
|
-
const decorationText = replacement.endsWith("\n")
|
|
23
|
-
? replacement.slice(0, -1)
|
|
24
|
-
: replacement;
|
|
25
|
-
const spec = {
|
|
26
|
-
text: decorationText,
|
|
27
|
-
originalText: original,
|
|
28
|
-
id: {},
|
|
29
|
-
};
|
|
30
|
-
return Decoration.inline(decorationFrom, decorationTo, {
|
|
31
|
-
class: `grammarSuggestion ${replacement === "" ? "removalSuggestion" : ""}`,
|
|
32
|
-
}, spec);
|
|
33
|
-
});
|
|
34
|
-
console.log({ newDecorations });
|
|
35
|
-
return Object.assign(Object.assign({}, pluginState), { decorations: pluginState.decorations.add(tr.doc, newDecorations), lastText: text });
|
|
36
|
-
};
|
|
37
|
-
export const handleAccept = (pluginState, meta, tr) => {
|
|
38
|
-
const newDecorations = pluginState.decorations.remove(pluginState.decorations.find(0, tr.doc.nodeSize, (spec) => spec.id === meta.id));
|
|
39
|
-
return Object.assign(Object.assign({}, pluginState), { lastText: getTextWithNewlines(tr.doc), decorations: newDecorations.map(tr.mapping, tr.doc), popupDecoration: DecorationSet.empty });
|
|
40
|
-
};
|
|
41
|
-
export const handleDocChange = (pluginState, tr, oldState, withYjs) => {
|
|
42
|
-
// Do it more efficiently. There's no need to calculate the whole mapping etc.
|
|
43
|
-
const oldText = docToTextWithMapping(oldState.doc).text;
|
|
44
|
-
const { text, mapping } = docToTextWithMapping(tr.doc);
|
|
45
|
-
if (text === oldText)
|
|
46
|
-
return pluginState;
|
|
47
|
-
let pmMapping = tr.mapping;
|
|
48
|
-
if (withYjs) {
|
|
49
|
-
const diffStart = tr.doc.content.findDiffStart(oldState.doc.content);
|
|
50
|
-
const diffEnd = oldState.doc.content.findDiffEnd(tr.doc.content);
|
|
51
|
-
console.log("here");
|
|
52
|
-
const map = diffEnd && diffStart
|
|
53
|
-
? new StepMap([diffStart, diffEnd.a - diffStart, diffEnd.b - diffStart])
|
|
54
|
-
: new StepMap([0, 0, 0]);
|
|
55
|
-
pmMapping = new Mapping([map]);
|
|
56
|
-
}
|
|
57
|
-
const changedRegion = getChangedRegions(oldText, text);
|
|
58
|
-
const mappedDecorations = pluginState.decorations.map(pmMapping, tr.doc);
|
|
59
|
-
const decorationsStart = textPosToDocPos(changedRegion.start, mapping);
|
|
60
|
-
const decorationsEnd = textPosToDocPos(changedRegion.end, mapping);
|
|
61
|
-
const mappedPopupDecoration = pluginState.popupDecoration.map(pmMapping, tr.doc);
|
|
62
|
-
return Object.assign(Object.assign({}, pluginState), { decorations: mappedDecorations.remove(mappedDecorations.find(decorationsStart, decorationsEnd)), popupDecoration: mappedPopupDecoration.remove(mappedPopupDecoration.find(decorationsStart, decorationsEnd)) });
|
|
63
|
-
};
|
|
64
|
-
const applySuggestion = (view, decoration) => {
|
|
65
|
-
var _a;
|
|
66
|
-
const currentDecoration = (_a = grammarSuggestPluginKey
|
|
67
|
-
.getState(view.state)) === null || _a === void 0 ? void 0 : _a.decorations.find(0, view.state.doc.nodeSize, (spec) => spec.id === decoration.spec.id)[0];
|
|
68
|
-
if (!currentDecoration)
|
|
69
|
-
return;
|
|
70
|
-
const { text } = currentDecoration.spec;
|
|
71
|
-
const { from, to } = currentDecoration;
|
|
72
|
-
const meta = {
|
|
73
|
-
type: GrammarSuggestMetaType.acceptSuggestion,
|
|
74
|
-
id: decoration.spec.id,
|
|
75
|
-
};
|
|
76
|
-
const paragraphs = text.split("\n");
|
|
77
|
-
const paragraphNodes = paragraphs.map((paragraph) => view.state.schema.node("paragraph", null, view.state.schema.text(paragraph)));
|
|
78
|
-
const fragment = Fragment.fromArray(paragraphNodes);
|
|
79
|
-
let { tr } = view.state;
|
|
80
|
-
tr = tr.setSelection(TextSelection.create(view.state.doc, from, to));
|
|
81
|
-
tr.selection.replace(tr, new Slice(fragment, 1, 1));
|
|
82
|
-
tr.setMeta(grammarSuggestPluginKey, meta);
|
|
83
|
-
view.dispatch(tr);
|
|
84
|
-
};
|
|
85
|
-
const discardSuggestion = (view, decoration) => {
|
|
86
|
-
const { spec } = decoration;
|
|
87
|
-
const meta = {
|
|
88
|
-
type: GrammarSuggestMetaType.discardSuggestion,
|
|
89
|
-
id: spec.id,
|
|
90
|
-
};
|
|
91
|
-
const tr = view.state.tr.setMeta(grammarSuggestPluginKey, meta);
|
|
92
|
-
view.dispatch(tr);
|
|
93
|
-
};
|
|
94
|
-
export const handleOpenSuggestion = (pluginState, meta, tr, options) => {
|
|
95
|
-
const { decoration } = meta;
|
|
96
|
-
const spec = { id: decoration.spec.id };
|
|
97
|
-
return Object.assign(Object.assign({}, pluginState), { popupDecoration: DecorationSet.create(tr.doc, [
|
|
98
|
-
Decoration.widget(decoration.from, (view, getPos) => {
|
|
99
|
-
const pos = getPos();
|
|
100
|
-
if (!pos)
|
|
101
|
-
return document.createElement("div");
|
|
102
|
-
return options.createUpdatePopup(view, decoration, pos, applySuggestion, discardSuggestion);
|
|
103
|
-
}, Object.assign(Object.assign({}, spec), { stopEvent: () => true })),
|
|
104
|
-
]) });
|
|
105
|
-
};
|
|
106
|
-
export const handleClick = (view, pos) => {
|
|
107
|
-
const pluginState = grammarSuggestPluginKey.getState(view.state);
|
|
108
|
-
if (!pluginState)
|
|
109
|
-
return false;
|
|
110
|
-
const { decorations } = pluginState;
|
|
111
|
-
const decoration = decorations.find(pos, pos)[0];
|
|
112
|
-
if (!decoration) {
|
|
113
|
-
const meta = {
|
|
114
|
-
type: GrammarSuggestMetaType.closeSuggestion,
|
|
115
|
-
};
|
|
116
|
-
view.dispatch(view.state.tr.setMeta(grammarSuggestPluginKey, meta));
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
119
|
-
const popupDecoration = pluginState.popupDecoration.find()[0];
|
|
120
|
-
if ((popupDecoration === null || popupDecoration === void 0 ? void 0 : popupDecoration.spec.id) === decoration.spec.id)
|
|
121
|
-
return false;
|
|
122
|
-
const meta = {
|
|
123
|
-
type: GrammarSuggestMetaType.openSuggestion,
|
|
124
|
-
decoration,
|
|
125
|
-
};
|
|
126
|
-
view.dispatch(view.state.tr.setMeta(grammarSuggestPluginKey, meta));
|
|
127
|
-
return false;
|
|
128
|
-
};
|
|
129
|
-
export const handleDiscardSuggestion = (pluginState, meta, tr) => {
|
|
130
|
-
return Object.assign(Object.assign({}, pluginState), { decorations: pluginState.decorations.remove(pluginState.decorations.find(0, tr.doc.nodeSize, (spec) => spec.id === meta.id)), popupDecoration: DecorationSet.empty });
|
|
131
|
-
};
|
package/dist/getDiff.d.ts
DELETED
package/dist/getDiff.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { convertDiffToReplaceSet, mergeReplacePair, } from "@emergence-engineering/fast-diff-merge";
|
|
2
|
-
import diff from "fast-diff";
|
|
3
|
-
const reduceReplaceSet = (replaceSet) => {
|
|
4
|
-
return replaceSet.reduce((acc, curr) => {
|
|
5
|
-
const last = acc[acc.length - 1];
|
|
6
|
-
const head = acc.slice(0, acc.length - 1);
|
|
7
|
-
if (!last)
|
|
8
|
-
return [curr];
|
|
9
|
-
const merged = mergeReplacePair(last, curr);
|
|
10
|
-
return [...head, ...merged];
|
|
11
|
-
}, []);
|
|
12
|
-
};
|
|
13
|
-
export const getDiff = (original, fixed) => {
|
|
14
|
-
const changes = diff(original, fixed);
|
|
15
|
-
const replaceSet = convertDiffToReplaceSet(changes);
|
|
16
|
-
return reduceReplaceSet(reduceReplaceSet(replaceSet));
|
|
17
|
-
};
|
package/dist/makeRequest.js
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
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 debounce from "lodash.debounce";
|
|
11
|
-
import { docToTextWithMapping } from "@emergence-engineering/prosemirror-text-map";
|
|
12
|
-
import { getChangedRegions, getTextWithNewlines, grammarSuggestPluginKey, } from "./utils";
|
|
13
|
-
import { GrammarSuggestMetaType, } from "./types";
|
|
14
|
-
const isJsonString = (str) => {
|
|
15
|
-
try {
|
|
16
|
-
JSON.parse(str);
|
|
17
|
-
}
|
|
18
|
-
catch (e) {
|
|
19
|
-
return true;
|
|
20
|
-
}
|
|
21
|
-
return false;
|
|
22
|
-
};
|
|
23
|
-
export const request = (apiKey, text) => __awaiter(void 0, void 0, void 0, function* () {
|
|
24
|
-
const input = [...text.split("\n")];
|
|
25
|
-
return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion", {
|
|
26
|
-
method: "POST",
|
|
27
|
-
cache: "no-cache",
|
|
28
|
-
headers: {
|
|
29
|
-
"Content-Type": "application/json",
|
|
30
|
-
Authorization: `Bearer ${apiKey}`,
|
|
31
|
-
},
|
|
32
|
-
body: JSON.stringify({
|
|
33
|
-
model: "gpt-3.5-turbo",
|
|
34
|
-
modelParams: {
|
|
35
|
-
input,
|
|
36
|
-
},
|
|
37
|
-
}),
|
|
38
|
-
})
|
|
39
|
-
.then((response) => {
|
|
40
|
-
if (response.ok) {
|
|
41
|
-
return response.json();
|
|
42
|
-
}
|
|
43
|
-
return Promise.reject(response);
|
|
44
|
-
})
|
|
45
|
-
.then((jsonData) => {
|
|
46
|
-
if (!jsonData || jsonData.some((i) => isJsonString(i))) {
|
|
47
|
-
return {
|
|
48
|
-
fixed: false,
|
|
49
|
-
result: text,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
return {
|
|
53
|
-
result: jsonData
|
|
54
|
-
.map((data) => JSON.parse(data).result)
|
|
55
|
-
.join("\n"),
|
|
56
|
-
fixed: true,
|
|
57
|
-
};
|
|
58
|
-
})
|
|
59
|
-
.catch((e) => {
|
|
60
|
-
e.text().then((text) => {
|
|
61
|
-
console.error({ status: e.status, text });
|
|
62
|
-
});
|
|
63
|
-
return {
|
|
64
|
-
fixed: false,
|
|
65
|
-
result: text,
|
|
66
|
-
};
|
|
67
|
-
});
|
|
68
|
-
});
|
|
69
|
-
export const createMakeRequest = (options, apiKey) => debounce((view) => {
|
|
70
|
-
var _a;
|
|
71
|
-
// The document changed, start API request
|
|
72
|
-
const versionAtRequestStart = docToTextWithMapping(view.state.doc);
|
|
73
|
-
const oldText = ((_a = grammarSuggestPluginKey.getState(view.state)) === null || _a === void 0 ? void 0 : _a.lastText) || "";
|
|
74
|
-
const changedRegion = getChangedRegions(oldText, versionAtRequestStart.text);
|
|
75
|
-
request(apiKey, changedRegion.newText)
|
|
76
|
-
.then((fix) => {
|
|
77
|
-
// Check if the document version has changed while we were waiting
|
|
78
|
-
if (getTextWithNewlines(view.state.doc) !== versionAtRequestStart.text) {
|
|
79
|
-
// The state changed, abort
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
// State did not change, update the plugin state
|
|
83
|
-
const meta = {
|
|
84
|
-
type: GrammarSuggestMetaType.suggestionUpdate,
|
|
85
|
-
fix,
|
|
86
|
-
changedRegion,
|
|
87
|
-
mapping: versionAtRequestStart.mapping,
|
|
88
|
-
text: versionAtRequestStart.text,
|
|
89
|
-
};
|
|
90
|
-
view.dispatch(view.state.tr.setMeta(grammarSuggestPluginKey, meta));
|
|
91
|
-
})
|
|
92
|
-
.catch((error) => {
|
|
93
|
-
console.error("Grammar suggest API error", error);
|
|
94
|
-
});
|
|
95
|
-
}, options.debounceMs);
|
package/dist/makeTaksRequest.js
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
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
|
-
export const request = (apiKey, text, pluginState, view, task, selection, params) => __awaiter(void 0, void 0, void 0, function* () {
|
|
13
|
-
var _a;
|
|
14
|
-
let res = "";
|
|
15
|
-
const controller = new AbortController();
|
|
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
|
-
signal: controller.signal,
|
|
25
|
-
body: JSON.stringify({
|
|
26
|
-
model: "gpt-3.5-turbo",
|
|
27
|
-
modelParams: {
|
|
28
|
-
input: [text],
|
|
29
|
-
task,
|
|
30
|
-
params,
|
|
31
|
-
},
|
|
32
|
-
}),
|
|
33
|
-
});
|
|
34
|
-
const reader = (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader();
|
|
35
|
-
const processStream = ({ done, value }) => __awaiter(void 0, void 0, void 0, function* () {
|
|
36
|
-
var _b;
|
|
37
|
-
if (done) {
|
|
38
|
-
return;
|
|
39
|
-
}
|
|
40
|
-
if ((_b = completePluginKey.getState(view.state)) === null || _b === void 0 ? void 0 : _b.isCancelled) {
|
|
41
|
-
yield controller.abort();
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
const chunk = new TextDecoder().decode(value);
|
|
45
|
-
try {
|
|
46
|
-
res += chunk;
|
|
47
|
-
view.dispatch(view.state.tr.setMeta(completePluginKey, Object.assign({ type: task, status: Status.streaming, result: res }, (selection && { selection }))));
|
|
48
|
-
}
|
|
49
|
-
catch (error) {
|
|
50
|
-
console.error("Could not parse stream message", chunk, error);
|
|
51
|
-
}
|
|
52
|
-
// Continue processing the stream
|
|
53
|
-
/* eslint-disable-next-line consistent-return */
|
|
54
|
-
return reader === null || reader === void 0 ? void 0 : reader.read().then(processStream);
|
|
55
|
-
});
|
|
56
|
-
yield (reader === null || reader === void 0 ? void 0 : reader.read().then(processStream));
|
|
57
|
-
view.dispatch(view.state.tr.setMeta(completePluginKey, Object.assign({ type: task, status: Status.finished, result: res }, (selection && { selection }))));
|
|
58
|
-
}
|
|
59
|
-
catch (error) {
|
|
60
|
-
console.error("Error:", error);
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
export const completeRequest = (pluginState, view, apiKey) => __awaiter(void 0, void 0, void 0, function* () {
|
|
64
|
-
// get last 2 paragraphs from state.doc
|
|
65
|
-
const { doc } = view.state;
|
|
66
|
-
const paragraphNodes = [];
|
|
67
|
-
doc.descendants((node) => {
|
|
68
|
-
if (node.type.name === "paragraph") {
|
|
69
|
-
paragraphNodes.push(node.textContent);
|
|
70
|
-
}
|
|
71
|
-
});
|
|
72
|
-
let text = "";
|
|
73
|
-
if (paragraphNodes.length >= 2) {
|
|
74
|
-
text = paragraphNodes.slice(-2).join(" ");
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
text = paragraphNodes.join(" ");
|
|
78
|
-
}
|
|
79
|
-
request(apiKey, text, pluginState, view, OpenAiPromptsWithoutParam.Complete);
|
|
80
|
-
});
|
|
81
|
-
export const makeShorterLonger = (task, pluginState, view, apiKey, maxSelection, params) => {
|
|
82
|
-
const selection = view.state.selection;
|
|
83
|
-
if (!selection) {
|
|
84
|
-
view.dispatch(view.state.tr.setMeta(completePluginKey, {
|
|
85
|
-
task,
|
|
86
|
-
status: Status.done,
|
|
87
|
-
}));
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
// if selection is too big
|
|
91
|
-
const selectedText = view.state.doc.textBetween(selection.from, selection.to);
|
|
92
|
-
if (selectedText.length > maxSelection) {
|
|
93
|
-
view.dispatch(view.state.tr.setMeta(completePluginKey, {
|
|
94
|
-
type: task,
|
|
95
|
-
status: Status.error,
|
|
96
|
-
error: "Selection is too big",
|
|
97
|
-
}));
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
const text = view.state.doc.textBetween(selection.from, selection.to, "\n");
|
|
101
|
-
request(apiKey, text, pluginState, view, task, selection, params);
|
|
102
|
-
};
|
package/dist/mapping.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { Node } from "prosemirror-model";
|
|
2
|
-
import { TextMappingItem } from "./types";
|
|
3
|
-
export declare const docToTextWithMapping: (doc: Node) => {
|
|
4
|
-
text: string;
|
|
5
|
-
mapping: TextMappingItem[];
|
|
6
|
-
};
|
|
7
|
-
export declare const textPosToDocPos: (textPos: number, mapping: TextMappingItem[]) => number;
|
package/dist/mapping.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/mapping.test.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { EditorState } from "prosemirror-state";
|
|
2
|
-
import { doc, p, h1, schema } from "prosemirror-test-builder";
|
|
3
|
-
import { textPosToDocPos, docToTextWithMapping } from "./mapping";
|
|
4
|
-
describe("mapping utils for empty doc", () => {
|
|
5
|
-
const initialDoc = doc();
|
|
6
|
-
const { text, mapping } = docToTextWithMapping(initialDoc);
|
|
7
|
-
expect(text).toEqual("");
|
|
8
|
-
expect(mapping).toEqual([{ docPos: 1, textPos: 0 }]);
|
|
9
|
-
});
|
|
10
|
-
describe("mapping utils", () => {
|
|
11
|
-
const initialDoc = doc(p("test"), h1("test2"));
|
|
12
|
-
const state = EditorState.create({ doc: initialDoc, schema });
|
|
13
|
-
const { text, mapping } = docToTextWithMapping(initialDoc);
|
|
14
|
-
console.log({ text, mapping });
|
|
15
|
-
const cases = Array.from(new Array(text.length)).map((i, idx) => idx);
|
|
16
|
-
it.each(cases)("map between text position and document position", (idx) => {
|
|
17
|
-
// Create an insertion in the text. Map that position to a document position, apply a transaction with a character insert, get the text back.
|
|
18
|
-
// The two texts should be the same.
|
|
19
|
-
const textPosition = textPosToDocPos(idx, mapping);
|
|
20
|
-
const newDoc = state.tr.insertText("a", textPosition).doc;
|
|
21
|
-
const newText = docToTextWithMapping(newDoc).text;
|
|
22
|
-
expect(newText).toEqual(`${text.slice(0, idx)}a${text.slice(idx)}`);
|
|
23
|
-
});
|
|
24
|
-
});
|
package/dist/mergeDiffs.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import diff from "fast-diff";
|
|
2
|
-
export interface Replace {
|
|
3
|
-
from: number;
|
|
4
|
-
to: number;
|
|
5
|
-
original: string;
|
|
6
|
-
replacement: string;
|
|
7
|
-
}
|
|
8
|
-
export declare const isIdentity: (replace: Replace) => boolean;
|
|
9
|
-
export declare const convertDiffToReplaceSet: (diffSet: diff.Diff[]) => Replace[];
|
|
10
|
-
export declare const mergeReplacePair: (leftReplace: Replace, rightReplace: Replace) => Replace[];
|
|
11
|
-
export declare const getDiff: (original: string, fixed: string) => Replace[];
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/plugin.js
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { Plugin } from "prosemirror-state";
|
|
2
|
-
import { DecorationSet } from "prosemirror-view";
|
|
3
|
-
import { completePluginKey, getTextWithNewlines, grammarSuggestPluginKey, } from "./utils";
|
|
4
|
-
import { GrammarSuggestMetaType, Status, } from "./types";
|
|
5
|
-
import { createMakeRequest } from "./makeRequest";
|
|
6
|
-
import { handleAccept, handleClick, handleDiscardSuggestion, handleDocChange, handleOpenSuggestion, handleUpdate, } from "./eventHandlers";
|
|
7
|
-
import { defaultOptions } from "./defaults";
|
|
8
|
-
console.log("wtf2");
|
|
9
|
-
export const grammarSuggestPlugin = (apiKey, options = defaultOptions) => {
|
|
10
|
-
let init = false;
|
|
11
|
-
return new Plugin({
|
|
12
|
-
key: grammarSuggestPluginKey,
|
|
13
|
-
state: {
|
|
14
|
-
init() {
|
|
15
|
-
return {
|
|
16
|
-
lastText: "",
|
|
17
|
-
decorations: DecorationSet.empty,
|
|
18
|
-
popupDecoration: DecorationSet.empty,
|
|
19
|
-
};
|
|
20
|
-
},
|
|
21
|
-
apply(tr, pluginState, oldState, newState) {
|
|
22
|
-
console.log("apply");
|
|
23
|
-
const meta = tr.getMeta(grammarSuggestPluginKey);
|
|
24
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.type) === GrammarSuggestMetaType.suggestionUpdate) {
|
|
25
|
-
return handleUpdate(pluginState, meta, tr);
|
|
26
|
-
}
|
|
27
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.type) === GrammarSuggestMetaType.acceptSuggestion) {
|
|
28
|
-
return handleAccept(pluginState, meta, tr);
|
|
29
|
-
}
|
|
30
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.type) === GrammarSuggestMetaType.openSuggestion) {
|
|
31
|
-
return handleOpenSuggestion(pluginState, meta, tr, options);
|
|
32
|
-
}
|
|
33
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.type) === GrammarSuggestMetaType.closeSuggestion) {
|
|
34
|
-
return Object.assign(Object.assign({}, pluginState), { popupDecoration: DecorationSet.empty });
|
|
35
|
-
}
|
|
36
|
-
if ((meta === null || meta === void 0 ? void 0 : meta.type) === GrammarSuggestMetaType.discardSuggestion) {
|
|
37
|
-
return handleDiscardSuggestion(pluginState, meta, tr);
|
|
38
|
-
}
|
|
39
|
-
// return the new plugin state after a transaction
|
|
40
|
-
if (tr.docChanged) {
|
|
41
|
-
return handleDocChange(pluginState, tr, oldState, options.withYjs);
|
|
42
|
-
}
|
|
43
|
-
return pluginState;
|
|
44
|
-
},
|
|
45
|
-
},
|
|
46
|
-
props: {
|
|
47
|
-
handleClick,
|
|
48
|
-
decorations: (state) => {
|
|
49
|
-
const pluginState = grammarSuggestPluginKey.getState(state);
|
|
50
|
-
if (!pluginState)
|
|
51
|
-
return null;
|
|
52
|
-
const completePluginState = completePluginKey.getState(state);
|
|
53
|
-
if ((completePluginState === null || completePluginState === void 0 ? void 0 : completePluginState.status) !== Status.idle)
|
|
54
|
-
return pluginState.decorations;
|
|
55
|
-
return pluginState.decorations.add(state.doc, pluginState.popupDecoration.find());
|
|
56
|
-
},
|
|
57
|
-
},
|
|
58
|
-
view() {
|
|
59
|
-
const makeRequest = createMakeRequest(options, apiKey);
|
|
60
|
-
return {
|
|
61
|
-
update(view, prevState) {
|
|
62
|
-
const pluginState = grammarSuggestPluginKey.getState(view.state);
|
|
63
|
-
// When editor state changes, check if the version changed
|
|
64
|
-
if ((view.state.doc.textBetween(0, view.state.doc.nodeSize - 2, "/n") !==
|
|
65
|
-
prevState.doc.textBetween(0, prevState.doc.nodeSize - 2, "/n") ||
|
|
66
|
-
!init) &&
|
|
67
|
-
pluginState &&
|
|
68
|
-
pluginState.lastText !== getTextWithNewlines(view.state.doc)) {
|
|
69
|
-
console.log("inside if");
|
|
70
|
-
init = true;
|
|
71
|
-
makeRequest(view);
|
|
72
|
-
}
|
|
73
|
-
},
|
|
74
|
-
};
|
|
75
|
-
},
|
|
76
|
-
});
|
|
77
|
-
};
|
package/dist/utils.js
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import { PluginKey } from "prosemirror-state";
|
|
2
|
-
import diff from "fast-diff";
|
|
3
|
-
import { OpenAiPromptsWithoutParam, OpenAiPromptsWithParam, } from "./types";
|
|
4
|
-
export const completePluginKey = new PluginKey("completePlugin");
|
|
5
|
-
export const isCompleteMeta = (meta) => {
|
|
6
|
-
return (Object.values(OpenAiPromptsWithParam).includes(meta.type) ||
|
|
7
|
-
Object.values(OpenAiPromptsWithoutParam).includes(meta.type));
|
|
8
|
-
};
|
|
9
|
-
export const grammarSuggestPluginKey = new PluginKey("grammarSuggestPlugin");
|
|
10
|
-
export const getTextWithNewlines = (doc) => {
|
|
11
|
-
let text = "";
|
|
12
|
-
let currentBlock = "";
|
|
13
|
-
let firstBlockDone = false;
|
|
14
|
-
doc.descendants((node, pos) => {
|
|
15
|
-
console.log({ node });
|
|
16
|
-
if (node.type.isBlock) {
|
|
17
|
-
if (!firstBlockDone) {
|
|
18
|
-
firstBlockDone = true;
|
|
19
|
-
return;
|
|
20
|
-
}
|
|
21
|
-
text += `${currentBlock}\n`;
|
|
22
|
-
currentBlock = "";
|
|
23
|
-
}
|
|
24
|
-
else if (node.isText) {
|
|
25
|
-
currentBlock += `${node.text}`; // itt hianyzik a `\n`
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
text += currentBlock;
|
|
29
|
-
return text;
|
|
30
|
-
};
|
|
31
|
-
export const getLastChangePos = (oldText, changes) => {
|
|
32
|
-
const lastChange = changes[changes.length - 1];
|
|
33
|
-
if (lastChange[0] !== diff.EQUAL)
|
|
34
|
-
return oldText.length;
|
|
35
|
-
const changesWithoutLast = changes.slice(0, changes.length - 1);
|
|
36
|
-
let lastChangePos = 0;
|
|
37
|
-
for (const change of changesWithoutLast) {
|
|
38
|
-
const [type, text] = change;
|
|
39
|
-
if (type === diff.EQUAL) {
|
|
40
|
-
lastChangePos += text.length;
|
|
41
|
-
}
|
|
42
|
-
if (type === diff.DELETE) {
|
|
43
|
-
lastChangePos += text.length;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return lastChangePos;
|
|
47
|
-
};
|
|
48
|
-
// TODO: when enters are pressed the new paragraphs are not part of the region
|
|
49
|
-
// - Make a diff between the last stored text and the current one.
|
|
50
|
-
// - We get the end of the beginning identity and the start of the end identity.
|
|
51
|
-
// - Get the first & last newlines before the start and after the end.
|
|
52
|
-
export const getChangedRegions = (oldText, newText) => {
|
|
53
|
-
if (oldText === newText)
|
|
54
|
-
return {
|
|
55
|
-
start: oldText.length,
|
|
56
|
-
end: oldText.length,
|
|
57
|
-
oldStart: oldText.length,
|
|
58
|
-
oldEnd: oldText.length,
|
|
59
|
-
oldText: "",
|
|
60
|
-
newText: "",
|
|
61
|
-
};
|
|
62
|
-
const changes = diff(oldText, newText);
|
|
63
|
-
const fistChange = changes[0];
|
|
64
|
-
const firstChangePos = fistChange[0] === diff.EQUAL ? fistChange[1].length - 1 : 0;
|
|
65
|
-
const lastChangePos = getLastChangePos(oldText, changes);
|
|
66
|
-
const firstNewlinePosFromFirstChange = oldText.lastIndexOf("\n", firstChangePos);
|
|
67
|
-
const lastNewlinePosFromLastChange = oldText.indexOf("\n", lastChangePos);
|
|
68
|
-
const oldStart = firstNewlinePosFromFirstChange === -1
|
|
69
|
-
? 0
|
|
70
|
-
: firstNewlinePosFromFirstChange + 1;
|
|
71
|
-
const oldEnd = lastNewlinePosFromLastChange === -1
|
|
72
|
-
? oldText.length
|
|
73
|
-
: lastNewlinePosFromLastChange;
|
|
74
|
-
const oldChange = oldText.slice(oldStart, oldEnd);
|
|
75
|
-
const newChange = newText.slice(oldStart, newText.length - (oldText.length - oldEnd));
|
|
76
|
-
return {
|
|
77
|
-
start: oldStart,
|
|
78
|
-
end: oldStart + newChange.length,
|
|
79
|
-
oldStart,
|
|
80
|
-
oldEnd,
|
|
81
|
-
oldText: oldChange,
|
|
82
|
-
newText: newChange,
|
|
83
|
-
};
|
|
84
|
-
};
|