UI debug details

This commit is contained in:
Tony Air 2020-05-14 01:45:17 +07:00
parent 513a5f1774
commit 1f15be7009
2 changed files with 364 additions and 351 deletions

View File

@ -6,15 +6,7 @@ import MAP_DRIVER from './_components/drivers/_map.google';
//import MAP_DRIVER from './_components/drivers/_map.mapbox'; //import MAP_DRIVER from './_components/drivers/_map.mapbox';
const CONSTS = { const CONSTS = {
ENVS: [ ENVS: ['xs', 'sm', 'md', 'lg', 'xl', 'xxl', 'xxxl'],
'xs',
'sm',
'md',
'lg',
'xl',
'xxl',
'xxxl',
],
MAP_DRIVER, MAP_DRIVER,
}; };

View File

@ -17,148 +17,148 @@ import SmoothScroll from 'smooth-scroll';
const smoothScroll = SmoothScroll(); const smoothScroll = SmoothScroll();
const MainUI = (($) => { const MainUI = (($) => {
// Constants // Constants
const W = window; const W = window;
const D = document; const D = document;
const $Body = $('body'); const $Body = $('body');
const NAME = 'MainUI'; const NAME = 'MainUI';
// get browser locale // get browser locale
//const Locale = $('html').attr('lang').substring(0, 2); //const Locale = $('html').attr('lang').substring(0, 2);
const $AlertNotify = $('#AlertNotify'); const $AlertNotify = $('#AlertNotify');
const $SiteWideMessage = $('#SiteWideMessage'); const $SiteWideMessage = $('#SiteWideMessage');
// get browser window visibility preferences // get browser window visibility preferences
// Opera 12.10, Firefox >=18, Chrome >=31, IE11 // Opera 12.10, Firefox >=18, Chrome >=31, IE11
const HiddenName = 'hidden'; const HiddenName = 'hidden';
const VisibilityChangeEvent = 'visibilitychange'; const VisibilityChangeEvent = 'visibilitychange';
// update visibility state // update visibility state
D.addEventListener(VisibilityChangeEvent, () => { D.addEventListener(VisibilityChangeEvent, () => {
if (D.visibilityState === HiddenName) { if (D.visibilityState === HiddenName) {
console.log('Tab: hidden'); console.log('Tab: hidden');
$Body.addClass('is-hidden'); $Body.addClass('is-hidden');
$Body.trigger(Events.TABHIDDEN); $Body.trigger(Events.TABHIDDEN);
} else { } else {
console.log('Tab: focused'); console.log('Tab: focused');
$Body.removeClass('is-hidden'); $Body.removeClass('is-hidden');
$Body.trigger(Events.TABFOCUSED); $Body.trigger(Events.TABFOCUSED);
} }
}); });
// update online/offline state // update online/offline state
const updateOnlineStatus = () => { const updateOnlineStatus = () => {
if (typeof navigator.onLine === 'undefined') { if (typeof navigator.onLine === 'undefined') {
return; return;
} }
if (!navigator.onLine) { if (!navigator.onLine) {
console.log('Tab: offline'); console.log('Tab: offline');
$Body.addClass('is-offline'); $Body.addClass('is-offline');
$Body.trigger(Events.OFFLINE); $Body.trigger(Events.OFFLINE);
} else { } else {
console.log('Tab: online'); console.log('Tab: online');
$Body.removeClass('is-offline'); $Body.removeClass('is-offline');
$Body.trigger(Events.ONLINE); $Body.trigger(Events.ONLINE);
} }
}; };
W.addEventListener( W.addEventListener(
'offline', 'offline',
() => { () => {
updateOnlineStatus(); updateOnlineStatus();
}, },
false, false,
); );
W.addEventListener( W.addEventListener(
'online', 'online',
() => { () => {
updateOnlineStatus(); updateOnlineStatus();
}, },
false, false,
); );
W.addEventListener('load', () => { W.addEventListener('load', () => {
updateOnlineStatus(); updateOnlineStatus();
}); });
$(W).on(`${Events.AJAX}`, () => { $(W).on(`${Events.AJAX}`, () => {
updateOnlineStatus(); updateOnlineStatus();
}); });
// scrollTo // scrollTo
const ScrollTo = (trigger, selector) => { const ScrollTo = (trigger, selector) => {
smoothScroll.animateScroll(D.querySelector(selector), trigger, { smoothScroll.animateScroll(D.querySelector(selector), trigger, {
speed: 500, speed: 500,
offset: -20, offset: -20,
//easing: 'easeInOutCubic', //easing: 'easeInOutCubic',
// Callback API // Callback API
//before: (anchor, toggle) => {}, // Callback to run before scroll //before: (anchor, toggle) => {}, // Callback to run before scroll
//`after: (anchor, toggle) => {} // Callback to run after scroll //`after: (anchor, toggle) => {} // Callback to run after scroll
}); });
}; };
// session ping // session ping
const pingInterval = setInterval(() => { const pingInterval = setInterval(() => {
if ($Body.hasClass('is-offline')) { if ($Body.hasClass('is-offline')) {
return; return;
} }
$.ajax({ $.ajax({
sync: false, sync: false,
async: true, async: true,
cache: false, cache: false,
url: '/Security/ping', url: '/Security/ping',
global: false, global: false,
type: 'POST', type: 'POST',
complete(data, datastatus) { complete(data, datastatus) {
if (datastatus !== 'success') { if (datastatus !== 'success') {
clearInterval(pingInterval); clearInterval(pingInterval);
$Body.addClass('is-offline'); $Body.addClass('is-offline');
//W.location.reload(false); //W.location.reload(false);
} else { } else {
$Body.removeClass('is-offline'); $Body.removeClass('is-offline');
} }
}, },
}); });
}, 300000); // 5 min in ms }, 300000); // 5 min in ms
W.URLDetails = { W.URLDetails = {
base: $('base').attr('href'), base: $('base').attr('href'),
relative: '/', relative: '/',
hash: '', hash: '',
}; };
let eventFired = false; let eventFired = false;
const setTouchScreen = (bool) => { const setTouchScreen = (bool) => {
if (W.IsTouchScreen === bool || eventFired) { if (W.IsTouchScreen === bool || eventFired) {
return; return;
} }
eventFired = true; eventFired = true;
W.IsTouchScreen = bool; W.IsTouchScreen = bool;
$.support.touch = W.IsTouchScreen; $.support.touch = W.IsTouchScreen;
if (bool) { if (bool) {
console.log(`${NAME}: Touch screen enabled`); console.log(`${NAME}: Touch screen enabled`);
} else { } else {
console.log(`${NAME}: Touch screen disabled`); console.log(`${NAME}: Touch screen disabled`);
} }
// prevent firing touch and mouse events together // prevent firing touch and mouse events together
setTimeout(() => { setTimeout(() => {
eventFired = false; eventFired = false;
}, 200); }, 200);
}; };
setTouchScreen('ontouchstart' in window || navigator.msMaxTouchPoints > 0); setTouchScreen('ontouchstart' in window || navigator.msMaxTouchPoints > 0);
// disable touch on mouse events // disable touch on mouse events
/*D.addEventListener('mousemove', () => { /*D.addEventListener('mousemove', () => {
setTouchScreen(false); setTouchScreen(false);
}); });
@ -166,40 +166,40 @@ const MainUI = (($) => {
setTouchScreen(false); setTouchScreen(false);
});*/ });*/
// enable touch screen on touch events // enable touch screen on touch events
D.addEventListener('touchmove', () => { D.addEventListener('touchmove', () => {
setTouchScreen(true); setTouchScreen(true);
}); });
D.addEventListener('touchstart', () => { D.addEventListener('touchstart', () => {
setTouchScreen(true); setTouchScreen(true);
}); });
class MainUI { class MainUI {
// Static methods // Static methods
static init() { static init() {
this.dispose(); this.dispose();
console.log(`Initializing: ${NAME}`); console.log(`Initializing: ${NAME}`);
// update location details // update location details
this.updateLocation(); this.updateLocation();
// mark available offline areas // mark available offline areas
if ('caches' in W) { if ('caches' in W) {
$('a.offline').addClass('offline-available'); $('a.offline').addClass('offline-available');
} }
this.loadImages(); this.loadImages();
// detect bootstrap screen size // detect bootstrap screen size
this.detectBootstrapScreenSize(); this.detectBootstrapScreenSize();
// mark external links // mark external links
$('a.external,a[rel="external"]').attr('target', '_blank'); $('a.external,a[rel="external"]').attr('target', '_blank');
// show encoded emails // show encoded emails
/*$(D).find('.obm').each(() => { /*$(D).find('.obm').each(() => {
if ($(this).attr('data-val') !== undefined) { if ($(this).attr('data-val') !== undefined) {
const email = $(this).attr('data-val').split('') const email = $(this).attr('data-val').split('')
.reverse() .reverse()
@ -219,254 +219,275 @@ const MainUI = (($) => {
} }
} }
});*/ });*/
// //
// scroll links // scroll links
$('.js-scrollTo').on('click', (e) => { $('.js-scrollTo').on('click', (e) => {
e.preventDefault(); e.preventDefault();
const el = e.currentTarget; const el = e.currentTarget;
const $el = $(e.currentTarget); const $el = $(e.currentTarget);
ScrollTo(el, $el.attr('data-target')); ScrollTo(el, $el.attr('data-target'));
}); });
// load external fonts // load external fonts
if ($('[data-extfont]').length) { if ($('[data-extfont]').length) {
$.getScript( $.getScript(
'//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js', '//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js',
() => { () => {
const fonts = []; const fonts = [];
$('[data-extfont]').each((i, el) => { $('[data-extfont]').each((i, el) => {
fonts[i] = $(el).attr('data-extfont'); fonts[i] = $(el).attr('data-extfont');
}); });
W.WebFont.load({ W.WebFont.load({
google: { google: {
families: fonts, families: fonts,
}, },
}); });
}, },
); );
} }
// data-set links // data-set links
$('[data-set-target]').on('click', (e) => { $('[data-set-target]').on('click', (e) => {
const $el = $(e.currentTarget); const $el = $(e.currentTarget);
const $target = $($el.data('set-target')); const $target = $($el.data('set-target'));
if (!$target.length) { if (!$target.length) {
return; return;
} }
$target.each((i, targetEl) => { $target.each((i, targetEl) => {
const $targetEl = $(targetEl); const $targetEl = $(targetEl);
const tag = $targetEl.prop('tagName').toLowerCase(); const tag = $targetEl.prop('tagName').toLowerCase();
if (tag === 'input' || tag === 'select') { if (tag === 'input' || tag === 'select') {
$targetEl.val($el.data('set-val')); $targetEl.val($el.data('set-val'));
} else if (!$targetEl.hasClass('field')) { } else if (!$targetEl.hasClass('field')) {
$targetEl.text($el.data('set-val')); $targetEl.text($el.data('set-val'));
} }
}); });
$el.trigger(Events.SET_TARGET_UPDATE); $el.trigger(Events.SET_TARGET_UPDATE);
$target.closest('form').trigger(Events.SET_TARGET_UPDATE); $target.closest('form').trigger(Events.SET_TARGET_UPDATE);
}); });
// emulate links // emulate links
$('.a[data-href]').on('click', (e) => { $('.a[data-href]').on('click', (e) => {
const $el = $(e.currentTarget); const $el = $(e.currentTarget);
const href = $el.data('href'); const href = $el.data('href');
if (!href.length) { if (!href.length) {
console.warn('Missing data-href'); console.warn('Missing data-href');
console.warn($el); console.warn($el);
} }
W.location.assign(href); W.location.assign(href);
}); });
// hide spinner // hide spinner
Spinner.hide(() => { Spinner.hide(() => {
$Body.addClass('loaded'); $Body.addClass('loaded');
}); });
// fire page printing // fire page printing
if (W.URLDetails['hash'].indexOf('printpage') > -1) { if (W.URLDetails['hash'].indexOf('printpage') > -1) {
W.print(); W.print();
} }
$Body.data(NAME, this); $Body.data(NAME, this);
} }
static detectBootstrapScreenSize() { static detectBootstrapScreenSize() {
const $el = $('<div class="env-test"></div>'); const $el = $('<div class="env-test"></div>');
let envs = [...Consts.ENVS]; let envs = [...Consts.ENVS];
$Body.append($el); $Body.append($el);
let curEnv = envs.shift(); let curEnv = envs.shift();
envs = envs.reverse(); envs = envs.reverse();
for (let i = 0; i < envs.length; ++i) { for (let i = 0; i < envs.length; ++i) {
const env = envs[i]; const env = envs[i];
$el.addClass(`d-${env}-none`); $el.addClass(`d-${env}-none`);
if ($el.is(':hidden')) { if ($el.is(':hidden')) {
curEnv = env; curEnv = env;
break; break;
} }
} }
$el.remove(); $el.remove();
$Body.removeClass(envs); $Body.removeClass(envs);
$Body.addClass(curEnv); $Body.addClass(curEnv);
return curEnv; return curEnv;
} }
static updateLocation(url) { static updateLocation(url) {
let location = url || W.location.href; let location = url || W.location.href;
location = location.replace(W.URLDetails['base'], '/'); location = location.replace(W.URLDetails['base'], '/');
const hash = location.indexOf('#'); const hash = location.indexOf('#');
W.URLDetails.relative = location.split('#')[0]; W.URLDetails.relative = location.split('#')[0];
W.URLDetails.hash = W.URLDetails.hash =
hash >= 0 ? location.substr(location.indexOf('#')) : ''; hash >= 0 ? location.substr(location.indexOf('#')) : '';
} }
// show site-wide alert // show site-wide alert
static alert(msg, cls) { static alert(msg, cls) {
$SiteWideMessage.fadeOut('fast'); $SiteWideMessage.fadeOut('fast');
$SiteWideMessage.html( $SiteWideMessage.html(
`<div class="page-alert"><div class="alert alert-${cls}"><i class="close" data-dismiss="alert">&times;</i>${msg}</div></div>`, `<div class="page-alert"><div class="alert alert-${cls}"><i class="close" data-dismiss="alert">&times;</i>${msg}</div></div>`,
); );
$SiteWideMessage.find('.page-alert').alert(); $SiteWideMessage.find('.page-alert').alert();
$SiteWideMessage.find('.close[data-dismiss="alert"]').click(() => { $SiteWideMessage.find('.close[data-dismiss="alert"]').click(() => {
$SiteWideMessage.fadeOut('slow', () => { $SiteWideMessage.fadeOut('slow', () => {
$SiteWideMessage.find('.page-alert').alert('close'); $SiteWideMessage.find('.page-alert').alert('close');
}); });
}); });
$SiteWideMessage.fadeIn('slow'); $SiteWideMessage.fadeIn('slow');
if ($AlertNotify.length) { if ($AlertNotify.length) {
$AlertNotify[0].play(); $AlertNotify[0].play();
} }
$(W).trigger(`${Events.ALLERTAPPEARED}`); $(W).trigger(`${Events.ALLERTAPPEARED}`);
} }
// hide site-wide alert // hide site-wide alert
static alertHide() { static alertHide() {
if ($SiteWideMessage.length !== 0) { if ($SiteWideMessage.length !== 0) {
$SiteWideMessage.fadeOut('slow', () => { $SiteWideMessage.fadeOut('slow', () => {
$SiteWideMessage.find('.alert').alert('close'); $SiteWideMessage.find('.alert').alert('close');
}); });
} }
if ($AlertNotify.length && typeof $AlertNotify[0].stop !== 'undefined') { if (
$AlertNotify[0].stop(); $AlertNotify.length &&
} typeof $AlertNotify[0].stop !== 'undefined'
) {
$AlertNotify[0].stop();
}
$(W).trigger(`${Events.ALLERTREMOVED}`); $(W).trigger(`${Events.ALLERTREMOVED}`);
} }
// load all images // load all images
static loadImages() { static loadImages() {
const $imgs = $Body.find('img'); const $imgs = $Body.find('img');
const $imgUrls = []; const $imgUrls = [];
const $imgLazyUrls = []; const $imgLazyUrls = [];
// collect image details // collect image details
$imgs.each((i, el) => { $imgs.each((i, el) => {
const $el = $(el); const $el = $(el);
const src = $el.attr('src'); const src = $el.attr('src');
const lazySrc = $el.data('lazy-src'); const lazySrc = $el.data('lazy-src');
if (src && src.length) { if (src && src.length) {
$imgUrls.push(src); $imgUrls.push(src);
} }
if (lazySrc && lazySrc.length) { if (lazySrc && lazySrc.length) {
$imgLazyUrls.push(lazySrc); $imgLazyUrls.push(lazySrc);
$el.addClass('loading'); $el.addClass('loading');
AjaxUI.preload([lazySrc]).then(() => { AjaxUI.preload([lazySrc]).then(() => {
$el.attr('src', lazySrc); $el.attr('src', lazySrc);
$el.addClass('loaded'); $el.addClass('loaded');
$el.removeClass('loading'); $el.removeClass('loading');
$el.trigger(`${Events.LAZYIMAGEREADY}`); $el.trigger(`${Events.LAZYIMAGEREADY}`);
}); });
} }
}); });
// load lazy backgrounds // load lazy backgrounds
$Body.find('[data-lazy-bg]').each((i, el) => { $Body.find('[data-lazy-bg]').each((i, el) => {
const $el = $(el); const $el = $(el);
const lazySrc = $el.data('lazy-bg'); const lazySrc = $el.data('lazy-bg');
if (lazySrc && lazySrc.length) { if (lazySrc && lazySrc.length) {
$imgLazyUrls.push(lazySrc); $imgLazyUrls.push(lazySrc);
$el.addClass('loading'); $el.addClass('loading');
AjaxUI.preload([lazySrc]).then(() => { AjaxUI.preload([lazySrc]).then(() => {
$el.css({ 'background-image': `url(${lazySrc})` }); $el.css({ 'background-image': `url(${lazySrc})` });
$el.addClass('loaded'); $el.addClass('loaded');
$el.removeClass('loading'); $el.removeClass('loading');
$el.trigger(`${Events.LAZYIMAGEREADY}`); $el.trigger(`${Events.LAZYIMAGEREADY}`);
}); });
} }
}); });
// load defined images // load defined images
AjaxUI.preload($imgUrls).then(() => { AjaxUI.preload($imgUrls).then(() => {
$(W).trigger('images-loaded'); $(W).trigger('images-loaded');
// load lazy images // load lazy images
AjaxUI.preload($imgLazyUrls).then(() => { AjaxUI.preload($imgLazyUrls).then(() => {
console.log('All images are loaded!'); console.log('All images are loaded!');
setTimeout(() => { setTimeout(() => {
$(W).trigger(`${Events.LAZYIMAGESREADY}`); $(W).trigger(`${Events.LAZYIMAGESREADY}`);
}, 100); }, 100);
}); });
}); });
} }
static dispose() { static dispose() {
console.log(`Destroying: ${NAME}`); console.log(`Destroying: ${NAME}`);
} }
} }
$(W).on(`${Events.AJAX} ${Events.LOADED}`, () => { $(W).on(`${Events.AJAX} ${Events.LOADED}`, () => {
MainUI.init(); MainUI.init();
}); });
$(W).on('resize', () => { $(W).on('resize', () => {
MainUI.detectBootstrapScreenSize(); MainUI.detectBootstrapScreenSize();
}); });
$(W).on('beforeunload unload', () => { $(W).on('beforeunload unload', () => {
Spinner.show(() => { Spinner.show(() => {
$Body.removeClass('loaded'); $Body.removeClass('loaded');
}); });
}); });
// hide spinner on target _blank // hide spinner on target _blank
$('[target="_blank"],.external').on('click submit', () => { $('[target="_blank"],.external').on('click submit', () => {
setTimeout(() => { setTimeout(() => {
Spinner.hide(() => { Spinner.hide(() => {
$Body.addClass('loaded'); $Body.addClass('loaded');
}); });
}, 1000); }, 1000);
}); });
W.MainUI = MainUI;
return MainUI; console.clear();
console.info(
'%cUI Kit: https://github.com/a2nt/webpack-bootstrap-ui-kit by Tony Air (tony@twma.pro)',
'color:yellow;font-size:16px',
);
console.groupCollapsed('Events');
Object.keys(Events).forEach((k) => {
console.info(k + ': ' + Events[k]);
});
console.groupEnd('Events');
console.groupCollapsed('Consts');
Object.keys(Consts).forEach((k) => {
console.info(k + ': ' + Consts[k]);
});
console.groupEnd('Events');
W.MainUI = MainUI;
return MainUI;
})($); })($);
export default MainUI; export default MainUI;