prosemirror-suggestcat-plugin 0.1.12 → 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.
@@ -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
@@ -5,4 +5,4 @@ export { completePlugin } from "./completePlugin";
5
5
  export * from "./types";
6
6
  export { request as completeRequest } from "./makeTaksRequest";
7
7
  export { request as suggescatRequest } from "./makeRequest";
8
- export { getDiff } from "./mergeDiffs";
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 s}from"prosemirror-view";import r 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=r(e,t),o=n[0],s=o[0]===r.EQUAL?o[1].length-1:0,a=((e,t)=>{if(t[t.length-1][0]!==r.EQUAL)return e.length;const n=t.slice(0,t.length-1);let o=0;for(const e of n){const[t,n]=e;t===r.EQUAL&&(o+=n.length),t===r.DELETE&&(o+=n.length)}return o})(e,n),i=e.lastIndexOf("\n",s),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()||"",s=n.join(" ")+(n.length?" ":"");return[...s.length?[{from:e.from,to:e.from+s.length,original:s,replacement:s}]:[],{from:e.from+s.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()||"",s=(n.length?" ":"")+n.join(" ");return" "===s?[{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},...s.length?[{from:e.to+o.length,to:t.to,original:s,replacement:s}]:[]]}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 r.EQUAL:const e=n.lastIndexOf("\n"),o={from:t,to:t+n.length,original:n,replacement:n};if(-1!==e&&"\n"!==n){const o=[{from:t,to:t+e+1,original:n.slice(0,e+1),replacement:n.slice(0,e+1)},{from:t+e+1,to:t+n.length,original:n.slice(e+1),replacement:n.slice(e+1)}];return t+=n.length,o}return t+=n.length,[o];case r.DELETE:const s={from:t,to:t+n.length,original:n,replacement:""};return t+=n.length,[s];case r.INSERT:return[{from:t,to:t,original:"",replacement:n}]}})).flat()})(r(e,t));return M(M(n))},L=(e,n)=>{var o;const s=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(!s)return;const{text:r}=s.spec,{from:a,to:i}=s,c={type:g.acceptSuggestion,id:n.spec.id},l=r.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},s=e.state.tr.setMeta(S,o);e.dispatch(s)},D=(e,t)=>{const n=S.getState(e.state);if(!n)return!1;const{decorations:o}=n,s=o.find(t,t)[0];if(!s){const t={type:g.closeSuggestion};return e.dispatch(e.state.tr.setMeta(S,t)),!1}const r=n.popupDecoration.find()[0];if((null==r?void 0:r.spec.id)===s.spec.id)return!1;const a={type:g.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(S,a)),!1},A={debounceMs:2e3,createUpdatePopup:(e,t,n,o,s)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:a}=t,i=e.dom.getBoundingClientRect();r.id=u.grammarSuggestPopup;const c=e.coordsAtPos(n),l=e.dom.scrollTop||0,d=e.dom.scrollLeft||0;r.style.left=`${c.left-i.left+d}px`,r.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)},r.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)},r.appendChild(g),r},withYjs:!1},I={maxSelection:1e3},R=(e,t=A)=>{let r=!1;return new n({key:S,state:{init:()=>({lastText:"",decorations:s.empty,popupDecoration:s.empty}),apply(e,n,r,a){const i=e.getMeta(S);return(null==i?void 0:i.type)===g.suggestionUpdate?((e,t,n)=>{const{changedRegion:s,fix:r,mapping:a,text:i}=t,c=P(s.newText,r.result).filter((e=>!E(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:n,replacement:r})=>{const i=T(s.start+e,a),c=T(s.start+(r.endsWith("\n")?t-1:t),a),l={text:r.endsWith("\n")?r.slice(0,-1):r,originalText:n,id:{}};return o.inline(i,c,{class:"grammarSuggestion "+(""===r?"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:s.empty})})(n,i,e):(null==i?void 0:i.type)===g.openSuggestion?((e,t,n,r)=>{const{decoration:a}=t,i={id:a.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:s.create(n.doc,[o.widget(a.from,((e,t)=>{const n=t();return n?r.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:s.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:s.empty}))(n,i,e):e.docChanged?((e,t,n,o)=>{const s=C(n.doc).text,{text:r,mapping:a}=C(t.doc);if(r===s)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),s=new c(o&&e?[e,o.a-e,o.b-e]:[0,0,0]);i=new l([s])}const d=b(s,r),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,r,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),s=(null===(n=S.getState(e.state))||void 0===n?void 0:n.lastText)||"",r=b(s,o.text);O(t,r.newText).then((t=>{if(w(e.state.doc)!==o.text)return;const n={type:g.suggestionUpdate,fix:t,changedRegion:r,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")&&r||!o||o.lastText===w(e.state.doc)||(r=!0,n(e))}}}})},U=(e,t,n,o,s,r,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:s,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:s,status:v.streaming,result:n},r&&{selection:r})))}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:s,status:v.finished,result:n},r&&{selection:r})))}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,s){const r=e.getMeta(y);return t.status===v.done||t.status===v.rejected?(o=!1,{status:v.idle}):(null==r?void 0:r.status)===v.cancelled?Object.assign(Object.assign(Object.assign({},t),r),{isCancelled:!0}):r&&(e=>Object.values(x).includes(e.type)||Object.values(f).includes(e.type))(r)?t.type&&r.type!==t.type?t:Object.assign(Object.assign({},t),r):t}},view:()=>({update(e,n){const s=y.getState(e.state);let r=e.state.tr;if((null==s?void 0:s.status)===v.new&&!o)switch(s.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,s,r)=>{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>s)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,r)})(s.type,0,e,0,t.maxSelection,s.params)}if((null==s?void 0:s.status)===v.accepted){if(s.error)return r.setMeta(y,{type:s.type,status:v.done}),void e.dispatch(r);switch(s.type){case f.Complete:r=r.insertText(s.result||"",e.state.doc.nodeSize-2),r.setMeta(y,{type:f.Complete,status:v.done}),e.dispatch(r),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(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=d.fromArray(t);r.selection.replace(r,new p(n,0,0))}r.setMeta(y,{type:s.type,status:v.done}),e.dispatch(r),e.focus()}}}})})};export{u as GrammarSuggestElementClass,g as GrammarSuggestMetaType,m as MoodParamType,x as OpenAiPromptsWithParam,f as OpenAiPromptsWithoutParam,v as Status,h as TranslationTargetLanguage,N as completePlugin,y as completePluginKey,U as completeRequest,I as defaultCompleteOptions,A as defaultOptions,b as getChangedRegions,P as getDiff,R as grammarSuggestPlugin,O 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 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 e,t,o,r,s,a,n=require("prosemirror-state"),i=require("prosemirror-view"),p=require("fast-diff"),c=require("tslib"),l=require("lodash.debounce"),g=require("prosemirror-transform"),d=require("prosemirror-model");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,(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 n.PluginKey("completePlugin"),u=new n.PluginKey("grammarSuggestPlugin"),h=e=>{let t="";return e.descendants(((e,o)=>{e.isText&&(t+=`${e.text}\n`)})),t},x=(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),r=o[0],s=r[0]===p.EQUAL?r[1].length-1:0,a=((e,t)=>{if(t[t.length-1][0]!==p.EQUAL)return e.length;const o=t.slice(0,t.length-1);let r=0;for(const e of o){const[t,o]=e;t===p.EQUAL&&(r+=o.length),t===p.DELETE&&(r+=o.length)}return r})(e,o),n=e.lastIndexOf("\n",s),i=e.indexOf("\n",a),c=-1===n?0:n+1,l=-1===i?e.length:i,g=e.slice(c,l),d=t.slice(c,t.length-(e.length-l));return{start:c,end:c+d.length,oldStart:c,oldEnd:l,oldText:g,newText:d}},f=[{docPos:1,textPos:0}],S=e=>{let t="";const o=[];return e.descendants(((e,r)=>{e.isText&&(o.push({docPos:r,textPos:t.length}),t+=`${e.text}\n`)})),{text:t,mapping:o.length?o:f}},P=(e,t)=>{for(let o=0;o<t.length;o++)if(e>=t[o].textPos&&(void 0===t[o+1]||e<t[o+1].textPos))return t[o].docPos+(e-t[o].textPos);throw new Error("textPositionToDocumentPosition: textPos not found in mapping")},y=(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})))})),v=e=>e.replacement===e.original,O=e=>e.reduce(((e,t)=>{const o=e[e.length-1],r=e.slice(0,e.length-1);if(!o)return[t];return[...r,...((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(v(e)&&v(t))return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}];if(v(e)){if(t.replacement.startsWith(" ")&&""===t.original||t.original.startsWith(" ")&&""===t.replacement)return[e,t];const o=e.original.split(" "),r=o.pop()||"",s=o.join(" ")+(o.length?" ":"");return[...s.length?[{from:e.from,to:e.from+s.length,original:s,replacement:s}]:[],{from:e.from+s.length,to:t.to,original:r+t.original,replacement:r+t.replacement}]}if(v(t)){if(e.replacement.endsWith(" ")&&""===e.original||e.original.endsWith(" ")&&""===e.replacement)return[e,t];const o=t.original.split(" "),r=o.shift()||"",s=(o.length?" ":"")+o.join(" ");return" "===s?[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]:[{from:e.from,to:e.to+r.length,original:e.original+r,replacement:e.replacement+r},...s.length?[{from:e.to+r.length,to:t.to,original:s,replacement:s}]:[]]}return[{from:e.from,to:t.to,original:e.original+t.original,replacement:e.replacement+t.replacement}]})(o,t)]}),[]),T=(e,t)=>{const o=(e=>{let t=0;return e.map((([e,o])=>{switch(e){case p.EQUAL:const e=o.lastIndexOf("\n"),r={from:t,to:t+o.length,original:o,replacement:o};if(-1!==e&&"\n"!==o){const r=[{from:t,to:t+e+1,original:o.slice(0,e+1),replacement:o.slice(0,e+1)},{from:t+e+1,to:t+o.length,original:o.slice(e+1),replacement:o.slice(e+1)}];return t+=o.length,r}return t+=o.length,[r];case p.DELETE:const s={from:t,to:t+o.length,original:o,replacement:""};return t+=o.length,[s];case p.INSERT:return[{from:t,to:t,original:"",replacement:o}]}})).flat()})(p(e,t));return O(O(o))},w=(e,t)=>{var o;const r=null===(o=u.getState(e.state))||void 0===o?void 0:o.decorations.find(0,e.state.doc.nodeSize,(e=>e.id===t.spec.id))[0];if(!r)return;const{text:s}=r.spec,{from:a,to:i}=r,p={type:exports.GrammarSuggestMetaType.acceptSuggestion,id:t.spec.id},c=s.split("\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),l=d.Fragment.fromArray(c);let{tr:g}=e.state;g=g.setSelection(n.TextSelection.create(e.state.doc,a,i)),g.selection.replace(g,new d.Slice(l,1,1)),g.setMeta(u,p),e.dispatch(g)},M=(e,t)=>{const{spec:o}=t,r={type:exports.GrammarSuggestMetaType.discardSuggestion,id:o.id},s=e.state.tr.setMeta(u,r);e.dispatch(s)},A=(e,t)=>{const o=u.getState(e.state);if(!o)return!1;const{decorations:r}=o,s=r.find(t,t)[0];if(!s){const t={type:exports.GrammarSuggestMetaType.closeSuggestion};return e.dispatch(e.state.tr.setMeta(u,t)),!1}const a=o.popupDecoration.find()[0];if((null==a?void 0:a.spec.id)===s.spec.id)return!1;const n={type:exports.GrammarSuggestMetaType.openSuggestion,decoration:s};return e.dispatch(e.state.tr.setMeta(u,n)),!1},C={debounceMs:2e3,createUpdatePopup:(e,t,o,r,s)=>{const a=document.createElement("div");a.className="grammar-suggest-tooltip";const{spec:n}=t,i=e.dom.getBoundingClientRect();a.id=exports.GrammarSuggestElementClass.grammarSuggestPopup;const p=e.coordsAtPos(o),c=e.dom.scrollTop||0,l=e.dom.scrollLeft||0;a.style.left=`${p.left-i.left+l}px`,a.style.top=`${p.bottom-i.top+c+5}px`;const g=document.createElement("div");g.className="grammar-suggest-tooltip-apply",g.innerText=n.text||n.originalText,n.text||(g.style.textDecoration="line-through",g.style.color="red"),g.onclick=()=>{r(e,t)},a.appendChild(g);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{s(e,t)},a.appendChild(d),a},withYjs:!1},b={maxSelection:1e3},j=(e,t,o,r,s,a,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:s,params:n}})})).body)||void 0===e?void 0:e.getReader(),l=({done:e,value:t})=>c.__awaiter(void 0,void 0,void 0,(function*(){var n;if(e)return;if(null===(n=m.getState(r.state))||void 0===n?void 0:n.isCancelled)return void(yield i.abort());const c=(new TextDecoder).decode(t);try{o+=c,r.dispatch(r.state.tr.setMeta(m,Object.assign({type:s,status:exports.Status.streaming,result:o},a&&{selection:a})))}catch(e){console.error("Could not parse stream message",c,e)}return null==p?void 0:p.read().then(l)}));yield null==p?void 0:p.read().then(l),r.dispatch(r.state.tr.setMeta(m,Object.assign({type:s,status:exports.Status.finished,result:o},a&&{selection:a})))}catch(e){console.error("Error:",e)}}));exports.completePlugin=(e,t=b)=>{let o=!1;return new n.Plugin({key:m,state:{init:()=>({status:exports.Status.idle}),apply(e,t,r,s){const a=e.getMeta(m);return t.status===exports.Status.done||t.status===exports.Status.rejected?(o=!1,{status:exports.Status.idle}):(null==a?void 0:a.status)===exports.Status.cancelled?Object.assign(Object.assign(Object.assign({},t),a),{isCancelled:!0}):a&&(e=>Object.values(exports.OpenAiPromptsWithParam).includes(e.type)||Object.values(exports.OpenAiPromptsWithoutParam).includes(e.type))(a)?t.type&&a.type!==t.type?t:Object.assign(Object.assign({},t),a):t}},view:()=>({update(e,r){const s=m.getState(e.state);let a=e.state.tr;if((null==s?void 0:s.status)===exports.Status.new&&!o)switch(s.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 r="";r=o.length>=2?o.slice(-2).join(" "):o.join(" "),j(0,r,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,r,s,a)=>{const n=o.state.selection;if(!n)return void o.dispatch(o.state.tr.setMeta(m,{task:e,status:exports.Status.done}));if(o.state.doc.textBetween(n.from,n.to).length>s)return void o.dispatch(o.state.tr.setMeta(m,{type:e,status:exports.Status.error,error:"Selection is too big"}));const i=o.state.doc.textBetween(n.from,n.to,"\n");j(0,i,0,o,e,n,a)})(s.type,0,e,0,t.maxSelection,s.params)}if((null==s?void 0:s.status)===exports.Status.accepted){if(s.error)return a.setMeta(m,{type:s.type,status:exports.Status.done}),void e.dispatch(a);switch(s.type){case exports.OpenAiPromptsWithoutParam.Complete:a=a.insertText(s.result||"",e.state.doc.nodeSize-2),a.setMeta(m,{type:exports.OpenAiPromptsWithoutParam.Complete,status:exports.Status.done}),e.dispatch(a),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(s.selection&&s.result){const t=s.result.split("\n\n").map((t=>e.state.schema.node("paragraph",null,e.state.schema.text(t)))),o=d.Fragment.fromArray(t);a.selection.replace(a,new d.Slice(o,0,0))}a.setMeta(m,{type:s.type,status:exports.Status.done}),e.dispatch(a),e.focus()}}}})})},exports.completePluginKey=m,exports.completeRequest=j,exports.defaultCompleteOptions=b,exports.defaultOptions=C,exports.getChangedRegions=x,exports.getDiff=T,exports.grammarSuggestPlugin=(e,t=C)=>{let o=!1;return new n.Plugin({key:u,state:{init:()=>({lastText:"",decorations:i.DecorationSet.empty,popupDecoration:i.DecorationSet.empty}),apply(e,o,r,s){const a=e.getMeta(u);return(null==a?void 0:a.type)===exports.GrammarSuggestMetaType.suggestionUpdate?((e,t,o)=>{const{changedRegion:r,fix:s,mapping:a,text:n}=t,p=T(r.newText,s.result).filter((e=>!v(e))).filter((e=>e.original!==`${e.replacement}\n`)).map((({from:e,to:t,original:o,replacement:s})=>{const n=P(r.start+e,a),p=P(r.start+(s.endsWith("\n")?t-1:t),a),c={text:s.endsWith("\n")?s.slice(0,-1):s,originalText:o,id:{}};return i.Decoration.inline(n,p,{class:"grammarSuggestion "+(""===s?"removalSuggestion":"")},c)}));return Object.assign(Object.assign({},e),{decorations:e.decorations.add(o.doc,p),lastText:n})})(o,a,e):(null==a?void 0:a.type)===exports.GrammarSuggestMetaType.acceptSuggestion?((e,t,o)=>{const r=e.decorations.remove(e.decorations.find(0,o.doc.nodeSize,(e=>e.id===t.id)));return Object.assign(Object.assign({},e),{lastText:h(o.doc),decorations:r.map(o.mapping,o.doc),popupDecoration:i.DecorationSet.empty})})(o,a,e):(null==a?void 0:a.type)===exports.GrammarSuggestMetaType.openSuggestion?((e,t,o,r)=>{const{decoration:s}=t,a={id:s.spec.id};return Object.assign(Object.assign({},e),{popupDecoration:i.DecorationSet.create(o.doc,[i.Decoration.widget(s.from,((e,t)=>{const o=t();return o?r.createUpdatePopup(e,s,o,w,M):document.createElement("div")}),Object.assign(Object.assign({},a),{stopEvent:()=>!0}))])})})(o,a,e,t):(null==a?void 0:a.type)===exports.GrammarSuggestMetaType.closeSuggestion?Object.assign(Object.assign({},o),{popupDecoration:i.DecorationSet.empty}):(null==a?void 0:a.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,a,e):e.docChanged?((e,t,o,r)=>{const s=S(o.doc).text,{text:a,mapping:n}=S(t.doc);if(a===s)return e;let i=t.mapping;if(r){const e=t.doc.content.findDiffStart(o.doc.content),r=o.doc.content.findDiffEnd(t.doc.content),s=r&&e?new g.StepMap([e,r.a-e,r.b-e]):new g.StepMap([0,0,0]);i=new g.Mapping([s])}const p=x(s,a),c=e.decorations.map(i,t.doc),l=P(p.start,n),d=P(p.end,n),m=e.popupDecoration.map(i,t.doc);return Object.assign(Object.assign({},e),{decorations:c.remove(c.find(l,d)),popupDecoration:m.remove(m.find(l,d))})})(o,e,r,t.withYjs):o}},props:{handleClick:A,decorations:e=>{const t=u.getState(e);if(!t)return null;const o=m.getState(e);return(null==o?void 0:o.status)!==exports.Status.idle?t.decorations:t.decorations.add(e.doc,t.popupDecoration.find())}},view(){const r=((e,t)=>l((e=>{var o;const r=S(e.state.doc),s=(null===(o=u.getState(e.state))||void 0===o?void 0:o.lastText)||"",a=x(s,r.text);y(t,a.newText).then((t=>{if(h(e.state.doc)!==r.text)return;const o={type:exports.GrammarSuggestMetaType.suggestionUpdate,fix:t,changedRegion:a,mapping:r.mapping,text:r.text};e.dispatch(e.state.tr.setMeta(u,o))})).catch((e=>{console.error("Grammar suggest API error",e)}))}),e.debounceMs))(t,e);return{update(e,t){const s=u.getState(e.state);e.state.doc.textBetween(0,e.state.doc.nodeSize-2,"/n")===t.doc.textBetween(0,t.doc.nodeSize-2,"/n")&&o||!s||s.lastText===h(e.state.doc)||(o=!0,r(e))}}}})},exports.suggescatRequest=y;
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;
@@ -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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prosemirror-suggestcat-plugin",
3
- "version": "0.1.12",
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",