1212// See the License for the specific language governing permissions and
1313// limitations under the License.
1414
15- import { Pipe , PipeTransform } from '@angular/core' ;
15+ import { Pipe , PipeTransform , OnDestroy } from '@angular/core' ;
1616import { Translate } from '@singletons' ;
1717import { CoreLogger } from '@static/logger' ;
1818import { dayjs } from '@/core/utils/dayjs' ;
19+ import { Subscription } from 'rxjs' ;
1920
2021/**
2122 * Pipe to turn a UNIX timestamp to "time ago".
2223 */
2324@Pipe ( {
2425 name : 'coreTimeAgo' ,
26+ pure : false ,
2527} )
26- export class CoreTimeAgoPipe implements PipeTransform {
28+ export class CoreTimeAgoPipe implements PipeTransform , OnDestroy {
2729
28- private logger : CoreLogger ;
30+ protected logger : CoreLogger ;
31+ protected cachedResult ?: string ;
32+ protected subscription : Subscription ;
33+
34+ protected lastTimestamp ?: number | string ;
2935
3036 constructor ( ) {
3137 this . logger = CoreLogger . getInstance ( 'CoreTimeAgoPipe' ) ;
38+
39+ this . subscription = Translate . onLangChange . subscribe ( ( ) => {
40+ this . cachedResult = undefined ;
41+ } ) ;
3242 }
3343
3444 /**
35- * Turn a UNIX timestamp to "time ago".
45+ * Pipes a timestamp into a "time ago" format .
3646 *
3747 * @param timestamp The UNIX timestamp (without milliseconds).
3848 * @returns Formatted time.
3949 */
4050 transform ( timestamp : string | number ) : string {
51+ if ( this . lastTimestamp !== timestamp ) {
52+ this . lastTimestamp = timestamp ;
53+ this . cachedResult = undefined ;
54+ }
55+
56+ if ( this . cachedResult === undefined ) {
57+ this . cachedResult = this . formatTimeAgo ( timestamp ) ;
58+ }
59+
60+ return this . cachedResult ;
61+ }
62+
63+ /**
64+ * Turn a UNIX timestamp to "time ago".
65+ *
66+ * @param timestamp The UNIX timestamp (without milliseconds).
67+ * @returns Formatted time.
68+ */
69+ protected formatTimeAgo ( timestamp : string | number ) : string {
4170 if ( typeof timestamp === 'string' ) {
4271 // Convert the value to a number.
4372 const numberTimestamp = parseInt ( timestamp , 10 ) ;
@@ -52,4 +81,11 @@ export class CoreTimeAgoPipe implements PipeTransform {
5281 return Translate . instant ( 'core.ago' , { $a : dayjs ( timestamp * 1000 ) . fromNow ( true ) } ) ;
5382 }
5483
84+ /**
85+ * @inheritdoc
86+ */
87+ ngOnDestroy ( ) : void {
88+ this . subscription . unsubscribe ( ) ;
89+ }
90+
5591}
0 commit comments