This repository has been archived by the owner on Aug 30, 2018. It is now read-only.
/
timber.js.liquid
executable file
·496 lines (402 loc) · 15.1 KB
/
timber.js.liquid
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
/* Jonathan Snook - MIT License - https://github.com/snookca/prepareTransition */
(function(a){a.fn.prepareTransition=function(){return this.each(function(){var b=a(this);b.one("TransitionEnd webkitTransitionEnd transitionend oTransitionEnd",function(){b.removeClass("is-transitioning")});var c=["transition-duration","-moz-transition-duration","-webkit-transition-duration","-o-transition-duration"];var d=0;a.each(c,function(a,c){d=parseFloat(b.css(c))||d});if(d!=0){b.addClass("is-transitioning");b[0].offsetWidth}})}})(jQuery);
/* replaceUrlParam - http://stackoverflow.com/questions/7171099/how-to-replace-url-parameter-with-javascript-jquery */
function replaceUrlParam(e,r,a){var n=new RegExp("("+r+"=).*?(&|$)"),c=e;return c=e.search(n)>=0?e.replace(n,"$1"+a+"$2"):c+(c.indexOf("?")>0?"&":"?")+r+"="+a};
/*============================================================================
Money Format
- Shopify.format money is defined in option_selection.js.
If that file is not included, it is redefined here.
==============================================================================*/
if ((typeof Shopify) === 'undefined') { Shopify = {}; }
if (!Shopify.formatMoney) {
Shopify.formatMoney = function(cents, format) {
var value = '',
placeholderRegex = /\{\{\s*(\w+)\s*\}\}/,
formatString = (format || this.money_format);
if (typeof cents == 'string') {
cents = cents.replace('.','');
}
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
precision = defaultOption(precision, 2);
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) {
return 0;
}
number = (number/100.0).toFixed(precision);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1] ? (decimal + parts[1]) : '';
return dollars + cents;
}
switch(formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
};
}
// Timber functions
window.timber = window.timber || {};
timber.cacheSelectors = function () {
timber.cache = {
// General
$html : $('html'),
$body : $(document.body),
// Navigation
$navigation : $('#AccessibleNav'),
$mobileSubNavToggle : $('.mobile-nav__toggle'),
// Collection Pages
$changeView : $('.change-view'),
// Product Page
$productImage : $('#ProductPhotoImg'),
$thumbImages : $('#ProductThumbs').find('a.product-single__thumbnail'),
// Customer Pages
$recoverPasswordLink : $('#RecoverPassword'),
$hideRecoverPasswordLink : $('#HideRecoverPasswordLink'),
$recoverPasswordForm : $('#RecoverPasswordForm'),
$customerLoginForm : $('#CustomerLoginForm'),
$passwordResetSuccess : $('#ResetSuccess')
};
};
timber.init = function () {
FastClick.attach(document.body);
timber.cacheSelectors();
timber.accessibleNav();
timber.drawersInit();
timber.mobileNavToggle();
timber.productImageSwitch();
timber.responsiveVideos();
timber.collectionViews();
timber.loginForms();
};
timber.accessibleNav = function () {
var $nav = timber.cache.$navigation,
$allLinks = $nav.find('a'),
$topLevel = $nav.children('li').find('a'),
$parents = $nav.find('.site-nav--has-dropdown'),
$subMenuLinks = $nav.find('.site-nav__dropdown').find('a'),
activeClass = 'nav-hover',
focusClass = 'nav-focus';
// Mouseenter
$parents.on('mouseenter touchstart', function(evt) {
var $el = $(this);
if (!$el.hasClass(activeClass)) {
evt.preventDefault();
}
showDropdown($el);
});
// Mouseout
$parents.on('mouseleave', function() {
hideDropdown($(this));
});
$subMenuLinks.on('touchstart', function(evt) {
// Prevent touchstart on body from firing instead of link
evt.stopImmediatePropagation();
});
$allLinks.focus(function() {
handleFocus($(this));
});
$allLinks.blur(function() {
removeFocus($topLevel);
});
// accessibleNav private methods
function handleFocus ($el) {
var $subMenu = $el.next('ul'),
hasSubMenu = $subMenu.hasClass('sub-nav') ? true : false,
isSubItem = $('.site-nav__dropdown').has($el).length,
$newFocus = null;
// Add focus class for top level items, or keep menu shown
if (!isSubItem) {
removeFocus($topLevel);
addFocus($el);
} else {
$newFocus = $el.closest('.site-nav--has-dropdown').find('a');
addFocus($newFocus);
}
}
function showDropdown ($el) {
$el.addClass(activeClass);
setTimeout(function() {
timber.cache.$body.on('touchstart', function() {
hideDropdown($el);
});
}, 250);
}
function hideDropdown ($el) {
$el.removeClass(activeClass);
timber.cache.$body.off('touchstart');
}
function addFocus ($el) {
$el.addClass(focusClass);
}
function removeFocus ($el) {
$el.removeClass(focusClass);
}
};
timber.drawersInit = function () {
timber.LeftDrawer = new timber.Drawers('NavDrawer', 'left');
{% if settings.ajax_cart_method == "drawer" %}
timber.RightDrawer = new timber.Drawers('CartDrawer', 'right', {
'onDrawerOpen': ajaxCart.load
});
{% endif %}
};
timber.mobileNavToggle = function () {
timber.cache.$mobileSubNavToggle.on('click', function() {
$(this).parent().toggleClass('mobile-nav--expanded');
});
};
timber.getHash = function () {
return window.location.hash;
};
timber.productPage = function (options) {
var moneyFormat = options.money_format,
variant = options.variant,
selector = options.selector;
// Selectors
var $productImage = $('#ProductPhotoImg'),
$addToCart = $('#AddToCart'),
$productPrice = $('#ProductPrice'),
$comparePrice = $('#ComparePrice'),
$quantityElements = $('.quantity-selector, label + .js-qty'),
$addToCartText = $('#AddToCartText');
if (variant) {
// Update variant image, if one is set
if (variant.featured_image) {
var newImg = variant.featured_image,
el = $productImage[0];
Shopify.Image.switchImage(newImg, el, timber.switchImage);
}
// Select a valid variant if available
if (variant.available) {
// Available, enable the submit button, change text, show quantity elements
$addToCart.removeClass('disabled').prop('disabled', false);
$addToCartText.html({{ 'products.product.add_to_cart' | t | json }});
$quantityElements.show();
} else {
// Sold out, disable the submit button, change text, hide quantity elements
$addToCart.addClass('disabled').prop('disabled', true);
$addToCartText.html({{ 'products.product.sold_out' | t | json }});
$quantityElements.hide();
}
// Regardless of stock, update the product price
$productPrice.html( Shopify.formatMoney(variant.price, moneyFormat) );
// Also update and show the product's compare price if necessary
if (variant.compare_at_price > variant.price) {
$comparePrice
.html({{ 'products.product.compare_at' | t | json }} + ' ' + Shopify.formatMoney(variant.compare_at_price, moneyFormat))
.show();
} else {
$comparePrice.hide();
}
} else {
// The variant doesn't exist, disable submit button.
// This may be an error or notice that a specific variant is not available.
// To only show available variants, implement linked product options:
// - http://docs.shopify.com/manual/configuration/store-customization/advanced-navigation/linked-product-options
$addToCart.addClass('disabled').prop('disabled', true);
$addToCartText.html({{ 'products.product.unavailable' | t | json }});
$quantityElements.hide();
}
};
timber.productImageSwitch = function () {
if (timber.cache.$thumbImages.length) {
// Switch the main image with one of the thumbnails
// Note: this does not change the variant selected, just the image
timber.cache.$thumbImages.on('click', function(evt) {
evt.preventDefault();
var newImage = $(this).attr('href');
timber.switchImage(newImage, null, timber.cache.$productImage);
});
}
};
timber.switchImage = function (src, imgObject, el) {
// Make sure element is a jquery object
var $el = $(el);
$el.attr('src', src);
};
timber.responsiveVideos = function () {
var $iframeVideo = $('iframe[src*="youtube.com/embed"], iframe[src*="player.vimeo"]');
var $iframeReset = $iframeVideo.add('iframe#admin_bar_iframe');
$iframeVideo.each(function () {
// Add wrapper to make video responsive
$(this).wrap('<div class="video-wrapper"></div>');
});
$iframeReset.each(function () {
// Re-set the src attribute on each iframe after page load
// for Chrome's "incorrect iFrame content on 'back'" bug.
// https://code.google.com/p/chromium/issues/detail?id=395791
// Need to specifically target video and admin bar
this.src = this.src;
});
};
timber.collectionViews = function () {
if (timber.cache.$changeView.length) {
timber.cache.$changeView.on('click', function() {
var view = $(this).data('view'),
url = document.URL,
hasParams = url.indexOf('?') > -1;
if (hasParams) {
window.location = replaceUrlParam(url, 'view', view);
} else {
window.location = url + '?view=' + view;
}
});
}
};
timber.loginForms = function() {
function showRecoverPasswordForm() {
timber.cache.$recoverPasswordForm.show();
timber.cache.$customerLoginForm.hide();
}
function hideRecoverPasswordForm() {
timber.cache.$recoverPasswordForm.hide();
timber.cache.$customerLoginForm.show();
}
timber.cache.$recoverPasswordLink.on('click', function(evt) {
evt.preventDefault();
showRecoverPasswordForm();
});
timber.cache.$hideRecoverPasswordLink.on('click', function(evt) {
evt.preventDefault();
hideRecoverPasswordForm();
});
// Allow deep linking to recover password form
if (timber.getHash() == '#recover') {
showRecoverPasswordForm();
}
};
timber.resetPasswordSuccess = function() {
timber.cache.$passwordResetSuccess.show();
};
/*============================================================================
Drawer modules
- Docs http://shopify.github.io/Timber/#drawers
==============================================================================*/
timber.Drawers = (function () {
var Drawer = function (id, position, options) {
var defaults = {
close: '.js-drawer-close',
open: '.js-drawer-open-' + position,
openClass: 'js-drawer-open',
dirOpenClass: 'js-drawer-open-' + position
};
this.$nodes = {
parent: $('body, html'),
page: $('#PageContainer'),
moved: $('.is-moved-by-drawer')
};
this.config = $.extend(defaults, options);
this.position = position;
this.$drawer = $('#' + id);
if (!this.$drawer.length) {
return false;
}
this.drawerIsOpen = false;
this.init();
};
Drawer.prototype.init = function () {
$(this.config.open).on('click', $.proxy(this.open, this));
this.$drawer.find(this.config.close).on('click', $.proxy(this.close, this));
};
Drawer.prototype.open = function (evt) {
// Keep track if drawer was opened from a click, or called by another function
var externalCall = false;
// Prevent following href if link is clicked
if (evt) {
evt.preventDefault();
} else {
externalCall = true;
}
// Without this, the drawer opens, the click event bubbles up to $nodes.page
// which closes the drawer.
if (evt && evt.stopPropagation) {
evt.stopPropagation();
// save the source of the click, we'll focus to this on close
this.$activeSource = $(evt.currentTarget);
}
if (this.drawerIsOpen && !externalCall) {
return this.close();
}
// Notify the drawer is going to open
timber.cache.$body.trigger('beforeDrawerOpen.timber', this);
// Add is-transitioning class to moved elements on open so drawer can have
// transition for close animation
this.$nodes.moved.addClass('is-transitioning');
this.$drawer.prepareTransition();
this.$nodes.parent.addClass(this.config.openClass + ' ' + this.config.dirOpenClass);
this.drawerIsOpen = true;
// Set focus on drawer
this.trapFocus(this.$drawer, 'drawer_focus');
// Run function when draw opens if set
if (this.config.onDrawerOpen && typeof(this.config.onDrawerOpen) == 'function') {
if (!externalCall) {
this.config.onDrawerOpen();
}
}
if (this.$activeSource && this.$activeSource.attr('aria-expanded')) {
this.$activeSource.attr('aria-expanded', 'true');
}
// Lock scrolling on mobile
this.$nodes.page.on('touchmove.drawer', function () {
return false;
});
this.$nodes.page.on('click.drawer', $.proxy(function () {
this.close();
return false;
}, this));
// Notify the drawer has opened
timber.cache.$body.trigger('afterDrawerOpen.timber', this);
};
Drawer.prototype.close = function () {
if (!this.drawerIsOpen) { // don't close a closed drawer
return;
}
// Notify the drawer is going to close
timber.cache.$body.trigger('beforeDrawerClose.timber', this);
// deselect any focused form elements
$(document.activeElement).trigger('blur');
// Ensure closing transition is applied to moved elements, like the nav
this.$nodes.moved.prepareTransition({ disableExisting: true });
this.$drawer.prepareTransition({ disableExisting: true });
this.$nodes.parent.removeClass(this.config.dirOpenClass + ' ' + this.config.openClass);
this.drawerIsOpen = false;
// Remove focus on drawer
this.removeTrapFocus(this.$drawer, 'drawer_focus');
this.$nodes.page.off('.drawer');
// Notify the drawer is closed now
timber.cache.$body.trigger('afterDrawerClose.timber', this);
};
Drawer.prototype.trapFocus = function ($container, eventNamespace) {
var eventName = eventNamespace ? 'focusin.' + eventNamespace : 'focusin';
$container.attr('tabindex', '-1');
$container.focus();
$(document).on(eventName, function (evt) {
if ($container[0] !== evt.target && !$container.has(evt.target).length) {
$container.focus();
}
});
};
Drawer.prototype.removeTrapFocus = function ($container, eventNamespace) {
var eventName = eventNamespace ? 'focusin.' + eventNamespace : 'focusin';
$container.removeAttr('tabindex');
$(document).off(eventName);
};
return Drawer;
})();
// Initialize Timber's JS on docready
$(timber.init);