Skip to content
This repository was archived by the owner on May 2, 2021. It is now read-only.

Commit 1af76f1

Browse files
committed
firebase test
1 parent 859f281 commit 1af76f1

File tree

17 files changed

+275
-106
lines changed

17 files changed

+275
-106
lines changed

.eleventy.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ module.exports = function (eleventyConfig) {
7171

7272
eleventyConfig.addPassthroughCopy({ 'static/*.*': '.' });
7373

74+
eleventyConfig.addWatchTarget('./src/_js/');
75+
7476
eleventyConfig.addDataExtension('yaml', (contents) =>
7577
yaml.safeLoad(contents),
7678
);

src/.eslintrc

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
"root": true,
33
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
44
"env": {
5-
"browser": true
5+
"browser": true,
6+
"es6": true
7+
},
8+
"globals": {
9+
"process": true
610
},
711
"parserOptions": {
812
"ecmaVersion": 2020,
@@ -14,5 +18,13 @@
1418
"block-scoped-var": "error",
1519
"consistent-return": "error",
1620
"eqeqeq": "error"
17-
}
21+
},
22+
"overrides": [
23+
{
24+
"files": ["**/*-worker.js"],
25+
"env": {
26+
"serviceworker": true
27+
}
28+
}
29+
]
1830
}

src/_data/env.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/* eslint-env node */
2+
module.exports = {
3+
PRODUCTION: process.env.ELEVENTY_ENV === 'production',
4+
};

src/_includes/footer.njk

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -66,23 +66,4 @@
6666
</div>
6767
</div>
6868
</div>
69-
</footer>
70-
<script type="module">
71-
const toggler = document.querySelector('.navbar-toggle');
72-
if (toggler) {
73-
const target = document.querySelector(toggler.dataset.target)
74-
toggler.addEventListener('click', (e) => {
75-
e.preventDefault();
76-
const opened = !toggler.classList.contains('collapsed')
77-
toggler.classList[opened ? 'add' : 'remove']('collapsed')
78-
toggler.setAttribute('aria-expanded', String(!opened))
79-
target.classList[opened ? 'remove' : 'add']('in')
80-
if (opened) {
81-
}
82-
})
83-
}
84-
85-
if ('serviceWorker' in navigator) {
86-
navigator.serviceWorker.register('/service-worker.js');
87-
}
88-
</script>
69+
</footer>

