Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created June 25, 2024 08:51
Show Gist options
  • Save anjanesh/fcbdddfb82940141fc29a8f721a78ef3 to your computer and use it in GitHub Desktop.
Save anjanesh/fcbdddfb82940141fc29a8f721a78ef3 to your computer and use it in GitHub Desktop.
Last Saved At
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Cache-control" content="no-cache">
<title>Last Saved Date-Time</title>
<script src="https://unpkg.com/alpinejs@3.14.1/dist/cdn.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4.4/build/global/luxon.min.js"></script>
<script>
let saveSOFLocally = () =>
{
Alpine.store('global_data').name = document.getElementById('name').value;
Alpine.store('global_data').description = document.getElementById('description').value;
let currentDate = new Date();
Alpine.store('global_data').lastSaved = luxon.DateTime.now();
Alpine.store('global_data').lastSavedLocale = currentDate.toLocaleString();
localStorage.setItem("product-data", JSON.stringify(Alpine.store('global_data')));
}
document.addEventListener('alpine:init', () =>
{
let locally_stored_data = localStorage.getItem("product-data");
if (locally_stored_data)
{
locally_stored_data = JSON.parse(locally_stored_data);
Alpine.store('global_data', locally_stored_data);
}
else
{
Alpine.store('global_data',
{
name: '',
description: '',
});
}
});
</script>
</head>
<body>
<section
x-data="{
local_lastSavedDiffForHumans: '',
updateInterval: 1000, // Start with 1 second interval
lastSavedDiffForHumans()
{
const now = luxon.DateTime.now();
date = luxon.DateTime.fromISO(Alpine.store('global_data').lastSaved);
const diffInMinutes = now.diff(date, 'minutes').minutes;
if (diffInMinutes >= 60)
{
this.updateInterval = 3600000; // Change to 1 hour interval after 1 hour
}
else if (diffInMinutes >= 1)
{
this.updateInterval = 60000; // Keep 1 minute interval for the first hour
}
return date.toRelative();
},
}"
x-init="
local_lastSavedDiffForHumans = lastSavedDiffForHumans();
setInterval(() =>
{
local_lastSavedDiffForHumans = lastSavedDiffForHumans();
console.log('running');
}, updateInterval);
"
>
Product Name :<br/>
<input id="name" name="name" x-model="$store.global_data['name']"/><br/>
Product Description :<br/>
<textarea id="description" name="description" x-model="$store.global_data['description']"></textarea><br/>
<button type="button" @click="saveSOFLocally();">Save locally</button>
<div style="display: flex; flex-direction: column;">
<span>Last Saved:</span>
<span x-text="local_lastSavedDiffForHumans == '' || local_lastSavedDiffForHumans == null ? 'Never' : ''"></span>
<span x-text="Alpine.store('global_data').lastSavedLocale"></span>
<span x-text="local_lastSavedDiffForHumans"></span>
</div>
</section>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment