zs3-ui-components 1.1.8 → 1.1.10
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.
Potentially problematic release.
This version of zs3-ui-components might be problematic. Click here for more details.
- package/README.md +152 -7
- package/dist/index.d.ts +2 -0
- package/dist/index.js +456 -301
- package/dist/zs3.d.ts +6 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
| | |
|
|
6
6
|
|------------|----------------------------------------------|
|
|
7
7
|
| **Paquet** | `zs3-ui-components` |
|
|
8
|
-
| **Versio** | 1.1.
|
|
8
|
+
| **Versio** | 1.1.9 |
|
|
9
9
|
| **Llicencia** | ISC |
|
|
10
10
|
| **Autor** | Manuel Candeal |
|
|
11
11
|
| **Repositori** | [github.com/manuelcandeal/zs3-ui-components](https://github.com/manuelcandeal/zs3-ui-components) |
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
- [$Debug (debug)](#debug-debug)
|
|
24
24
|
- [$Storage (storage)](#storage-storage)
|
|
25
25
|
- [$Store](#store)
|
|
26
|
+
- [HttpClient](#httpclient)
|
|
26
27
|
- [Sistema de Temes (ThemeManager)](#sistema-de-temes-thememanager)
|
|
27
28
|
- [CSS Variables](#css-variables)
|
|
28
29
|
- [Internacionalitzacio ($I18n)](#internacionalitzacio-i18n)
|
|
@@ -166,19 +167,23 @@ La classe `ZS3` proporciona una API similar a jQuery per a la manipulacio d'elem
|
|
|
166
167
|
```typescript
|
|
167
168
|
// Seleccionar elements amb la funcio $
|
|
168
169
|
const element = $('selector') // Retorna ZS3 | null (cerca des de document)
|
|
169
|
-
const element = $('selector', rootEl) // Cerca dins d'un HTMLElement
|
|
170
|
+
const element = $('selector', rootEl) // Cerca dins d'un HTMLElement, Document o ShadowRoot
|
|
170
171
|
const element = new ZS3('selector') // Constructor directe (cerca des de document)
|
|
171
|
-
const element = new ZS3('selector', rootEl) // Constructor amb element arrel
|
|
172
|
+
const element = new ZS3('selector', rootEl) // Constructor amb element arrel (HTMLElement, Document o ShadowRoot)
|
|
172
173
|
|
|
173
174
|
// Crear ZS3 des d'un HTMLElement
|
|
174
175
|
const zs3 = ZS3.fromElement(htmlElement)
|
|
175
176
|
```
|
|
176
177
|
|
|
177
|
-
El segon parametre (`root`) es opcional i per defecte es `document`.
|
|
178
|
+
El segon parametre (`root`) es opcional i per defecte es `document`. Accepta `Document`, `HTMLElement` o `ShadowRoot`, la qual cosa permet limitar la cerca a un subarbre del DOM concret, incloent shadow roots de Web Components:
|
|
178
179
|
|
|
179
180
|
```typescript
|
|
180
181
|
const container = document.getElementById('app')
|
|
181
182
|
const buttons = $('button', container) // Nomes els botons dins de #app
|
|
183
|
+
|
|
184
|
+
// Dins d'un Web Component (shadow DOM)
|
|
185
|
+
const btn = $('button', this.root) // this.root pot ser ShadowRoot o HTMLElement
|
|
186
|
+
btn?.addEvent('click', handler)
|
|
182
187
|
```
|
|
183
188
|
|
|
184
189
|
### Propietats
|
|
@@ -375,8 +380,8 @@ El mateix parell `selector:eventType` pot estar actiu en múltiples roots simult
|
|
|
375
380
|
|
|
376
381
|
| Metode | Signatura | Descripcio |
|
|
377
382
|
|--------|-----------|------------|
|
|
378
|
-
| `start()` | `(selector: string, eventType: keyof HTMLElementEventMap, root?: Document \| HTMLElement) => void` | Inicia el debug. Es poden registrar múltiples roots per al mateix selector+event. |
|
|
379
|
-
| `stop()` | `(selector: string, eventType: keyof HTMLElementEventMap, root?: Document \| HTMLElement) => void` | Atura el debug per al root indicat. Si hi ha més roots actius per al mateix selector+event, els altres continuen. |
|
|
383
|
+
| `start()` | `(selector: string, eventType: keyof HTMLElementEventMap, root?: Document \| HTMLElement \| ShadowRoot) => void` | Inicia el debug. Es poden registrar múltiples roots per al mateix selector+event. |
|
|
384
|
+
| `stop()` | `(selector: string, eventType: keyof HTMLElementEventMap, root?: Document \| HTMLElement \| ShadowRoot) => void` | Atura el debug per al root indicat. Si hi ha més roots actius per al mateix selector+event, els altres continuen. |
|
|
380
385
|
| `stopAll()` | `() => void` | Atura tot el debugging, per a tots els selectors, events i roots actius. |
|
|
381
386
|
| `list()` | `() => string[]` | Llista tots els debugs actius en format `selector:eventType`. Si hi ha múltiples roots per al mateix parell, apareix una entrada per cada root. |
|
|
382
387
|
|
|
@@ -585,6 +590,146 @@ store.subscribe('*', (state) => {
|
|
|
585
590
|
|
|
586
591
|
---
|
|
587
592
|
|
|
593
|
+
## HttpClient
|
|
594
|
+
|
|
595
|
+
Client HTTP basat en `fetch` amb suport per a interceptors, reintentos automàtics i timeout. Cada instància té la seva pròpia configuració, per la qual cosa no s'exposa com a singleton global.
|
|
596
|
+
|
|
597
|
+
```typescript
|
|
598
|
+
import { HttpClient, HttpError } from 'zs3-ui-components'
|
|
599
|
+
import type { HttpClientConfig, HttpResponse } from 'zs3-ui-components'
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
### Configuració
|
|
603
|
+
|
|
604
|
+
```typescript
|
|
605
|
+
const api = new HttpClient({
|
|
606
|
+
baseUrl: 'https://api.exemple.com', // Base de totes les URLs relatives
|
|
607
|
+
timeout: 10_000, // ms abans de cancel·lar (per defecte 10000)
|
|
608
|
+
retries: 2, // Reintentos automàtics en errors 5xx/timeout
|
|
609
|
+
retryDelay: 1_000, // ms entre reintent (es duplica cada vegada)
|
|
610
|
+
headers: { // Capçaleres per defecte (Content-Type i Accept: application/json ja inclosos)
|
|
611
|
+
Authorization: 'Bearer token',
|
|
612
|
+
},
|
|
613
|
+
})
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
### Metodes
|
|
617
|
+
|
|
618
|
+
| Metode | Signatura | Descripcio |
|
|
619
|
+
|--------|-----------|------------|
|
|
620
|
+
| `get()` | `<T>(url: string, params?: Record<string, string>) => Promise<HttpResponse<T>>` | Peticio GET. Els `params` s'afegeixen com a query string. |
|
|
621
|
+
| `post()` | `<T>(url: string, body?: unknown) => Promise<HttpResponse<T>>` | Peticio POST amb body JSON. |
|
|
622
|
+
| `put()` | `<T>(url: string, body?: unknown) => Promise<HttpResponse<T>>` | Peticio PUT. |
|
|
623
|
+
| `patch()` | `<T>(url: string, body?: unknown) => Promise<HttpResponse<T>>` | Peticio PATCH. |
|
|
624
|
+
| `delete()` | `<T>(url: string) => Promise<HttpResponse<T>>` | Peticio DELETE. |
|
|
625
|
+
| `request()` | `<T>(config: HttpRequestConfig) => Promise<HttpResponse<T>>` | Peticio completament configurable. |
|
|
626
|
+
|
|
627
|
+
### Resposta
|
|
628
|
+
|
|
629
|
+
Tots els metodes retornen `Promise<HttpResponse<T>>`:
|
|
630
|
+
|
|
631
|
+
```typescript
|
|
632
|
+
interface HttpResponse<T> {
|
|
633
|
+
data: T // Cos de la resposta (parseig JSON automatic)
|
|
634
|
+
status: number
|
|
635
|
+
statusText: string
|
|
636
|
+
headers: Headers
|
|
637
|
+
config: HttpRequestConfig
|
|
638
|
+
}
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
### Interceptors
|
|
642
|
+
|
|
643
|
+
Els interceptors permeten modificar totes les peticions o respostes de forma centralitzada. Retornen una funció per cancel·lar-los.
|
|
644
|
+
|
|
645
|
+
```typescript
|
|
646
|
+
// Interceptor de peticio: afegir token a totes les crides
|
|
647
|
+
const removeAuth = api.onRequest(config => ({
|
|
648
|
+
...config,
|
|
649
|
+
headers: { ...config.headers, Authorization: `Bearer ${getToken()}` },
|
|
650
|
+
}))
|
|
651
|
+
|
|
652
|
+
// Interceptor de resposta: transformar dades
|
|
653
|
+
api.onResponse(response => ({
|
|
654
|
+
...response,
|
|
655
|
+
data: transform(response.data),
|
|
656
|
+
}))
|
|
657
|
+
|
|
658
|
+
// Interceptor d'error: gestio centralitzada
|
|
659
|
+
api.onError(async error => {
|
|
660
|
+
if (error.isUnauthorized) {
|
|
661
|
+
await refreshToken()
|
|
662
|
+
// Si es retorna un HttpResponse, la peticio es considera recuperada
|
|
663
|
+
}
|
|
664
|
+
throw error // Si es relanca, l'error arriba al catch del cridant
|
|
665
|
+
})
|
|
666
|
+
|
|
667
|
+
// Cancel·lar un interceptor
|
|
668
|
+
removeAuth()
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
### Gestio d'errors
|
|
672
|
+
|
|
673
|
+
Els errors HTTP (4xx, 5xx) i de xarxa es llancen com a `HttpError`:
|
|
674
|
+
|
|
675
|
+
```typescript
|
|
676
|
+
try {
|
|
677
|
+
const { data } = await api.get<Post[]>('/posts')
|
|
678
|
+
} catch (error) {
|
|
679
|
+
if (error instanceof HttpError) {
|
|
680
|
+
console.log(error.status) // 404, 500...
|
|
681
|
+
console.log(error.isNotFound) // true si 404
|
|
682
|
+
console.log(error.isUnauthorized) // true si 401
|
|
683
|
+
console.log(error.isServerError) // true si 5xx
|
|
684
|
+
console.log(error.isTimeout) // true si timeout
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
### Exemple complet
|
|
690
|
+
|
|
691
|
+
```typescript
|
|
692
|
+
import { HttpClient, HttpError } from 'zs3-ui-components'
|
|
693
|
+
import { $ } from 'zs3-ui-components'
|
|
694
|
+
|
|
695
|
+
interface Post { id: number; title: string; body: string }
|
|
696
|
+
|
|
697
|
+
const api = new HttpClient({
|
|
698
|
+
baseUrl: 'https://jsonplaceholder.typicode.com',
|
|
699
|
+
timeout: 8_000,
|
|
700
|
+
retries: 1,
|
|
701
|
+
})
|
|
702
|
+
|
|
703
|
+
// GET amb parametres de query
|
|
704
|
+
const { data: posts } = await api.get<Post[]>('/posts', { _limit: '5' })
|
|
705
|
+
|
|
706
|
+
// POST
|
|
707
|
+
const { data: nou, status } = await api.post<Post>('/posts', {
|
|
708
|
+
title: 'Nou post',
|
|
709
|
+
body: 'Contingut',
|
|
710
|
+
userId: 1,
|
|
711
|
+
})
|
|
712
|
+
|
|
713
|
+
// PATCH (modificacio parcial)
|
|
714
|
+
await api.patch(`/posts/${nou.id}`, { title: 'Titol modificat' })
|
|
715
|
+
|
|
716
|
+
// DELETE
|
|
717
|
+
await api.delete(`/posts/${nou.id}`)
|
|
718
|
+
|
|
719
|
+
// Integrat amb ZS3
|
|
720
|
+
$('#btn-load')?.addEvent('click', async () => {
|
|
721
|
+
try {
|
|
722
|
+
const { data } = await api.get<Post[]>('/posts', { _limit: '3' })
|
|
723
|
+
const html = data.map(p => `<li>${p.title}</li>`).join('')
|
|
724
|
+
$('ul#llista')?.html(html)
|
|
725
|
+
} catch (e) {
|
|
726
|
+
if (e instanceof HttpError) $('p#error')?.html(`Error ${e.status}`)
|
|
727
|
+
}
|
|
728
|
+
})
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
---
|
|
732
|
+
|
|
588
733
|
## Sistema de Temes (ThemeManager)
|
|
589
734
|
|
|
590
735
|
El sistema de temes permet canviar l'aparenca visual de tota l'aplicacio.
|
|
@@ -1932,7 +2077,7 @@ ZS3 suporta handlers d'events inline directament als atributs HTML dels componen
|
|
|
1932
2077
|
|
|
1933
2078
|
| Variable | Tipus | Descripcio |
|
|
1934
2079
|
|----------|-------|------------|
|
|
1935
|
-
| `$` | `(selector: string, root?: Document \| HTMLElement) => ZS3 \| null` | Funcio de seleccio d'elements. El segon parametre opcional limita la cerca a un element arrel. |
|
|
2080
|
+
| `$` | `(selector: string, root?: Document \| HTMLElement \| ShadowRoot) => ZS3 \| null` | Funcio de seleccio d'elements. El segon parametre opcional limita la cerca a un element arrel. |
|
|
1936
2081
|
| `log` | `$Log` | Sistema de logging. |
|
|
1937
2082
|
| `debug` | `$Debug` | Utilitat de debugging. |
|
|
1938
2083
|
| `params` | `$Parameters` | Gestio de parametres d'URL. |
|
package/dist/index.d.ts
CHANGED
|
@@ -14,6 +14,8 @@ export { $I18n, i18n } from './i18n';
|
|
|
14
14
|
export type { I18nConfig } from './i18n';
|
|
15
15
|
export { defaultTranslations, DEFAULT_LOCALE, DEFAULT_FALLBACK_LOCALE, } from './i18n/defaults';
|
|
16
16
|
export type { FrameworkTranslations } from './i18n/defaults';
|
|
17
|
+
export { HttpClient, HttpError } from './http';
|
|
18
|
+
export type { HttpMethod, HttpRequestConfig, HttpResponse, HttpClientConfig, RequestInterceptor, ResponseInterceptor, ErrorInterceptor, } from './http';
|
|
17
19
|
export type { EventDescription } from './types';
|
|
18
20
|
export { $BaseComponent } from './components/zs3-BaseComponent';
|
|
19
21
|
export type { BaseComponentOptions, AttributeChangeCallback } from './components/zs3-BaseComponent';
|