From a25c991a4ebc535dfbbf5dc4d4b873198323f026 Mon Sep 17 00:00:00 2001 From: Priyadi Iman Nurcahyo <1102197+priyadi@users.noreply.github.com> Date: Sun, 8 Oct 2023 21:14:11 +0700 Subject: [PATCH] Make the Stimulus controller to expire links using the expiration in the query string. --- CHANGELOG.md | 2 ++ assets/src/autoexpire.js | 50 +++++++++++++++++++++++++++++----------- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a15102..1d80e72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ * Add a Stimulus controller to disable expired links. * Add `temporary_url_autoexpire` Twig function. * Add expiration in the query string of the resulting URL. +* Make the Stimulus controller to expire links using the expiration in the + query string. ## 1.2.1 diff --git a/assets/src/autoexpire.js b/assets/src/autoexpire.js index 6b62aa1..44d46ca 100644 --- a/assets/src/autoexpire.js +++ b/assets/src/autoexpire.js @@ -1,16 +1,40 @@ -'use strict'; +'use strict' + +import { Controller } from '@hotwired/stimulus' -import { Controller } from '@hotwired/stimulus'; export default class extends Controller { - connect() { - let element = this.element; - setTimeout(function () { - element.classList.add('disabled'); - element.setAttribute('disabled', 'disabled'); - element.setAttribute('tabindex', '-1'); - element.setAttribute('aria-disabled', 'true'); - element.setAttribute('title', 'This link has expired. Please refresh the page, and try again.'); - element.href = '#'; - }, 1800000); - } + connect() { + let element = this.element + + let href = element.getAttribute('href') + if (!href) { + return; + } + + let url = new URL(href, 'http://example.com/') + if (!url) { + return; + } + + let expiration = parseInt(url.searchParams.get('expiration')) + let secondsToExpiration = 1800 + + if (expiration) { + let now = new Date().getTime() / 1000 + secondsToExpiration = expiration - now + } + + if (secondsToExpiration < 0) { + secondsToExpiration = 1 + } + + setTimeout(function () { + element.classList.add('disabled') + element.setAttribute('disabled', 'disabled') + element.setAttribute('tabindex', '-1') + element.setAttribute('aria-disabled', 'true') + element.setAttribute('title', 'This link has expired. Please refresh the page, and try again.') + element.href = '#' + }, secondsToExpiration * 1000) + } } \ No newline at end of file