@liftitapp/wa-conversations 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,6 +30,7 @@ Un host con SOLO HTML monta el visor completo — sin escribir una línea de JS:
30
30
  | `api-url` | La base del servicio (`http:`/`https:`; otro esquema se rechaza) | Cambiarla en caliente remonta igual — es otro backend. El caso de uso normal es setearla una vez |
31
31
  | `token` | El Bearer de cada request | **Se lee en CADA request, nunca se cachea**: rotar el atributo al renovar sesión funciona sin más, y NO remonta el visor |
32
32
  | `phone` | **Opcional** — preselecciona el hilo de ese teléfono al montar | **Reactivo**: cambiarlo remonta el visor con la preselección nueva. Sin él, el visor arranca en la lista como siempre |
33
+ | `pinned` | **Opcional** — ancla el visor a `phone`: ni lista ni "Volver", a cualquier ancho | Booleano **por presencia** (como `disabled`): `pinned`, `pinned=""` y `pinned="pinned"` anclan; sólo `pinned="false"` desactiva. **Reactivo**. Sin `phone` no hace nada |
33
34
 
34
35
  Sobre `phone`: el valor viaja **verbatim** al visor y tiene que ser la forma canónica del
35
36
  servicio — **E.164 CON `+`** (p. ej. `+573112620405`). Con otra forma el hilo carga igual, pero el
@@ -37,6 +38,13 @@ resaltado de la fila en la lista no matchea. **Normalizar el teléfono es respon
37
38
  host.** En layout angosto (contenedor ≤ 520 px) con `phone` seteado, el visor muestra **solo el
38
39
  hilo**, con un botón "Volver" hacia la lista.
39
40
 
41
+ Sobre `pinned`: es para el host que ya sabe de QUIÉN es la conversación y monta el visor dentro de
42
+ su propio contexto — el drawer que abre una fila de una tabla. Ahí la lista no es una comodidad:
43
+ ofrecería saltar a las conversaciones de otras personas desde una fila que habla de una sola, y el
44
+ "Volver" llevaría a una bandeja que ese drawer no promete. Con `pinned`, el mismo elemento a 780 px
45
+ sigue mostrando **solo** el hilo anclado; sin `pinned`, a ese ancho muestra lista e hilo lado a
46
+ lado — que es lo que quiere el host que abre el visor como bandeja.
47
+
40
48
  Con configuración incompleta (atributo ausente o vacío, y sin property `fetcher` que los supla),
41
49
  el elemento pinta un **panel dentro del shadow DOM** que nombra los atributos faltantes — nombres,
42
50
  jamás valores — y remite a este README.
@@ -495,7 +495,7 @@ var v=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
495
495
  background: #ffffff;
496
496
  cursor: pointer;
497
497
  }
