@foundationui/smart-input
Advanced tools
Comparing version 1.0.20 to 1.0.22
@@ -1,2 +0,2 @@ | ||
import e,{useEffect as t}from"react";import{createEditor as o,Transforms as n,Editor as l,Node as i}from"slate";import{withHistory as r}from"slate-history";import{withReact as s,ReactEditor as c,DefaultElement as a,Slate as p,Editable as d}from"slate-react";import m from"lodash.debounce";import u from"lodash.throttle";import{ulid as h}from"ulid";function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},f.apply(this,arguments)}class C{constructor(e,t,o){var n=this;this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=h(),this.fetchCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=m(async function(e,t){var o,l;if(0===e.length)return null;const i=++n.sequenceId;if(null!=(o=n.currentCompletion)&&o.completion&&(n.currentCompletion.text+n.currentCompletion.completion).startsWith(e))return null;n.currentCompletion={text:e,sequenceId:i};const r=n.fetchCache[e];if(r)return n.addCompletion(e,r),n.currentCompletion.completion=r.completion,r;if(n.mockCompletion){const t=n.mockCompletion(e);return t?await new Promise(o=>{var l,r;setTimeout(()=>{var l;const r={input:e,sid:h(),completion:t};n.fetchCache[e]=r,(null==(l=n.currentCompletion)?void 0:l.sequenceId)===i&&(n.addCompletion(e,r),n.currentCompletion.completion=t),o(r)},(l=200,r=1e3,l=Math.ceil(l),r=Math.floor(r),Math.floor(Math.random()*(r-l+1))+l))}):{input:e,sid:h(),completion:null}}const s=await fetch("https://api.foundation-ui.com/completions",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.modelId}`},body:JSON.stringify({model:n.modelId,input:e,session:n.sessionId,context:t})});if(200!==s.status)return console.error("Couldn't fetch completions"),null;const c=await s.json();return n.fetchCache[e]=c,(null==(l=n.currentCompletion)?void 0:l.sequenceId)===i&&(n.addCompletion(e,c),n.currentCompletion.completion=c.completion),c},200),this.sendEvents=u((e,t)=>{fetch("https://api.foundation-ui.com/events",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.modelId}`},body:JSON.stringify({model:this.modelId,session:this.sessionId,input:e,context:t})}).then(e=>{200!==e.status&&console.error("Error sending events")}).catch(e=>console.error(e))},1e3,{trailing:!0}),this.addCompletion=e,this.modelId=t,this.mockCompletion=o}updateCompletion(e,t){this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch("https://api.foundation-ui.com/completions",{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.modelId}`},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(o=>{200!==o.status&&console.error("Couldn't update completion"),t.seen&&this.alreadySeen.add(e),t.accepted&&this.alreadyAccepted.add(e)}).catch(e=>console.error(e))}}function y(i){const m=e.useMemo(()=>r(s(o())),[]),[u,h]=e.useState(null),[y]=e.useState(new C((e,t)=>{k(t)},i.modelId,i.modelId?i.mockCompletion:()=>" -- sample completion --")),g=()=>{v.acceptCompletion(m,y,u),h(null)},k=e=>{i.value&&(v.addCompletion(m,y,e),h(e))},w=()=>{v.removeCompletion(m),h(null)};y.addCompletion=(e,t)=>{t&&(e+t).startsWith(i.value)&&k(t)};const x=[{type:"text",children:[{text:i.value,type:void 0}]}];t(()=>{i.editorRef&&(i.editorRef.current=f({},c.toDOMNode(m,m),{focus:()=>{setTimeout(()=>{c.focus(m),n.select(m,i.value?l.end(m,[]):l.start(m,[]))},50)}}))});const A=e.useCallback(t=>{switch(t.element.type){case"text":return i.renderText(f({},t));case"completion":return i.renderCompletion(f({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return e.createElement(a,t)}},[i.renderText,i.renderCompletion]),b=e.useCallback(e=>i.renderPlaceholder(f({},e,e.attributes||{},{style:f({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},e.style||{})})),[i.renderPlaceholder]);/*#__PURE__*/return e.createElement(p,{editor:m,value:x,onChange:e=>{var t;const o=v.serialize(e.filter(e=>"completion"!==e.type));null==(t=y.fetchCompletion(o,i.context||{}))||t.catch(e=>console.error(e)),y.sendEvents(o,i.context||{}),i.onChange(o)}},/*#__PURE__*/e.createElement(d,{placeholder:i.placeholder,className:i.className,style:f({},i.style||{},{whiteSpace:i.multiline?void 0:"pre"}),onPaste:e=>{w(),e.preventDefault();const t=e.clipboardData.getData("Text");m.insertText(i.multiline?t:t.replaceAll("\n",""))},renderPlaceholder:i.renderPlaceholder?b:void 0,renderElement:A,onBlur:e=>{w(),y.currentCompletion=null,i.onBlur&&i.onBlur(e)},onFocus:e=>{i.onFocus&&(i.onFocus(e),null==m.selection&&n.select(m,i.value?l.end(m,[]):l.start(m,[])))},onKeyDown:e=>{var t,o;const n=Boolean(null==u||null==(t=u.completion)||null==(o=t.trim())?void 0:o.length);if("Tab"===e.key&&n)e.preventDefault(),g(),y.currentCompletion=null;else if("ArrowRight"===e.key&&n)e.preventDefault(),g(),y.currentCompletion=null;else if("ArrowLeft"===e.key&&n)w(),y.currentCompletion=null;else if("ArrowDown"!==e.key&&"ArrowUp"!==e.key||!n)if("Backspace"===e.key)y.currentCompletion=null,w();else if("Enter"!==e.key||e.metaKey){if("Shift"!==e.key){var l;if(u&&!e.metaKey&&null!=(l=u.completion)&&l.startsWith(e.key)&&1===e.key.length){const e=u.completion.substring(1);v.updateCompletion(m,e),h(f({},u,{completion:e}))}else y.currentCompletion=null,w()}}else e.preventDefault(),i.multiline&&(w(),m.insertText("\n"));else w();i.onKeyDown&&i.onKeyDown(e)}}))}const v={isCompletionActive:e=>!!e.children.find(e=>"completion"===e.type),isCursorAtEndOfDocument:e=>{const t=e.selection;if(!t)return!1;const[o]=t.anchor.path;return o===e.children.length-1&&t.anchor.offset===i.string(e.children[o]).length},acceptCompletion:(e,t,o)=>{v.isCompletionActive(e)&&null!=o&&o.completion&&(v.removeCompletion(e),e.insertText(o.completion),t.updateCompletion(o.sid,{accepted:!0}))},addCompletion(e,t,o){const l=v.isCompletionActive(e),i=v.isCursorAtEndOfDocument(e);!l&&i&&null!=o&&o.completion&&(n.insertNodes(e,{type:"completion",children:[{text:o.completion}]},{at:[e.children.length]}),t.updateCompletion(o.sid,{seen:!0}))},removeCompletion(e){v.isCompletionActive(e)&&n.removeNodes(e,{at:[e.children.length-1]})},updateCompletion(e,t){v.isCompletionActive(e)&&t.length>0&&n.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:e=>e.map(e=>i.string(e)).join("\n")};export{y as SmartInput}; | ||
import e,{useEffect as t}from"react";import{createEditor as o,Transforms as n,Editor as i,Node as l}from"slate";import{withHistory as r}from"slate-history";import{withReact as s,ReactEditor as c,DefaultElement as a,Slate as p,Editable as d}from"slate-react";import{ulid as m}from"ulid";function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},u.apply(this,arguments)}class h{constructor(e,t,o,n){var i=this;this.apiUrl=void 0,this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=m(),this.completionCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=function(e,t=50,o={}){var n,i;let l;const r=null!=(n=o.isImmediate)&&n,s=null!=(i=o.callback)&&i,c=o.maxWait;let a=Date.now(),p=[];const d=function(...o){const n=this;return new Promise((i,d)=>{const m=r&&void 0===l;if(void 0!==l&&clearTimeout(l),l=setTimeout(function(){if(l=void 0,a=Date.now(),!r){const t=e.apply(n,o);s&&s(t),p.forEach(({resolve:e})=>e(t)),p=[]}},function(){if(void 0!==c){const e=Date.now()-a;if(e+t>=c)return c-e}return t}()),m){const t=e.apply(n,o);return s&&s(t),i(t)}p.push({resolve:i,reject:d})})};return d.cancel=function(e){void 0!==l&&clearTimeout(l),p.forEach(({reject:t})=>t(e)),p=[]},d}(async function(e,t){var o,n;if(0===e.length)return null;const l=++i.sequenceId;if(null!=(o=i.currentCompletion)&&o.completion&&(i.currentCompletion.text+i.currentCompletion.completion).startsWith(e))return null;i.currentCompletion={text:e,sequenceId:l};const r=i.completionCache[e];if(r)return i.addCompletion(e,r),i.currentCompletion.completion=r.completion,r;if(i.mockCompletion){const t=i.mockCompletion(e);return t?await new Promise(o=>{var n,r;setTimeout(()=>{var n;const r={input:e,sid:m(),completion:t};i.completionCache[e]=r,(null==(n=i.currentCompletion)?void 0:n.sequenceId)===l&&(i.addCompletion(e,r),i.currentCompletion.completion=t),o(r)},(n=200,r=1e3,n=Math.ceil(n),r=Math.floor(r),Math.floor(Math.random()*(r-n+1))+n))}):{input:e,sid:m(),completion:null}}const s=await fetch(`${i.apiUrl}/completions`,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.modelId}`},body:JSON.stringify({model:i.modelId,input:e,session:i.sessionId,context:t})});if(200!==s.status)return console.error("Couldn't fetch completions"),null;const c=await s.json();return i.completionCache[e]=c,(null==(n=i.currentCompletion)?void 0:n.sequenceId)===l&&(i.addCompletion(e,c),i.currentCompletion.completion=c.completion),c},200),this.sendEvents=function(e,t){let o,n;return function(){const t=arguments,i=this;return o||(o=!0,setTimeout(()=>o=!1,1e3),n=e.apply(i,t)),n}}((e,t)=>{fetch(`${this.apiUrl}/events`,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.modelId}`},body:JSON.stringify({model:this.modelId,session:this.sessionId,input:e,context:t})}).then(e=>{200!==e.status&&console.error("Error sending events")}).catch(e=>console.error(e))}),this.apiUrl=e,this.addCompletion=t,this.modelId=o,this.mockCompletion=n}updateCompletion(e,t){this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch(`${this.apiUrl}/completions`,{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.modelId}`},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(o=>{200!==o.status&&console.error("Couldn't update completion"),t.seen&&this.alreadySeen.add(e),t.accepted&&this.alreadyAccepted.add(e)}).catch(e=>console.error(e))}}function f(l){const m=e.useMemo(()=>r(s(o())),[]),[f,v]=e.useState(null),[y]=e.useState(new h(l.devApiUrl||"https://api.foundation-ui.com/smartinput",(e,t)=>{w(t)},l.modelId,l.modelId?l.mockCompletion:()=>" -- sample completion --")),g=()=>{C.acceptCompletion(m,y,f),v(null)},w=e=>{l.value&&(C.addCompletion(m,y,e),v(e))},k=()=>{C.removeCompletion(m),v(null)};y.addCompletion=(e,t)=>{t&&(e+t).startsWith(l.value)&&w(t)};const x=[{type:"text",children:[{text:l.value,type:void 0}]}];t(()=>{l.editorRef&&(l.editorRef.current=u({},c.toDOMNode(m,m),{focus:()=>{setTimeout(()=>{c.focus(m),n.select(m,l.value?i.end(m,[]):i.start(m,[]))},50)}}))});const A=e.useCallback(t=>{switch(t.element.type){case"text":return l.renderText(u({},t));case"completion":return l.renderCompletion(u({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return e.createElement(a,t)}},[l.renderText,l.renderCompletion]),T=e.useCallback(e=>l.renderPlaceholder(u({},e,e.attributes||{},{style:u({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},e.style||{})})),[l.renderPlaceholder]);/*#__PURE__*/return e.createElement(p,{editor:m,value:x,onChange:e=>{var t;const o=C.serialize(e.filter(e=>"completion"!==e.type));null==(t=y.fetchCompletion(o,l.context||{}))||t.catch(e=>console.error(e)),y.sendEvents(o,l.context||{}),l.onChange(o)}},/*#__PURE__*/e.createElement(d,{placeholder:l.placeholder,className:l.className,style:u({},l.style||{},{whiteSpace:l.multiline?void 0:"pre"}),onPaste:e=>{k(),e.preventDefault();const t=e.clipboardData.getData("Text");m.insertText(l.multiline?t:t.replaceAll("\n",""))},renderPlaceholder:l.renderPlaceholder?T:void 0,renderElement:A,onBlur:e=>{k(),y.currentCompletion=null,l.onBlur&&l.onBlur(e)},onFocus:e=>{l.onFocus&&(l.onFocus(e),null==m.selection&&n.select(m,l.value?i.end(m,[]):i.start(m,[])))},onKeyDown:e=>{var t,o;const n=Boolean(null==f||null==(t=f.completion)||null==(o=t.trim())?void 0:o.length);if("Tab"===e.key&&n)e.preventDefault(),g(),y.currentCompletion=null;else if("ArrowRight"===e.key&&n)e.preventDefault(),g(),y.currentCompletion=null;else if("ArrowLeft"===e.key&&n)k(),y.currentCompletion=null;else if("ArrowDown"!==e.key&&"ArrowUp"!==e.key||!n)if("Backspace"===e.key)y.currentCompletion=null,k();else if("Enter"!==e.key||e.metaKey){if("Shift"!==e.key){var i;if(f&&!e.metaKey&&null!=(i=f.completion)&&i.startsWith(e.key)&&1===e.key.length){const e=f.completion.substring(1);C.updateCompletion(m,e),v(u({},f,{completion:e}))}else y.currentCompletion=null,k()}}else e.preventDefault(),l.multiline&&(k(),m.insertText("\n"));else k();l.onKeyDown&&l.onKeyDown(e)}}))}const C={isCompletionActive:e=>!!e.children.find(e=>"completion"===e.type),isCursorAtEndOfDocument:e=>{const t=e.selection;if(!t)return!1;const[o]=t.anchor.path;return o===e.children.length-1&&t.anchor.offset===l.string(e.children[o]).length},acceptCompletion:(e,t,o)=>{C.isCompletionActive(e)&&null!=o&&o.completion&&(C.removeCompletion(e),e.insertText(o.completion),t.updateCompletion(o.sid,{accepted:!0}))},addCompletion(e,t,o){const i=C.isCompletionActive(e),l=C.isCursorAtEndOfDocument(e);!i&&l&&null!=o&&o.completion&&(n.insertNodes(e,{type:"completion",children:[{text:o.completion}]},{at:[e.children.length]}),t.updateCompletion(o.sid,{seen:!0}))},removeCompletion(e){C.isCompletionActive(e)&&n.removeNodes(e,{at:[e.children.length-1]})},updateCompletion(e,t){C.isCompletionActive(e)&&t.length>0&&n.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:e=>e.map(e=>l.string(e)).join("\n")};export{f as SmartInput}; | ||
//# sourceMappingURL=index.modern.js.map |
@@ -1,2 +0,2 @@ | ||
import e,{useEffect as t}from"react";import{createEditor as n,Transforms as o,Editor as r,Node as i}from"slate";import{withHistory as l}from"slate-history";import{withReact as c,ReactEditor as s,DefaultElement as u,Slate as a,Editable as p}from"slate-react";import m from"lodash.debounce";import d from"lodash.throttle";import{ulid as h}from"ulid";function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},f.apply(this,arguments)}var v=/*#__PURE__*/function(){function e(e,t,n){var o=this,r=this;this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=h(),this.fetchCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=m(function(e,t){try{var n,o,i=function(n){return o?n:Promise.resolve(fetch("https://api.foundation-ui.com/completions",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.modelId},body:JSON.stringify({model:r.modelId,input:e,session:r.sessionId,context:t})})).then(function(t){return 200!==t.status?(console.error("Couldn't fetch completions"),null):Promise.resolve(t.json()).then(function(t){var n;return r.fetchCache[e]=t,(null==(n=r.currentCompletion)?void 0:n.sequenceId)===l&&(r.addCompletion(e,t),r.currentCompletion.completion=t.completion),t})})};if(0===e.length)return Promise.resolve(null);var l=++r.sequenceId;if(null!=(n=r.currentCompletion)&&n.completion&&(r.currentCompletion.text+r.currentCompletion.completion).startsWith(e))return Promise.resolve(null);r.currentCompletion={text:e,sequenceId:l};var c=r.fetchCache[e];if(c)return r.addCompletion(e,c),r.currentCompletion.completion=c.completion,Promise.resolve(c);var s=function(){if(r.mockCompletion){var t=function(t){if(o)return t;var n={input:e,sid:h(),completion:null};return o=1,n},n=r.mockCompletion(e),i=function(){if(n)return Promise.resolve(new Promise(function(t){var o,i;setTimeout(function(){var o,i={input:e,sid:h(),completion:n};r.fetchCache[e]=i,(null==(o=r.currentCompletion)?void 0:o.sequenceId)===l&&(r.addCompletion(e,i),r.currentCompletion.completion=n),t(i)},(o=200,i=1e3,o=Math.ceil(o),i=Math.floor(i),Math.floor(Math.random()*(i-o+1))+o))})).then(function(e){return o=1,e})}();return i&&i.then?i.then(t):t(i)}}();return Promise.resolve(s&&s.then?s.then(i):i(s))}catch(e){return Promise.reject(e)}},200),this.sendEvents=d(function(e,t){fetch("https://api.foundation-ui.com/events",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.modelId},body:JSON.stringify({model:o.modelId,session:o.sessionId,input:e,context:t})}).then(function(e){200!==e.status&&console.error("Error sending events")}).catch(function(e){return console.error(e)})},1e3,{trailing:!0}),this.addCompletion=e,this.modelId=t,this.mockCompletion=n}return e.prototype.updateCompletion=function(e,t){var n=this;this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch("https://api.foundation-ui.com/completions",{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.modelId},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(function(o){200!==o.status&&console.error("Couldn't update completion"),t.seen&&n.alreadySeen.add(e),t.accepted&&n.alreadyAccepted.add(e)}).catch(function(e){return console.error(e)})},e}();function C(i){var m=e.useMemo(function(){return l(c(n()))},[]),d=e.useState(null),h=d[0],C=d[1],g=e.useState(new v(function(e,t){A(t)},i.modelId,i.modelId?i.mockCompletion:function(){return" -- sample completion --"})),k=g[0],x=function(){y.acceptCompletion(m,k,h),C(null)},A=function(e){i.value&&(y.addCompletion(m,k,e),C(e))},P=function(){y.removeCompletion(m),C(null)};k.addCompletion=function(e,t){t&&(e+t).startsWith(i.value)&&A(t)};var b=[{type:"text",children:[{text:i.value,type:void 0}]}];t(function(){i.editorRef&&(i.editorRef.current=f({},s.toDOMNode(m,m),{focus:function(){setTimeout(function(){s.focus(m),o.select(m,i.value?r.end(m,[]):r.start(m,[]))},50)}}))});var I=e.useCallback(function(t){switch(t.element.type){case"text":return i.renderText(f({},t));case"completion":return i.renderCompletion(f({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return e.createElement(u,t)}},[i.renderText,i.renderCompletion]),w=e.useCallback(function(e){return i.renderPlaceholder(f({},e,e.attributes||{},{style:f({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},e.style||{})}))},[i.renderPlaceholder]);/*#__PURE__*/return e.createElement(a,{editor:m,value:b,onChange:function(e){var t,n=y.serialize(e.filter(function(e){return"completion"!==e.type}));null==(t=k.fetchCompletion(n,i.context||{}))||t.catch(function(e){return console.error(e)}),k.sendEvents(n,i.context||{}),i.onChange(n)}},/*#__PURE__*/e.createElement(p,{placeholder:i.placeholder,className:i.className,style:f({},i.style||{},{whiteSpace:i.multiline?void 0:"pre"}),onPaste:function(e){P(),e.preventDefault();var t=e.clipboardData.getData("Text");m.insertText(i.multiline?t:t.replaceAll("\n",""))},renderPlaceholder:i.renderPlaceholder?w:void 0,renderElement:I,onBlur:function(e){P(),k.currentCompletion=null,i.onBlur&&i.onBlur(e)},onFocus:function(e){i.onFocus&&(i.onFocus(e),null==m.selection&&o.select(m,i.value?r.end(m,[]):r.start(m,[])))},onKeyDown:function(e){var t,n,o=Boolean(null==h||null==(t=h.completion)||null==(n=t.trim())?void 0:n.length);if("Tab"===e.key&&o)e.preventDefault(),x(),k.currentCompletion=null;else if("ArrowRight"===e.key&&o)e.preventDefault(),x(),k.currentCompletion=null;else if("ArrowLeft"===e.key&&o)P(),k.currentCompletion=null;else if("ArrowDown"!==e.key&&"ArrowUp"!==e.key||!o)if("Backspace"===e.key)k.currentCompletion=null,P();else if("Enter"!==e.key||e.metaKey){if("Shift"!==e.key){var r;if(h&&!e.metaKey&&null!=(r=h.completion)&&r.startsWith(e.key)&&1===e.key.length){var l=h.completion.substring(1);y.updateCompletion(m,l),C(f({},h,{completion:l}))}else k.currentCompletion=null,P()}}else e.preventDefault(),i.multiline&&(P(),m.insertText("\n"));else P();i.onKeyDown&&i.onKeyDown(e)}}))}var y={isCompletionActive:function(e){return!!e.children.find(function(e){return"completion"===e.type})},isCursorAtEndOfDocument:function(e){var t=e.selection;if(!t)return!1;var n=t.anchor.path[0];return n===e.children.length-1&&t.anchor.offset===i.string(e.children[n]).length},acceptCompletion:function(e,t,n){y.isCompletionActive(e)&&null!=n&&n.completion&&(y.removeCompletion(e),e.insertText(n.completion),t.updateCompletion(n.sid,{accepted:!0}))},addCompletion:function(e,t,n){var r=y.isCompletionActive(e),i=y.isCursorAtEndOfDocument(e);!r&&i&&null!=n&&n.completion&&(o.insertNodes(e,{type:"completion",children:[{text:n.completion}]},{at:[e.children.length]}),t.updateCompletion(n.sid,{seen:!0}))},removeCompletion:function(e){y.isCompletionActive(e)&&o.removeNodes(e,{at:[e.children.length-1]})},updateCompletion:function(e,t){y.isCompletionActive(e)&&t.length>0&&o.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:function(e){return e.map(function(e){return i.string(e)}).join("\n")}};export{C as SmartInput}; | ||
import e,{useEffect as t}from"react";import{createEditor as n,Transforms as o,Editor as r,Node as i}from"slate";import{withHistory as l}from"slate-history";import{withReact as c,ReactEditor as u,DefaultElement as a,Slate as s,Editable as p}from"slate-react";import{ulid as m}from"ulid";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},d.apply(this,arguments)}var f=/*#__PURE__*/function(){function e(e,t,n,o){var r,i,l,c=this,u=this;this.apiUrl=void 0,this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=m(),this.completionCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=function(e,t,n){var o,r,i;void 0===t&&(t=50),void 0===n&&(n={});var l=null!=(o=n.isImmediate)&&o,c=null!=(r=n.callback)&&r,u=n.maxWait,a=Date.now(),s=[];function p(){if(void 0!==u){var e=Date.now()-a;if(e+t>=u)return u-e}return t}var m=function(){var t=[].slice.call(arguments),n=this;return new Promise(function(o,r){var u=l&&void 0===i;if(void 0!==i&&clearTimeout(i),i=setTimeout(function(){if(i=void 0,a=Date.now(),!l){var o=e.apply(n,t);c&&c(o),s.forEach(function(e){return(0,e.resolve)(o)}),s=[]}},p()),u){var m=e.apply(n,t);return c&&c(m),o(m)}s.push({resolve:o,reject:r})})};return m.cancel=function(e){void 0!==i&&clearTimeout(i),s.forEach(function(t){return(0,t.reject)(e)}),s=[]},m}(function(e,t){try{var n,o,r=function(n){return o?n:Promise.resolve(fetch(u.apiUrl+"/completions",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u.modelId},body:JSON.stringify({model:u.modelId,input:e,session:u.sessionId,context:t})})).then(function(t){return 200!==t.status?(console.error("Couldn't fetch completions"),null):Promise.resolve(t.json()).then(function(t){var n;return u.completionCache[e]=t,(null==(n=u.currentCompletion)?void 0:n.sequenceId)===i&&(u.addCompletion(e,t),u.currentCompletion.completion=t.completion),t})})};if(0===e.length)return Promise.resolve(null);var i=++u.sequenceId;if(null!=(n=u.currentCompletion)&&n.completion&&(u.currentCompletion.text+u.currentCompletion.completion).startsWith(e))return Promise.resolve(null);u.currentCompletion={text:e,sequenceId:i};var l=u.completionCache[e];if(l)return u.addCompletion(e,l),u.currentCompletion.completion=l.completion,Promise.resolve(l);var c=function(){if(u.mockCompletion){var t=function(t){if(o)return t;var n={input:e,sid:m(),completion:null};return o=1,n},n=u.mockCompletion(e),r=function(){if(n)return Promise.resolve(new Promise(function(t){var o,r;setTimeout(function(){var o,r={input:e,sid:m(),completion:n};u.completionCache[e]=r,(null==(o=u.currentCompletion)?void 0:o.sequenceId)===i&&(u.addCompletion(e,r),u.currentCompletion.completion=n),t(r)},(o=200,r=1e3,o=Math.ceil(o),r=Math.floor(r),Math.floor(Math.random()*(r-o+1))+o))})).then(function(e){return o=1,e})}();return r&&r.then?r.then(t):t(r)}}();return Promise.resolve(c&&c.then?c.then(r):r(c))}catch(e){return Promise.reject(e)}},200),this.sendEvents=(r=function(e,t){fetch(c.apiUrl+"/events",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+c.modelId},body:JSON.stringify({model:c.modelId,session:c.sessionId,input:e,context:t})}).then(function(e){200!==e.status&&console.error("Error sending events")}).catch(function(e){return console.error(e)})},function(){var e=arguments,t=this;return i||(i=!0,setTimeout(function(){return i=!1},1e3),l=r.apply(t,e)),l}),this.apiUrl=e,this.addCompletion=t,this.modelId=n,this.mockCompletion=o}return e.prototype.updateCompletion=function(e,t){var n=this;this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch(this.apiUrl+"/completions",{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.modelId},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(function(o){200!==o.status&&console.error("Couldn't update completion"),t.seen&&n.alreadySeen.add(e),t.accepted&&n.alreadyAccepted.add(e)}).catch(function(e){return console.error(e)})},e}();function h(i){var m=e.useMemo(function(){return l(c(n()))},[]),h=e.useState(null),C=h[0],y=h[1],g=e.useState(new f(i.devApiUrl||"https://api.foundation-ui.com/smartinput",function(e,t){x(t)},i.modelId,i.modelId?i.mockCompletion:function(){return" -- sample completion --"})),k=g[0],w=function(){v.acceptCompletion(m,k,C),y(null)},x=function(e){i.value&&(v.addCompletion(m,k,e),y(e))},A=function(){v.removeCompletion(m),y(null)};k.addCompletion=function(e,t){t&&(e+t).startsWith(i.value)&&x(t)};var P=[{type:"text",children:[{text:i.value,type:void 0}]}];t(function(){i.editorRef&&(i.editorRef.current=d({},u.toDOMNode(m,m),{focus:function(){setTimeout(function(){u.focus(m),o.select(m,i.value?r.end(m,[]):r.start(m,[]))},50)}}))});var T=e.useCallback(function(t){switch(t.element.type){case"text":return i.renderText(d({},t));case"completion":return i.renderCompletion(d({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return e.createElement(a,t)}},[i.renderText,i.renderCompletion]),I=e.useCallback(function(e){return i.renderPlaceholder(d({},e,e.attributes||{},{style:d({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},e.style||{})}))},[i.renderPlaceholder]);/*#__PURE__*/return e.createElement(s,{editor:m,value:P,onChange:function(e){var t,n=v.serialize(e.filter(function(e){return"completion"!==e.type}));null==(t=k.fetchCompletion(n,i.context||{}))||t.catch(function(e){return console.error(e)}),k.sendEvents(n,i.context||{}),i.onChange(n)}},/*#__PURE__*/e.createElement(p,{placeholder:i.placeholder,className:i.className,style:d({},i.style||{},{whiteSpace:i.multiline?void 0:"pre"}),onPaste:function(e){A(),e.preventDefault();var t=e.clipboardData.getData("Text");m.insertText(i.multiline?t:t.replaceAll("\n",""))},renderPlaceholder:i.renderPlaceholder?I:void 0,renderElement:T,onBlur:function(e){A(),k.currentCompletion=null,i.onBlur&&i.onBlur(e)},onFocus:function(e){i.onFocus&&(i.onFocus(e),null==m.selection&&o.select(m,i.value?r.end(m,[]):r.start(m,[])))},onKeyDown:function(e){var t,n,o=Boolean(null==C||null==(t=C.completion)||null==(n=t.trim())?void 0:n.length);if("Tab"===e.key&&o)e.preventDefault(),w(),k.currentCompletion=null;else if("ArrowRight"===e.key&&o)e.preventDefault(),w(),k.currentCompletion=null;else if("ArrowLeft"===e.key&&o)A(),k.currentCompletion=null;else if("ArrowDown"!==e.key&&"ArrowUp"!==e.key||!o)if("Backspace"===e.key)k.currentCompletion=null,A();else if("Enter"!==e.key||e.metaKey){if("Shift"!==e.key){var r;if(C&&!e.metaKey&&null!=(r=C.completion)&&r.startsWith(e.key)&&1===e.key.length){var l=C.completion.substring(1);v.updateCompletion(m,l),y(d({},C,{completion:l}))}else k.currentCompletion=null,A()}}else e.preventDefault(),i.multiline&&(A(),m.insertText("\n"));else A();i.onKeyDown&&i.onKeyDown(e)}}))}var v={isCompletionActive:function(e){return!!e.children.find(function(e){return"completion"===e.type})},isCursorAtEndOfDocument:function(e){var t=e.selection;if(!t)return!1;var n=t.anchor.path[0];return n===e.children.length-1&&t.anchor.offset===i.string(e.children[n]).length},acceptCompletion:function(e,t,n){v.isCompletionActive(e)&&null!=n&&n.completion&&(v.removeCompletion(e),e.insertText(n.completion),t.updateCompletion(n.sid,{accepted:!0}))},addCompletion:function(e,t,n){var r=v.isCompletionActive(e),i=v.isCursorAtEndOfDocument(e);!r&&i&&null!=n&&n.completion&&(o.insertNodes(e,{type:"completion",children:[{text:n.completion}]},{at:[e.children.length]}),t.updateCompletion(n.sid,{seen:!0}))},removeCompletion:function(e){v.isCompletionActive(e)&&o.removeNodes(e,{at:[e.children.length-1]})},updateCompletion:function(e,t){v.isCompletionActive(e)&&t.length>0&&o.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:function(e){return e.map(function(e){return i.string(e)}).join("\n")}};export{h as SmartInput}; | ||
//# sourceMappingURL=index.module.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("slate"),require("slate-history"),require("slate-react"),require("lodash.debounce"),require("lodash.throttle"),require("ulid")):"function"==typeof define&&define.amd?define(["exports","react","slate","slate-history","slate-react","lodash.debounce","lodash.throttle","ulid"],t):t((e||self).smartInput={},e.react,e.slate,e.slateHistory,e.slateReact,e.debounce,e.throttle,e.ulid)}(this,function(e,t,n,o,r,i,l,c){function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=/*#__PURE__*/u(t),s=/*#__PURE__*/u(i),d=/*#__PURE__*/u(l);function p(){return p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},p.apply(this,arguments)}var m=/*#__PURE__*/function(){function e(e,t,n){var o=this,r=this;this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=c.ulid(),this.fetchCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=s.default(function(e,t){try{var n,o,i=function(n){return o?n:Promise.resolve(fetch("https://api.foundation-ui.com/completions",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r.modelId},body:JSON.stringify({model:r.modelId,input:e,session:r.sessionId,context:t})})).then(function(t){return 200!==t.status?(console.error("Couldn't fetch completions"),null):Promise.resolve(t.json()).then(function(t){var n;return r.fetchCache[e]=t,(null==(n=r.currentCompletion)?void 0:n.sequenceId)===l&&(r.addCompletion(e,t),r.currentCompletion.completion=t.completion),t})})};if(0===e.length)return Promise.resolve(null);var l=++r.sequenceId;if(null!=(n=r.currentCompletion)&&n.completion&&(r.currentCompletion.text+r.currentCompletion.completion).startsWith(e))return Promise.resolve(null);r.currentCompletion={text:e,sequenceId:l};var u=r.fetchCache[e];if(u)return r.addCompletion(e,u),r.currentCompletion.completion=u.completion,Promise.resolve(u);var a=function(){if(r.mockCompletion){var t=function(t){if(o)return t;var n={input:e,sid:c.ulid(),completion:null};return o=1,n},n=r.mockCompletion(e),i=function(){if(n)return Promise.resolve(new Promise(function(t){var o,i;setTimeout(function(){var o,i={input:e,sid:c.ulid(),completion:n};r.fetchCache[e]=i,(null==(o=r.currentCompletion)?void 0:o.sequenceId)===l&&(r.addCompletion(e,i),r.currentCompletion.completion=n),t(i)},(o=200,i=1e3,o=Math.ceil(o),i=Math.floor(i),Math.floor(Math.random()*(i-o+1))+o))})).then(function(e){return o=1,e})}();return i&&i.then?i.then(t):t(i)}}();return Promise.resolve(a&&a.then?a.then(i):i(a))}catch(e){return Promise.reject(e)}},200),this.sendEvents=d.default(function(e,t){fetch("https://api.foundation-ui.com/events",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o.modelId},body:JSON.stringify({model:o.modelId,session:o.sessionId,input:e,context:t})}).then(function(e){200!==e.status&&console.error("Error sending events")}).catch(function(e){return console.error(e)})},1e3,{trailing:!0}),this.addCompletion=e,this.modelId=t,this.mockCompletion=n}return e.prototype.updateCompletion=function(e,t){var n=this;this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch("https://api.foundation-ui.com/completions",{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.modelId},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(function(o){200!==o.status&&console.error("Couldn't update completion"),t.seen&&n.alreadySeen.add(e),t.accepted&&n.alreadyAccepted.add(e)}).catch(function(e){return console.error(e)})},e}(),f={isCompletionActive:function(e){return!!e.children.find(function(e){return"completion"===e.type})},isCursorAtEndOfDocument:function(e){var t=e.selection;if(!t)return!1;var o=t.anchor.path[0];return o===e.children.length-1&&t.anchor.offset===n.Node.string(e.children[o]).length},acceptCompletion:function(e,t,n){f.isCompletionActive(e)&&null!=n&&n.completion&&(f.removeCompletion(e),e.insertText(n.completion),t.updateCompletion(n.sid,{accepted:!0}))},addCompletion:function(e,t,o){var r=f.isCompletionActive(e),i=f.isCursorAtEndOfDocument(e);!r&&i&&null!=o&&o.completion&&(n.Transforms.insertNodes(e,{type:"completion",children:[{text:o.completion}]},{at:[e.children.length]}),t.updateCompletion(o.sid,{seen:!0}))},removeCompletion:function(e){f.isCompletionActive(e)&&n.Transforms.removeNodes(e,{at:[e.children.length-1]})},updateCompletion:function(e,t){f.isCompletionActive(e)&&t.length>0&&n.Transforms.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:function(e){return e.map(function(e){return n.Node.string(e)}).join("\n")}};e.SmartInput=function(e){var i=a.default.useMemo(function(){return o.withHistory(r.withReact(n.createEditor()))},[]),l=a.default.useState(null),c=l[0],u=l[1],s=a.default.useState(new m(function(e,t){h(t)},e.modelId,e.modelId?e.mockCompletion:function(){return" -- sample completion --"}))[0],d=function(){f.acceptCompletion(i,s,c),u(null)},h=function(t){e.value&&(f.addCompletion(i,s,t),u(t))},v=function(){f.removeCompletion(i),u(null)};s.addCompletion=function(t,n){n&&(t+n).startsWith(e.value)&&h(n)};var C=[{type:"text",children:[{text:e.value,type:void 0}]}];t.useEffect(function(){e.editorRef&&(e.editorRef.current=p({},r.ReactEditor.toDOMNode(i,i),{focus:function(){setTimeout(function(){r.ReactEditor.focus(i),n.Transforms.select(i,e.value?n.Editor.end(i,[]):n.Editor.start(i,[]))},50)}}))});var y=a.default.useCallback(function(t){switch(t.element.type){case"text":return e.renderText(p({},t));case"completion":return e.renderCompletion(p({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return a.default.createElement(r.DefaultElement,t)}},[e.renderText,e.renderCompletion]),g=a.default.useCallback(function(t){return e.renderPlaceholder(p({},t,t.attributes||{},{style:p({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},t.style||{})}))},[e.renderPlaceholder]);/*#__PURE__*/return a.default.createElement(r.Slate,{editor:i,value:C,onChange:function(t){var n,o=f.serialize(t.filter(function(e){return"completion"!==e.type}));null==(n=s.fetchCompletion(o,e.context||{}))||n.catch(function(e){return console.error(e)}),s.sendEvents(o,e.context||{}),e.onChange(o)}},/*#__PURE__*/a.default.createElement(r.Editable,{placeholder:e.placeholder,className:e.className,style:p({},e.style||{},{whiteSpace:e.multiline?void 0:"pre"}),onPaste:function(t){v(),t.preventDefault();var n=t.clipboardData.getData("Text");i.insertText(e.multiline?n:n.replaceAll("\n",""))},renderPlaceholder:e.renderPlaceholder?g:void 0,renderElement:y,onBlur:function(t){v(),s.currentCompletion=null,e.onBlur&&e.onBlur(t)},onFocus:function(t){e.onFocus&&(e.onFocus(t),null==i.selection&&n.Transforms.select(i,e.value?n.Editor.end(i,[]):n.Editor.start(i,[])))},onKeyDown:function(t){var n,o,r=Boolean(null==c||null==(n=c.completion)||null==(o=n.trim())?void 0:o.length);if("Tab"===t.key&&r)t.preventDefault(),d(),s.currentCompletion=null;else if("ArrowRight"===t.key&&r)t.preventDefault(),d(),s.currentCompletion=null;else if("ArrowLeft"===t.key&&r)v(),s.currentCompletion=null;else if("ArrowDown"!==t.key&&"ArrowUp"!==t.key||!r)if("Backspace"===t.key)s.currentCompletion=null,v();else if("Enter"!==t.key||t.metaKey){if("Shift"!==t.key){var l;if(c&&!t.metaKey&&null!=(l=c.completion)&&l.startsWith(t.key)&&1===t.key.length){var a=c.completion.substring(1);f.updateCompletion(i,a),u(p({},c,{completion:a}))}else s.currentCompletion=null,v()}}else t.preventDefault(),e.multiline&&(v(),i.insertText("\n"));else v();e.onKeyDown&&e.onKeyDown(t)}}))}}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("slate"),require("slate-history"),require("slate-react"),require("ulid")):"function"==typeof define&&define.amd?define(["exports","react","slate","slate-history","slate-react","ulid"],t):t((e||self).smartInput={},e.react,e.slate,e.slateHistory,e.slateReact,e.ulid)}(this,function(e,t,n,o,r,i){function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=/*#__PURE__*/l(t);function a(){return a=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},a.apply(this,arguments)}var u=/*#__PURE__*/function(){function e(e,t,n,o){var r,l,c,a=this,u=this;this.apiUrl=void 0,this.addCompletion=void 0,this.modelId=void 0,this.mockCompletion=void 0,this.sequenceId=0,this.sessionId=i.ulid(),this.completionCache={},this.alreadySeen=new Set,this.alreadyAccepted=new Set,this.currentCompletion=null,this.fetchCompletion=function(e,t,n){var o,r,i;void 0===t&&(t=50),void 0===n&&(n={});var l=null!=(o=n.isImmediate)&&o,c=null!=(r=n.callback)&&r,a=n.maxWait,u=Date.now(),s=[];function d(){if(void 0!==a){var e=Date.now()-u;if(e+t>=a)return a-e}return t}var p=function(){var t=[].slice.call(arguments),n=this;return new Promise(function(o,r){var a=l&&void 0===i;if(void 0!==i&&clearTimeout(i),i=setTimeout(function(){if(i=void 0,u=Date.now(),!l){var o=e.apply(n,t);c&&c(o),s.forEach(function(e){return(0,e.resolve)(o)}),s=[]}},d()),a){var p=e.apply(n,t);return c&&c(p),o(p)}s.push({resolve:o,reject:r})})};return p.cancel=function(e){void 0!==i&&clearTimeout(i),s.forEach(function(t){return(0,t.reject)(e)}),s=[]},p}(function(e,t){try{var n,o,r=function(n){return o?n:Promise.resolve(fetch(u.apiUrl+"/completions",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+u.modelId},body:JSON.stringify({model:u.modelId,input:e,session:u.sessionId,context:t})})).then(function(t){return 200!==t.status?(console.error("Couldn't fetch completions"),null):Promise.resolve(t.json()).then(function(t){var n;return u.completionCache[e]=t,(null==(n=u.currentCompletion)?void 0:n.sequenceId)===l&&(u.addCompletion(e,t),u.currentCompletion.completion=t.completion),t})})};if(0===e.length)return Promise.resolve(null);var l=++u.sequenceId;if(null!=(n=u.currentCompletion)&&n.completion&&(u.currentCompletion.text+u.currentCompletion.completion).startsWith(e))return Promise.resolve(null);u.currentCompletion={text:e,sequenceId:l};var c=u.completionCache[e];if(c)return u.addCompletion(e,c),u.currentCompletion.completion=c.completion,Promise.resolve(c);var a=function(){if(u.mockCompletion){var t=function(t){if(o)return t;var n={input:e,sid:i.ulid(),completion:null};return o=1,n},n=u.mockCompletion(e),r=function(){if(n)return Promise.resolve(new Promise(function(t){var o,r;setTimeout(function(){var o,r={input:e,sid:i.ulid(),completion:n};u.completionCache[e]=r,(null==(o=u.currentCompletion)?void 0:o.sequenceId)===l&&(u.addCompletion(e,r),u.currentCompletion.completion=n),t(r)},(o=200,r=1e3,o=Math.ceil(o),r=Math.floor(r),Math.floor(Math.random()*(r-o+1))+o))})).then(function(e){return o=1,e})}();return r&&r.then?r.then(t):t(r)}}();return Promise.resolve(a&&a.then?a.then(r):r(a))}catch(e){return Promise.reject(e)}},200),this.sendEvents=(r=function(e,t){fetch(a.apiUrl+"/events",{method:"POST",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+a.modelId},body:JSON.stringify({model:a.modelId,session:a.sessionId,input:e,context:t})}).then(function(e){200!==e.status&&console.error("Error sending events")}).catch(function(e){return console.error(e)})},function(){var e=arguments,t=this;return l||(l=!0,setTimeout(function(){return l=!1},1e3),c=r.apply(t,e)),c}),this.apiUrl=e,this.addCompletion=t,this.modelId=n,this.mockCompletion=o}return e.prototype.updateCompletion=function(e,t){var n=this;this.mockCompletion||(t.seen&&!this.alreadySeen.has(e)||t.accepted&&!this.alreadyAccepted.has(e))&&fetch(this.apiUrl+"/completions",{method:"PUT",mode:"cors",headers:{"Content-Type":"application/json",Authorization:"Bearer "+this.modelId},body:JSON.stringify({completionSid:e,seen:t.seen,accepted:t.accepted})}).then(function(o){200!==o.status&&console.error("Couldn't update completion"),t.seen&&n.alreadySeen.add(e),t.accepted&&n.alreadyAccepted.add(e)}).catch(function(e){return console.error(e)})},e}(),s={isCompletionActive:function(e){return!!e.children.find(function(e){return"completion"===e.type})},isCursorAtEndOfDocument:function(e){var t=e.selection;if(!t)return!1;var o=t.anchor.path[0];return o===e.children.length-1&&t.anchor.offset===n.Node.string(e.children[o]).length},acceptCompletion:function(e,t,n){s.isCompletionActive(e)&&null!=n&&n.completion&&(s.removeCompletion(e),e.insertText(n.completion),t.updateCompletion(n.sid,{accepted:!0}))},addCompletion:function(e,t,o){var r=s.isCompletionActive(e),i=s.isCursorAtEndOfDocument(e);!r&&i&&null!=o&&o.completion&&(n.Transforms.insertNodes(e,{type:"completion",children:[{text:o.completion}]},{at:[e.children.length]}),t.updateCompletion(o.sid,{seen:!0}))},removeCompletion:function(e){s.isCompletionActive(e)&&n.Transforms.removeNodes(e,{at:[e.children.length-1]})},updateCompletion:function(e,t){s.isCompletionActive(e)&&t.length>0&&n.Transforms.delete(e,{at:{anchor:{path:[e.children.length-1,0],offset:0},focus:{path:[e.children.length-1,0],offset:1}}})},serialize:function(e){return e.map(function(e){return n.Node.string(e)}).join("\n")}};e.SmartInput=function(e){var i=c.default.useMemo(function(){return o.withHistory(r.withReact(n.createEditor()))},[]),l=c.default.useState(null),d=l[0],p=l[1],m=c.default.useState(new u(e.devApiUrl||"https://api.foundation-ui.com/smartinput",function(e,t){h(t)},e.modelId,e.modelId?e.mockCompletion:function(){return" -- sample completion --"}))[0],f=function(){s.acceptCompletion(i,m,d),p(null)},h=function(t){e.value&&(s.addCompletion(i,m,t),p(t))},v=function(){s.removeCompletion(i),p(null)};m.addCompletion=function(t,n){n&&(t+n).startsWith(e.value)&&h(n)};var C=[{type:"text",children:[{text:e.value,type:void 0}]}];t.useEffect(function(){e.editorRef&&(e.editorRef.current=a({},r.ReactEditor.toDOMNode(i,i),{focus:function(){setTimeout(function(){r.ReactEditor.focus(i),n.Transforms.select(i,e.value?n.Editor.end(i,[]):n.Editor.start(i,[]))},50)}}))});var y=c.default.useCallback(function(t){switch(t.element.type){case"text":return e.renderText(a({},t));case"completion":return e.renderCompletion(a({},t,{contentEditable:"false",suppressContentEditableWarning:!0}));default:/*#__PURE__*/return c.default.createElement(r.DefaultElement,t)}},[e.renderText,e.renderCompletion]),g=c.default.useCallback(function(t){return e.renderPlaceholder(a({},t,t.attributes||{},{style:a({position:"absolute",pointerEvents:"none",width:"100%",maxWidth:"100%",userSelect:"none",textDecoration:"none"},t.style||{})}))},[e.renderPlaceholder]);/*#__PURE__*/return c.default.createElement(r.Slate,{editor:i,value:C,onChange:function(t){var n,o=s.serialize(t.filter(function(e){return"completion"!==e.type}));null==(n=m.fetchCompletion(o,e.context||{}))||n.catch(function(e){return console.error(e)}),m.sendEvents(o,e.context||{}),e.onChange(o)}},/*#__PURE__*/c.default.createElement(r.Editable,{placeholder:e.placeholder,className:e.className,style:a({},e.style||{},{whiteSpace:e.multiline?void 0:"pre"}),onPaste:function(t){v(),t.preventDefault();var n=t.clipboardData.getData("Text");i.insertText(e.multiline?n:n.replaceAll("\n",""))},renderPlaceholder:e.renderPlaceholder?g:void 0,renderElement:y,onBlur:function(t){v(),m.currentCompletion=null,e.onBlur&&e.onBlur(t)},onFocus:function(t){e.onFocus&&(e.onFocus(t),null==i.selection&&n.Transforms.select(i,e.value?n.Editor.end(i,[]):n.Editor.start(i,[])))},onKeyDown:function(t){var n,o,r=Boolean(null==d||null==(n=d.completion)||null==(o=n.trim())?void 0:o.length);if("Tab"===t.key&&r)t.preventDefault(),f(),m.currentCompletion=null;else if("ArrowRight"===t.key&&r)t.preventDefault(),f(),m.currentCompletion=null;else if("ArrowLeft"===t.key&&r)v(),m.currentCompletion=null;else if("ArrowDown"!==t.key&&"ArrowUp"!==t.key||!r)if("Backspace"===t.key)m.currentCompletion=null,v();else if("Enter"!==t.key||t.metaKey){if("Shift"!==t.key){var l;if(d&&!t.metaKey&&null!=(l=d.completion)&&l.startsWith(t.key)&&1===t.key.length){var c=d.completion.substring(1);s.updateCompletion(i,c),p(a({},d,{completion:c}))}else m.currentCompletion=null,v()}}else t.preventDefault(),e.multiline&&(v(),i.insertText("\n"));else v();e.onKeyDown&&e.onKeyDown(t)}}))}}); | ||
//# sourceMappingURL=index.umd.js.map |
@@ -74,2 +74,6 @@ import React, { MutableRefObject } from 'react'; | ||
mockCompletion?: (text: string) => string; | ||
/** | ||
* If provided, the component will make requests to this URL instead of the default API URL. | ||
*/ | ||
devApiUrl?: string; | ||
} | ||
@@ -76,0 +80,0 @@ /** |
@@ -1,7 +0,8 @@ | ||
/// <reference types="lodash" /> | ||
import { ICompletionResponse } from './ICompletionResponse'; | ||
import { ICompletionResponse } from './protocol'; | ||
/** | ||
* Responsible for fetching completions from a model and adding them to the input. | ||
* Each `<SmartInput />` component rendered to the DOM will have its own instance of this class as state. | ||
*/ | ||
export declare class SmartInputFetcher { | ||
private apiUrl; | ||
addCompletion: (text: string, completion: ICompletionResponse) => void; | ||
@@ -11,12 +12,25 @@ modelId?: string | undefined; | ||
/** | ||
* sequenceId is used to ensure that we don't add completions from a previous fetch | ||
* sequenceId is used to ensure that we don't add completions from a previous fetch, | ||
* we increment it each time we request to fetch a new completion because the user input has changed | ||
*/ | ||
sequenceId: number; | ||
/** | ||
* sessionId is used to track this particular instantiation of the `<SmartInput />` component | ||
*/ | ||
sessionId: string; | ||
fetchCache: Record<string, ICompletionResponse | null>; | ||
/** | ||
* completionCache is used to cache the completions that we've already fetched from the model | ||
*/ | ||
completionCache: Record<string, ICompletionResponse | null>; | ||
/** | ||
* alreadySeen tracks which completions we've marked as seen (reduce chattiness) | ||
*/ | ||
alreadySeen: Set<string>; | ||
/** | ||
* alreadyAccepted tracks which completions we've marked as acceoted (reduce chattiness) | ||
*/ | ||
alreadyAccepted: Set<string>; | ||
/** | ||
* currentCompletion is used to track the latest text that was sent to the model for fetching completions, and the | ||
* completion that was returned (if any ~ we may be waiting for it). | ||
* currentCompletion tracks the latest text that was sent to the model for fetching completions, and the | ||
* completion that was returned (if any ~ we may still be waiting for it) | ||
*/ | ||
@@ -28,4 +42,4 @@ currentCompletion: { | ||
} | null; | ||
constructor(addCompletion: (text: string, completion: ICompletionResponse) => void, modelId?: string | undefined, mockCompletion?: ((text: string) => string | null) | undefined); | ||
fetchCompletion: import("lodash").DebouncedFunc<(text: string, context: any) => Promise<ICompletionResponse | null>>; | ||
constructor(apiUrl: string, addCompletion: (text: string, completion: ICompletionResponse) => void, modelId?: string | undefined, mockCompletion?: ((text: string) => string | null) | undefined); | ||
fetchCompletion: import("./util/debounce").DebouncedFunction<any[], (text: string, context: any) => Promise<ICompletionResponse | null>>; | ||
updateCompletion(completionSid: string, arg: { | ||
@@ -35,3 +49,3 @@ seen?: boolean; | ||
}): void; | ||
sendEvents: import("lodash").DebouncedFunc<(text: string, context: any) => void>; | ||
sendEvents: (text: string, context: any) => void; | ||
} |
{ | ||
"name": "@foundationui/smart-input", | ||
"version": "1.0.20", | ||
"version": "1.0.22", | ||
"description": "Smart input/textarea component for React. Learns to provide inline, tab-completeable suggestions.", | ||
@@ -33,4 +33,2 @@ "source": "src/index.ts", | ||
"scripts": { | ||
"clean": "rimraf dist", | ||
"declarations": "tsc -p tsconfig.json", | ||
"build": "microbundle --jsx React.createElement", | ||
@@ -43,5 +41,3 @@ "dev": "microbundle watch --jsx React.createElement", | ||
"dependencies": { | ||
"@babel/runtime": "^7.20.7", | ||
"lodash.debounce": "^4.0.8", | ||
"lodash.throttle": "^4.1.1", | ||
"@types/lodash.debounce": "^4.0.7", | ||
"slate": "^0.87.0", | ||
@@ -57,28 +53,8 @@ "slate-history": "^0.86.0", | ||
"devDependencies": { | ||
"@babel/cli": "^7.20.7", | ||
"@babel/core": "^7.20.12", | ||
"@babel/plugin-transform-runtime": "^7.19.6", | ||
"@babel/preset-env": "^7.20.2", | ||
"@babel/preset-react": "^7.18.6", | ||
"@babel/preset-typescript": "^7.18.6", | ||
"@rollup/plugin-babel": "^6.0.3", | ||
"@rollup/plugin-commonjs": "^24.0.0", | ||
"@rollup/plugin-node-resolve": "^15.0.1", | ||
"@rollup/plugin-typescript": "^10.0.1", | ||
"@types/lodash.debounce": "^4.0.7", | ||
"@types/lodash.throttle": "^4.1.7", | ||
"@types/react": "^16.8.0", | ||
"@types/react-dom": "^16.8.0", | ||
"cross-env": "^7.0.3", | ||
"microbundle": "^0.15.1", | ||
"npm-run-all": "^4.1.5", | ||
"prettier": "^2.8.1", | ||
"react": "^16.8.0", | ||
"react-dom": "^16.8.0", | ||
"rimraf": "^3.0.2", | ||
"rollup": "^2.79.1", | ||
"rollup-plugin-node-externals": "^5.0.3", | ||
"rollup-plugin-peer-deps-external": "^2.2.4", | ||
"rollup-plugin-terser": "^7.0.2", | ||
"tslib": "^2.4.1", | ||
"typescript": "^4.9.4" | ||
@@ -85,0 +61,0 @@ }, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
180417
7
7
17
305
12
+ Added@types/lodash.debounce@4.0.9(transitive)
- Removed@babel/runtime@^7.20.7
- Removedlodash.debounce@^4.0.8
- Removedlodash.throttle@^4.1.1
- Removed@babel/runtime@7.26.7(transitive)
- Removedlodash.debounce@4.0.8(transitive)
- Removedlodash.throttle@4.1.1(transitive)
- Removedregenerator-runtime@0.14.1(transitive)