| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246 |
- /*!
- Justified Gallery
- Version: 3.8.1
- Plugin URL: http://miromannino.github.io/Justified-Gallery/
- License: Copyright (c) 2020 Miro Mannino | Released under the MIT License
- !*/
- (function (factory) {
- if (typeof define === 'function' && define.amd) {
- // AMD. Register as an anonymous module.
- define(['jquery'], factory);
- } else if (typeof module === 'object' && module.exports) {
- // Node/CommonJS
- module.exports = function (root, jQuery) {
- if (jQuery === undefined) {
- // require('jQuery') returns a factory that requires window to
- // build a jQuery instance, we normalize how we use modules
- // that require this pattern but the window provided is a noop
- // if it's defined (how jquery works)
- if (typeof window !== 'undefined') {
- jQuery = require('jquery');
- }
- else {
- jQuery = require('jquery')(root);
- }
- }
- factory(jQuery);
- return jQuery;
- };
- } else {
- // Browser globals
- factory(jQuery);
- }
- }(function ($) {
- /**
- * Justified Gallery controller constructor
- *
- * @param $gallery the gallery to build
- * @param settings the settings (the defaults are in JustifiedGallery.defaults)
- * @constructor
- */
- var JustifiedGallery = function ($gallery, settings) {
-
- this.settings = settings;
- this.checkSettings();
-
- this.imgAnalyzerTimeout = null;
- this.entries = null;
- this.buildingRow = {
- entriesBuff: [],
- width: 0,
- height: 0,
- aspectRatio: 0
- };
- this.lastFetchedEntry = null;
- this.lastAnalyzedIndex = -1;
- this.yield = {
- every: 2, // do a flush every n flushes (must be greater than 1)
- flushed: 0 // flushed rows without a yield
- };
- this.border = settings.border >= 0 ? settings.border : settings.margins;
- this.maxRowHeight = this.retrieveMaxRowHeight();
- this.suffixRanges = this.retrieveSuffixRanges();
- this.offY = this.border;
- this.rows = 0;
- this.spinner = {
- phase: 0,
- timeSlot: 150,
- $el: $('<div class="jg-spinner"><span></span><span></span><span></span></div>'),
- intervalId: null
- };
- this.scrollBarOn = false;
- this.checkWidthIntervalId = null;
- this.galleryWidth = $gallery.width();
- this.$gallery = $gallery;
-
- };
-
- /** @returns {String} the best suffix given the width and the height */
- JustifiedGallery.prototype.getSuffix = function (width, height) {
- var longestSide, i;
- longestSide = (width > height) ? width : height;
- for (i = 0; i < this.suffixRanges.length; i++) {
- if (longestSide <= this.suffixRanges[i]) {
- return this.settings.sizeRangeSuffixes[this.suffixRanges[i]];
- }
- }
- return this.settings.sizeRangeSuffixes[this.suffixRanges[i - 1]];
- };
-
- /**
- * Remove the suffix from the string
- *
- * @returns {string} a new string without the suffix
- */
- JustifiedGallery.prototype.removeSuffix = function (str, suffix) {
- return str.substring(0, str.length - suffix.length);
- };
-
- /**
- * @returns {boolean} a boolean to say if the suffix is contained in the str or not
- */
- JustifiedGallery.prototype.endsWith = function (str, suffix) {
- return str.indexOf(suffix, str.length - suffix.length) !== -1;
- };
-
- /**
- * Get the used suffix of a particular url
- *
- * @param str
- * @returns {String} return the used suffix
- */
- JustifiedGallery.prototype.getUsedSuffix = function (str) {
- for (var si in this.settings.sizeRangeSuffixes) {
- if (this.settings.sizeRangeSuffixes.hasOwnProperty(si)) {
- if (this.settings.sizeRangeSuffixes[si].length === 0) continue;
- if (this.endsWith(str, this.settings.sizeRangeSuffixes[si])) return this.settings.sizeRangeSuffixes[si];
- }
- }
- return '';
- };
-
- /**
- * Given an image src, with the width and the height, returns the new image src with the
- * best suffix to show the best quality thumbnail.
- *
- * @returns {String} the suffix to use
- */
- JustifiedGallery.prototype.newSrc = function (imageSrc, imgWidth, imgHeight, image) {
- var newImageSrc;
-
- if (this.settings.thumbnailPath) {
- newImageSrc = this.settings.thumbnailPath(imageSrc, imgWidth, imgHeight, image);
- } else {
- var matchRes = imageSrc.match(this.settings.extension);
- var ext = (matchRes !== null) ? matchRes[0] : '';
- newImageSrc = imageSrc.replace(this.settings.extension, '');
- newImageSrc = this.removeSuffix(newImageSrc, this.getUsedSuffix(newImageSrc));
- newImageSrc += this.getSuffix(imgWidth, imgHeight) + ext;
- }
-
- return newImageSrc;
- };
-
- /**
- * Shows the images that is in the given entry
- *
- * @param $entry the entry
- * @param callback the callback that is called when the show animation is finished
- */
- JustifiedGallery.prototype.showImg = function ($entry, callback) {
- if (this.settings.cssAnimation) {
- $entry.addClass('jg-entry-visible');
- if (callback) callback();
- } else {
- $entry.stop().fadeTo(this.settings.imagesAnimationDuration, 1.0, callback);
- $entry.find(this.settings.imgSelector).stop().fadeTo(this.settings.imagesAnimationDuration, 1.0, callback);
- }
- };
-
- /**
- * Extract the image src form the image, looking from the 'safe-src', and if it can't be found, from the
- * 'src' attribute. It saves in the image data the 'jg.originalSrc' field, with the extracted src.
- *
- * @param $image the image to analyze
- * @returns {String} the extracted src
- */
- JustifiedGallery.prototype.extractImgSrcFromImage = function ($image) {
- var imageSrc = $image.data('safe-src');
- var imageSrcLoc = 'data-safe-src';
- if (typeof imageSrc === 'undefined') {
- imageSrc = $image.attr('src');
- imageSrcLoc = 'src';
- }
- $image.data('jg.originalSrc', imageSrc); // this is saved for the destroy method
- $image.data('jg.src', imageSrc); // this will change overtime
- $image.data('jg.originalSrcLoc', imageSrcLoc); // this is saved for the destroy method
- return imageSrc;
- };
-
- /** @returns {jQuery} the image in the given entry */
- JustifiedGallery.prototype.imgFromEntry = function ($entry) {
- var $img = $entry.find(this.settings.imgSelector);
- return $img.length === 0 ? null : $img;
- };
-
- /** @returns {jQuery} the caption in the given entry */
- JustifiedGallery.prototype.captionFromEntry = function ($entry) {
- var $caption = $entry.find('> .jg-caption');
- return $caption.length === 0 ? null : $caption;
- };
-
- /**
- * Display the entry
- *
- * @param {jQuery} $entry the entry to display
- * @param {int} x the x position where the entry must be positioned
- * @param y the y position where the entry must be positioned
- * @param imgWidth the image width
- * @param imgHeight the image height
- * @param rowHeight the row height of the row that owns the entry
- */
- JustifiedGallery.prototype.displayEntry = function ($entry, x, y, imgWidth, imgHeight, rowHeight) {
- $entry.width(imgWidth);
- $entry.height(rowHeight);
- $entry.css('top', y);
- $entry.css('left', x);
-
- var $image = this.imgFromEntry($entry);
- if ($image !== null) {
- $image.css('width', imgWidth);
- $image.css('height', imgHeight);
- $image.css('margin-left', - imgWidth / 2);
- $image.css('margin-top', - imgHeight / 2);
-
- // Image reloading for an high quality of thumbnails
- var imageSrc = $image.data('jg.src');
- if (imageSrc) {
- imageSrc = this.newSrc(imageSrc, imgWidth, imgHeight, $image[0]);
-
- $image.one('error', function () {
- this.resetImgSrc($image); //revert to the original thumbnail
- });
-
- var loadNewImage = function () {
- // if (imageSrc !== newImageSrc) {
- $image.attr('src', imageSrc);
- // }
- };
-
- if ($entry.data('jg.loaded') === 'skipped' && imageSrc) {
- this.onImageEvent(imageSrc, (function() {
- this.showImg($entry, loadNewImage); //load the new image after the fadeIn
- $entry.data('jg.loaded', true);
- }).bind(this));
- } else {
- this.showImg($entry, loadNewImage); //load the new image after the fadeIn
- }
-
- }
-
- } else {
- this.showImg($entry);
- }
-
- this.displayEntryCaption($entry);
- };
-
- /**
- * Display the entry caption. If the caption element doesn't exists, it creates the caption using the 'alt'
- * or the 'title' attributes.
- *
- * @param {jQuery} $entry the entry to process
- */
- JustifiedGallery.prototype.displayEntryCaption = function ($entry) {
- var $image = this.imgFromEntry($entry);
- if ($image !== null && this.settings.captions) {
- var $imgCaption = this.captionFromEntry($entry);
-
- // Create it if it doesn't exists
- if ($imgCaption === null) {
- var caption = $image.attr('alt');
- if (!this.isValidCaption(caption)) caption = $entry.attr('title');
- if (this.isValidCaption(caption)) { // Create only we found something
- $imgCaption = $('<div class="jg-caption">' + caption + '</div>');
- $entry.append($imgCaption);
- $entry.data('jg.createdCaption', true);
- }
- }
-
- // Create events (we check again the $imgCaption because it can be still inexistent)
- if ($imgCaption !== null) {
- if (!this.settings.cssAnimation) $imgCaption.stop().fadeTo(0, this.settings.captionSettings.nonVisibleOpacity);
- this.addCaptionEventsHandlers($entry);
- }
- } else {
- this.removeCaptionEventsHandlers($entry);
- }
- };
-
- /**
- * Validates the caption
- *
- * @param caption The caption that should be validated
- * @return {boolean} Validation result
- */
- JustifiedGallery.prototype.isValidCaption = function (caption) {
- return (typeof caption !== 'undefined' && caption.length > 0);
- };
-
- /**
- * The callback for the event 'mouseenter'. It assumes that the event currentTarget is an entry.
- * It shows the caption using jQuery (or using CSS if it is configured so)
- *
- * @param {Event} eventObject the event object
- */
- JustifiedGallery.prototype.onEntryMouseEnterForCaption = function (eventObject) {
- var $caption = this.captionFromEntry($(eventObject.currentTarget));
- if (this.settings.cssAnimation) {
- $caption.addClass('jg-caption-visible').removeClass('jg-caption-hidden');
- } else {
- $caption.stop().fadeTo(this.settings.captionSettings.animationDuration,
- this.settings.captionSettings.visibleOpacity);
- }
- };
-
- /**
- * The callback for the event 'mouseleave'. It assumes that the event currentTarget is an entry.
- * It hides the caption using jQuery (or using CSS if it is configured so)
- *
- * @param {Event} eventObject the event object
- */
- JustifiedGallery.prototype.onEntryMouseLeaveForCaption = function (eventObject) {
- var $caption = this.captionFromEntry($(eventObject.currentTarget));
- if (this.settings.cssAnimation) {
- $caption.removeClass('jg-caption-visible').removeClass('jg-caption-hidden');
- } else {
- $caption.stop().fadeTo(this.settings.captionSettings.animationDuration,
- this.settings.captionSettings.nonVisibleOpacity);
- }
- };
-
- /**
- * Add the handlers of the entry for the caption
- *
- * @param $entry the entry to modify
- */
- JustifiedGallery.prototype.addCaptionEventsHandlers = function ($entry) {
- var captionMouseEvents = $entry.data('jg.captionMouseEvents');
- if (typeof captionMouseEvents === 'undefined') {
- captionMouseEvents = {
- mouseenter: $.proxy(this.onEntryMouseEnterForCaption, this),
- mouseleave: $.proxy(this.onEntryMouseLeaveForCaption, this)
- };
- $entry.on('mouseenter', undefined, undefined, captionMouseEvents.mouseenter);
- $entry.on('mouseleave', undefined, undefined, captionMouseEvents.mouseleave);
- $entry.data('jg.captionMouseEvents', captionMouseEvents);
- }
- };
-
- /**
- * Remove the handlers of the entry for the caption
- *
- * @param $entry the entry to modify
- */
- JustifiedGallery.prototype.removeCaptionEventsHandlers = function ($entry) {
- var captionMouseEvents = $entry.data('jg.captionMouseEvents');
- if (typeof captionMouseEvents !== 'undefined') {
- $entry.off('mouseenter', undefined, captionMouseEvents.mouseenter);
- $entry.off('mouseleave', undefined, captionMouseEvents.mouseleave);
- $entry.removeData('jg.captionMouseEvents');
- }
- };
-
- /**
- * Clear the building row data to be used for a new row
- */
- JustifiedGallery.prototype.clearBuildingRow = function () {
- this.buildingRow.entriesBuff = [];
- this.buildingRow.aspectRatio = 0;
- this.buildingRow.width = 0;
- };
-
- /**
- * Justify the building row, preparing it to
- *
- * @param isLastRow
- * @param hiddenRow undefined or false for normal behavior. hiddenRow = true to hide the row.
- * @returns a boolean to know if the row has been justified or not
- */
- JustifiedGallery.prototype.prepareBuildingRow = function (isLastRow, hiddenRow) {
- var i, $entry, imgAspectRatio, newImgW, newImgH, justify = true;
- var minHeight = 0;
- var availableWidth = this.galleryWidth - 2 * this.border - (
- (this.buildingRow.entriesBuff.length - 1) * this.settings.margins);
- var rowHeight = availableWidth / this.buildingRow.aspectRatio;
- var defaultRowHeight = this.settings.rowHeight;
- var justifiable = this.buildingRow.width / availableWidth > this.settings.justifyThreshold;
-
- //Skip the last row if we can't justify it and the lastRow == 'hide'
- if (hiddenRow || (isLastRow && this.settings.lastRow === 'hide' && !justifiable)) {
- for (i = 0; i < this.buildingRow.entriesBuff.length; i++) {
- $entry = this.buildingRow.entriesBuff[i];
- if (this.settings.cssAnimation)
- $entry.removeClass('jg-entry-visible');
- else {
- $entry.stop().fadeTo(0, 0.1);
- $entry.find('> img, > a > img').fadeTo(0, 0);
- }
- }
- return -1;
- }
-
- // With lastRow = nojustify, justify if is justificable (the images will not become too big)
- if (isLastRow && !justifiable && this.settings.lastRow !== 'justify' && this.settings.lastRow !== 'hide') {
- justify = false;
-
- if (this.rows > 0) {
- defaultRowHeight = (this.offY - this.border - this.settings.margins * this.rows) / this.rows;
- justify = defaultRowHeight * this.buildingRow.aspectRatio / availableWidth > this.settings.justifyThreshold;
- }
- }
-
- for (i = 0; i < this.buildingRow.entriesBuff.length; i++) {
- $entry = this.buildingRow.entriesBuff[i];
- imgAspectRatio = $entry.data('jg.width') / $entry.data('jg.height');
-
- if (justify) {
- newImgW = (i === this.buildingRow.entriesBuff.length - 1) ? availableWidth : rowHeight * imgAspectRatio;
- newImgH = rowHeight;
- } else {
- newImgW = defaultRowHeight * imgAspectRatio;
- newImgH = defaultRowHeight;
- }
-
- availableWidth -= Math.round(newImgW);
- $entry.data('jg.jwidth', Math.round(newImgW));
- $entry.data('jg.jheight', Math.ceil(newImgH));
- if (i === 0 || minHeight > newImgH) minHeight = newImgH;
- }
-
- this.buildingRow.height = minHeight;
- return justify;
- };
-
- /**
- * Flush a row: justify it, modify the gallery height accordingly to the row height
- *
- * @param isLastRow
- * @param hiddenRow undefined or false for normal behavior. hiddenRow = true to hide the row.
- */
- JustifiedGallery.prototype.flushRow = function (isLastRow, hiddenRow) {
- var settings = this.settings;
- var $entry, buildingRowRes, offX = this.border, i;
-
- buildingRowRes = this.prepareBuildingRow(isLastRow, hiddenRow);
- if (hiddenRow || (isLastRow && settings.lastRow === 'hide' && buildingRowRes === -1)) {
- this.clearBuildingRow();
- return;
- }
-
- if (this.maxRowHeight) {
- if (this.maxRowHeight < this.buildingRow.height) this.buildingRow.height = this.maxRowHeight;
- }
-
- //Align last (unjustified) row
- if (isLastRow && (settings.lastRow === 'center' || settings.lastRow === 'right')) {
- var availableWidth = this.galleryWidth - 2 * this.border - (this.buildingRow.entriesBuff.length - 1) * settings.margins;
-
- for (i = 0; i < this.buildingRow.entriesBuff.length; i++) {
- $entry = this.buildingRow.entriesBuff[i];
- availableWidth -= $entry.data('jg.jwidth');
- }
-
- if (settings.lastRow === 'center')
- offX += Math.round(availableWidth / 2);
- else if (settings.lastRow === 'right')
- offX += availableWidth;
- }
-
- var lastEntryIdx = this.buildingRow.entriesBuff.length - 1;
- for (i = 0; i <= lastEntryIdx; i++) {
- $entry = this.buildingRow.entriesBuff[this.settings.rtl ? lastEntryIdx - i : i];
- this.displayEntry($entry, offX, this.offY, $entry.data('jg.jwidth'), $entry.data('jg.jheight'), this.buildingRow.height);
- offX += $entry.data('jg.jwidth') + settings.margins;
- }
-
- //Gallery Height
- this.galleryHeightToSet = this.offY + this.buildingRow.height + this.border;
- this.setGalleryTempHeight(this.galleryHeightToSet + this.getSpinnerHeight());
-
- if (!isLastRow || (this.buildingRow.height <= settings.rowHeight && buildingRowRes)) {
- //Ready for a new row
- this.offY += this.buildingRow.height + settings.margins;
- this.rows += 1;
- this.clearBuildingRow();
- this.settings.triggerEvent.call(this, 'jg.rowflush');
- }
- };
-
-
- // Scroll position not restoring: https://github.com/miromannino/Justified-Gallery/issues/221
- var galleryPrevStaticHeight = 0;
-
- JustifiedGallery.prototype.rememberGalleryHeight = function () {
- galleryPrevStaticHeight = this.$gallery.height();
- this.$gallery.height(galleryPrevStaticHeight);
- };
-
- // grow only
- JustifiedGallery.prototype.setGalleryTempHeight = function (height) {
- galleryPrevStaticHeight = Math.max(height, galleryPrevStaticHeight);
- this.$gallery.height(galleryPrevStaticHeight);
- };
-
- JustifiedGallery.prototype.setGalleryFinalHeight = function (height) {
- galleryPrevStaticHeight = height;
- this.$gallery.height(height);
- };
-
- /**
- * Checks the width of the gallery container, to know if a new justification is needed
- */
- JustifiedGallery.prototype.checkWidth = function () {
- this.checkWidthIntervalId = setInterval($.proxy(function () {
-
- // if the gallery is not currently visible, abort.
- if (!this.$gallery.is(":visible")) return;
-
- var galleryWidth = parseFloat(this.$gallery.width());
- if (Math.abs(galleryWidth - this.galleryWidth) > this.settings.refreshSensitivity) {
- this.galleryWidth = galleryWidth;
- this.rewind();
-
- this.rememberGalleryHeight();
-
- // Restart to analyze
- this.startImgAnalyzer(true);
- }
- }, this), this.settings.refreshTime);
- };
-
- /**
- * @returns {boolean} a boolean saying if the spinner is active or not
- */
- JustifiedGallery.prototype.isSpinnerActive = function () {
- return this.spinner.intervalId !== null;
- };
-
- /**
- * @returns {int} the spinner height
- */
- JustifiedGallery.prototype.getSpinnerHeight = function () {
- return this.spinner.$el.innerHeight();
- };
-
- /**
- * Stops the spinner animation and modify the gallery height to exclude the spinner
- */
- JustifiedGallery.prototype.stopLoadingSpinnerAnimation = function () {
- clearInterval(this.spinner.intervalId);
- this.spinner.intervalId = null;
- this.setGalleryTempHeight(this.$gallery.height() - this.getSpinnerHeight());
- this.spinner.$el.detach();
- };
-
- /**
- * Starts the spinner animation
- */
- JustifiedGallery.prototype.startLoadingSpinnerAnimation = function () {
- var spinnerContext = this.spinner;
- var $spinnerPoints = spinnerContext.$el.find('span');
- clearInterval(spinnerContext.intervalId);
- this.$gallery.append(spinnerContext.$el);
- this.setGalleryTempHeight(this.offY + this.buildingRow.height + this.getSpinnerHeight());
- spinnerContext.intervalId = setInterval(function () {
- if (spinnerContext.phase < $spinnerPoints.length) {
- $spinnerPoints.eq(spinnerContext.phase).fadeTo(spinnerContext.timeSlot, 1);
- } else {
- $spinnerPoints.eq(spinnerContext.phase - $spinnerPoints.length).fadeTo(spinnerContext.timeSlot, 0);
- }
- spinnerContext.phase = (spinnerContext.phase + 1) % ($spinnerPoints.length * 2);
- }, spinnerContext.timeSlot);
- };
-
- /**
- * Rewind the image analysis to start from the first entry.
- */
- JustifiedGallery.prototype.rewind = function () {
- this.lastFetchedEntry = null;
- this.lastAnalyzedIndex = -1;
- this.offY = this.border;
- this.rows = 0;
- this.clearBuildingRow();
- };
-
- /**
- * @returns {String} `settings.selector` rejecting spinner element
- */
- JustifiedGallery.prototype.getSelectorWithoutSpinner = function () {
- return this.settings.selector + ', div:not(.jg-spinner)';
- };
-
- /**
- * @returns {Array} all entries matched by `settings.selector`
- */
- JustifiedGallery.prototype.getAllEntries = function () {
- var selector = this.getSelectorWithoutSpinner();
- return this.$gallery.children(selector).toArray();
- };
-
- /**
- * Update the entries searching it from the justified gallery HTML element
- *
- * @param norewind if norewind only the new entries will be changed (i.e. randomized, sorted or filtered)
- * @returns {boolean} true if some entries has been founded
- */
- JustifiedGallery.prototype.updateEntries = function (norewind) {
- var newEntries;
-
- if (norewind && this.lastFetchedEntry != null) {
- var selector = this.getSelectorWithoutSpinner();
- newEntries = $(this.lastFetchedEntry).nextAll(selector).toArray();
- } else {
- this.entries = [];
- newEntries = this.getAllEntries();
- }
-
- if (newEntries.length > 0) {
-
- // Sort or randomize
- if ($.isFunction(this.settings.sort)) {
- newEntries = this.sortArray(newEntries);
- } else if (this.settings.randomize) {
- newEntries = this.shuffleArray(newEntries);
- }
- this.lastFetchedEntry = newEntries[newEntries.length - 1];
-
- // Filter
- if (this.settings.filter) {
- newEntries = this.filterArray(newEntries);
- } else {
- this.resetFilters(newEntries);
- }
-
- }
-
- this.entries = this.entries.concat(newEntries);
- return true;
- };
-
- /**
- * Apply the entries order to the DOM, iterating the entries and appending the images
- *
- * @param entries the entries that has been modified and that must be re-ordered in the DOM
- */
- JustifiedGallery.prototype.insertToGallery = function (entries) {
- var that = this;
- $.each(entries, function () {
- $(this).appendTo(that.$gallery);
- });
- };
-
- /**
- * Shuffle the array using the Fisher-Yates shuffle algorithm
- *
- * @param a the array to shuffle
- * @return the shuffled array
- */
- JustifiedGallery.prototype.shuffleArray = function (a) {
- var i, j, temp;
- for (i = a.length - 1; i > 0; i--) {
- j = Math.floor(Math.random() * (i + 1));
- temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
- this.insertToGallery(a);
- return a;
- };
-
- /**
- * Sort the array using settings.comparator as comparator
- *
- * @param a the array to sort (it is sorted)
- * @return the sorted array
- */
- JustifiedGallery.prototype.sortArray = function (a) {
- a.sort(this.settings.sort);
- this.insertToGallery(a);
- return a;
- };
-
- /**
- * Reset the filters removing the 'jg-filtered' class from all the entries
- *
- * @param a the array to reset
- */
- JustifiedGallery.prototype.resetFilters = function (a) {
- for (var i = 0; i < a.length; i++) $(a[i]).removeClass('jg-filtered');
- };
-
- /**
- * Filter the entries considering theirs classes (if a string has been passed) or using a function for filtering.
- *
- * @param a the array to filter
- * @return the filtered array
- */
- JustifiedGallery.prototype.filterArray = function (a) {
- var settings = this.settings;
- if ($.type(settings.filter) === 'string') {
- // Filter only keeping the entries passed in the string
- return a.filter(function (el) {
- var $el = $(el);
- if ($el.is(settings.filter)) {
- $el.removeClass('jg-filtered');
- return true;
- } else {
- $el.addClass('jg-filtered').removeClass('jg-visible');
- return false;
- }
- });
- } else if ($.isFunction(settings.filter)) {
- // Filter using the passed function
- var filteredArr = a.filter(settings.filter);
- for (var i = 0; i < a.length; i++) {
- if (filteredArr.indexOf(a[i]) === -1) {
- $(a[i]).addClass('jg-filtered').removeClass('jg-visible');
- } else {
- $(a[i]).removeClass('jg-filtered');
- }
- }
- return filteredArr;
- }
- };
-
- /**
- * Revert the image src to the default value.
- */
- JustifiedGallery.prototype.resetImgSrc = function ($img) {
- if ($img.data('jg.originalSrcLoc') === 'src') {
- $img.attr('src', $img.data('jg.originalSrc'));
- } else {
- $img.attr('src', '');
- }
- };
-
- /**
- * Destroy the Justified Gallery instance.
- *
- * It clears all the css properties added in the style attributes. We doesn't backup the original
- * values for those css attributes, because it costs (performance) and because in general one
- * shouldn't use the style attribute for an uniform set of images (where we suppose the use of
- * classes). Creating a backup is also difficult because JG could be called multiple times and
- * with different style attributes.
- */
- JustifiedGallery.prototype.destroy = function () {
- clearInterval(this.checkWidthIntervalId);
- this.stopImgAnalyzerStarter();
-
- // Get fresh entries list since filtered entries are absent in `this.entries`
- $.each(this.getAllEntries(), $.proxy(function (_, entry) {
- var $entry = $(entry);
-
- // Reset entry style
- $entry.css('width', '');
- $entry.css('height', '');
- $entry.css('top', '');
- $entry.css('left', '');
- $entry.data('jg.loaded', undefined);
- $entry.removeClass('jg-entry jg-filtered jg-entry-visible');
-
- // Reset image style
- var $img = this.imgFromEntry($entry);
- if ($img) {
- $img.css('width', '');
- $img.css('height', '');
- $img.css('margin-left', '');
- $img.css('margin-top', '');
- this.resetImgSrc($img);
- $img.data('jg.originalSrc', undefined);
- $img.data('jg.originalSrcLoc', undefined);
- $img.data('jg.src', undefined);
- }
-
- // Remove caption
- this.removeCaptionEventsHandlers($entry);
- var $caption = this.captionFromEntry($entry);
- if ($entry.data('jg.createdCaption')) {
- // remove also the caption element (if created by jg)
- $entry.data('jg.createdCaption', undefined);
- if ($caption !== null) $caption.remove();
- } else {
- if ($caption !== null) $caption.fadeTo(0, 1);
- }
-
- }, this));
-
- this.$gallery.css('height', '');
- this.$gallery.removeClass('justified-gallery');
- this.$gallery.data('jg.controller', undefined);
- this.settings.triggerEvent.call(this, 'jg.destroy');
- };
-
- /**
- * Analyze the images and builds the rows. It returns if it found an image that is not loaded.
- *
- * @param isForResize if the image analyzer is called for resizing or not, to call a different callback at the end
- */
- JustifiedGallery.prototype.analyzeImages = function (isForResize) {
- for (var i = this.lastAnalyzedIndex + 1; i < this.entries.length; i++) {
- var $entry = $(this.entries[i]);
- if ($entry.data('jg.loaded') === true || $entry.data('jg.loaded') === 'skipped') {
- var availableWidth = this.galleryWidth - 2 * this.border - (
- (this.buildingRow.entriesBuff.length - 1) * this.settings.margins);
- var imgAspectRatio = $entry.data('jg.width') / $entry.data('jg.height');
-
- this.buildingRow.entriesBuff.push($entry);
- this.buildingRow.aspectRatio += imgAspectRatio;
- this.buildingRow.width += imgAspectRatio * this.settings.rowHeight;
- this.lastAnalyzedIndex = i;
-
- if (availableWidth / (this.buildingRow.aspectRatio + imgAspectRatio) < this.settings.rowHeight) {
- this.flushRow(false, this.settings.maxRowsCount > 0 && this.rows === this.settings.maxRowsCount);
-
- if (++this.yield.flushed >= this.yield.every) {
- this.startImgAnalyzer(isForResize);
- return;
- }
- }
- } else if ($entry.data('jg.loaded') !== 'error') {
- return;
- }
- }
-
- // Last row flush (the row is not full)
- if (this.buildingRow.entriesBuff.length > 0) {
- this.flushRow(true, this.settings.maxRowsCount > 0 && this.rows === this.settings.maxRowsCount);
- }
-
- if (this.isSpinnerActive()) {
- this.stopLoadingSpinnerAnimation();
- }
-
- /* Stop, if there is, the timeout to start the analyzeImages.
- This is because an image can be set loaded, and the timeout can be set,
- but this image can be analyzed yet.
- */
- this.stopImgAnalyzerStarter();
-
- this.setGalleryFinalHeight(this.galleryHeightToSet);
-
- //On complete callback
- this.settings.triggerEvent.call(this, isForResize ? 'jg.resize' : 'jg.complete');
- };
-
- /**
- * Stops any ImgAnalyzer starter (that has an assigned timeout)
- */
- JustifiedGallery.prototype.stopImgAnalyzerStarter = function () {
- this.yield.flushed = 0;
- if (this.imgAnalyzerTimeout !== null) {
- clearTimeout(this.imgAnalyzerTimeout);
- this.imgAnalyzerTimeout = null;
- }
- };
-
- /**
- * Starts the image analyzer. It is not immediately called to let the browser to update the view
- *
- * @param isForResize specifies if the image analyzer must be called for resizing or not
- */
- JustifiedGallery.prototype.startImgAnalyzer = function (isForResize) {
- var that = this;
- this.stopImgAnalyzerStarter();
- this.imgAnalyzerTimeout = setTimeout(function () {
- that.analyzeImages(isForResize);
- }, 0.001); // we can't start it immediately due to a IE different behaviour
- };
-
- /**
- * Checks if the image is loaded or not using another image object. We cannot use the 'complete' image property,
- * because some browsers, with a 404 set complete = true.
- *
- * @param imageSrc the image src to load
- * @param onLoad callback that is called when the image has been loaded
- * @param onError callback that is called in case of an error
- */
- JustifiedGallery.prototype.onImageEvent = function (imageSrc, onLoad, onError) {
- if (!onLoad && !onError) return;
-
- var memImage = new Image();
- var $memImage = $(memImage);
- if (onLoad) {
- $memImage.one('load', function () {
- $memImage.off('load error');
- onLoad(memImage);
- });
- }
- if (onError) {
- $memImage.one('error', function () {
- $memImage.off('load error');
- onError(memImage);
- });
- }
- memImage.src = imageSrc;
- };
-
- /**
- * Init of Justified Gallery controlled
- * It analyzes all the entries starting theirs loading and calling the image analyzer (that works with loaded images)
- */
- JustifiedGallery.prototype.init = function () {
- var imagesToLoad = false, skippedImages = false, that = this;
- $.each(this.entries, function (index, entry) {
- var $entry = $(entry);
- var $image = that.imgFromEntry($entry);
-
- $entry.addClass('jg-entry');
-
- if ($entry.data('jg.loaded') !== true && $entry.data('jg.loaded') !== 'skipped') {
-
- // Link Rel global overwrite
- if (that.settings.rel !== null) $entry.attr('rel', that.settings.rel);
-
- // Link Target global overwrite
- if (that.settings.target !== null) $entry.attr('target', that.settings.target);
-
- if ($image !== null) {
-
- // Image src
- var imageSrc = that.extractImgSrcFromImage($image);
-
- /* If we have the height and the width, we don't wait that the image is loaded,
- but we start directly with the justification */
- if (that.settings.waitThumbnailsLoad === false || !imageSrc) {
- var width = parseFloat($image.attr('width'));
- var height = parseFloat($image.attr('height'));
- if ($image.prop('tagName') === 'svg') {
- width = parseFloat($image[0].getBBox().width);
- height = parseFloat($image[0].getBBox().height);
- }
- if (!isNaN(width) && !isNaN(height)) {
- $entry.data('jg.width', width);
- $entry.data('jg.height', height);
- $entry.data('jg.loaded', 'skipped');
- skippedImages = true;
- that.startImgAnalyzer(false);
- return true; // continue
- }
- }
-
- $entry.data('jg.loaded', false);
- imagesToLoad = true;
-
- // Spinner start
- if (!that.isSpinnerActive()) that.startLoadingSpinnerAnimation();
-
- that.onImageEvent(imageSrc, function (loadImg) { // image loaded
- $entry.data('jg.width', loadImg.width);
- $entry.data('jg.height', loadImg.height);
- $entry.data('jg.loaded', true);
- that.startImgAnalyzer(false);
- }, function () { // image load error
- $entry.data('jg.loaded', 'error');
- that.startImgAnalyzer(false);
- });
-
- } else {
- $entry.data('jg.loaded', true);
- $entry.data('jg.width', $entry.width() | parseFloat($entry.css('width')) | 1);
- $entry.data('jg.height', $entry.height() | parseFloat($entry.css('height')) | 1);
- }
-
- }
-
- });
-
- if (!imagesToLoad && !skippedImages) this.startImgAnalyzer(false);
- this.checkWidth();
- };
-
- /**
- * Checks that it is a valid number. If a string is passed it is converted to a number
- *
- * @param settingContainer the object that contains the setting (to allow the conversion)
- * @param settingName the setting name
- */
- JustifiedGallery.prototype.checkOrConvertNumber = function (settingContainer, settingName) {
- if ($.type(settingContainer[settingName]) === 'string') {
- settingContainer[settingName] = parseFloat(settingContainer[settingName]);
- }
-
- if ($.type(settingContainer[settingName]) === 'number') {
- if (isNaN(settingContainer[settingName])) throw 'invalid number for ' + settingName;
- } else {
- throw settingName + ' must be a number';
- }
- };
-
- /**
- * Checks the sizeRangeSuffixes and, if necessary, converts
- * its keys from string (e.g. old settings with 'lt100') to int.
- */
- JustifiedGallery.prototype.checkSizeRangesSuffixes = function () {
- if ($.type(this.settings.sizeRangeSuffixes) !== 'object') {
- throw 'sizeRangeSuffixes must be defined and must be an object';
- }
-
- var suffixRanges = [];
- for (var rangeIdx in this.settings.sizeRangeSuffixes) {
- if (this.settings.sizeRangeSuffixes.hasOwnProperty(rangeIdx)) suffixRanges.push(rangeIdx);
- }
-
- var newSizeRngSuffixes = { 0: '' };
- for (var i = 0; i < suffixRanges.length; i++) {
- if ($.type(suffixRanges[i]) === 'string') {
- try {
- var numIdx = parseInt(suffixRanges[i].replace(/^[a-z]+/, ''), 10);
- newSizeRngSuffixes[numIdx] = this.settings.sizeRangeSuffixes[suffixRanges[i]];
- } catch (e) {
- throw 'sizeRangeSuffixes keys must contains correct numbers (' + e + ')';
- }
- } else {
- newSizeRngSuffixes[suffixRanges[i]] = this.settings.sizeRangeSuffixes[suffixRanges[i]];
- }
- }
-
- this.settings.sizeRangeSuffixes = newSizeRngSuffixes;
- };
-
- /**
- * check and convert the maxRowHeight setting
- * requires rowHeight to be already set
- * TODO: should be always called when only rowHeight is changed
- * @return number or null
- */
- JustifiedGallery.prototype.retrieveMaxRowHeight = function () {
- var newMaxRowHeight = null;
- var rowHeight = this.settings.rowHeight;
-
- if ($.type(this.settings.maxRowHeight) === 'string') {
- if (this.settings.maxRowHeight.match(/^[0-9]+%$/)) {
- newMaxRowHeight = rowHeight * parseFloat(this.settings.maxRowHeight.match(/^([0-9]+)%$/)[1]) / 100;
- } else {
- newMaxRowHeight = parseFloat(this.settings.maxRowHeight);
- }
- } else if ($.type(this.settings.maxRowHeight) === 'number') {
- newMaxRowHeight = this.settings.maxRowHeight;
- } else if (this.settings.maxRowHeight === false || this.settings.maxRowHeight == null) {
- return null;
- } else {
- throw 'maxRowHeight must be a number or a percentage';
- }
-
- // check if the converted value is not a number
- if (isNaN(newMaxRowHeight)) throw 'invalid number for maxRowHeight';
-
- // check values, maxRowHeight must be >= rowHeight
- if (newMaxRowHeight < rowHeight) newMaxRowHeight = rowHeight;
-
- return newMaxRowHeight;
- };
-
- /**
- * Checks the settings
- */
- JustifiedGallery.prototype.checkSettings = function () {
- this.checkSizeRangesSuffixes();
-
- this.checkOrConvertNumber(this.settings, 'rowHeight');
- this.checkOrConvertNumber(this.settings, 'margins');
- this.checkOrConvertNumber(this.settings, 'border');
- this.checkOrConvertNumber(this.settings, 'maxRowsCount');
-
- var lastRowModes = [
- 'justify',
- 'nojustify',
- 'left',
- 'center',
- 'right',
- 'hide'
- ];
- if (lastRowModes.indexOf(this.settings.lastRow) === -1) {
- throw 'lastRow must be one of: ' + lastRowModes.join(', ');
- }
-
- this.checkOrConvertNumber(this.settings, 'justifyThreshold');
- if (this.settings.justifyThreshold < 0 || this.settings.justifyThreshold > 1) {
- throw 'justifyThreshold must be in the interval [0,1]';
- }
- if ($.type(this.settings.cssAnimation) !== 'boolean') {
- throw 'cssAnimation must be a boolean';
- }
-
- if ($.type(this.settings.captions) !== 'boolean') throw 'captions must be a boolean';
- this.checkOrConvertNumber(this.settings.captionSettings, 'animationDuration');
-
- this.checkOrConvertNumber(this.settings.captionSettings, 'visibleOpacity');
- if (this.settings.captionSettings.visibleOpacity < 0 ||
- this.settings.captionSettings.visibleOpacity > 1) {
- throw 'captionSettings.visibleOpacity must be in the interval [0, 1]';
- }
-
- this.checkOrConvertNumber(this.settings.captionSettings, 'nonVisibleOpacity');
- if (this.settings.captionSettings.nonVisibleOpacity < 0 ||
- this.settings.captionSettings.nonVisibleOpacity > 1) {
- throw 'captionSettings.nonVisibleOpacity must be in the interval [0, 1]';
- }
-
- this.checkOrConvertNumber(this.settings, 'imagesAnimationDuration');
- this.checkOrConvertNumber(this.settings, 'refreshTime');
- this.checkOrConvertNumber(this.settings, 'refreshSensitivity');
- if ($.type(this.settings.randomize) !== 'boolean') throw 'randomize must be a boolean';
- if ($.type(this.settings.selector) !== 'string') throw 'selector must be a string';
-
- if (this.settings.sort !== false && !$.isFunction(this.settings.sort)) {
- throw 'sort must be false or a comparison function';
- }
-
- if (this.settings.filter !== false && !$.isFunction(this.settings.filter) &&
- $.type(this.settings.filter) !== 'string') {
- throw 'filter must be false, a string or a filter function';
- }
- };
-
- /**
- * It brings all the indexes from the sizeRangeSuffixes and it orders them. They are then sorted and returned.
- * @returns {Array} sorted suffix ranges
- */
- JustifiedGallery.prototype.retrieveSuffixRanges = function () {
- var suffixRanges = [];
- for (var rangeIdx in this.settings.sizeRangeSuffixes) {
- if (this.settings.sizeRangeSuffixes.hasOwnProperty(rangeIdx)) suffixRanges.push(parseInt(rangeIdx, 10));
- }
- suffixRanges.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; });
- return suffixRanges;
- };
-
- /**
- * Update the existing settings only changing some of them
- *
- * @param newSettings the new settings (or a subgroup of them)
- */
- JustifiedGallery.prototype.updateSettings = function (newSettings) {
- // In this case Justified Gallery has been called again changing only some options
- this.settings = $.extend({}, this.settings, newSettings);
- this.checkSettings();
-
- // As reported in the settings: negative value = same as margins, 0 = disabled
- this.border = this.settings.border >= 0 ? this.settings.border : this.settings.margins;
-
- this.maxRowHeight = this.retrieveMaxRowHeight();
- this.suffixRanges = this.retrieveSuffixRanges();
- };
-
- JustifiedGallery.prototype.defaults = {
- sizeRangeSuffixes: {}, /* e.g. Flickr configuration
- {
- 100: '_t', // used when longest is less than 100px
- 240: '_m', // used when longest is between 101px and 240px
- 320: '_n', // ...
- 500: '',
- 640: '_z',
- 1024: '_b' // used as else case because it is the last
- }
- */
- thumbnailPath: undefined, /* If defined, sizeRangeSuffixes is not used, and this function is used to determine the
- path relative to a specific thumbnail size. The function should accept respectively three arguments:
- current path, width and height */
- rowHeight: 120, // required? required to be > 0?
- maxRowHeight: false, // false or negative value to deactivate. Positive number to express the value in pixels,
- // A string '[0-9]+%' to express in percentage (e.g. 300% means that the row height
- // can't exceed 3 * rowHeight)
- maxRowsCount: 0, // maximum number of rows to be displayed (0 = disabled)
- margins: 1,
- border: -1, // negative value = same as margins, 0 = disabled, any other value to set the border
-
- lastRow: 'nojustify', // … which is the same as 'left', or can be 'justify', 'center', 'right' or 'hide'
-
- justifyThreshold: 0.90, /* if row width / available space > 0.90 it will be always justified
- * (i.e. lastRow setting is not considered) */
- waitThumbnailsLoad: true,
- captions: true,
- cssAnimation: true,
- imagesAnimationDuration: 500, // ignored with css animations
- captionSettings: { // ignored with css animations
- animationDuration: 500,
- visibleOpacity: 0.7,
- nonVisibleOpacity: 0.0
- },
- rel: null, // rewrite the rel of each analyzed links
- target: null, // rewrite the target of all links
- extension: /\.[^.\\/]+$/, // regexp to capture the extension of an image
- refreshTime: 200, // time interval (in ms) to check if the page changes its width
- refreshSensitivity: 0, // change in width allowed (in px) without re-building the gallery
- randomize: false,
- rtl: false, // right-to-left mode
- sort: false, /*
- - false: to do not sort
- - function: to sort them using the function as comparator (see Array.prototype.sort())
- */
- filter: false, /*
- - false, null or undefined: for a disabled filter
- - a string: an entry is kept if entry.is(filter string) returns true
- see jQuery's .is() function for further information
- - a function: invoked with arguments (entry, index, array). Return true to keep the entry, false otherwise.
- It follows the specifications of the Array.prototype.filter() function of JavaScript.
- */
- selector: 'a', // The selector that is used to know what are the entries of the gallery
- imgSelector: '> img, > a > img, > svg, > a > svg', // The selector that is used to know what are the images of each entry
- triggerEvent: function (event) { // This is called to trigger events, the default behavior is to call $.trigger
- this.$gallery.trigger(event); // Consider that 'this' is this set to the JustifiedGallery object, so it can
- } // access to fields such as $gallery, useful to trigger events with jQuery.
- };
-
- /**
- * Justified Gallery plugin for jQuery
- *
- * Events
- * - jg.complete : called when all the gallery has been created
- * - jg.resize : called when the gallery has been resized
- * - jg.rowflush : when a new row appears
- *
- * @param arg the action (or the settings) passed when the plugin is called
- * @returns {*} the object itself
- */
- $.fn.justifiedGallery = function (arg) {
- return this.each(function (index, gallery) {
- var $gallery = $(gallery);
- $gallery.addClass('justified-gallery');
- var controller = $gallery.data('jg.controller');
- if (typeof controller === 'undefined') {
- // Create controller and assign it to the object data
- if (typeof arg !== 'undefined' && arg !== null && $.type(arg) !== 'object') {
- if (arg === 'destroy') return; // Just a call to an unexisting object
- throw 'The argument must be an object';
- }
- controller = new JustifiedGallery($gallery, $.extend({}, JustifiedGallery.prototype.defaults, arg));
- $gallery.data('jg.controller', controller);
- } else if (arg === 'norewind') {
- // In this case we don't rewind: we analyze only the latest images (e.g. to complete the last unfinished row
- // ... left to be more readable
- } else if (arg === 'destroy') {
- controller.destroy();
- return;
- } else {
- // In this case Justified Gallery has been called again changing only some options
- controller.updateSettings(arg);
- controller.rewind();
- }
- // Update the entries list
- if (!controller.updateEntries(arg === 'norewind')) return;
- // Init justified gallery
- controller.init();
- });
- };
- }));
|