498
- `}),i===`loading`&&(0,y.jsx)(`p`,{className:`wa-thread__note`,children:`Cargando conversación…`}),a!==null&&(0,y.jsxs)(`div`,{className:`wa-thread__error`,role:`alert`,children:[(0,y.jsxs)(`p`,{children:[`No se pudo cargar la conversación: `,a.message]}),(0,y.jsx)(`button`,{type:`button`,onClick:c,children:`Reintentar`})]}),i===`empty`&&(0,y.jsx)(`p`,{className:`wa-thread__note`,children:`Sin mensajes en esta conversación.`}),(0,y.jsxs)(`div`,{className:`wa-thread__messages`,ref:u,children:[o&&(0,y.jsx)(`button`,{ref:m,type:`button`,className:`wa-thread__older`,onClick:p,disabled:i===`loading-older`,children:i===`loading-older`?`Cargando…`:`Cargar mensajes anteriores`}),h.map((t,n)=>(0,y.jsxs)(`div`,{className:`wa-thread__group`,children:[t.label!==null&&(0,y.jsx)(`div`,{className:`wa-thread__day`,children:t.label}),t.items.map(({message:t,position:n})=>(0,y.jsx)(Ce,{message:t,showServiceState:g[n],fetcher:e},t.id??`sin-wamid-${n}`))]},t.key??`sin-dia-${n}`))]})]})}function je({fetcher:e,initialPhone:t,className:n}){let r=(0,l.useRef)(null),i=x(r),[a,o]=(0,l.useState)(t??null),s=n?`wa-conversations ${n}`:`wa-conversations`;return e===void 0?(0,y.jsx)(`div`,{className:s,children:(0,y.jsx)(`p`,{children:`Visor de conversaciones de WhatsApp — falta el fetcher del host.`})}):(0,y.jsxs)(`div`,{ref:r,className:s,"data-layout":i,children:[(0,y.jsx)(`style`,{children:`
498
+ `}),i===`loading`&&(0,y.jsx)(`p`,{className:`wa-thread__note`,children:`Cargando conversación…`}),a!==null&&(0,y.jsxs)(`div`,{className:`wa-thread__error`,role:`alert`,children:[(0,y.jsxs)(`p`,{children:[`No se pudo cargar la conversación: `,a.message]}),(0,y.jsx)(`button`,{type:`button`,onClick:c,children:`Reintentar`})]}),i===`empty`&&(0,y.jsx)(`p`,{className:`wa-thread__note`,children:`Sin mensajes en esta conversación.`}),(0,y.jsxs)(`div`,{className:`wa-thread__messages`,ref:u,children:[o&&(0,y.jsx)(`button`,{ref:m,type:`button`,className:`wa-thread__older`,onClick:p,disabled:i===`loading-older`,children:i===`loading-older`?`Cargando…`:`Cargar mensajes anteriores`}),h.map((t,n)=>(0,y.jsxs)(`div`,{className:`wa-thread__group`,children:[t.label!==null&&(0,y.jsx)(`div`,{className:`wa-thread__day`,children:t.label}),t.items.map(({message:t,position:n})=>(0,y.jsx)(Ce,{message:t,showServiceState:g[n],fetcher:e},t.id??`sin-wamid-${n}`))]},t.key??`sin-dia-${n}`))]})]})}function je({fetcher:e,initialPhone:t,pinned:n=!1,className:r}){let i=(0,l.useRef)(null),a=x(i),[o,s]=(0,l.useState)(t??null),c=r?`wa-conversations ${r}`:`wa-conversations`;if(e===void 0)return(0,y.jsx)(`div`,{className:c,children:(0,y.jsx)(`p`,{children:`Visor de conversaciones de WhatsApp — falta el fetcher del host.`})});let u=n&&o!==null;return(0,y.jsxs)(`div`,{ref:i,className:c,"data-layout":a,children:[(0,y.jsx)(`style`,{children:`
499
499
  .wa-conversations {
500
500
  box-sizing: border-box;
501
501
  display: flex;
@@ -547,7 +547,7 @@ var v=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
547
547
  flex: 1 1 auto;
548
548
  color: #616e7c;
549
549
  }
