UNPKG

@es-js/terminal

Version:

Componente de Terminal para navegadores web, diseñado para el Lenguaje de Programación EsJS. Basado en XTerminal.

20 lines (18 loc) 15.5 kB
var Bt=Object.defineProperty;var _t=(h,p,g)=>p in h?Bt(h,p,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[p]=g;var v=(h,p,g)=>(_t(h,typeof p!="symbol"?p+"":p,g),g),nt=(h,p,g)=>{if(!p.has(h))throw TypeError("Cannot "+g)};var l=(h,p,g)=>(nt(h,p,"read from private field"),g?g.call(h):p.get(h)),k=(h,p,g)=>{if(p.has(h))throw TypeError("Cannot add the same private member more than once");p instanceof WeakSet?p.add(h):p.set(h,g)},C=(h,p,g,_)=>(nt(h,p,"write to private field"),_?_.call(h,g):p.set(h,g),g);var X=(h,p,g)=>(nt(h,p,"access private method"),g);(function(h,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(h=typeof globalThis<"u"?globalThis:h||self,p(h.EsTerminal={}))})(this,function(h){var D,T,y,F,N,w,O,P,z,Q,K;"use strict";function p(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}/*! * is-number <https://github.com/jonschlinkert/is-number> * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */var g=function(i){return typeof i=="number"?i-i===0:typeof i=="string"&&i.trim()!==""?Number.isFinite?Number.isFinite(+i):isFinite(+i):!1};const _=p(g);/** * XTerminal - v2.1.9 * @author Henry Hale * @license MIT * @url https://github.com/henryhale/xterminal */class rt{constructor(){k(this,D,void 0);v(this,"isDisposed");this.isDisposed=!1,C(this,D,[])}register(e){this.isDisposed?e==null||e.dispose():l(this,D).push(e)}dispose(){this.isDisposed||(this.isDisposed=!0,l(this,D).forEach(e=>e==null?void 0:e.dispose()))}}D=new WeakMap;class bt extends rt{constructor(){super();k(this,T,void 0);C(this,T,{stack:[],store:new Map}),this.register({dispose:()=>l(this,T).store.clear()})}on(t,n){var a;const o=l(this,T).store;o.has(t)?(a=o.get(t))==null||a.add(n):o.set(t,new Set([n]))}once(t,n){var u;const o=(...c)=>{n.call(void 0,...c),this.off(t,o)},a=l(this,T).store;a.has(t)?(u=a.get(t))==null||u.add(o):a.set(t,new Set([o]))}off(t,n){const o=l(this,T).store.get(t);if(o){for(const a of o)if(a===n){o.delete(n);break}}}emit(t,...n){if(this.isDisposed)return;const o=l(this,T).stack;if(o.includes(t))return;const a=l(this,T).store.get(t);if(a){o.push(t);for(const u of a)u.call(void 0,...n);o.pop()}}}T=new WeakMap;const ot=Array.isArray;function ct(i){return typeof i=="object"&&i!==null}function L(i){return typeof i=="function"}class mt{constructor(e=[]){v(this,"store");v(this,"ptr");this.store=ot(e)?e:[],this.ptr=-1}get size(){return this.store.length}get list(){return[].slice.call(this.store).reverse()}add(e){e&&e!==this.store[0]&&this.store.unshift(e),this.ptr=-1}get previous(){return this.ptr++,this.ptr>=this.size&&(this.ptr=this.size-1),this.store[this.ptr]||""}get next(){return this.ptr--,this.ptr<=-1&&(this.ptr=-1),this.store[this.ptr]||""}clear(){this.store.splice(0)}}const A="&nbsp;",wt="xt",at="xt-inactive",kt="xt-cursor",xt="xt-stdout",Tt="xt-stdin";function lt(i){i&&i.scrollTo(0,i.scrollHeight)}function E(i,e){const t=document.createElement(i);return ct(e)&&(e!=null&&e.id&&(t.id=e.id||""),e!=null&&e.class&&(t.className=e.class||""),e!=null&&e.content&&t.appendChild(document.createTextNode(""+e.content)),e!=null&&e.html&&(t.innerHTML=e.html),ot(e==null?void 0:e.children)&&e.children.forEach(n=>t.append(n)),ct(e==null?void 0:e.props)&&Object.entries(e.props).forEach(n=>t.setAttribute(n[0],n[1]))),t}function Et(i=""){return(""+i).replace(/(\n)|(\n\r)|(\r\n)/g,"<br/>").replace(/\s{2}/g,A.repeat(2)).replace(/\t/g,A.repeat(4))}class St{constructor(e){v(this,"el");v(this,"console");v(this,"lastOutput");v(this,"onoutput");const{outputBox:t,consoleBox:n}=function(o){const a=E("span"),u=E("div",{class:xt,children:[a]});return o.appendChild(u),{outputBox:u,consoleBox:a}}(e);this.el=t,this.console=n}write(e,t){this.lastOutput=E("span",{html:Et(e)}),this.console.appendChild(this.lastOutput),L(this.onoutput)&&this.onoutput(),L(t)&&t()}clear(){this.console&&(this.console.innerHTML="")}clearLast(){var e;this.lastOutput&&((e=this.lastOutput.parentNode)==null||e.removeChild(this.lastOutput)),this.lastOutput=void 0}}const ut="Enter";function S(i,e,t,n){i.addEventListener(e,t,n);let o=!1;return{dispose(){o||(i.removeEventListener(e,t,n),o=!0)}}}const Ct=0;function ht(i,...e){return setTimeout(i,Ct,...e)}function pt(i){let e;return(...t)=>{L(i)&&(clearTimeout(e),e=ht(i,...t))}}let I;function R(i){const e=new Set;let t=!1;return{get value(){return!t&&L(I)&&e.add(I),i},set value(n){i=n,t||e.forEach(o=>o.call(void 0))},dispose(){t||(t=!0,e.clear())}}}function Y(i){if(L(i)){I=i;try{i.call(void 0)}finally{I=null}}}class Lt extends rt{constructor(t){super();v(this,"el");v(this,"buffer");v(this,"data");v(this,"ptr");v(this,"isActive");v(this,"showInput");v(this,"isFocused");v(this,"onkeypress");this.el=function(u){const c=E("input",{props:{spellcheck:!1,autocapitalize:"off",autocomplete:"off"}}),m=E("div",{class:Tt,children:[c]});return u.appendChild(m),c}(t),this.buffer="",this.data=R(""),this.ptr=R(0),this.isActive=R(!0),this.showInput=R(!0),this.isFocused=R(!1),this.register(this.data),this.register(this.ptr),this.register(this.isActive),this.register(this.showInput),this.register(this.isFocused);const n=()=>function(u,c,m){let j="selectionStart"in(W=u)?W.selectionStart:0;var W;const $=c.value.length;j>$?j=$:j<0&&(j=0),m.value=j}(this.el,this.data,this.ptr),o=pt(n),a=pt(()=>{this.data.value=this.buffer=this.el.value});Y(n),this.register(S(this.el,"blur",()=>this.isFocused.value=!1)),this.register(S(this.el,"focus",()=>this.isFocused.value=!0,!1)),this.register(S(this.el,"keyup",()=>this.isActive.value&&o(),!1)),this.register(S(this.el,"input",()=>{a(),o()})),this.register(S(this.el,"keydown",u=>{u.stopImmediatePropagation();const c=this.data.value;u.key===ut&&(this.el&&(this.el.value=""),this.data.value="",this.buffer="",this.showInput.value=!0),this.isActive.value&&L(this.onkeypress)&&(this.onkeypress({key:u.key,altKey:u.altKey,ctrlKey:u.ctrlKey,metaKey:u.metaKey,shiftKey:u.shiftKey,value:c,cancel(){u.preventDefault(),u.stopPropagation()}}),o())}))}blur(){this.el&&this.el.blur()}focus(){this.el&&this.el.focus()}pause(){this.isActive.value=!1}resume(){this.isActive.value=!0}setValue(t){t=t||this.buffer,this.el&&(this.el.value=t),this.data.value=t}pipe(t){var u;const n=E("span"),o=E("span",{class:kt,html:A}),a=E("span");(u=t.el)==null||u.append(n,o,a),Y(()=>{const c=this.ptr.value,m=this.data.value;if(!this.isActive.value||!this.showInput.value)return n.innerHTML="",o.innerHTML=A,void(a.innerHTML="");n.innerHTML=m.substring(0,c).replace(/\s{2}/g," "+A),o.innerHTML=m.substring(c,c+1).trim()||A,a.innerHTML=m.substring(c+1).replace(/\s{2}/g," "+A)})}}function Mt(i,e){const t=E("div",{class:wt,props:{tabindex:0}}),n=new mt,o=new St(t),a=new Lt(t),u={input:a,output:o,history:n,completer:c=>c};return a.pipe(o),o.onoutput=()=>lt(t),i.register(S(t,"keydown",function(c){a.focus(),ht(()=>{a.el.dispatchEvent(new KeyboardEvent("keydown",c)),a.el.dispatchEvent(new KeyboardEvent("input",c))})})),i.register(S(t,"focus",()=>a.isFocused.value=!0)),i.register(S(t,"blur",()=>a.isFocused.value=!1)),function(){const c=window||{},m=navigator||{};return!(!("ontouchstart"in c)&&!m.maxTouchPoints||!/Mobi/.test(m.userAgent))}()&&i.register(S(t,"click",a.focus.bind(a))),e.appendChild(t),a.onkeypress=c=>{c.key==ut?(c.cancel(),n.add(c.value),i.writeln(c.value),i.emit("data",c.value)):c.key=="Tab"?(c.cancel(),L(u.completer)&&a.setValue(u.completer(c.value))):c.key=="ArrowDown"?(c.cancel(),a.setValue(n.next)):c.key=="ArrowUp"?(c.cancel(),a.setValue(n.previous)):i.emit("keypress",c),lt(t)},Y(()=>{a.isFocused.value?t.classList.remove(at):t.classList.add(at)}),u}class jt extends Error{constructor(e){super(e="[x] "+e),this.name="XTerminalError"}}class At extends bt{constructor(t){super();k(this,y,void 0);v(this,"isMounted");this.isMounted=!1,t&&(t!=null&&t.target)&&this.mount(t.target)}focus(){l(this,y).input.focus()}blur(){l(this,y).input.blur()}pause(){l(this,y).input.pause(),this.emit("pause")}resume(){l(this,y).input.resume(),this.emit("resume")}write(t,n){l(this,y).output.write(""+t,n)}writeln(t,n){l(this,y).output.write(t+` `,n)}clear(){l(this,y).output.clear(),this.emit("clear")}clearLast(){l(this,y).output.clearLast()}get history(){return l(this,y).history.list||[]}set history(t){t.forEach(n=>l(this,y).history.add(n))}clearHistory(){l(this,y).history.clear()}setCompleter(t){L(t)&&(l(this,y).completer=t)}mount(t){if(!this.isMounted){if(t&&typeof t=="string"&&(t=document.querySelector(t)),!(t instanceof HTMLElement))throw new jt("mount: A parent HTMLElement (target) is required");!t.isConnected&&console&&console.warn("'mount' was called on an HTMLElement (target) that is not attached to DOM."),t.innerHTML="",C(this,y,Mt(this,t)),this.isMounted=!0}}dispose(){var o;super.dispose();const t=l(this,y);t.history.clear(),t.completer=void 0,t.input.dispose();const n=t.output.el.parentNode;(o=n==null?void 0:n.parentNode)==null||o.removeChild(n)}static get version(){return"2.1.9"}}y=new WeakMap;class Ht extends Error{constructor(e){super(e||"Promise was canceled"),this.name="CancelError"}get isCanceled(){return!0}}const x=Object.freeze({pending:Symbol("pending"),canceled:Symbol("canceled"),resolved:Symbol("resolved"),rejected:Symbol("rejected")}),et=class et{constructor(e){k(this,z);k(this,F,[]);k(this,N,!0);k(this,w,x.pending);k(this,O,void 0);k(this,P,void 0);C(this,O,new Promise((t,n)=>{C(this,P,n);const o=c=>{(l(this,w)!==x.canceled||!u.shouldReject)&&(t(c),X(this,z,Q).call(this,x.resolved))},a=c=>{(l(this,w)!==x.canceled||!u.shouldReject)&&(n(c),X(this,z,Q).call(this,x.rejected))},u=c=>{if(l(this,w)!==x.pending)throw new Error(`The \`onCancel\` handler was attached after the promise ${l(this,w).description}.`);l(this,F).push(c)};Object.defineProperties(u,{shouldReject:{get:()=>l(this,N),set:c=>{C(this,N,c)}}}),e(o,a,u)}))}static fn(e){return(...t)=>new et((n,o,a)=>{t.push(a),e(...t).then(n,o)})}then(e,t){return l(this,O).then(e,t)}catch(e){return l(this,O).catch(e)}finally(e){return l(this,O).finally(e)}cancel(e){if(l(this,w)===x.pending){if(X(this,z,Q).call(this,x.canceled),l(this,F).length>0)try{for(const t of l(this,F))t()}catch(t){l(this,P).call(this,t);return}l(this,N)&&l(this,P).call(this,new Ht(e))}}get isCanceled(){return l(this,w)===x.canceled}};F=new WeakMap,N=new WeakMap,w=new WeakMap,O=new WeakMap,P=new WeakMap,z=new WeakSet,Q=function(e){l(this,w)===x.pending&&C(this,w,e)};let U=et;Object.setPrototypeOf(U.prototype,Promise.prototype);let s=null,b=null,Z=!1,J=!1,V=!1,tt=[],M=null;const H="> ";let q=H;const G=()=>{function i(r,d={}){typeof r=="string"&&(r=document.querySelector(r)),r&&(M=r,s=new At,s.mount(M),s.pause(),s.on("data",async f=>{if(Z)if(V)s==null||s.emit("input:enter");else if(J){if((b==null?void 0:b.trim())===""){s==null||s.writeln(q);return}s==null||s.emit("input",b),s==null||s.writeln("")}else f.trim()===""?s==null||s.writeln(q):(s==null||s.emit("input",f),s==null||s.writeln(f))}),s.on("keypress",f=>{if(V)f.cancel();else if(J){const B=f.key.toLowerCase();if(f.cancel(),B==="backspace"&&(b!=null&&b.length))b=b.substring(0,b.length-1);else{const it=f.altKey||f.ctrlKey||f.metaKey;if(B.length!==1||it)return;b+=f.key}s==null||s.clearLast(),s==null||s.write(`${q}${"*".repeat((b==null?void 0:b.length)||1)}`)}}),dt(d.theme||"dark"))}function e(){tt.map(r=>r.cancel()),tt=[],s==null||s.dispose()}function t(...r){r.map(d=>{switch(typeof d){case"object":return s==null?void 0:s.writeln(JSON.stringify(d,null,2));default:return s==null?void 0:s.writeln(String(d))}})}function n(){s==null||s.pause(),Z=!1,J=!1,V=!1,q=H,b=null}async function o(r=H,d="porDefecto"){s==null||s.resume(),q=r,Z=!0;const f=new U((B,it,vt)=>{if(!s)return it(new Error("Terminal not initialized"));vt.shouldReject=!1,vt(()=>{n()}),s.write(r),V?s.once("input:enter",()=>{n(),B(null)}):s.once("input",qt=>{n(),B($(qt??"",d))})});return tt.push(f),f}function a(r=H){return o(r,"cadena")}function u(r=H){return o(r,"numero")}function c(r=H,d="porDefecto"){return b="",J=!0,o(r,d)}function m(r=H,d="porDefecto"){return V=!0,o(r,d)}function j(){s==null||s.clear()}function W(){s==null||s.clearLast()}function $(r,d){switch(d){case"cadena":return String(r.trim());case"numero":return Number(r);default:return _(r)?$(r,"numero"):$(r,"cadena")}}function Nt(r){return`<div style="text-align: center;">${r}</div>`}function Pt(r){return`<div style="text-align: left;">${r}</div>`}function zt(r){return`<div style="text-align: right;">${r}</div>`}function Kt(r){return`<div style="text-align: justify;">${r}</div>`}function $t(r,d,f="_nuevo"){return f=f==="_nuevo"?"_blank":f,`<a href="${r}" target="${f}">${d||r}</a>`}function dt(r){M==null||M.classList.toggle("dark",r==="dark")}function Rt(){s==null||s.focus()}function ft(...r){r.map(d=>{switch(typeof d){case"object":return s==null?void 0:s.write(JSON.stringify(d,null,2));default:return s==null?void 0:s.write(String(d))}})}function Vt(r,d){gt(r),yt(d)}function gt(r){st("--xt-bg",r)}function yt(r){st("--xt-fg",r)}function st(r,d){M==null||M.style.setProperty(r,d)}return{escribir:t,log:t,imprimir:t,escribirSinSalto:ft,imprimirSinSalto:ft,leer:o,leerCadena:a,leerNumero:u,leerSecreto:c,leerEnter:m,iniciar:i,destruir:e,limpiar:j,clear:j,limpiarUltimaLinea:W,centrar:Nt,alinearIzquierda:Pt,alinearDerecha:zt,justificar:Kt,enlace:$t,setTheme:dt,enfocar:Rt,configurarColores:Vt,configurarColorFondo:gt,configurarColorFrente:yt,establecerVariableCss:st}},Ot=`:root{--xt-bg:#191a22;--xt-fg:#efefef;--xt-font-family:monospace;--xt-font-size:min(15px,calc(2vw + 5px));--xt-padding:min(6px,calc(1.25vw + 4px))}.xt,.xt *,.xt :after,.xt :before{-webkit-box-sizing:border-box;box-sizing:border-box;font-family:var(--xt-font-family);font-size:var(--xt-font-size)}.xt{background-color:var(--xt-bg);color:var(--xt-fg);height:100%;max-height:100%;max-width:100%;overflow-wrap:break-word;overflow-x:hidden;overflow-y:auto;padding:var(--xt-padding);width:100%}.xt>.xt-stdout>span:first{word-wrap:break-word}.xt>.xt-stdout>.xt-cursor{background-color:var(--xt-fg);border:.25px solid transparent;color:var(--xt-bg)}.xt.xt-inactive>.xt-stdout>.xt-cursor{background-color:transparent;border-color:currentColor;color:var(--xt-fg)}.xt>.xt-stdin{height:0;margin-top:2px;position:relative}.xt>.xt-stdin>input{border:0;outline:0 none;position:absolute;top:-20px;z-index:-100}.xt .xt-hidden{display:none}:host{--xt-bg: #ffffff;--xt-fg: #000000}.dark{--xt-bg: #121212;--xt-fg: #efefef}@keyframes blink{0%{opacity:0}50%{opacity:1}to{opacity:0}}.xt-cursor{animation:blink 1s linear infinite}.cargando:after{animation:changeContent .8s linear infinite;content:"⠋"}@keyframes changeContent{10%{content:"⠙"}20%{content:"⠹"}30%{content:"⠸"}40%{content:"⠼"}50%{content:"⠴"}60%{content:"⠦"}70%{content:"⠧"}80%{content:"⠇"}90%{content:"⠏"}} `;class Dt extends HTMLElement{constructor(){super();k(this,K,void 0);C(this,K,this.attachShadow({mode:"open"})),l(this,K).innerHTML=` <style> ${Ot} </style> <div style="width: 100%; height: 100%;"></div> `}connectedCallback(){G().iniciar(l(this,K).querySelector("div"),{theme:this.getAttribute("tema")==="oscuro"?"dark":"light"})}disconnectedCallback(){G().destruir()}}K=new WeakMap,customElements.get("es-terminal")||customElements.define("es-terminal",Dt);const Ft=G();h.Terminal=Ft,h.usarTerminal=G,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});