Skip to content

Commit

Permalink
adds jquery feature flag (#1541)
Browse files Browse the repository at this point in the history
Co-authored-by: Ali Hassan <[email protected]>
  • Loading branch information
sheralim012 and Alihassanc5 authored Apr 4, 2023
1 parent f38a488 commit 83e4c36
Show file tree
Hide file tree
Showing 12 changed files with 243 additions and 35 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ services:
SUPERSET_USERNAME: ''
SUPERSET_PASSWORD: ''
PUSH_NOTIFICATION: 'enable'
JQUERY: 'enable'
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./:/app/
Expand Down
6 changes: 6 additions & 0 deletions home/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@ def show_footers(request):
if start_link:
show_footers_ = False
return {'show_footers': show_footers_}


def jquery(request):
return {
'jquery': settings.JQUERY,
}
2 changes: 1 addition & 1 deletion home/wagtail_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def global_admin_css():
def global_admin_js():
return format_html(
'<script src="{}"></script>',
static("js/global/admin.js")
static("js/admin.js")
)


Expand Down
2 changes: 2 additions & 0 deletions iogt/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
'home.processors.show_footers',
'messaging.processors.add_vapid_public_key',
'notifications.processors.push_notification',
'home.processors.jquery',
],
},
},
Expand Down Expand Up @@ -536,5 +537,6 @@
SUPERSET_PASSWORD = os.getenv('SUPERSET_PASSWORD')

PUSH_NOTIFICATION = os.getenv('PUSH_NOTIFICATION', 'disable') == 'enable'
JQUERY = os.getenv('JQUERY', 'enable') == 'enable'

DATA_UPLOAD_MAX_NUMBER_FIELDS = int(os.getenv('DATA_UPLOAD_MAX_NUMBER_FIELDS', '') or '1000')
28 changes: 27 additions & 1 deletion home/static/js/global/admin.js → iogt/static/js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,31 @@ $(document).ready(function () {
$('#id_page_permissions-ADD').parent().prepend('<h4 style="color: #FF0000; font-weight: bold; margin: 5px;">' +
'Giving a Group the EDIT permission will also allow them to download data for Polls, Surveys, and Quizzes ' +
'for the Pages they can access.</h4>')

});

function validateFileUpload(fileInput, file_size_threshold) {
if (!fileInput.files || !fileInput.files[0])
return true;
else {
var file = fileInput.files[0];
if (file.size >= file_size_threshold)
return confirm('The file you have uploaded exceeds ' + Math.round(file_size_threshold / 1024 / 1024) + 'mb. ' +
'This will prohibit access to the file in a low bandwidth setting, may restrict feature phone access, or ' +
'violate your mobile network operator agreements. To reduce file size, try resizing and compressing your ' +
'file. Do you want to continue?');
}

return true;
}

function validateFreeBasicsFileUpload(fileInput, file_size_threshold) {
if (!fileInput.files || !fileInput.files[0])
return true;
else {
var file = fileInput.files[0];
if (file.size >= file_size_threshold)
alert(`File size exceeds facebook free basics limit (${file_size_threshold / 1024}KB).`);
}

return true;
}
200 changes: 200 additions & 0 deletions iogt/static/js/iogt-no-jquery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
const ready = (callback) => {
if (document.readyState != "loading") callback();
else document.addEventListener("DOMContentLoaded", callback);
};

const init = (event) => {
const show = (el) => el.style.display = 'block';
const hide = (el) => el.style.display = 'none';

const externalLinkOverlay = document.querySelector('#external-link-overlay');
externalLinkOverlay.addEventListener('click', (event) => hide(event.target));

const submitWhenOffline = gettext('You cannot submit when offline');

const readContent = document.querySelectorAll('.complete');
const commentLikeHolders = document.querySelectorAll('.like-holder');
const replyLinks = document.querySelectorAll('.reply-link');
const offlineAppBtns = document.querySelectorAll('.offline-app-btn');
const chatbotBtns = document.querySelectorAll('.chatbot-btn');
const questionnaireSubmitBtns = document.querySelectorAll('.questionnaire-submit-btn');
const externalLinks = document.querySelectorAll('a[href*="/external-link/?next="]');
const elementsToToggle = [
'.download-app-btn',
'.login-create-account-btn',
'.change-digital-pin',
'.comments__form',
'.logout-btn',
'.progress-holder',
'.report-comment',
'.search-form-holder',
].flatMap(
(selector) => Array.from(document.querySelectorAll(selector))
);
console.log(elementsToToggle);

const blockExternalLinks = (event) => {
event.preventDefault();
show(externalLinkOverlay);
};

// for JS enabled devices hide double menu
const hideFooterMenu = () => {
hide(document.querySelector('.footer-head'));
};

const disableForOfflineAccess = (event) => {
elementsToToggle.forEach(hide);
replyLinks.forEach(hide)
readContent.forEach((el) => el.classList.remove('complete'));
commentLikeHolders.forEach((el) => el.setAttribute('style', 'display:none !important'));
offlineAppBtns.forEach(show);
chatbotBtns.forEach((btn) => {
btn.style['pointer-events'] = 'none';
btn.style.background = '#808080';
});
questionnaireSubmitBtns.forEach((btn) => {
btn.style['pointer-events'] = 'none';
const span = btn.querySelector('span');
span.innerHTML = `${span.innerHTML} (${submitWhenOffline})`;
});
externalLinks.forEach((link) => {
link.addEventListener('click', blockExternalLinks);
});
};

const enableForOnlineAccess = (event) => {
elementsToToggle.forEach(show);
readContent.forEach((el) => el.classList.add('complete'));
commentLikeHolders.forEach((el) => el.setAttribute('style', 'display:inline-block !important'));
replyLinks.forEach((el) => el.setAttribute('style', 'display:inline-block'));
offlineAppBtns.forEach(hide);
chatbotBtns.forEach((btn) => {
btn.style['pointer-events'] = 'all';
btn.style.background = '#F7F7F9';
});
questionnaireSubmitBtns.forEach((btn) => {
btn.style['pointer-events'] = 'all';
const span = btn.querySelector('span');
span.innerHTML = span.innerHTML.split(`(${submitWhenOffline})`)[0];
});
externalLinks.forEach((link) => {
show(link);
link.removeEventListener('click', blockExternalLinks);
});
};

window.addEventListener('offline', disableForOfflineAccess);
window.addEventListener('online', enableForOnlineAccess);

window.navigator.onLine ? enableForOnlineAccess() : disableForOfflineAccess();
hideFooterMenu();

};