550
- `}),(i===`wide`||a===null)&&(0,y.jsx)(ue,{fetcher:e,selectedPhone:a,onSelect:e=>o(e.phone)}),a===null?i===`wide`&&(0,y.jsx)(`p`,{className:`wa-conversations__empty`,children:`Selecciona una conversación`}):(0,y.jsxs)(`div`,{className:`wa-conversations__thread`,children:[i===`narrow`&&(0,y.jsx)(`button`,{type:`button`,className:`wa-conversations__back`,onClick:()=>o(null),children:`Volver`}),(0,y.jsx)(Ae,{fetcher:e,phone:a})]})]})}function Me(e){let t;try{t=new URL(e)}catch{throw Error(`api-url inválida: no es una URL absoluta`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`api-url inválida: esquema no permitido (${t.protocol})`)}function Ne(e,t,n){if(n.resource===`media`)return new URL(`${e}/conversations/media/${encodeURIComponent(n.mediaId)}`);if(n.resource===`thread`){let r=new URL(`${e}/conversations/${t}/${encodeURIComponent(n.phone)}/thread`);return n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),r}let r=new URL(`${e}/conversations`);return r.searchParams.set(`phone_number_id`,t),n.phone!==void 0&&r.searchParams.set(`phone`,n.phone),n.from!==void 0&&r.searchParams.set(`from`,n.from),n.to!==void 0&&r.searchParams.set(`to`,n.to),n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),r}function Pe(e,t){return async(n,r)=>{let i=!1;for(;;){let a=e.getAttribute(`api-url`)??``,o=e.getAttribute(`phone-number-id`)??``;Me(a);let s=Ne(a,o,n),c=e.getAttribute(`token`)??``,l=await fetch(s,{headers:{authorization:`Bearer ${c}`},signal:r?.signal});if(!(l.status===401&&t!==void 0&&!i&&(i=!0,(e.getAttribute(`token`)??``)!==c||!t.pending()&&(e.dispatchEvent(new CustomEvent(`wa-conversations:unauthorized`,{bubbles:!0,composed:!0,detail:{status:401}})),(e.getAttribute(`token`)??``)!==c)||await t()))){if(!l.ok)throw Error(`${l.status} ${await l.text()}`);return l.json()}}}}var Fe=`:host {
550
+ `}),!u&&(a===`wide`||o===null)&&(0,y.jsx)(ue,{fetcher:e,selectedPhone:o,onSelect:e=>s(e.phone)}),o===null?a===`wide`&&(0,y.jsx)(`p`,{className:`wa-conversations__empty`,children:`Selecciona una conversación`}):(0,y.jsxs)(`div`,{className:`wa-conversations__thread`,children:[a===`narrow`&&!u&&(0,y.jsx)(`button`,{type:`button`,className:`wa-conversations__back`,onClick:()=>s(null),children:`Volver`}),(0,y.jsx)(Ae,{fetcher:e,phone:o})]})]})}function Me(e){let t;try{t=new URL(e)}catch{throw Error(`api-url inválida: no es una URL absoluta`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`api-url inválida: esquema no permitido (${t.protocol})`)}function Ne(e,t,n){if(n.resource===`media`)return new URL(`${e}/conversations/media/${encodeURIComponent(n.mediaId)}`);if(n.resource===`thread`){let r=new URL(`${e}/conversations/${t}/${encodeURIComponent(n.phone)}/thread`);return n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),r}let r=new URL(`${e}/conversations`);return r.searchParams.set(`phone_number_id`,t),n.phone!==void 0&&r.searchParams.set(`phone`,n.phone),n.from!==void 0&&r.searchParams.set(`from`,n.from),n.to!==void 0&&r.searchParams.set(`to`,n.to),n.cursor!==void 0&&r.searchParams.set(`cursor`,n.cursor),n.limit!==void 0&&r.searchParams.set(`limit`,String(n.limit)),r}function Pe(e,t){return async(n,r)=>{let i=!1;for(;;){let a=e.getAttribute(`api-url`)??``,o=e.getAttribute(`phone-number-id`)??``;Me(a);let s=Ne(a,o,n),c=e.getAttribute(`token`)??``,l=await fetch(s,{headers:{authorization:`Bearer ${c}`},signal:r?.signal});if(!(l.status===401&&t!==void 0&&!i&&(i=!0,(e.getAttribute(`token`)??``)!==c||!t.pending()&&(e.dispatchEvent(new CustomEvent(`wa-conversations:unauthorized`,{bubbles:!0,composed:!0,detail:{status:401}})),(e.getAttribute(`token`)??``)!==c)||await t()))){if(!l.ok)throw Error(`${l.status} ${await l.text()}`);return l.json()}}}}var Fe=`:host {
551
551
  height: 100%;
552
552
  display: block;
553
553
  }
@@ -595,4 +595,4 @@ var v=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.
595
595
  color: #5d6b76;
596
596
  margin: 0;
597
597
  }
