@bereasoftware/time-guard 2.6.1 → 2.7.1

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.
Files changed (98) hide show
  1. package/README.en.md +232 -0
  2. package/README.md +259 -4
  3. package/dist/angular/index.cjs +148 -0
  4. package/dist/angular/index.d.ts +2 -0
  5. package/dist/angular/index.es.js +143 -0
  6. package/dist/angular.d.ts +59 -0
  7. package/dist/calendars/index.cjs +357 -2
  8. package/dist/calendars/index.es.js +99 -68
  9. package/dist/chunk-BbtWAPZS.cjs +36 -0
  10. package/dist/core-BFdo248T.cjs +1892 -0
  11. package/dist/core-CyBR5PPd.js +1809 -0
  12. package/dist/core.d.ts +224 -0
  13. package/dist/index.d.ts +9 -0
  14. package/dist/locales/african.locale.d.ts +7 -0
  15. package/dist/locales/index.cjs +7 -1
  16. package/dist/{types/locales → locales}/index.d.ts +2 -2
  17. package/dist/locales/index.es.js +3 -3
  18. package/dist/locales/south-american.locale.d.ts +7 -0
  19. package/dist/locales-B1mDDyn_.cjs +3537 -0
  20. package/dist/{locales-DSBvgSaw.js → locales-By7IK3Ep.js} +749 -33
  21. package/dist/native/index.cjs +48 -0
  22. package/dist/native/index.d.ts +2 -0
  23. package/dist/native/index.es.js +18 -0
  24. package/dist/native.d.ts +9 -0
  25. package/dist/plugins/advanced-format.cjs +105 -2
  26. package/dist/plugins/advanced-format.es.js +63 -45
  27. package/dist/plugins/duration.cjs +258 -2
  28. package/dist/plugins/duration.es.js +165 -61
  29. package/dist/plugins/relative-time.cjs +166 -2
  30. package/dist/plugins/relative-time.es.js +74 -37
  31. package/dist/qwik/index.cjs +104 -0
  32. package/dist/qwik/index.d.ts +2 -0
  33. package/dist/qwik/index.es.js +100 -0
  34. package/dist/qwik.d.ts +32 -0
  35. package/dist/react/index.cjs +112 -0
  36. package/dist/react/index.d.ts +2 -0
  37. package/dist/react/index.es.js +103 -0
  38. package/dist/react.d.ts +46 -0
  39. package/dist/solid/index.cjs +127 -0
  40. package/dist/solid/index.d.ts +2 -0
  41. package/dist/solid/index.es.js +122 -0
  42. package/dist/solid.d.ts +53 -0
  43. package/dist/svelte/index.cjs +398 -0
  44. package/dist/svelte/index.d.ts +2 -0
  45. package/dist/svelte/index.es.js +393 -0
  46. package/dist/svelte.d.ts +88 -0
  47. package/dist/time-guard.cjs +7359 -4
  48. package/dist/time-guard.es.js +3625 -8085
  49. package/dist/time-guard.iife.js +13549 -4
  50. package/dist/time-guard.umd.js +13550 -4
  51. package/dist/types/index.d.ts +651 -127
  52. package/dist/vue/index.cjs +143 -0
  53. package/dist/vue/index.d.ts +2 -0
  54. package/dist/vue/index.es.js +137 -0
  55. package/dist/vue.d.ts +35 -0
  56. package/package.json +107 -27
  57. package/dist/calendars/index.cjs.map +0 -1
  58. package/dist/calendars/index.es.js.map +0 -1
  59. package/dist/locales-DSBvgSaw.js.map +0 -1
  60. package/dist/locales-ybx7jS8G.cjs +0 -2
  61. package/dist/locales-ybx7jS8G.cjs.map +0 -1
  62. package/dist/plugins/advanced-format.cjs.map +0 -1
  63. package/dist/plugins/advanced-format.es.js.map +0 -1
  64. package/dist/plugins/duration.cjs.map +0 -1
  65. package/dist/plugins/duration.es.js.map +0 -1
  66. package/dist/plugins/relative-time.cjs.map +0 -1
  67. package/dist/plugins/relative-time.es.js.map +0 -1
  68. package/dist/time-guard.cjs.map +0 -1
  69. package/dist/time-guard.es.js.map +0 -1
  70. package/dist/time-guard.iife.js.map +0 -1
  71. package/dist/time-guard.umd.js.map +0 -1
  72. package/dist/types/types/index.d.ts +0 -641
  73. /package/dist/{types/adapters → adapters}/temporal.adapter.d.ts +0 -0
  74. /package/dist/{types/calendars → calendars}/calendar.manager.d.ts +0 -0
  75. /package/dist/{types/calendars → calendars}/index.d.ts +0 -0
  76. /package/dist/{types/formatters → formatters}/date.formatter.d.ts +0 -0
  77. /package/dist/{types/locales → locales}/additional.locale.d.ts +0 -0
  78. /package/dist/{types/locales → locales}/asian.locale.d.ts +0 -0
  79. /package/dist/{types/locales → locales}/english.locale.d.ts +0 -0
  80. /package/dist/{types/locales → locales}/european.locale.d.ts +0 -0
  81. /package/dist/{types/locales → locales}/locale.manager.d.ts +0 -0
  82. /package/dist/{types/locales → locales}/middle-eastern.locale.d.ts +0 -0
  83. /package/dist/{types/locales → locales}/nordic.locale.d.ts +0 -0
  84. /package/dist/{types/locales → locales}/romance.locale.d.ts +0 -0
  85. /package/dist/{types/locales → locales}/slavic.locale.d.ts +0 -0
  86. /package/dist/{types/locales → locales}/spanish.locale.d.ts +0 -0
  87. /package/dist/{types/plugins → plugins}/advanced-format/index.d.ts +0 -0
  88. /package/dist/{types/plugins → plugins}/advanced-format.d.ts +0 -0
  89. /package/dist/{types/plugins → plugins}/duration/index.d.ts +0 -0
  90. /package/dist/{types/plugins → plugins}/duration/types.d.ts +0 -0
  91. /package/dist/{types/plugins → plugins}/duration.d.ts +0 -0
  92. /package/dist/{types/plugins → plugins}/index.d.ts +0 -0
  93. /package/dist/{types/plugins → plugins}/manager.d.ts +0 -0
  94. /package/dist/{types/plugins → plugins}/relative-time/index.d.ts +0 -0
  95. /package/dist/{types/plugins → plugins}/relative-time/types.d.ts +0 -0
  96. /package/dist/{types/plugins → plugins}/relative-time.d.ts +0 -0
  97. /package/dist/{types/time-guard.d.ts → time-guard.d.ts} +0 -0
  98. /package/dist/{types/utils → utils}/duration-locale.d.ts +0 -0