const download = pageId => {
fetch(`/page-tree/${pageId}/`)
.then(resp => resp.json())
.then(urls => {
caches.open('iogt')
.then(cache => {
cache.addAll(urls);
});
});
};

const getItem = (key, defaultValue) => {
return JSON.parse(localStorage.getItem(key, defaultValue));
};

const setItem = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};

const registerPushNotification = registration => {
if (!registration.showNotification) {
return;
}
if (Notification.permission === 'denied') {
return;
}
if (!'PushManager' in window) {
return;
}
subscribe(registration);
};

const urlB64ToUint8Array = base64String => {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
const outputData = outputArray.map((output, index) => rawData.charCodeAt(index));

return outputData;
};

const subscribe = registration => {
registration.pushManager.getSubscription()
.then(subscription => {
if (subscription) {
sendSubscriptionToServer(subscription, 'subscribe');
return;
}
const vapidKeyMeta = document.querySelector('meta[name="vapid-key"]');
const vapidKey = vapidKeyMeta.content;
const options = {
userVisibleOnly: true,
// if key exists, create applicationServerKey property
...(vapidKey && {applicationServerKey: urlB64ToUint8Array(vapidKey)})
};

registration.pushManager.subscribe(options)
.then(subscription => {
sendSubscriptionToServer(subscription, 'subscribe');
})
.catch(error => {
console.log("Error during subscribe()", error);
});
})
.catch(error => {
console.log("Error during getSubscription()", error);
});
};

const sendSubscriptionToServer = (subscription, statusType) => {
const browser = navigator.userAgent.match(/(firefox|msie|chrome|safari|trident)/ig)[0].toLowerCase();
const data = {
status_type: statusType,
subscription: subscription.toJSON(),
browser: browser,
};

fetch('/webpush/subscribe/', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'content-type': 'application/json'
},
credentials: "include"
}).then(resp => {
setItem('isPushNotificationRegistered', statusType === 'subscribe');
});
};


const unSubscribePushNotifications = () => {
const isPushNotificationRegistered = getItem('isPushNotificationRegistered', false);
if (isPushNotificationRegistered && isAuthenticated && 'serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.pushManager.getSubscription().then(subscription => {
subscription && sendSubscriptionToServer(subscription, 'unsubscribe');
});
});
}
};

ready(init);
27 changes: 0 additions & 27 deletions iogt/static/js/iogt.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,3 @@
function validateFileUpload(fileInput, file_size_threshold) {
if (!fileInput.files || !fileInput.files[0])
return true;
else {
var file = fileInput.files[0];
if (file.size >= file_size_threshold)
return confirm('The file you have uploaded exceeds ' + Math.round(file_size_threshold / 1024 / 1024) + 'mb. ' +
'This will prohibit access to the file in a low bandwidth setting, may restrict feature phone access, or ' +
'violate your mobile network operator agreements. To reduce file size, try resizing and compressing your ' +
'file. Do you want to continue?');
}

return true;
}

function validateFreeBasicsFileUpload(fileInput, file_size_threshold) {
if (!fileInput.files || !fileInput.files[0])
return true;
else {
var file = fileInput.files[0];
if (file.size >= file_size_threshold)
alert(`File size exceeds facebook free basics limit (${file_size_threshold / 1024}KB).`);
}

return true;
}

$(document).ready(() => {
const externalLinkOverlay = $('#external-link-overlay')

Expand Down
8 changes: 6 additions & 2 deletions iogt/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,13 @@
{% endif %}
</script>
<script src="{% url 'javascript-catalog' %}"></script>
<script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'js/iogt.js' %}"></script>
<script src="{% static 'js/sw-init.js' %}"></script>
{% if jquery %}
<script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'js/iogt.js' %}"></script>
{% else %}
<script src="{% static 'js/iogt-no-jquery.js' %}"></script>
{% endif %}
<noscript>
<style type="text/css">
#hideOnNonJSDevice, .hideOnNonJSDevice {
Expand Down
1 change: 0 additions & 1 deletion iogt/templates/wagtaildocs/documents/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


{% block extra_js %}
<script type="text/javascript" src="{% static 'js/iogt.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=submit]').click(function () {
Expand Down
1 change: 0 additions & 1 deletion iogt/templates/wagtailimages/images/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

{% block extra_js %}
{{ block.super }}
<script type="text/javascript" src="{% static 'js/iogt.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=submit]').click(function () {
Expand Down
1 change: 0 additions & 1 deletion iogt/templates/wagtailmedia/media/add.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


{% block extra_js %}
<script type="text/javascript" src="{% static 'js/iogt.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button[type=submit]').click(function () {
Expand Down
1 change: 0 additions & 1 deletion iogt/templates/wagtailmedia/media/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


{% block extra_js %}
<script type="text/javascript" src="{% static 'js/iogt.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=submit]').click(function () {
Expand Down

0 comments on commit 83e4c36

Please sign in to comment.