598
- `;const Ie=[`phone-number-id`,`api-url`,`token`];let Le;function Re(){return Le||(Le=new CSSStyleSheet,Le.replaceSync(Fe)),Le}function ze(){if(typeof HTMLElement>`u`||typeof customElements>`u`||customElements.get(`wa-conversations`))return;class e extends HTMLElement{static observedAttributes=[...Ie,`phone`];#e=null;#t;#n;#r=null;get fetcher(){return this.#t}set fetcher(e){this.#t=e,this.#e!==null&&this.#c()}connectedCallback(){this.#i(`fetcher`);let e=this.shadowRoot??this.attachShadow({mode:`open`});e.adoptedStyleSheets=[Re()],this.#e??=(0,u.createRoot)(e),this.#c()}attributeChangedCallback(e,t,n){t!==n&&(e===`token`&&n!==null&&this.#o(!0),this.#e!==null&&this.#c())}#i(e){if(Object.prototype.hasOwnProperty.call(this,e)){let t=this,n=t[e];delete t[e],this[e]=n}}#a=Object.assign((e=3e3)=>{if(this.#r===null){let t,n=new Promise(e=>{t=e}),r=setTimeout(()=>this.#o(!1),e);this.#r={promise:n,resolve:t,timer:r}}return this.#r.promise},{pending:()=>this.#r!==null});#o(e){let t=this.#r;t!==null&&(this.#r=null,clearTimeout(t.timer),t.resolve(e))}#s(){return this.#t===void 0?Ie.some(e=>{let t=this.getAttribute(e);return t===null||t===``})?null:(this.#n??=Pe(this,this.#a),this.#n):this.#t}#c(){if(this.#e===null)return;let e=this.#s();if(e===null){this.#e.render(null),this.#u();return}this.#d();let t=this.getAttribute(`phone`),n=`${this.getAttribute(`phone-number-id`)??``}#${this.getAttribute(`api-url`)??``}#${t??``}`;this.#e.render((0,l.createElement)(je,{key:n,fetcher:e,initialPhone:t??void 0}))}#l=null;#u(){this.#d();let e=this.shadowRoot;if(e===null)return;let t=document.createElement(`div`);t.className=`wa-config-panel`;let n=document.createElement(`p`);n.className=`wa-config-panel__title`,n.textContent=`Visor de conversaciones — configuración incompleta`,t.appendChild(n);let r=document.createElement(`p`);r.className=`wa-config-panel__intro`,r.textContent=`Para montar el visor faltan estos atributos:`,t.appendChild(r);let i=document.createElement(`ul`);i.className=`wa-config-panel__list`;for(let e of Ie){let t=this.getAttribute(e);if(t!==null&&t!==``)continue;let n=document.createElement(`li`),r=document.createElement(`code`);r.textContent=e,n.appendChild(r),i.appendChild(n)}t.appendChild(i);let a=document.createElement(`p`);a.className=`wa-config-panel__hint`;let o=document.createElement(`code`);o.textContent=`@liftitapp/wa-conversations`;let s=document.createElement(`code`);s.textContent=`fetcher`,a.append(`Consulta el README de `,o,` — o asigna la property `,s,` desde JavaScript.`),t.appendChild(a),e.appendChild(t),this.#l=t}#d(){this.#l?.remove(),this.#l=null}disconnectedCallback(){queueMicrotask(()=>{this.isConnected||(this.#e?.unmount(),this.#e=null)})}}customElements.define(`wa-conversations`,e)}ze();
598
+ `;const Ie=[`phone-number-id`,`api-url`,`token`];let Le;function Re(){return Le||(Le=new CSSStyleSheet,Le.replaceSync(Fe)),Le}function ze(){if(typeof HTMLElement>`u`||typeof customElements>`u`||customElements.get(`wa-conversations`))return;class e extends HTMLElement{static observedAttributes=[...Ie,`phone`,`pinned`];#e=null;#t;#n;#r=null;get fetcher(){return this.#t}set fetcher(e){this.#t=e,this.#e!==null&&this.#c()}connectedCallback(){this.#i(`fetcher`);let e=this.shadowRoot??this.attachShadow({mode:`open`});e.adoptedStyleSheets=[Re()],this.#e??=(0,u.createRoot)(e),this.#c()}attributeChangedCallback(e,t,n){t!==n&&(e===`token`&&n!==null&&this.#o(!0),this.#e!==null&&this.#c())}#i(e){if(Object.prototype.hasOwnProperty.call(this,e)){let t=this,n=t[e];delete t[e],this[e]=n}}#a=Object.assign((e=3e3)=>{if(this.#r===null){let t,n=new Promise(e=>{t=e}),r=setTimeout(()=>this.#o(!1),e);this.#r={promise:n,resolve:t,timer:r}}return this.#r.promise},{pending:()=>this.#r!==null});#o(e){let t=this.#r;t!==null&&(this.#r=null,clearTimeout(t.timer),t.resolve(e))}#s(){return this.#t===void 0?Ie.some(e=>{let t=this.getAttribute(e);return t===null||t===``})?null:(this.#n??=Pe(this,this.#a),this.#n):this.#t}#c(){if(this.#e===null)return;let e=this.#s();if(e===null){this.#e.render(null),this.#u();return}this.#d();let t=this.getAttribute(`phone`),n=this.hasAttribute(`pinned`)&&this.getAttribute(`pinned`)!==`false`,r=`${this.getAttribute(`phone-number-id`)??``}#${this.getAttribute(`api-url`)??``}#${t??``}#${n}`;this.#e.render((0,l.createElement)(je,{key:r,fetcher:e,initialPhone:t??void 0,pinned:n}))}#l=null;#u(){this.#d();let e=this.shadowRoot;if(e===null)return;let t=document.createElement(`div`);t.className=`wa-config-panel`;let n=document.createElement(`p`);n.className=`wa-config-panel__title`,n.textContent=`Visor de conversaciones — configuración incompleta`,t.appendChild(n);let r=document.createElement(`p`);r.className=`wa-config-panel__intro`,r.textContent=`Para montar el visor faltan estos atributos:`,t.appendChild(r);let i=document.createElement(`ul`);i.className=`wa-config-panel__list`;for(let e of Ie){let t=this.getAttribute(e);if(t!==null&&t!==``)continue;let n=document.createElement(`li`),r=document.createElement(`code`);r.textContent=e,n.appendChild(r),i.appendChild(n)}t.appendChild(i);let a=document.createElement(`p`);a.className=`wa-config-panel__hint`;let o=document.createElement(`code`);o.textContent=`@liftitapp/wa-conversations`;let s=document.createElement(`code`);s.textContent=`fetcher`,a.append(`Consulta el README de `,o,` — o asigna la property `,s,` desde JavaScript.`),t.appendChild(a),e.appendChild(t),this.#l=t}#d(){this.#l?.remove(),this.#l=null}disconnectedCallback(){queueMicrotask(()=>{this.isConnected||(this.#e?.unmount(),this.#e=null)})}}customElements.define(`wa-conversations`,e)}ze();
@@ -236,10 +236,22 @@ interface WaConversationsProps {
236
236
  * cambia la key de render y remonta este shell con la preselección nueva (WC-03).
237
237
  */
238
238
  initialPhone?: string;
239
+ /**
240
+ * Ancla el visor a `initialPhone`: ni lista ni "Volver", en angosto y en ancho por igual.
241
+ *
242
+ * Es para el host que ya sabe de QUIÉN es la conversación y monta el visor dentro de su propio
243
+ * contexto — el drawer por fila de la tabla de Registro (DEV-4990). Ahí la lista no es una
244
+ * comodidad sino una fuga: ofrecería saltar a las conversaciones de OTRAS personas desde una
245
+ * fila que habla de una sola, y el "Volver" llevaría a una bandeja que ese drawer no promete.
246
+ *
247
+ * Sin `initialPhone` no hace nada (no hay nada que anclar): el visor arranca en la lista como
248
+ * siempre. No se convierte en un modo aparte — el mismo shell con una rama menos.
249
+ */
250
+ pinned?: boolean;
239
251
  /** Clase extra para el contenedor raíz. */
240
252
  className?: string;
241
253
  }