package/README.en.md CHANGED
@@ -44,6 +44,7 @@ A modern, production-grade date/time manipulation library built with **TypeScrip
44
44
  - [Advanced Calculations](#advanced-calculations)
45
45
  - [Calendar Systems](#calendar-systems)
46
46
  - [Plugins](#plugins)
47
+ - [Framework Integrations](#framework-integrations)
47
48
  - [Documentation](#documentation)
48
49
  - [Supported Locales](#supported-locales)
49
50
  - [API Overview](#api-overview)
@@ -1442,6 +1443,237 @@ date.format('DD/MM/YYYY "at" HH:mm'); // 13/03/2024 at 14:30
1442
1443
 
1443
1444
  ---
1444
1445
 
1446
+ ## 🔌 Framework Integrations
1447
+ <a id="framework-integrations"></a>
1448
+
1449
+ TimeGuard includes high-performance, native integrations for **React**, **Vue**, and **Angular** packaged under specific subpath exports. These integrations are built following SOLID principles and optimized to prevent memory leaks and unnecessary change detection/rendering cycles.
1450
+
1451
+ ### 📦 Installing Optional Peer Dependencies
1452
+
1453
+ Since framework integrations are optional, ensure you have the respective framework packages installed in your project:
1454
+
1455
+ ```bash
1456
+ # For React
1457
+ npm install react react-dom
1458
+
1459
+ # For Vue
1460
+ npm install vue
1461
+
1462
+ # For Angular
1463
+ npm install @angular/core rxjs
1464
+ ```
1465
+
1466
+ ---
1467
+
1468
+ ### ⚛️ React (`@bereasoftware/time-guard/react`)
1469
+
1470
+ The React integration exposes custom reactive hooks backed by a global context configuration provider.
1471
+
1472
+ #### 1. Global Context: `TimeGuardProvider`
1473
+ Provides a default configuration (such as locale or timezone) down the React component tree.
1474
+
1475
+ ```tsx
1476
+ import React from 'react';
1477
+ import { TimeGuardProvider } from '@bereasoftware/time-guard/react';
1478
+
1479
+ export function App() {
1480
+ return (
1481
+ <TimeGuardProvider config={{ locale: 'en', timezone: 'America/New_York' }}>
1482
+ <MyComponent />
1483
+ </TimeGuardProvider>
1484
+ );
1485
+ }
1486
+ ```
1487
+
1488
+ #### 2. Reactive Hooks
1489
+
1490
+ * **`useTimeGuard(input, config?)`**:
1491
+ Creates a reactive `TimeGuard` instance that automatically updates when input or configuration changes. Inherits configuration from the global context provider as a fallback.
1492
+ ```tsx
1493
+ import { useTimeGuard } from '@bereasoftware/time-guard/react';
1494
+
1495
+ function DateDisplay({ dateString }) {
1496
+ const tg = useTimeGuard(dateString);
1497
+ return <p>Date: {tg.format('LL')}</p>;
1498
+ }
1499
+ ```
1500
+
1501
+ * **`useCurrentTime(options?)`**:
1502
+ Returns a reactive `TimeGuard` representing the current time, ticking automatically at the specified interval (defaults to `1000ms`).
1503
+ ```tsx
1504
+ import { useCurrentTime } from '@bereasoftware/time-guard/react';
1505
+
1506
+ function LiveClock() {
1507
+ const now = useCurrentTime({ interval: 1000 });
1508
+ return <h2>Current Time: {now.format('HH:mm:ss')}</h2>;
1509
+ }
1510
+ ```
1511
+
1512
+ * **`useRelativeTime(date, options?)`**:
1513
+ Returns a dynamic relative time string (e.g. *"5 minutes ago"*) that is periodically updated at a regular interval (defaults to `60000ms`).
1514
+ ```tsx
1515
+ import { useRelativeTime } from '@bereasoftware/time-guard/react';
1516
+
1517
+ function CommentTime({ createdAt }) {
1518
+ const relative = useRelativeTime(createdAt, { interval: 30000 }); // updates every 30s
1519
+ return <span>Published {relative}</span>;
1520
+ }
1521
+ ```
1522
+
1523
+ * **`useTimeRange(start, end, config?)`**:
1524
+ Creates and manages a reactive `TimeRange` instance that updates when start, end, or configuration options change.
1525
+ ```tsx
1526
+ import { useTimeRange } from '@bereasoftware/time-guard/react';
1527
+
1528
+ function EventRange({ start, end }) {
1529
+ const range = useTimeRange(start, end);
1530
+ return (
1531
+ <div>
1532
+ <p>Total duration: {range.duration().humanize()}</p>
1533
+ <p>Is happening now?: {range.contains('now') ? 'Yes' : 'No'}</p>
1534
+ </div>
1535
+ );
1536
+ }
1537
+ ```
1538
+
1539
+ ---
1540
+
1541
+ ### 🟢 Vue (`@bereasoftware/time-guard/vue`)
1542
+
1543
+ The Vue integration supports Vue 3 Composition API composables, a global setup plugin, and a custom directive.
1544
+
1545
+ #### 1. Registering the Plugin: `TimeGuardVuePlugin`
1546
+ Registers the `v-time-guard` directive globally and configures defaults via `provide`/`inject`.
1547
+
1548
+ ```typescript
1549
+ import { createApp } from 'vue';
1550
+ import { TimeGuardVuePlugin } from '@bereasoftware/time-guard/vue';
1551
+ import App from './App.vue';
1552
+
1553
+ const app = createApp(App);
1554
+
1555
+ // Register plugin with default options
1556
+ app.use(TimeGuardVuePlugin, {
1557
+ locale: 'en',
1558
+ });
1559
+
1560
+ app.mount('#app');
1561
+ ```
1562
+
1563
+ #### 2. Custom Directive: `v-time-guard`
1564
+ A declarative and highly reactive directive for rendering formatted or relative dates directly in templates. Automatically cleans up polling intervals to prevent memory leaks when components unmount.
1565
+
1566
+ ```html
1567
+ <!-- Standard formatting -->
1568
+ <span v-time-guard:format="date" data-pattern="DD MMMM YYYY"></span>
1569
+
1570
+ <!-- Live relative time (recalculates every minute by default) -->
1571
+ <span v-time-guard:relative="date"></span>
1572
+
1573
+ <!-- Real-time clock (updates every second) -->
1574
+ <span v-time-guard:format="'now'" data-pattern="HH:mm:ss" data-live="true" data-interval="1000"></span>
1575
+ ```
1576
+
1577
+ #### 3. Composition API Composables
1578
+ * **`useTimeGuard(input, config?)`**: Returns a reactive `Ref<TimeGuard>`.
1579
+ * **`useCurrentTime(options?)`**: Returns a reactive `Ref<TimeGuard>` of the current time, with automatic interval cleanup on unmount.
1580
+ * **`useRelativeTime(date, options?)`**: Returns a reactive `Ref<string>` containing the relative time representation, with built-in deep watching.
1581
+
1582
+ ```html
1583
+ <script setup>
1584
+ import { useCurrentTime, useRelativeTime } from '@bereasoftware/time-guard/vue';
1585
+
1586
+ const now = useCurrentTime({ interval: 1000 });
1587
+ const relative = useRelativeTime('2026-05-20T08:00:00');
1588
+ </script>
1589
+
1590
+ <template>
1591
+ <div>
1592
+ <p>Current Time: {{ now.format('HH:mm:ss') }}</p>
1593
+ <p>Published: {{ relative }}</p>
1594
+ </div>
1595
+ </template>
1596
+ ```
1597
+
1598
+ ---
1599
+
1600
+ ### 🅰️ Angular (`@bereasoftware/time-guard/angular`)
1601
+
1602
+ The Angular integration is optimized for highly reactive Change Detection strategies (like `OnPush`). It provides dependency-injectable services and pure/impure pipes that run polling intervals outside Angular's Zone to maximize rendering performance.
1603
+
1604
+ #### 1. Global Setup Injection Token: `TIME_GUARD_CONFIG`
1605
+ Registers a global configuration at module or root level.
1606
+
1607
+ ```typescript
1608
+ import { NgModule } from '@angular/core';
1609
+ import { TIME_GUARD_CONFIG } from '@bereasoftware/time-guard/angular';
1610
+
1611
+ @NgModule({
1612
+ providers: [
1613
+ {
1614
+ provide: TIME_GUARD_CONFIG,
1615
+ useValue: { locale: 'en' }
1616
+ }
1617
+ ]
1618
+ })
1619
+ export class AppModule {}
1620
+ ```
1621
+
1622
+ #### 2. Provided Pipes
1623
+
1624
+ * **`TimeGuardFormatPipe` (`timeGuardFormat`)**:
1625
+ A pure pipe designed for lightning-fast date-time formatting in templates.
1626
+ ```html
1627
+ <p>{{ createdDate | timeGuardFormat:'DD/MM/YYYY' }}</p>
1628
+ ```
1629
+
1630
+ * **`TimeGuardRelativePipe` (`timeGuardRelative`)**:
1631
+ An impure pipe for showing humanized relative time representations.
1632
+ ```html
1633
+ <p>Published {{ createdDate | timeGuardRelative }}</p>
1634
+ ```
1635
+
1636
+ * **`TimeGuardLiveFormatPipe` (`timeGuardLiveFormat`)**:
1637
+ An optimized impure pipe utilizing `ChangeDetectorRef` to update live ticking clocks or dates without re-evaluating the entire component tree.
1638
+ ```html
1639
+ <!-- Real-time clock updating every second -->
1640
+ <h2>Current Time: {{ 'now' | timeGuardLiveFormat:'HH:mm:ss':1000 }}</h2>
1641
+
1642
+ <!-- Dynamic format updater for static date -->
1643
+ <p>Last update: {{ updateDate | timeGuardLiveFormat:'YYYY-MM-DD HH:mm:ss':5000 }}</p>
1644
+ ```
1645
+
1646
+ #### 3. Reactive Observable Service: `TimeGuardService`
1647
+ Exposes an injectable service featuring RxJS streams.
1648
+ `getCurrentTime()` returns an observable current time. Crucially, the polling ticks run **outside Angular's zone** (`runOutsideAngular`) and only re-enter Angular's zone (`NgZone.run`) when emitting values, reducing change detection churn and CPU usage in large-scale applications.
1649
+
1650
+ ```typescript
1651
+ import { Component, OnInit } from '@angular/core';
1652
+ import { TimeGuardService } from '@bereasoftware/time-guard/angular';
1653
+ import { Observable } from 'rxjs';
1654
+ import { TimeGuard } from '@bereasoftware/time-guard';
1655
+
1656
+ @Component({
1657
+ selector: 'app-clock',
1658
+ template: `
1659
+ <div *ngIf="time$ | async as time">
1660
+ Time: {{ time.format('HH:mm:ss') }}
1661
+ </div>
1662
+ `
1663
+ })
1664
+ export class ClockComponent implements OnInit {
1665
+ time$!: Observable<TimeGuard>;
1666
+
1667
+ constructor(private timeGuardService: TimeGuardService) {}
1668
+
1669
+ ngOnInit() {
1670
+ this.time$ = this.timeGuardService.getCurrentTime(1000);
1671
+ }
1672
+ }
1673
+ ```
1674
+
1675
+ ---
1676
+
1445
1677
  ## 🧪 Testing
1446
1678
 
1447
1679
  TimeGuard includes **530+ comprehensive tests** covering:
package/README.md CHANGED
@@ -1,11 +1,20 @@
1
- # TimeGuard 🕐
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/Berea-Soft/time-guard/refs/heads/main/src/assets/logo.png" alt="Time Guard Logo" />
3
+ <h1 align="center">Time Guard</h1>
4
+ <p align="center">
5
+ Una biblioteca moderna y de nivel producción para manipulación de fechas/horas construida con <strong>TypeScript</strong>, <strong>Temporal API</strong> y <strong>SOLID principles</strong>. TimeGuard aprovecha los estándares de JavaScript modernos y las mejores prácticas.
6
+ </p>
7
+ </p>
8
+ <br/>
9
+ <br/>
2
10
 
3
11
  > 📚 **Documentación disponible en otros idiomas:**
4
12
  >
5
13
  > - 🇪🇸 **Español** (este archivo - README.md)
6
14
  > - 🇬🇧 [English](README.en.md)
7
15
 
8
- Una biblioteca moderna y de nivel producción para manipulación de fechas/horas construida con **TypeScript**, **Temporal API** y **SOLID principles**. TimeGuard aprovecha los estándares de JavaScript modernos y las mejores prácticas.
16
+ <br/>
17
+ <br/>
9
18
 
10
19
  [![Pruebas](https://img.shields.io/badge/Pruebas-530%2B-green?style=for-the-badge)](#testing)
11
20
  [![Locales](https://img.shields.io/badge/Locales-40%2B-orange?style=for-the-badge)](#locales-soportadas)
@@ -49,6 +58,7 @@ Una biblioteca moderna y de nivel producción para manipulación de fechas/horas
49
58
  - [Cálculos Avanzados](#cálculos-avanzados)
50
59
  - [Sistemas de Calendario](#sistemas-de-calendario)
51
60
  - [Plugins](#plugins)
61
+ - [Integración con Frameworks](#integración-con-frameworks)
52
62
  - [Documentación](#documentación)
53
63
  - [Locales Soportadas](#locales-soportadas)
54
64
  - [Referencia API](#referencia-api)
@@ -60,6 +70,7 @@ Una biblioteca moderna y de nivel producción para manipulación de fechas/horas
60
70
  ---
61
71
 
62
72
  ## 🚀 Inicio Rápido
73
+ <a id="inicio-rápido"></a><a id="inicio-rapido"></a>
63
74
 
64
75
  ```typescript
65
76
  import { TimeGuard } from '@bereasoftware/time-guard';
@@ -94,6 +105,7 @@ console.log(date.isAfter(new Date('2020-01-01'))); // true
94
105
  ---
95
106
 
96
107
  ## 📦 Instalación
108
+ <a id="instalación"></a><a id="instalacion"></a>
97
109
 
98
110
  ```bash
99
111
  npm install @bereasoftware/time-guard
@@ -154,6 +166,7 @@ import advancedFormatPlugin from '@bereasoftware/time-guard/plugins/advanced-for
154
166
  ---
155
167
 
156
168
  ## 🏗️ Conceptos Clave
169
+ <a id="conceptos-clave"></a>
157
170
 
158
171
  ### 1. Inmutabilidad
159
172
 
@@ -223,6 +236,7 @@ date.format('MM/DD/YYYY');
223
236
  ---
224
237
 
225
238
  ## 🎯 Accesores de Componentes
239
+ <a id="accesores-de-componentes"></a>
226
240
 
227
241
  Acceso rápido a componentes individuales de la fecha:
228
242
 
@@ -252,6 +266,7 @@ console.log(date.inLeapYear()); // true
252
266
  ---
253
267
 
254
268
  ## ⏱️ Cálculos Avanzados
269
+ <a id="cálculos-avanzados"></a><a id="calculos-avanzados"></a>
255
270
 
256
271
  ### 🎯 API Semántica: `between()` - Sin Carga Mental
257
272
 
@@ -586,6 +601,7 @@ date.round({
586
601
  ---
587
602
 
588
603
  ## 📅 Sistemas de Calendario
604
+ <a id="sistemas-de-calendario"></a>
589
605
 
590
606
  TimeGuard incluye soporte para múltiples sistemas de calendario, extensible a través del gestor de calendarios:
591
607
 
@@ -682,7 +698,8 @@ console.log(calendar.isLeapYear(2567)); // true
682
698
 
683
699
  ---
684
700
 
685
- ## � Plugins
701
+ <a id="plugins"></a>
702
+ ## 🔌 Plugins
686
703
 
687
704
  TimeGuard incluye un sistema de plugins opcional para funcionalidad extendida:
688
705
 
@@ -725,7 +742,8 @@ TimeGuard incluye un sistema de plugins opcional para funcionalidad extendida:
725
742
 
726
743
  ---
727
744
 
728
- ## �📚 Documentation
745
+ <a id="documentación"></a><a id="documentacion"></a>
746
+ ## 📚 Documentación
729
747
 
730
748
  ### Archivos de Documentación Principal
731
749
 
@@ -745,6 +763,7 @@ TimeGuard incluye un sistema de plugins opcional para funcionalidad extendida:
745
763
  - **Arquitectura** → Ver [ARCHITECTURE.md](ARCHITECTURE.md)
746
764
 
747
765
  ## 🌍 Locales Soportadas
766
+ <a id="locales-soportadas"></a>
748
767
 
749
768
  TimeGuard proporciona **más de 40 idiomas y variantes regionales** con soporte completo de internacionalización. Los locales se organizan por familia de idiomas para facilitar el descubrimiento.
750
769
 
@@ -1242,6 +1261,7 @@ date.myMethod(); // "Hello from my plugin!"
1242
1261
  ---
1243
1262
 
1244
1263
  ## 🎯 Referencia API
1264
+ <a id="referencia-api"></a>
1245
1265
 
1246
1266
  ### Factory Methods
1247
1267
 
@@ -1626,7 +1646,239 @@ exactDiff.toString(); // "432000000" (milliseconds)
1626
1646
 
1627
1647
  ---
1628
1648
 
1649
+ ## 🔌 Integración con Frameworks
1650
+ <a id="integración-con-frameworks"></a><a id="integracion-con-frameworks"></a>
1651
+
1652
+ TimeGuard incluye integraciones nativas y optimizadas de alto rendimiento para **React**, **Vue** y **Angular** a través de subrutas específicas. Estas integraciones están diseñadas bajo los principios SOLID, con mitigación de fugas de memoria y optimizaciones de ciclo de renderizado.
1653
+
1654
+ ### 📦 Instalación de Dependencias Opcionales
1655
+
1656
+ Dado que las integraciones con frameworks son opcionales, debes asegurarte de tener instaladas las dependencias del framework correspondiente en tu proyecto.
1657
+
1658
+ ```bash
1659
+ # Para React
1660
+ npm install react react-dom
1661
+
1662
+ # Para Vue
1663
+ npm install vue
1664
+
1665
+ # Para Angular
1666
+ npm install @angular/core rxjs
1667
+ ```
1668
+
1669
+ ---
1670
+
1671
+ ### ⚛️ React (`@bereasoftware/time-guard/react`)
1672
+
1673
+ La integración con React proporciona un sistema de contexto global para la configuración y hooks reactivos de alta fidelidad.
1674
+
1675
+ #### 1. Contexto Global: `TimeGuardProvider`
1676
+ Permite propagar una configuración predeterminada (como el idioma o zona horaria) a todos los hooks dentro del árbol de componentes.
1677
+
1678
+ ```tsx
1679
+ import React from 'react';
1680
+ import { TimeGuardProvider } from '@bereasoftware/time-guard/react';
1681
+
1682
+ export function App() {
1683
+ return (
1684
+ <TimeGuardProvider config={{ locale: 'es', timezone: 'America/Mexico_City' }}>
1685
+ <MyComponent />
1686
+ </TimeGuardProvider>
1687
+ );
1688
+ }
1689
+ ```
1690
+
1691
+ #### 2. Hooks Reactivos
1692
+
1693
+ * **`useTimeGuard(input, config?)`**:
1694
+ Crea una instancia reactiva de `TimeGuard` que se actualiza automáticamente cuando el valor de entrada o la configuración cambian. Hereda la configuración del contexto de forma transparente.
1695
+ ```tsx
1696
+ import { useTimeGuard } from '@bereasoftware/time-guard/react';
1697
+
1698
+ function DateDisplay({ dateString }) {
1699
+ const tg = useTimeGuard(dateString);
1700
+ return <p>Fecha: {tg.format('LL')}</p>;
1701
+ }
1702
+ ```
1703
+
1704
+ * **`useCurrentTime(options?)`**:
1705
+ Retorna una instancia reactiva del tiempo actual que se actualiza automáticamente según el intervalo indicado (por defecto `1000ms`).
1706
+ ```tsx
1707
+ import { useCurrentTime } from '@bereasoftware/time-guard/react';
1708
+
1709
+ function LiveClock() {
1710
+ const now = useCurrentTime({ interval: 1000 });
1711
+ return <h2>Hora actual: {now.format('HH:mm:ss')}</h2>;
1712
+ }
1713
+ ```
1714
+
1715
+ * **`useRelativeTime(date, options?)`**:
1716
+ Retorna un string dinámico de tiempo relativo (ej. *"hace 5 minutos"*) que se recalcula de forma periódica e inalterable en intervalos regulares (por defecto cada `60000ms`).
1717
+ ```tsx
1718
+ import { useRelativeTime } from '@bereasoftware/time-guard/react';
1719
+
1720
+ function CommentTime({ createdAt }) {
1721
+ const relative = useRelativeTime(createdAt, { interval: 30000 }); // actualiza cada 30s
1722
+ return <span>Publicado {relative}</span>;
1723
+ }
1724
+ ```
1725
+
1726
+ * **`useTimeRange(start, end, config?)`**:
1727
+ Crea y gestiona una instancia reactiva de `TimeRange` que responde a cambios en los límites de inicio y fin.
1728
+ ```tsx
1729
+ import { useTimeRange } from '@bereasoftware/time-guard/react';
1730
+
1731
+ function EventRange({ start, end }) {
1732
+ const range = useTimeRange(start, end);
1733
+ return (
1734
+ <div>
1735
+ <p>Duración total: {range.duration().humanize()}</p>
1736
+ <p>¿Está ocurriendo ahora?: {range.contains('now') ? 'Sí' : 'No'}</p>
1737
+ </div>
1738
+ );
1739
+ }
1740
+ ```
1741
+
1742
+ ---
1743
+
1744
+ ### 🟢 Vue (`@bereasoftware/time-guard/vue`)
1745
+
1746
+ La integración con Vue 3 ofrece compatibilidad completa con la Composition API, un Plugin global y una directiva personalizada reactiva altamente configurable.
1747
+
1748
+ #### 1. Registro del Plugin: `TimeGuardVuePlugin`
1749
+ Registra la directiva `v-time-guard` de forma global y provee la configuración por defecto mediante `provide`/`inject`.
1750
+
1751
+ ```typescript
1752
+ import { createApp } from 'vue';
1753
+ import { TimeGuardVuePlugin } from '@bereasoftware/time-guard/vue';
1754
+ import App from './App.vue';
1755
+
1756
+ const app = createApp(App);
1757
+
1758
+ // Registrar plugin con opciones por defecto
1759
+ app.use(TimeGuardVuePlugin, {
1760
+ locale: 'es',
1761
+ });
1762
+
1763
+ app.mount('#app');
1764
+ ```
1765
+
1766
+ #### 2. Directiva Reactiva Dinámica: `v-time-guard`
1767
+ Permite formatear y mostrar fechas reactivamente de forma declarativa directamente en las plantillas. Soporta intervalos de actualización automática para evitar fugas de memoria al desmontar el elemento.
1768
+
1769
+ ```html
1770
+ <!-- Formateo estándar -->
1771
+ <span v-time-guard:format="fecha" data-pattern="DD MMMM YYYY"></span>
1772
+
1773
+ <!-- Tiempo relativo automático (actualiza cada minuto por defecto) -->
1774
+ <span v-time-guard:relative="fecha"></span>
1775
+
1776
+ <!-- Reloj en tiempo real (actualización cada segundo) -->
1777
+ <span v-time-guard:format="'now'" data-pattern="HH:mm:ss" data-live="true" data-interval="1000"></span>
1778
+ ```
1779
+
1780
+ #### 3. Composables de la Composition API
1781
+ * **`useTimeGuard(input, config?)`**: Retorna una `Ref<TimeGuard>` reactiva.
1782
+ * **`useCurrentTime(options?)`**: Retorna una `Ref<TimeGuard>` del tiempo actual con limpieza automática del intervalo en `onUnmounted`.
1783
+ * **`useRelativeTime(date, options?)`**: Retorna una `Ref<string>` con el tiempo relativo actualizado periódicamente con watch profundo incorporado.
1784
+
1785
+ ```html
1786
+ <script setup>
1787
+ import { useCurrentTime, useRelativeTime } from '@bereasoftware/time-guard/vue';
1788
+
1789
+ const now = useCurrentTime({ interval: 1000 });
1790
+ const relative = useRelativeTime('2026-05-20T08:00:00');
1791
+ </script>
1792
+
1793
+ <template>
1794
+ <div>
1795
+ <p>Hora actual: {{ now.format('HH:mm:ss') }}</p>
1796
+ <p>Publicado hace: {{ relative }}</p>
1797
+ </div>
1798
+ </template>
1799
+ ```
1800
+
1801
+ ---
1802
+
1803
+ ### 🅰️ Angular (`@bereasoftware/time-guard/angular`)
1804
+
1805
+ La integración con Angular está optimizada para la detección de cambios (`ChangeDetectionStrategy.OnPush`), utilizando servicios inyectables y pipes puros/impuros que ejecutan temporizadores fuera de la zona de Angular (`NgZone.runOutsideAngular`) para maximizar el rendimiento.
1806
+
1807
+ #### 1. Configuración Global: `TIME_GUARD_CONFIG`
1808
+ Registra la configuración en el módulo o a nivel de root mediante Dependency Injection (DI).
1809
+
1810
+ ```typescript
1811
+ import { NgModule } from '@angular/core';
1812
+ import { TIME_GUARD_CONFIG } from '@bereasoftware/time-guard/angular';
1813
+
1814
+ @NgModule({
1815
+ providers: [
1816
+ {
1817
+ provide: TIME_GUARD_CONFIG,
1818
+ useValue: { locale: 'es' }
1819
+ }
1820
+ ]
1821
+ })
1822
+ export class AppModule {}
1823
+ ```
1824
+
1825
+ #### 2. Pipes Disponibles
1826
+
1827
+ * **`TimeGuardFormatPipe` (`timeGuardFormat`)**:
1828
+ Pipe puro diseñado para formatear valores de fecha/hora de forma ultra-rápida sin sobrecargar la detección de cambios.
1829
+ ```html
1830
+ <p>{{ createdDate | timeGuardFormat:'DD/MM/YYYY' }}</p>
1831
+ ```
1832
+
1833
+ * **`TimeGuardRelativePipe` (`timeGuardRelative`)**:
1834
+ Pipe impuro para mostrar la representación humanizada relativa de una fecha.
1835
+ ```html
1836
+ <p>Publicado {{ createdDate | timeGuardRelative }}</p>
1837
+ ```
1838
+
1839
+ * **`TimeGuardLiveFormatPipe` (`timeGuardLiveFormat`)**:
1840
+ Pipe impuro de alto rendimiento optimizado con `ChangeDetectorRef` para crear relojes o actualizaciones dinámicas en tiempo real en plantillas sin redibujar todo el árbol.
1841
+ ```html
1842
+ <!-- Reloj digital en vivo actualizándose cada segundo -->
1843
+ <h2>Hora actual: {{ 'now' | timeGuardLiveFormat:'HH:mm:ss':1000 }}</h2>
1844
+
1845
+ <!-- Fecha estática actualizando su formato dinámicamente -->
1846
+ <p>Actualizado: {{ updateDate | timeGuardLiveFormat:'YYYY-MM-DD HH:mm:ss':5000 }}</p>
1847
+ ```
1848
+
1849
+ #### 3. Servicio Reactivo: `TimeGuardService`
1850
+ Provee acceso inyectable a flujos reactivos basados en **RxJS**.
1851
+ El método `getCurrentTime()` emite el tiempo actual en base a un intervalo. Internamente corre **fuera de la zona de Angular** (`runOutsideAngular`) y solo reingresa a la zona (`NgZone.run`) para emitir valores, lo que evita disparar ciclos de renderizado y disminuye drásticamente el consumo de CPU en aplicaciones SPA de gran escala.
1852
+
1853
+ ```typescript
1854
+ import { Component, OnInit } from '@angular/core';
1855
+ import { TimeGuardService } from '@bereasoftware/time-guard/angular';
1856
+ import { Observable } from 'rxjs';
1857
+ import { TimeGuard } from '@bereasoftware/time-guard';
1858
+
1859
+ @Component({
1860
+ selector: 'app-clock',
1861
+ template: `
1862
+ <div *ngIf="time$ | async as time">
1863
+ Hora: {{ time.format('HH:mm:ss') }}
1864
+ </div>
1865
+ `
1866
+ })
1867
+ export class ClockComponent implements OnInit {
1868
+ time$!: Observable<TimeGuard>;
1869
+
1870
+ constructor(private timeGuardService: TimeGuardService) {}
1871
+
1872
+ ngOnInit() {
1873
+ this.time$ = this.timeGuardService.getCurrentTime(1000);
1874
+ }
1875
+ }
1876
+ ```
1877
+
1878
+ ---
1879
+
1629
1880
  ## 🧪 Testing
1881
+ <a id="testing"></a>
1630
1882
 
1631
1883
  TimeGuard includes **530+ comprehensive tests** covering:
1632
1884
 
@@ -1665,6 +1917,7 @@ Edge cases: 65+ tests
1665
1917
  ---
1666
1918
 
1667
1919
  ## 🏛️ Arquitectura
1920
+ <a id="arquitectura"></a>
1668
1921
 
1669
1922
  TimeGuard is built on **SOLID principles** ensuring clean, maintainable, and extensible code:
1670
1923
 
@@ -1730,6 +1983,7 @@ time-guard/
1730
1983
  ---
1731
1984
 
1732
1985
  ## 🤝 Contribuir
1986
+ <a id="contribuir"></a>
1733
1987
 
1734
1988
  ¡Bienvenidas las contribuciones! Por favor:
1735
1989
 
@@ -1742,6 +1996,7 @@ time-guard/
1742
1996
  ---
1743
1997
 
1744
1998
  ## 📄 Licencia
1999
+ <a id="licencia"></a>
1745
2000
 
1746
2001
  Licencia MIT © 2024 Berea-Soft
1747
2002