-
Notifications
You must be signed in to change notification settings - Fork 2
/
test-bundle.js
1119 lines (926 loc) · 30.6 KB
/
test-bundle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.mimeticTest = global.mimeticTest || {})));
}(this, (function (exports) { 'use strict';
/**
* Default config properties if not defined.
*/
const defaults = {
loadEvent: 'DOMContentLoaded', // Load type
mobileWidth: 640, // Width before disabling for mobile phone devices.
scaleDelay: 16, // Miliseconds between calls on resize.
preserveDevicePixelRatio: false, // Preserve the device pixel ratio on zoom.
rootSelector: 'html', // Use the HTML element as the root element.
onScale: undefined,
onZoom: undefined,
onResize: undefined,
cutOffWidth: 0, // The minimum width to disable resizing.
relativeDesignWidth: 1024, // The width relative to the font size.
enableScale: true,
/**
* This is important particularly when users maximises and reverts the browser
* window. This delay determines the debounce threshold but also the trailing
* edge call.
*/
lateDetectionDelay: 500,
};
// const { expect } = chai;
const defaultsKeys = Object.keys(defaults);
describe('defaults', () => {
it('Should consist of properties', () => {
expect(defaultsKeys).to.have.length.above(1);
});
});
/* _.-~-.
7'' Q..\
_7 (_
_7 _/ _q. /
_7 . ___ /VVvv-'_ .
7/ / /~- \_\\ '-._ .-' / //
./ ( /-~-/ ||'=.__ '::. '-~'' { ___ / // ./{
V V-~-~| || __''_ ':::. ''~-~.___.-'' _/ // / {_ / { /
VV/-~-~-| / \ .'__'. '. ':: ____ _ _ _ ''.
/ /~~~~|| VVV/ / \ ) \ | _ \ ___ ___(_)___(_) | | __ _ .::'
/ (~-~-~\\.-' / \' \::::. | |_) / _ \/ __| |_ / | | |/ _` | :::'
/..\ /..\__/ ' '::: | _ < __/\__ \ |/ /| | | | (_| | ::'
vVVv vVVv ': |_| \_\___||___/_/___|_|_|_|\__,_| ''
*/
/*
Version: 0.9.2
Description: A Better Window Resize
Author: Julien Etienne
Repository: https://github.com/julienetie/resizilla
*/
/**
* request-frame-modern - Optimal requestAnimationFrame & cancelAnimationFrame polyfill for modern development
* @version v2.0.3
* @license MIT
* Copyright Julien Etienne 2015 All Rights Reserved.
*/
// Initial time of the timing lapse.
/**
* volve - Tiny, Performant Debounce and Throttle Functions,
* License: MIT
* Copyright Julien Etienne 2016 All Rights Reserved.
* github: https://github.com/julienetie/volve
*‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
*/
/**
* Date.now polyfill.
* {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/now}
*/
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
/**
* Debounce a function call during repetiton.
* @param {Function} callback - Callback function.
* @param {Number} delay - Delay in milliseconds.
* @param {Boolean} lead - Leading or trailing.
* @return {Function} - The debounce function.
*/
function debounce(callback, delay, lead) {
var debounceRange = 0;
var currentTime;
var lastCall;
var setDelay;
var timeoutId;
const call = parameters => {
callback(parameters);
};
return parameters => {
if (lead) {
currentTime = Date.now();
if (currentTime > debounceRange) {
callback(parameters);
}
debounceRange = currentTime + delay;
} else {
/**
* setTimeout is only used with the trail option.
*/
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
call(parameters);
}, delay);
}
};
}
const objectAssignPolyfill = () => {
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
// We must check against these specific cases.
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
};
// Add the Object.assign polyfill.
objectAssignPolyfill();
// Obtains the window or global according to the environment.
const windowGlobal = typeof window !== 'undefined' ? window : typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global;
// A list of option names to make naming and renaming simple.
const optionNames = 'handler,delay,incept,useCapture,orientationchange'.split(',');
// Default options that correspond with the optionNames.
const defaults$2 = [() => {}, 16, false, false, true];
/**
* Each option name is paired with the option value
* @return {Object}
*/
const convertPairsToLiterals = (value, i) => ({
[optionNames[i]]: value });
/**
* Adds the window event with the provided options.
* Returns the same handler for removeEventListeners.
* @return {Function}
*/
const addWindowEvent = (handler, delay, incept, windowObject, useCapture) => {
const debounced = debounce(handler, delay, incept);
windowObject.addEventListener('resize', debounced, useCapture);
return debounced;
};
const destroyPartial = (directHandler, useCapture, windowObject) => {
const destroyAPI = type => {
if (!type || type === 'all') {
// Remove both event listeners.
windowObject.removeEventListener('resize', directHandler, useCapture);
windowObject.removeEventListener('orientationchange', directHandler, useCapture);
} else {
// Remove specific event listener.
windowObject.removeEventListener(type, directHandler, useCapture);
}
};
return destroyAPI;
};
/**
* Partially apply variables as defaults
* @param {Array} defaults - Array of consecutive defaults.
* @param {object} windowObject - The window | global object.
*/
const resizillaPartial = (defaults, windowObject) => {
/**
* The API
* @param {Function} handler - The callback to execute on resize
* @param {Number} delay - Debounce delay in milliseconds
* @param {Boolean} incept - Debounce style
* @param {Boolean} useCapture - Bubbling/ capture options for events
* @param {Boolean} orientationChange - respond on orientation change
*/
return function resizillaFinal(...APIParameters) {
// The unchosen excess defaults.
const excessDefaults = defaults.slice(APIParameters.length, defaults.length);
// Concatenate the API options with the excess defaults.
const optionValues = [...APIParameters, ...excessDefaults];
// Final options as an object.
const mergedOptions = Object.assign(...optionValues.map(convertPairsToLiterals));
// Destructured options.
const {
handler,
delay,
incept,
useCapture,
orientationChange
} = mergedOptions;
// A direct reference to the added handler.
const directHandler = addWindowEvent(handler, delay, incept, windowObject, useCapture);
// Adds orientationchange event if required.
if (orientationChange) {
windowObject.addEventListener('orientationchange', directHandler, useCapture);
}
// Returns an destroyAPI method to remove event listeners.
return {
destroy: destroyPartial(directHandler, useCapture, windowObject)
};
};
};
// Creates the Resizilla function.
const resizilla = resizillaPartial(defaults$2, windowGlobal);
const objectAssignPolyfill$1 = () => {
if (typeof Object.assign != 'function') {
(function() {
Object.assign = function(target) {
'use strict';
// We must check against these specific cases.
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
};
const objectFreezePolyfill = () => {
/**
* Object.freeze polyfill
* ES5 15.2.3.9
* {@link http://es5.github.com/#x15.2.3.9}
*/
if (!Object.freeze) {
Object.freeze = function freeze(object) {
if (Object(object) !== object) {
throw new TypeError('Object.freeze can only be called on Objects.');
}
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
};
/**
* CSS Fixed units with pixel values.
*/
const CSSFixedUnits = [{
unit: 'xx-small',
// 9 / 16
PXValue: 9,
}, {
unit: 'x-small',
// 10 / 16
PXValue: 10,
}, {
unit: 'small',
// 13 / 16
PXValue: 13,
}, {
unit: 'normal',
// 16 / 16
PXValue: 16,
}, {
unit: 'medium',
// 16 / 16
PXValue: 16,
}, {
unit: 'large',
// 18 / 16
PXValue: 18,
}, {
unit: 'x-large',
// 24 / 16
PXValue: 24,
}, {
unit: 'xx-large',
// 32 / 16
PXValue: 32,
}];
/**
* CSS Units with pixel factor.
*/
const CSSUnits = [{
unit: 'px',
// 1 / 16
PXFactor: 1,
}, {
unit: 'pt',
// 96 / 72 / 16
PXFactor: 1.33333333328,
}, {
unit: 'em',
// 1
PXFactor: 16,
}, {
unit: 'rem',
// 1
PXFactor: 16,
}, {
unit: 'cm',
// ???
PXFactor: 16,
}, {
unit: 'q',
// ???
PXFactor: 16,
}, {
unit: 'in',
// ???
PXFactor: 16,
}, {
unit: 'pc',
// 96 / 72 / 12 / 16
PXFactor: 0.11111111104,
}, {
unit: 'ex',
// ???
PXFactor: 16,
}, {
unit: 'ch',
// ???
PXFactor: 16,
}, {
unit: 'vw',
// Needs override.
PXFactor: 16,
}, {
unit: 'vh',
// Needs override.
PXFactor: 16,
}, {
unit: 'vmin',
// Needs override.
PXFactor: 16,
}, {
unit: 'vmax',
// Needs override.
PXFactor: 16,
}];
const windowRef = window;
const documentRef = windowRef.document;
// Checks if string or number is a number.
const isNumber = value => Number(value) === value;
// A very simple compose function.
const basicCompose = (a, b) => c => a(b(c));
// converts pixels to REM values.
const pxToRem = fontSizePx => parseInt(fontSizePx, 10) / 16;
// Is Function.
const isFunction = value => typeof value === 'function';
// Gets the element's root font size.
const getFontSize = element => windowRef.getComputedStyle(element.documentElement, null).getPropertyValue('font-size');
// Gets the root element.
const getRootElement = (element) => {
const elements = {
html: parent => parent.documentElement,
body: parent => parent.body,
};
if (element instanceof windowRef.Element) {
if (element.nodeType === 1) {
return element;
}
throw new Error('rootElement is not a valid element');
}
return elements[element] ? elements[element](documentRef) : documentRef.querySelector(element);
};
const aliasValueToPX = value => CSSFixedUnits.filter(
metricInfo => value === metricInfo.unit).shift().PXValue;
const CSSUnitsToPixels = (value) => {
if (isNumber(value)) {
return value;
}
const suffix = value.replace(/[^a-z]+/gi, '');
const numberValue = value.replace(/[^\d.]*/g, '');
const metricInfo = CSSUnits.filter(
info => suffix === info.unit).shift();
const PXValue = metricInfo ? numberValue * metricInfo.PXFactor : aliasValueToPX(value);
return parseInt(PXValue, 10);
};
/**
* Sets up intializeMimetic via partial application.
* @param {Function} document.
* @param {Function} getRootREMValue - Gets the root font-size in REM units.
* @param {Function} CSSUnitsToPixels - Converts any CSS units to pixels.
* @param {Function} setRootFontSize - Sets the new root font size.
* @param {Function} resizilla - Calls handler on window resize and orientationchange events.
*/
function initializeMimeticPartial(
document,
getRootREMValue,
CSSUnitsToPixels,
setRootFontSize,
resizilla,
) {
// A resize object to store MIMETIC's resizilla's requirements.
const resize = {};
/**
* The intializeMimetic function.
* @param {object} config - The API parameters.
*/
function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
mobileWidth,
scaleDelay,
cutOffWidth,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// mobileWidth in pixels.
const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
mobileWidthPX,
cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
}
/**
* Remove both event listeners set via resizilla.
*/
initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy();
/**
* Re-instate resizilla.
*/
initalizeMimeticFinal.prototype.revive = function revive() {
resize.resizilla = resizilla(() => {
setRootFontSize(resize.settings, resize.setRootFontSizeScope);
}, resize.scaleDelay, false);
};
return initalizeMimeticFinal;
}
/**
* Set Root Font Size.
*/
const setRootFontSizePartial = (resizeRootFontSize) => {
const windowRef = window;
const documentRef = windowRef.document;
let lastOuterWidth;
return ({
rootFontSize,
initialOuterWidth,
relativeDesignWidth,
mobileWidth,
cutOffWidth,
preserveDevicePixelRatio,
onScale,
onZoom,
onResize,
enableScale,
mobileWidthPX,
cutOffWidthPX,
lateDetectionDelay,
}, setRootFontSize) => {
// Real time DOM measurments.
const innerWidth = windowRef.innerWidth;
const outerWidth = windowRef.outerWidth;
const clientWidth = documentRef.documentElement.clientWidth;
const DPR = windowRef.devicePixelRatio;
// Ratio between the outer and client width.
const outerClientRatio = outerWidth / clientWidth;
// A calulated DPR within the proximity of 0.05. for devices (eg.safari)
// that have a fixed DPR.
// @TODO check on large display devices with DPRs greater than 1.
const OCRProximity = outerClientRatio < 1.05 && outerClientRatio > 0.95
? 1 : outerClientRatio;
// A calculated DPR safe for safari browsers.
const safariSafeDPR = Number((OCRProximity).toFixed(5));
// Legacy internet explorer devicePixelRatio.
const IEDPR = Number(windowRef.screen.deviceXDPI / windowRef.screen.logicalXDPI);
// The devicePixelRatio with polyfilled support.
const alt = DPR === 1 ? safariSafeDPR : DPR;
const calculatedDPR = Math.abs(IEDPR || alt);
// The real viewport width.
const viewportWidth = parseInt(clientWidth * calculatedDPR, 10);
// The default device pixel ratio.
const defaultDPR = Math.round(clientWidth * (calculatedDPR / outerWidth));
/**
* Set variable inital values if not yet set.
*/
if (lastOuterWidth === undefined) {
lastOuterWidth = initialOuterWidth;
}
/**
* The window width compared to the design width.
*/
const designWidthRatio = innerWidth / relativeDesignWidth;
/**
* The minimum veiwport size to not react to.
*/
const cutOff = cutOffWidthPX > mobileWidthPX ? cutOffWidthPX : mobileWidthPX;
/**
* Mutate on next available frame.
*/
resizeRootFontSize({
innerWidth,
outerWidth,
relativeDesignWidth,
cutOff,
designWidthRatio,
calculatedDPR,
rootFontSize,
enableScale,
preserveDevicePixelRatio,
onScale,
onZoom,
onResize,
viewportWidth,
defaultDPR,
lateDetectionDelay,
}, setRootFontSize);
/**
* Updated Outer browser dimensions.
*/
lastOuterWidth = outerWidth;
};
};
let wasLastBeyondMobileWidth = true;
let renderOnce;
/**
* Directly mutates the root font size of a given Element.
* @param
*/
const mutateRootFontSizePartial = rootElement => (
rootFontSizeFinal,
resizeWithoutZoom,
hasScaledOrDPRIsDefault,
isDevicePixelRatioDefault,
isAboveDesignWidth,
isBeyondCutoff,
enableScale,
) => {
if (hasScaledOrDPRIsDefault || renderOnce) {
if (renderOnce) {
renderOnce = false;
}
if (isBeyondCutoff) {
// Set the rootElement's font size if scale is enabled.
if (enableScale) {
// eslint-disable-next-line
rootElement.style.fontSize = rootFontSizeFinal.toFixed(4) + 'rem';
}
// Indicate that the viewport has exceeded the mobileWidth.
wasLastBeyondMobileWidth = true;
} else if (wasLastBeyondMobileWidth) {
/**
* Prevent odd behaviour when refreshed.
* By removing the style attribute once when
* within the mobileWidth.
*/
if (wasLastBeyondMobileWidth) {
rootElement.removeAttribute('style');
}
// Reset as within mobileWidth.
wasLastBeyondMobileWidth = false;
}
}
};
// Default root selector. Not an option.
const { rootSelector } = defaults;
// The root font element.
const rootElement = getRootElement(rootSelector);
/**
* Mutate root font size with pre-sets.
* @param {HTMLElement} rootElement - Root element option.
* @param {Boolean} rootElement - Enable scale option.
* @return {Function} mutateRootFontSize.
*/
const mutateRootFontSize = mutateRootFontSizePartial(rootElement);
let callbacksRequireValidation = true;
let hasScaleCallback = false;
let hasZoomCallback = false;
let hasResizeCallback = false;
const setCallbacks = (
APIParameters,
isBeyondCutoff,
resizeWithoutZoom,
onScale,
onZoom,
onResize,
) => {
// Validates callbacks once.
if (callbacksRequireValidation && isBeyondCutoff) {
callbacksRequireValidation = false;
hasScaleCallback = isFunction(onScale);
hasZoomCallback = isFunction(onZoom);
hasResizeCallback = isFunction(onResize);
}
// Action onScale during resize without zoom.
if (resizeWithoutZoom && hasScaleCallback) {
onScale(APIParameters);
}
// Action onZoom during resize without scale.
if (!resizeWithoutZoom && hasZoomCallback) {
onZoom(APIParameters);
}
// Action onResize during either zoom or scale.
if (hasResizeCallback) {
onResize(APIParameters);
}
};
let lastDevicePixelRatio;
let setRootFontSizeTimeoutId;
let lastOuterWidth;
/**
* Calculate and apply the new font size to the root element.
*/
const resizeRootFontSize = (settings, setRootFontSizeTail) => {
const {
innerWidth,
outerWidth,
relativeDesignWidth,
cutOff,
designWidthRatio,
calculatedDPR,
rootFontSize,
enableScale,
preserveDevicePixelRatio,
onScale,
onZoom,
onResize,
viewportWidth,
defaultDPR,
lateDetectionDelay,
} = settings;
// Assigns lastOuterWidth with an inital value, never expected to be zero.
if (!lastOuterWidth) {
lastOuterWidth = outerWidth;
}
// Calculates the devicePixelRatio as if the default was 1.
const normalizedDPR = (1 / defaultDPR) * calculatedDPR;
// The preserved or non-preserved DPR via API settings.
const evalDPR = preserveDevicePixelRatio ? calculatedDPR : normalizedDPR;
// Truthy if the browser is resized without being zoomed.
const resizeWithoutZoom = calculatedDPR === lastDevicePixelRatio;
// Check to see if the window is at the default zoom level.
const isDevicePixelRatioDefault = defaultDPR === calculatedDPR;
// Determine if the resize event was last with or without zoom.
const resizeWithoutZoom2 = outerWidth === lastOuterWidth;
const isAboveDesignWidth = innerWidth > relativeDesignWidth;
const isBeyondCutoff = innerWidth > cutOff;
const rootFontSizeFinal = rootFontSize * designWidthRatio * evalDPR;
const hasScaledOrDPRIsDefault = resizeWithoutZoom || isDevicePixelRatioDefault;
mutateRootFontSize(
rootFontSizeFinal,
resizeWithoutZoom,
hasScaledOrDPRIsDefault,
isDevicePixelRatioDefault,
isAboveDesignWidth,
isBeyondCutoff,
enableScale,
);
clearTimeout(setRootFontSizeTimeoutId);
if (resizeWithoutZoom2) {
// setRootFontSizeTail to be independently conditional.
if (setRootFontSizeTail) {
setRootFontSizeTimeoutId = setTimeout(
() => {
setRootFontSizeTail();
}, lateDetectionDelay,
);
}
}
// The parameters passed to each callback as an object.
const APIParameters = {
viewportWidth,
innerWidth,
evalDPR,
calculatedDPR,
normalizedDPR,
};
setCallbacks(
APIParameters,
isBeyondCutoff,
resizeWithoutZoom,
onScale,
onZoom,
onResize,
);
// Store the last device pixel ratio for future comparision.
lastDevicePixelRatio = calculatedDPR;
// Re-assign the lastOuterWidth.
lastOuterWidth = outerWidth;
};
/**
* Sets up mimetic via partial application.
* @param {Function} initializeMimetic - Initalizes MIMETIC function.
*/
const mimeticPartial = (initializeMimetic, defaults) => (configurationObj) => {
// Assing configuration as an object.
const configuration = configurationObj || {};
// Merge configuration into defaults.
const overriddenDefaults = Object.assign(defaults, configuration);
// Prevent config mutations.
const config = Object.freeze(overriddenDefaults);
// Default load to DOMContentLoaded if not opted.
const loadEventOption = config.loadEvent === 'load' ? 'load' : 'DOMContentLoaded';
// Initalize mimetic on load.
window.addEventListener(loadEventOption, () => initializeMimetic(config));
// Return kill and revive methods.
return {
kill() {
initializeMimetic.prototype.kill();
},
revive() {
initializeMimetic.prototype.revive();
},
};
};
// Object Assign polyfill.
objectAssignPolyfill$1();
// Object Freeze polyfill.
objectFreezePolyfill();
/*
initializeMimetic initalizes resizilla
(A window resize plugin) to call setRootFontSize
on window resize.
setRootFontSize -> resizeRootFontSize which does
`rootElement.style.fontSize = 'xrem';`
This function is initally called on resize.
*/
const setRootFontSize = setRootFontSizePartial(resizeRootFontSize);
// Gets the root element value in REM units.
const getRootREMValue = basicCompose(
pxToRem,
getFontSize,
);
/*
Called initally and on prototype.revivie() to
setup and implement resizilla's event listeners.
initalizeMimetic contains a kill method to remove
resizilla's event listeners and a revive method to
restart Mimetic's initalization.
*/
const initializeMimetic = initializeMimeticPartial(
document,
getRootREMValue,
CSSUnitsToPixels,
setRootFontSize,
resizilla,
);
// The MIMETIC API.
const mimetic = mimeticPartial(initializeMimetic, defaults);
const { kill, revive } = mimetic();
describe('mimetic', () => {
it('Should exist', () => {
expect(mimetic).to.be.a('function');
});
it('Should contain a kill method', () => {
expect(kill).to.be.a('function');
});
it('Should contain a revive method', () => {
expect(revive).to.be.a('function');
});
});
const preCalculatedValues = {
"innerWidth": 1024,
"outerWidth": 1024,
"isDevicePixelRatioDefault": true,
"relativeDesignWidth": 1024,
"cutOff": 640,
"rootElement": document.documentElement,
"designWidthRatio": 1,
"calculatedDPR": 1,
"rootFontSize": 1.5, // Root font size exagerated to x1.5 = '24px'
"enableScale": true,
"preserveDevicePixelRatio": false,
"viewportWidth": 1024,
"defaultDPR": 1
};
const emulated1080P = {
"innerWidth": 1920,
"outerWidth": 1920,
"isDevicePixelRatioDefault": true,
"relativeDesignWidth": 1024,
"cutOff": 640,
"rootElement": document.documentElement,
"designWidthRatio": 1.875,
"calculatedDPR": 1,
"rootFontSize": 1,
"enableScale": true,
"preserveDevicePixelRatio": false,
"viewportWidth": 1920,
"defaultDPR": 1
};
const mobile = {
"innerWidth": 300,
"outerWidth": 300,
"isDevicePixelRatioDefault": true,
"relativeDesignWidth": 1024,
"cutOff": 640,
"rootElement": document.documentElement,
"designWidthRatio": 0.2929, // innerWidth / relativeDesignWidth.
"calculatedDPR": 1,
"rootFontSize": 1,
"enableScale": true,
"preserveDevicePixelRatio": false,
"viewportWidth": 300,