242
- declare function WaConversations({ fetcher, initialPhone, className }: WaConversationsProps): import("react").JSX.Element;
254
+ declare function WaConversations({ fetcher, initialPhone, pinned, className }: WaConversationsProps): import("react").JSX.Element;
243
255
  //#endregion
244
256
  //#region src/core/contract/thread.d.ts
245
257
  /**
@@ -1956,7 +1956,7 @@ const SHELL_CSS = `
1956
1956
  color: #616e7c;
1957
1957
  }
1958
1958
  `;
1959
- function WaConversations({ fetcher, initialPhone, className }) {
1959
+ function WaConversations({ fetcher, initialPhone, pinned = false, className }) {
1960
1960
  /**
1961
1961
  * El layout lo decide el ancho de ESTE contenedor, no el del viewport: el visor va embebido
1962
1962
  * (en lms-web-app vive dentro del layout del LMS, no a pantalla completa).
@@ -1974,20 +1974,21 @@ function WaConversations({ fetcher, initialPhone, className }) {
1974
1974
  className: rootClass,
1975
1975
  children: /* @__PURE__ */ jsx("p", { children: "Visor de conversaciones de WhatsApp — falta el fetcher del host." })
1976
1976
  });
1977
+ const anchored = pinned && selectedPhone !== null;
1977
1978
  return /* @__PURE__ */ jsxs("div", {
1978
1979
  ref: rootRef,
1979
1980
  className: rootClass,
1980
1981
  "data-layout": layout,
1981
1982
  children: [
1982
1983
  /* @__PURE__ */ jsx("style", { children: SHELL_CSS }),
1983
- (layout === "wide" || selectedPhone === null) && /* @__PURE__ */ jsx(ConversationList, {
1984
+ !anchored && (layout === "wide" || selectedPhone === null) && /* @__PURE__ */ jsx(ConversationList, {
1984
1985
  fetcher,
1985
1986
  selectedPhone,
1986
1987
  onSelect: (item) => setSelectedPhone(item.phone)
1987
1988
  }),
1988
1989
  selectedPhone !== null ? /* @__PURE__ */ jsxs("div", {
1989
1990
  className: "wa-conversations__thread",
1990
- children: [layout === "narrow" && /* @__PURE__ */ jsx("button", {
1991
+ children: [layout === "narrow" && !anchored && /* @__PURE__ */ jsx("button", {
1991
1992
  type: "button",
1992
1993
  className: "wa-conversations__back",
1993
1994
  onClick: () => setSelectedPhone(null),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liftitapp/wa-conversations",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Visor de conversaciones de WhatsApp del ecosistema Liftit: lista, hilo, media y composer.",
5
5
  "author": "Liftit",
6
6
  "license": "UNLICENSED",