prosemirror-suggestcat-plugin 0.1.11 → 0.1.13
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/eventHandlers.js +2 -2
- package/dist/index.d.ts +5 -3
- package/dist/index.es.js +1 -1
- package/dist/index.js +1 -1
- package/dist/makeRequest.d.ts +2 -1
- package/dist/makeRequest.js +4 -5
- package/dist/makeTaksRequest.d.ts +2 -0
- package/dist/makeTaksRequest.js +102 -0
- package/dist/mapping.test.js +24 -0
- package/dist/utils.d.ts +1 -0
- package/package.json +3 -1
package/dist/eventHandlers.js
CHANGED
|
@@ -2,10 +2,10 @@ import { Decoration, DecorationSet } from "prosemirror-view";
|
|
|
2
2
|
import { TextSelection } from "prosemirror-state";
|
|
3
3
|
import { Mapping, StepMap } from "prosemirror-transform";
|
|
4
4
|
import { Fragment, Slice } from "prosemirror-model";
|
|
5
|
+
import { getDiff, isIdentity } from "@emergence-engineering/fast-diff-merge";
|
|
6
|
+
import { docToTextWithMapping, textPosToDocPos, } from "@emergence-engineering/prosemirror-text-map";
|
|
5
7
|
import { GrammarSuggestMetaType, } from "./types";
|
|
6
8
|
import { getChangedRegions, getTextWithNewlines, grammarSuggestPluginKey, } from "./utils";
|
|
7
|
-
import { getDiff, isIdentity } from "./mergeDiffs";
|
|
8
|
-
import { docToTextWithMapping, textPosToDocPos } from "./mapping";
|
|
9
9
|
export const handleUpdate = (pluginState, meta, tr) => {
|
|
10
10
|
// Add decorations
|
|
11
11
|
const { changedRegion, fix, mapping, text } = meta;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export { grammarSuggestPlugin } from "./plugin";
|
|
2
2
|
export { defaultOptions, defaultCompleteOptions } from "./defaults";
|
|
3
|
-
export { completePluginKey } from "./utils";
|
|
3
|
+
export { completePluginKey, getChangedRegions } from "./utils";
|
|
4
4
|
export { completePlugin } from "./completePlugin";
|
|
5
|
-
export
|
|
6
|
-
export
|
|
5
|
+
export * from "./types";
|
|
6
|
+
export { request as completeRequest } from "./makeTaksRequest";
|
|
7
|
+
export { request as suggescatRequest } from "./makeRequest";
|
|
8
|
+
export { getDiff } from "@emergence-engineering/fast-diff-merge";
|
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 r}from"prosemirror-view";import s from"fast-diff";import{__awaiter as a}from"tslib";import i from"lodash.debounce";import{StepMap as c,Mapping as l}from"prosemirror-transform";import{Fragment as d,Slice as p}from"prosemirror-model";var g,u,m,h,f,x,v;!function(e){e.suggestionUpdate="suggestionUpdate",e.acceptSuggestion="acceptSuggestion",e.openSuggestion="openSuggestion",e.closeSuggestion="closeSuggestion",e.discardSuggestion="discardSuggestion"}(g||(g={})),function(e){e.grammarSuggestPopup="grammar-suggest-popup"}(u||(u={})),function(e){e.Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly"}(m||(m={})),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"}(h||(h={})),function(e){e.Complete="Complete",e.Improve="Improve",e.MakeLonger="MakeLonger",e.MakeShorter="MakeShorter",e.Simplify="Simplify",e.Explain="Explain",e.ActionItems="ActionItems"}(f||(f={})),function(e){e.ChangeTone="ChangeTone",e.Translate="Translate"}(x||(x={})),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"}(v||(v={}));const y=new e("completePlugin"),S=new e("grammarSuggestPlugin"),w=e=>{let t="";return e.descendants(((e,n)=>{e.isText&&(t+=`${e.text}\n`)})),t},b=(e,t)=>{if(e===t)return{start:e.length,end:e.length,oldStart:e.length,oldEnd:e.length,oldText:"",newText:""};const n=s(e,t),o=n[0],r=o[0]===s.EQUAL?o[1].length-1:0,a=((e,t)=>{if(t[t.length-1][0]!==s.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===s.EQUAL&&(o+=n.length),t===s.DELETE&&(o+=n.length)}return o})(e,n),i=e.lastIndexOf("\n",r),c=e.indexOf("\n",a),l=-1===i?0:i+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}],C=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")},O=(e,t)=>a(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})))})),E=e=>e.replacement===e.original,M=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(E(e)&&E(t))return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}];if(E(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(E(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)]}),[]),P=(e,t)=>{const n=(e=>{let t=0;return e.map((([e,n])=>{switch(e){case s.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 s.DELETE:const r={from:t,to:t+n.length,original:n,replacement:""};return t+=n.length,[r];case s.INSERT:return[{from:t,to:t,original:"",replacement:n}]}})).flat()})(s(e,t));return M(M(n))},L=(e,n)=>{var o;const r=null===(o=S.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===n.spec.id))[0];if(!r)return;const{text:s}=r.spec,{from:a,to:i}=r,c={type:g.acceptSuggestion,id:n.spec.id},l=s.split("\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),u=d.fromArray(l);let{tr:m}=e.state;m=m.setSelection(t.create(e.state.doc,a,i)),m.selection.replace(m,new p(u,1,1)),m.setMeta(S,c),e.dispatch(m)},k=(e,t)=>{const{spec:n}=t,o={type:g.discardSuggestion,id:n.id},r=e.state.tr.setMeta(S,o);e.dispatch(r)},D=(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:g.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 a={type:g.openSuggestion,decoration:r};return e.dispatch(e.state.tr.setMeta(S,a)),!1},A={debounceMs:2e3,createUpdatePopup:(e,t,n,o,r)=>{const s=document.createElement("div");s.className="grammar-suggest-tooltip";const{spec:a}=t,i=e.dom.getBoundingClientRect();s.id=u.grammarSuggestPopup;const c=e.coordsAtPos(n),l=e.dom.scrollTop||0,d=e.dom.scrollLeft||0;s.style.left=`${c.left-i.left+d}px`,s.style.top=`${c.bottom-i.top+l+5}px`;const p=document.createElement("div");p.className="grammar-suggest-tooltip-apply",p.innerText=a.text||a.originalText,a.text||(p.style.textDecoration="line-through",p.style.color="red"),p.onclick=()=>{o(e,t)},s.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=()=>{r(e,t)},s.appendChild(g),s},withYjs:!1},I={maxSelection:1e3},R=(e,t=A)=>{let s=!1;return new n({key:S,state:{init:()=>({lastText:"",decorations:r.empty,popupDecoration:r.empty}),apply(e,n,s,a){const i=e.getMeta(S);return(null==i?void 0:i.type)===g.suggestionUpdate?((e,t,n)=>{const{changedRegion:r,fix:s,mapping:a,text:i}=t,c=P(r.newText,s.result).filter((e=>!E(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:n,replacement:s})=>{const i=T(r.start+e,a),c=T(r.start+(s.endsWith("\n")?t-1:t),a),l={text:s.endsWith("\n")?s.slice(0,-1):s,originalText:n,id:{}};return o.inline(i,c,{class:"grammarSuggestion "+(""===s?"removalSuggestion":"")},l)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(n.doc,c),lastText:i})})(n,i,e):(null==i?void 0:i.type)===g.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:w(n.doc),decorations:o.map(n.mapping,n.doc),popupDecoration:r.empty})})(n,i,e):(null==i?void 0:i.type)===g.openSuggestion?((e,t,n,s)=>{const{decoration:a}=t,i={id:a.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:r.create(n.doc,[o.widget(a.from,((e,t)=>{const n=t();return n?s.createUpdatePopup(e,a,n,L,k):document.createElement("div")}),Object.assign(Object.assign({},i),{stopEvent:()=>!0}))])})})(n,i,e,t):(null==i?void 0:i.type)===g.closeSuggestion?Object.assign(Object.assign({},n),{popupDecoration:r.empty}):(null==i?void 0:i.type)===g.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:r.empty}))(n,i,e):e.docChanged?((e,t,n,o)=>{const r=C(n.doc).text,{text:s,mapping:a}=C(t.doc);if(s===r)return e;let i=t.mapping;if(o){const e=t.doc.content.findDiffStart(n.doc.content),o=n.doc.content.findDiffEnd(t.doc.content),r=new c(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);i=new l([r])}const d=b(r,s),p=e.decorations.map(i,t.doc),g=T(d.start,a),u=T(d.end,a),m=e.popupDecoration.map(i,t.doc);return Object.assign(Object.assign({},e),{decorations:p.remove(p.find(g,u)),popupDecoration:m.remove(m.find(g,u))})})(n,e,s,t.withYjs):n}},props:{handleClick:D,decorations:e=>{const t=S.getState(e);if(!t)return null;const n=y.getState(e);return(null==n?void 0:n.status)!==v.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const n=((e,t)=>i((e=>{var n;const o=C(e.state.doc),r=(null===(n=S.getState(e.state))||void 0===n?void 0:n.lastText)||"",s=b(r,o.text);O(t,s.newText).then((t=>{if(w(e.state.doc)!==o.text)return;const n={type:g.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))(t,e);return{update(e,t){const o=S.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&s||!o||o.lastText===w(e.state.doc)||(s=!0,n(e))}}}})},U=(e,t,n,o,r,s,i)=>a(void 0,void 0,void 0,(function*(){var e;let n="";const c=new AbortController;try{const l=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:r,params:i}})})).body)||void 0===e?void 0:e.getReader(),d=({done:e,value:t})=>a(void 0,void 0,void 0,(function*(){var a;if(e)return;if(null===(a=y.getState(o.state))||void 0===a?void 0:a.isCancelled)return void(yield c.abort());const i=(new TextDecoder).decode(t);try{n+=i,o.dispatch(o.state.tr.setMeta(y,Object.assign({type:r,status:v.streaming,result:n},s&&{selection:s})))}catch(e){console.error("Could not parse stream message",i,e)}return null==l?void 0:l.read().then(d)}));yield null==l?void 0:l.read().then(d),o.dispatch(o.state.tr.setMeta(y,Object.assign({type:r,status:v.finished,result:n},s&&{selection:s})))}catch(e){console.error("Error:",e)}})),N=(e,t=I)=>{let o=!1;return new n({key:y,state:{init:()=>({status:v.idle}),apply(e,t,n,r){const s=e.getMeta(y);return t.status===v.done||t.status===v.rejected?(o=!1,{status:v.idle}):(null==s?void 0:s.status)===v.cancelled?Object.assign(Object.assign(Object.assign({},t),s),{isCancelled:!0}):s&&(e=>Object.values(x).includes(e.type)||Object.values(f).includes(e.type))(s)?t.type&&s.type!==t.type?t:Object.assign(Object.assign({},t),s):t}},view:()=>({update(e,n){const r=y.getState(e.state);let s=e.state.tr;if((null==r?void 0:r.status)===v.new&&!o)switch(r.type){case f.Complete:o=!0,((e,t,n)=>{a(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(" "),U(0,o,0,t,f.Complete)}))})(0,e);break;case f.MakeLonger:case f.MakeShorter:case f.Improve:case f.Simplify:case f.Explain:case f.ActionItems:case x.Translate:case x.ChangeTone:o=!0,((e,t,n,o,r,s)=>{const a=n.state.selection;if(!a)return void n.dispatch(n.state.tr.setMeta(y,{task:e,status:v.done}));if(n.state.doc.textBetween(a.from,a.to).length>r)return void n.dispatch(n.state.tr.setMeta(y,{type:e,status:v.error,error:"Selection is too big"}));const i=n.state.doc.textBetween(a.from,a.to,"\n");U(0,i,0,n,e,a,s)})(r.type,0,e,0,t.maxSelection,r.params)}if((null==r?void 0:r.status)===v.accepted){if(r.error)return s.setMeta(y,{type:r.type,status:v.done}),void e.dispatch(s);switch(r.type){case f.Complete:s=s.insertText(r.result||"",e.state.doc.nodeSize-2),s.setMeta(y,{type:f.Complete,status:v.done}),e.dispatch(s),e.focus();break;case f.MakeLonger:case f.MakeShorter:case f.Improve:case f.Simplify:case f.Explain:case f.ActionItems:case x.Translate:case x.ChangeTone: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=d.fromArray(t);s.selection.replace(s,new p(n,0,0))}s.setMeta(y,{type:r.type,status:v.done}),e.dispatch(s),e.focus()}}}})})};export{m as MoodParamType,x as OpenAiPromptsWithParam,f as OpenAiPromptsWithoutParam,v as Status,h as TranslationTargetLanguage,N as completePlugin,y as completePluginKey,I as defaultCompleteOptions,A as defaultOptions,R as grammarSuggestPlugin};
|
|
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="";return e.descendants(((e,n)=>{e.isText&&(t+=`${e.text}\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)}})),R=(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,R as completePlugin,j as completePluginKey,I as completeRequest,P as defaultCompleteOptions,D as defaultOptions,O as getChangedRegions,A as grammarSuggestPlugin,M as suggescatRequest};
|
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.cancelled="cancelled",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!0}return!1})(t)))?{fixed:!1,result:e}:{result:t.map((t=>JSON.parse(t).result)).join("\n"),fixed:!0})).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:p}=r,c={type:t.acceptSuggestion,id:o.spec.id},l=s.split("\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),d=g.Fragment.fromArray(l);let{tr:u}=e.state;u=u.setSelection(i.TextSelection.create(e.state.doc,a,p)),u.selection.replace(u,new g.Slice(d,1,1)),u.setMeta(h,c),e.dispatch(u)},b=(e,o)=>{const{spec:n}=o,r={type:t.discardSuggestion,id:n.id},s=e.state.tr.setMeta(h,r);e.dispatch(s)},j=(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},C={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),l=t.dom.scrollTop||0,d=t.dom.scrollLeft||0;a.style.left=`${c.left-p.left+d}px`,a.style.top=`${c.bottom-p.top+l+5}px`;const u=document.createElement("div");u.className="grammar-suggest-tooltip-apply",u.innerText=i.text||i.originalText,i.text||(u.style.textDecoration="line-through",u.style.color="red"),u.onclick=()=>{r(t,o)},a.appendChild(u);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(t,o)},a.appendChild(g),a},withYjs:!1},M={maxSelection:1e3},W=(t,e,o,n,r,s,a)=>l.__awaiter(void 0,void 0,void 0,(function*(){var t;let o="";const i=new AbortController;try{const p=null===(t=(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:[e],task:r,params:a}})})).body)||void 0===t?void 0:t.getReader(),c=({done:t,value:e})=>l.__awaiter(void 0,void 0,void 0,(function*(){var a;if(t)return;if(null===(a=m.getState(n.state))||void 0===a?void 0:a.isCancelled)return void(yield i.abort());const l=(new TextDecoder).decode(e);try{o+=l,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",l,t)}return null==p?void 0:p.read().then(c)}));yield null==p?void 0:p.read().then(c),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=M)=>{let o=!1;return new i.Plugin({key:m,state:{init:()=>({status:exports.Status.idle}),apply(t,e,n,r){const s=t.getMeta(m);return e.status===exports.Status.done||e.status===exports.Status.rejected?(o=!1,{status:exports.Status.idle}):(null==s?void 0:s.status)===exports.Status.cancelled?Object.assign(Object.assign(Object.assign({},e),s),{isCancelled:!0}):s&&(t=>Object.values(exports.OpenAiPromptsWithParam).includes(t.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(t.type))(s)?e.type&&s.type!==e.type?e:Object.assign(Object.assign({},e),s):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);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 void o.dispatch(o.state.tr.setMeta(m,{task:t,status:exports.Status.done}));if(o.state.doc.textBetween(a.from,a.to).length>r)return void o.dispatch(o.state.tr.setMeta(m,{type:t,status:exports.Status.error,error:"Selection is too big"}));const i=o.state.doc.textBetween(a.from,a.to,"\n");W(0,i,0,o,t,a,s)})(r.type,0,t,0,e.maxSelection,r.params)}if((null==r?void 0:r.status)===exports.Status.accepted){if(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();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(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()}}}})})},exports.completePluginKey=m,exports.defaultCompleteOptions=M,exports.defaultOptions=C,exports.grammarSuggestPlugin=(e,o=C)=>{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,b):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:j,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 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"),u=require("@emergence-engineering/prosemirror-text-map"),l=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="";return e.descendants(((e,o)=>{e.isText&&(t+=`${e.text}\n`)})),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,u=e.slice(c,d),l=t.slice(c,t.length-(e.length-d));return{start:c,end:c+l.length,oldStart:c,oldEnd:d,oldText:u,newText:l}},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:u}=e.state;u=u.setSelection(n.TextSelection.create(e.state.doc,r,i)),u.selection.replace(u,new g.Slice(d,1,1)),u.setMeta(h,p),e.dispatch(u)},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 u=document.createElement("div");u.className="grammar-suggest-tooltip-apply",u.innerText=n.text||n.originalText,n.text||(u.style.textDecoration="line-through",u.style.color="red"),u.onclick=()=>{s(e,t)},r.appendChild(u);const l=document.createElement("div");return l.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>",l.className="grammar-suggest-tooltip-discard",l.onclick=()=>{a(e,t)},r.appendChild(l),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=u.textPosToDocPos(s.start+e,r),p=u.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=u.docToTextWithMapping(o.doc).text,{text:r,mapping:n}=u.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 l.StepMap([e,s.a-e,s.b-e]):new l.StepMap([0,0,0]);i=new l.Mapping([a])}const p=f(a,r),c=e.decorations.map(i,t.doc),d=u.textPosToDocPos(p.start,n),g=u.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=u.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/dist/makeRequest.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { EditorView } from "prosemirror-view";
|
|
2
|
-
import { GrammarSuggestPluginOptions } from "./types";
|
|
2
|
+
import { FixMistakeResultData, GrammarSuggestPluginOptions } from "./types";
|
|
3
|
+
export declare const request: (apiKey: string, text: string) => Promise<FixMistakeResultData>;
|
|
3
4
|
export declare const createMakeRequest: (options: GrammarSuggestPluginOptions, apiKey: string) => (view: EditorView) => void;
|
package/dist/makeRequest.js
CHANGED
|
@@ -8,9 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
10
|
import debounce from "lodash.debounce";
|
|
11
|
+
import { docToTextWithMapping } from "@emergence-engineering/prosemirror-text-map";
|
|
11
12
|
import { getChangedRegions, getTextWithNewlines, grammarSuggestPluginKey, } from "./utils";
|
|
12
13
|
import { GrammarSuggestMetaType, } from "./types";
|
|
13
|
-
import { docToTextWithMapping } from "./mapping";
|
|
14
14
|
const isJsonString = (str) => {
|
|
15
15
|
try {
|
|
16
16
|
JSON.parse(str);
|
|
@@ -20,10 +20,9 @@ const isJsonString = (str) => {
|
|
|
20
20
|
}
|
|
21
21
|
return false;
|
|
22
22
|
};
|
|
23
|
-
const
|
|
23
|
+
export const request = (apiKey, text) => __awaiter(void 0, void 0, void 0, function* () {
|
|
24
24
|
const input = [...text.split("\n")];
|
|
25
|
-
|
|
26
|
-
return fetch("http://127.0.0.1:5001/prosemirror-ai-plugin/us-central1/suggestion", {
|
|
25
|
+
return fetch("https://prosemirror-ai-plugin.web.app/api/suggestion", {
|
|
27
26
|
method: "POST",
|
|
28
27
|
cache: "no-cache",
|
|
29
28
|
headers: {
|
|
@@ -73,7 +72,7 @@ export const createMakeRequest = (options, apiKey) => debounce((view) => {
|
|
|
73
72
|
const versionAtRequestStart = docToTextWithMapping(view.state.doc);
|
|
74
73
|
const oldText = ((_a = grammarSuggestPluginKey.getState(view.state)) === null || _a === void 0 ? void 0 : _a.lastText) || "";
|
|
75
74
|
const changedRegion = getChangedRegions(oldText, versionAtRequestStart.text);
|
|
76
|
-
|
|
75
|
+
request(apiKey, changedRegion.newText)
|
|
77
76
|
.then((fix) => {
|
|
78
77
|
// Check if the document version has changed while we were waiting
|
|
79
78
|
if (getTextWithNewlines(view.state.doc) !== versionAtRequestStart.text) {
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { EditorView } from "prosemirror-view";
|
|
2
|
+
import { TextSelection } from "prosemirror-state";
|
|
2
3
|
import { CompletePluginState, MoodParams, TaskType, TranslationParams } from "./types";
|
|
4
|
+
export declare const request: (apiKey: string, text: string, pluginState: CompletePluginState, view: EditorView, task: TaskType, selection?: TextSelection, params?: MoodParams | TranslationParams) => Promise<void>;
|
|
3
5
|
export declare const completeRequest: (pluginState: CompletePluginState, view: EditorView, apiKey: string) => Promise<void>;
|
|
4
6
|
export declare const makeShorterLonger: (task: TaskType, pluginState: CompletePluginState, view: EditorView, apiKey: string, maxSelection: number, params?: MoodParams | TranslationParams) => void;
|
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
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/utils.d.ts
CHANGED
|
@@ -5,4 +5,5 @@ export declare const completePluginKey: PluginKey<CompletePluginState>;
|
|
|
5
5
|
export declare const isCompleteMeta: (meta: any) => meta is TaskMeta;
|
|
6
6
|
export declare const grammarSuggestPluginKey: PluginKey<GrammarSuggestPluginState>;
|
|
7
7
|
export declare const getTextWithNewlines: (node: Node) => string;
|
|
8
|
+
export declare const getLastChangePos: (oldText: string, changes: [number, string][]) => number;
|
|
8
9
|
export declare const getChangedRegions: (oldText: string, newText: string) => ChangedRegion;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prosemirror-suggestcat-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.13",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -19,6 +19,8 @@
|
|
|
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.3",
|
|
23
|
+
"@emergence-engineering/prosemirror-text-map": "^0.0.3",
|
|
22
24
|
"eslint": "^8.29.0",
|
|
23
25
|
"eslint-config-airbnb": "^19.0.4",
|
|
24
26
|
"eslint-config-prettier": "^8.5.0",
|