src/_includes/head.njk

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@
103103
{%- if isHome %}
104104
<script defer src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
105105
{%- endif %}
106+
<script defer src="https://www.gstatic.com/firebasejs/8.2.3/firebase-app.js"></script>
107+
<script defer src="https://www.gstatic.com/firebasejs/8.2.3/firebase-messaging.js"></script>
108+
<script type="module" src="/js/main.js"></script>
106109
<!-- Google Analytics -->
107110
<script>
108111
(function (i, s, o, g, r, a, m) {

src/_includes/header.njk

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
<!-- Header Start -->
22
<header>
3+
<div id="notification-bar" class="alert alert-warning" hidden>
4+
<button type="button" class="btn btn-link">Resta aggiornato sui prossimi eventi del FEVR!</button>
5+
<button type="button" class="close" aria-label="Chiudi"><span aria-hidden="true">&times;</span></button>
6+
</div>
7+
<div id="token"></div>
38
<div class="container">
49
<div class="row">
510
<div class="col-md-12">

src/_js/main.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/* global firebase */
2+
import { FIREBASE_CONFIG, VAPID_KEY } from './modules/constants';
3+
4+
const toggler = document.querySelector('.navbar-toggle');
5+
6+
if (toggler) {
7+
const target = document.querySelector(toggler.dataset.target);
8+
toggler.addEventListener('click', (e) => {
9+
e.preventDefault();
10+
const opened = !toggler.classList.contains('collapsed');
11+
toggler.classList[opened ? 'add' : 'remove']('collapsed');
12+
toggler.setAttribute('aria-expanded', String(!opened));
13+
target.classList[opened ? 'remove' : 'add']('in');
14+
});
15+
}
16+
17+
async function subscribe(sw) {
18+
const result = await Notification.requestPermission();
19+
20+
if (result !== 'granted' || !window.firebase) {
21+
return;
22+
}
23+
// Initialize Firebase
24+
25+
firebase.initializeApp(FIREBASE_CONFIG);
26+
27+
const messaging = firebase.messaging();
28+
29+
try {
30+
const token = await messaging.getToken({
31+
serviceWorkerRegistration: sw,
32+
vapidKey: VAPID_KEY,
33+
});
34+
if (!token) {
35+
return;
36+
}
37+
38+
console.log(token);
39+
document.getElementById('token').textContent = token;
40+
} catch (err) {
41+
console.error('An error occurred while retrieving token. ', err);
42+
}
43+
44+
messaging.onMessage((payload) => {
45+
console.log('Message received. ', payload);
46+
});
47+
}
48+
49+
// async function notify() {
50+
// const result = await Notification.requestPermission();
51+
// if (result !== 'granted') {
52+
// return;
53+
// }
54+
// const body = 'hello';
55+
// const icon = '/apple-touch-icon.png';
56+
// new Notification('Hello!', {
57+
// body,
58+
// icon,
59+
// });
60+
// }
61+
62+
function registerNotifier(sw) {
63+
const hideNotificationBar =
64+
localStorage.getItem('notificationBar') === 'hide';
65+
if (!hideNotificationBar) {
66+
const bar = document.getElementById('notification-bar');
67+
68+
const closeBar = () => {
69+
bar.hidden = true;
70+
localStorage.setItem('notificationBar', 'hide');
71+
};
72+
73+
bar.hidden = false;
74+
bar.querySelector('button.close').addEventListener('click', closeBar);
75+
76+
bar.querySelector('.btn.btn-link').addEventListener('click', async () => {
77+
const result = await Notification.requestPermission();
78+
closeBar();
79+
if (result === 'granted') {
80+
subscribe(sw);
81+
}
82+
});
83+
} else {
84+
subscribe(sw);
85+
}
86+
}
87+
88+
if (process.env.NODE_ENV === 'production') {
89+
if ('serviceWorker' in navigator) {
90+
navigator.serviceWorker
91+
.register('/service-worker.js')
92+
.then(registerNotifier);
93+
}
94+
} else {
95+
registerNotifier();
96+
}

src/_js/modules/constants.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export const FIREBASE_CONFIG = {
2+
apiKey: 'AIzaSyCHymmnW5dxfaUYpvQFNus3e_PR7bSzHIY',
3+
authDomain: 'fevr-push-server-45f58.firebaseapp.com',
4+
projectId: 'fevr-push-server-45f58',
5+
storageBucket: 'fevr-push-server-45f58.appspot.com',
6+
messagingSenderId: '428334462537',
7+
appId: '1:428334462537:web:458a7acdd08d453e51b198',
8+
};
9+
10+
export const VAPID_KEY =
11+
'BOZgaux-lAoD6nky7pDTWKeo5jaPgJ3KBfK1t7pfCr3lEJ0mmSElOiTiAzoyk3WC_QManXh4mFl7xuJdGj1QNbs';

src/_js/modules/message-worker.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/* global firebase */
2+
import { FIREBASE_CONFIG } from './constants';
3+
importScripts('https://www.gstatic.com/firebasejs/5.5.2/firebase-app.js');
4+
importScripts('https://www.gstatic.com/firebasejs/5.5.2/firebase-messaging.js');
5+
6+
firebase.initializeApp({
7+
messagingSenderId: FIREBASE_CONFIG.messagingSenderId,
8+
});
9+
10+
const messaging = firebase.messaging();
11+
12+
/*
13+
* We need a generic class to hold data and methods, that inherit from Event
14+
*/
15+
class CustomPushEvent extends Event {
16+
constructor(data) {
17+
super('push');
18+
19+
Object.assign(this, data);
20+
this.custom = true;
21+
}
22+
}
23+
24+
/*
25+
* Overrides push notification data, to avoid having 'notification' key and firebase blocking
26+
* the message handler from being called
27+
*/
28+
self.addEventListener('push', (e) => {
29+
// Skip if event is our own custom event
30+
if (e.custom) return;
31+
32+
// Kep old event data to override
33+
let oldData = e.data;
34+
35+
// Create a new event to dispatch
36+
let newEvent = new CustomPushEvent({
37+
data: {
38+
json() {
39+
let newData = oldData.json();
40+
newData._notification = newData.notification;
41+
delete newData.notification;
42+
return newData;
43+
},
44+
},
45+
46+
waitUntil: e.waitUntil.bind(e),
47+
});
48+
49+
// Stop event propagation
50+
e.stopImmediatePropagation();
51+
52+
// Dispatch the new wrapped event
53+
dispatchEvent(newEvent);
54+
});
55+
56+
messaging.setBackgroundMessageHandler(({ data }) => {
57+
const notificationOptions = {
58+
body: data.body,
59+
icon: '/apple-touch-icon.png',
60+
};
61+
return self.registration.showNotification(data.title, notificationOptions);
62+
});

src/_js/service-worker.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
/* eslint-disable no-undef */
2-
const cacheName = 'fevr-v2-cache';
31
import { registerRoute } from 'workbox-routing';
42
import { StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';
3+
import './modules/message-worker';
54

5+
const cacheName = 'fevr-v2-cache';
66
const listRegExp = /^\/(index\.html|eventi\/index\.html)/;
77

88
registerRoute(

0 commit comments

Comments
 (0)