Skip to content

Commit

Permalink
Added network and install alerts, badge and instant sw update support.
Browse files Browse the repository at this point in the history
  • Loading branch information
DellZHackintosh authored Apr 21, 2024
1 parent e2d2cbf commit cd2d080
Show file tree
Hide file tree
Showing 5 changed files with 168 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"githubPullRequests.ignoredPullRequestBranches": [
"master"
]
}
12 changes: 12 additions & 0 deletions assets/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ self.addEventListener("install", function (event) {
}

receiveInfo();
self.skipWaiting();
});

self.addEventListener("activate", (event) => {
event.waitUntil(clients.claim());
});

// If any fetch fails, it will show the offline page.
Expand Down Expand Up @@ -103,6 +108,13 @@ self.addEventListener('push', function (event) {

if (isJSON(event.data.text())) {
console.log(event.data.json());

if ('clearAppBadge' in navigator) {
const Badges = await idbKeyval.get('Badges') + 1;
await idbKeyval.set('Badges', Badges);
navigator.setAppBadge(Badges);
}

const options = {
body: event.data.json().content,
icon: event.data.json().icon,
Expand Down
114 changes: 114 additions & 0 deletions js/src/forum/addNetworkAndInstallAlerts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { extend } from 'flarum/common/extend';
import Page from 'flarum/common/components/Page';

export default () => {
extend(Page.prototype, 'oninit', () => {
const dismissAlert = () => {
localStorage.setItem('askvortov-pwa.install-alert.dismissed', JSON.stringify({ timestamp: new Date().getTime() }));
};

window.addEventListener('online', () => {
app.alerts.dismiss(app.cache.pwaOfflineAlert);

app.cache.pwaOnlineAlert = app.alerts.show(
{
type: 'success'
},
app.translator.trans('askvortsov-pwa.forum.alerts.online')
);
});

window.addEventListener('offline', () => {
app.alerts.dismiss(app.cache.pwaOnlineAlert);

app.cache.pwaOfflineAlert = app.alerts.show(
app.translator.trans('askvortsov-pwa.forum.alerts.offline')
);
});

if (
!localStorage.getItem('askvortov-pwa.install-alert.dismissed')
) window.addEventListener("beforeinstallprompt", function(e) {
e.preventDefault();
const alertId = app.alerts.show(
{
controls: [
Button.component(
{
className: 'Button Button--link',
onclick: () => {
app.alerts.dismiss(alertId);
e.prompt();
},
},
app.translator.trans('askvortsov-pwa.forum.alerts.install_button')
),
],
ondismiss: dismissAlert
},
app.translator.trans('askvortsov-pwa.forum.alerts.install')
);
});

if (
!localStorage.getItem('askvortov-pwa.install-alert.dismissed') &&
navigator.standalone === false
) app.alerts.show(
{
controls: [
Button.component(
{
className: 'Button Button--link',
onclick: () => {
window.alert(app.translator.trans('askvortsov-pwa.forum.alerts.install_on_safari_learn_more_text'));
},
},
app.translator.trans('askvortsov-pwa.forum.alerts.install_on_safari_learn_more')
),
],
ondismiss: dismissAlert
},
app.translator.trans('askvortsov-pwa.forum.alerts.install_on_safari')
);
});
}

export const updateAlert = () => {
let countdown = 30;
const CountdownComponent = {
async startCountdown() {
while (true) {
await new Promise(resolve => setTimeout(resolve, 1000));
countdown -= 1;
this.node.dom.innerText = app.translator.trans('askvortsov-pwa.forum.alerts.refresh', {countdown}).join('');
if (countdown <= 0) break;
}
window.location.reload();
},

oninit: function() {
this.startCountdown();
this.node = m('span', app.translator.trans('askvortsov-pwa.forum.alerts.refresh', {countdown}).join(''));
},

view: function() {
return this.node;
}
};

app.alerts.show(
{
controls: [
Button.component(
{
className: 'Button Button--link',
onclick: window.location.reload,
},
app.translator.trans('askvortsov-pwa.forum.alerts.refresh_button')
),
],
dismissible: false
},
m(CountdownComponent)
);
}
16 changes: 16 additions & 0 deletions js/src/forum/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import LinkButton from 'flarum/common/components/LinkButton';
import SessionDropdown from 'flarum/forum/components/SessionDropdown';
import addShareButtons from './addShareButtons';
import addPushNotifications, { refreshSubscription } from './addPushNotifications';
import addNetworkAndInstallAlerts, { updateAlert } from './addNetworkAndInstallAlerts';

app.initializers.add('askvortsov/flarum-pwa', () => {
const isInStandaloneMode = () =>
Expand All @@ -23,6 +24,7 @@ app.initializers.add('askvortsov/flarum-pwa', () => {
(await dbPromise).put('keyval', app.forum.data.attributes, 'flarum.forumPayload');

if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener("controllerchange", updateAlert);
navigator.serviceWorker
.register(basePath + '/sw', {
scope: basePath + '/',
Expand All @@ -36,7 +38,20 @@ app.initializers.add('askvortsov/flarum-pwa', () => {
}
};

const clearAppBadge = async () => {
const dbPromise = openDB('keyval-store', 1, {
upgrade(db) {
db.createObjectStore('keyval');
},
});
(await dbPromise).put('keyval', 0, 'Badges');
if ('clearAppBadge' in navigator) {
navigator.clearAppBadge();
};
}

registerSW();
clearAppBadge();
});

extend(SessionDropdown.prototype, 'items', (items) => {
Expand All @@ -58,4 +73,5 @@ app.initializers.add('askvortsov/flarum-pwa', () => {

addShareButtons();
addPushNotifications();
addNetworkAndInstallAlerts();
});
23 changes: 21 additions & 2 deletions resources/locale/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ askvortsov-pwa:
user_max_subscriptions_text: How many push subscriptions should each user be able to have at a time? When a user receives a push notification, each subscription will result in an API call. Each subscription typically corresponds to a browser the user has used.
window_controls_overlay_label: Enable Window Controls Overlay?
window_controls_overlay_text: |
If true, users will be able to get an more immersive, native-like experience by hiding the native titlebar. Window Controls Overlay enables or not depends on user's preference and browser's compatibility. You must customize your titlebar by adding some CSS/JS after enabled, or the controls will overlay some elements of your forum's top navbar and the window almost can't drag, resulting a bad experience.
If true, users will able to enable Window Controls Overlay to create an immersive, native-like experience. Window Controls Overlay enables or not depends on user's preference and browser's compatibility. You also should be sure you've done something to match this feature.
See also: <compatibilitylink>The compatibility of Window Controls Overlay</compatibilitylink> & <learnlink>About Window Controls Overlay in Microsoft Learn</learnlink>
custom_offline_page_label: Custom Offline Page
custom_offline_page_text: Provide your custom offline page by setting the path here. If empty, we'll use the default one.
heading: Progressive Web App Configuration
text: Configure your Flarum site to run as a progressive web app! Please note that this doesn't automatically put your site in the app store. Instead, this means that users have an 'Add to Homescreen' option for your site. We provide some status checks, however, the best way to test this is to try and install it (search on google for instructions on how to install progressive web apps). Also, please keep in mind that 'install this PWA' popups are controlled by browsers, and cannot be triggered by developers/admins/programs. I recommend including instructions for how to install a PWA in your site's documentation.
status_check_heading: Status Check
Expand Down Expand Up @@ -71,6 +73,23 @@ askvortsov-pwa:
alerts:
optin: You have push notifications enabled, but have not configured this device.
optin_button: Configure
online: Network connection is restored.
offline: Network connection is lost.
refresh: "An update is available. We'll refresh this app automatically for you {countdown, plural, =0 {now} one {in 1 second} other {in {countdown} seconds}}."
refresh_button: Refresh Now
install: You can install it as an app to get better experience.
install_button: Install
install_on_safari: You can add it to Home Screen/Dock to get better experience.
install_on_safari_learn_more: Learn More
install_on_safari_learn_more_text: |
When you add this app to Home Screen (iPhone & iPad)/Dock (Mac), it'll display as a standalone app. Besides, You'll get extra features that can enhance the app experience, such as badge and notification (if available).
In order to add it to Home Screen/Dock, click the Share button in the Safari toolbar, then choose Add to Home Screen/Dock.
If you don't see Add to Home Screen, you can add it. Scroll down to the bottom of the list, tap Edit Actions, then tap Add to Home Screen.
If you don't see Add to Dock, the Safari may doesn't support it. It requires macOS Sonoma or later.
discussion_controls:
share_button: Share
post_controls:
Expand Down

0 comments on commit cd2d080

Please sign in to comment.