Run Prettier on some of our JS assets

The motivation is that I'm about to change one of them to remove a
reference to an old placeholder library, so I want that change to be
clear!
This commit is contained in:
Emi Matchu 2024-02-18 20:34:24 -08:00
parent 0d23412fba
commit 95ff69ee9a
6 changed files with 443 additions and 340 deletions

View file

@ -1,20 +1,20 @@
(function () { (function () {
var CSRFProtection; var CSRFProtection;
var token = $('meta[name="csrf-token"]').attr('content'); var token = $('meta[name="csrf-token"]').attr("content");
if (token) { if (token) {
CSRFProtection = function (xhr, settings) { CSRFProtection = function (xhr, settings) {
var sendToken = ( var sendToken =
(typeof settings.useCSRFProtection === 'undefined') // default to true typeof settings.useCSRFProtection === "undefined" || // default to true
|| settings.useCSRFProtection); settings.useCSRFProtection;
if (sendToken) { if (sendToken) {
xhr.setRequestHeader('X-CSRF-Token', token); xhr.setRequestHeader("X-CSRF-Token", token);
}
} }
};
} else { } else {
CSRFProtection = $.noop; CSRFProtection = $.noop;
} }
$.ajaxSetup({ $.ajaxSetup({
beforeSend: CSRFProtection beforeSend: CSRFProtection,
}); });
})(); })();

View file

@ -1,3 +1,3 @@
document.getElementById('locale').addEventListener('change', function() { document.getElementById("locale").addEventListener("change", function () {
document.getElementById('locale-form').submit(); document.getElementById("locale-form").submit();
}); });

View file

@ -19,33 +19,33 @@
var hangerGroups = []; var hangerGroups = [];
$('div.closet-hangers-group').each(function () { $("div.closet-hangers-group").each(function () {
var el = $(this); var el = $(this);
var lists = []; var lists = [];
el.find('div.closet-list').each(function () { el.find("div.closet-list").each(function () {
var el = $(this); var el = $(this);
var id = el.attr('data-id'); var id = el.attr("data-id");
if (id) { if (id) {
lists[lists.length] = { lists[lists.length] = {
id: parseInt(id, 10), id: parseInt(id, 10),
label: el.find('h4').text() label: el.find("h4").text(),
} };
} }
}); });
hangerGroups[hangerGroups.length] = { hangerGroups[hangerGroups.length] = {
label: el.find('h3').text(), label: el.find("h3").text(),
lists: lists, lists: lists,
owned: (el.attr('data-owned') == 'true') owned: el.attr("data-owned") == "true",
}; };
}); });
$('div.closet-hangers-group span.toggle').live('click', function () { $("div.closet-hangers-group span.toggle").live("click", function () {
$(this).closest('.closet-hangers-group').toggleClass('hidden'); $(this).closest(".closet-hangers-group").toggleClass("hidden");
}); });
var hangersElQuery = '#closet-hangers'; var hangersElQuery = "#closet-hangers";
var hangersEl = $(hangersElQuery); var hangersEl = $(hangersElQuery);
/* /*
@ -54,8 +54,8 @@
*/ */
$('#toggle-compare').click(function () { $("#toggle-compare").click(function () {
hangersEl.toggleClass('comparing'); hangersEl.toggleClass("comparing");
}); });
/* /*
@ -94,32 +94,32 @@
// Ooh, this part is weird. We only want the name to be linked, so // Ooh, this part is weird. We only want the name to be linked, so
// lift everything else out. // lift everything else out.
var checkboxId = 'hanger-selected-' + hangerId; var checkboxId = "hanger-selected-" + hangerId;
var label = $('<label />', {'for': checkboxId}); var label = $("<label />", { for: checkboxId });
var link = hangerEl.children('a'); var link = hangerEl.children("a");
link.children(':not(.name)').detach().appendTo(label); link.children(":not(.name)").detach().appendTo(label);
link.detach().appendTo(label); link.detach().appendTo(label);
var checkbox = $('<input />', { var checkbox = $("<input />", {
type: 'checkbox', type: "checkbox",
id: checkboxId id: checkboxId,
}).appendTo(hangerEl); }).appendTo(hangerEl);
label.appendTo(hangerEl); label.appendTo(hangerEl);
// I don't usually like to _blank things, but it's too easy to click // I don't usually like to _blank things, but it's too easy to click
// the text when you didn't mean to and lose your selection work. // the text when you didn't mean to and lose your selection work.
link.attr('target', '_blank'); link.attr("target", "_blank");
$.tmpl("updateFormTmpl", { $.tmpl("updateFormTmpl", {
user_id: currentUserId, user_id: currentUserId,
closet_hanger_id: hangerId, closet_hanger_id: hangerId,
quantity: quantity, quantity: quantity,
list_id: listId, list_id: listId,
owned: owned owned: owned,
}).appendTo(quantityEl); }).appendTo(quantityEl);
$.tmpl("destroyFormTmpl", { $.tmpl("destroyFormTmpl", {
user_id: currentUserId, user_id: currentUserId,
closet_hanger_id: hangerId closet_hanger_id: hangerId,
}).appendTo(hangerEl); }).appendTo(hangerEl);
}); });
}); });
@ -135,33 +135,40 @@
}; };
$.fn.disableForms = function () { $.fn.disableForms = function () {
return this.data("formsDisabled", true).find("input").attr("disabled", "disabled").end(); return this.data("formsDisabled", true)
} .find("input")
.attr("disabled", "disabled")
.end();
};
$.fn.enableForms = function () { $.fn.enableForms = function () {
return this.data("formsDisabled", false).find("input").removeAttr("disabled").end(); return this.data("formsDisabled", false)
} .find("input")
.removeAttr("disabled")
.end();
};
$.fn.hasChanged = function () { $.fn.hasChanged = function () {
return this.attr('data-previous-value') != this.val(); return this.attr("data-previous-value") != this.val();
} };
$.fn.revertValue = function () { $.fn.revertValue = function () {
return this.each(function () { return this.each(function () {
var el = $(this); var el = $(this);
el.val(el.attr('data-previous-value')); el.val(el.attr("data-previous-value"));
}); });
} };
$.fn.storeValue = function () { $.fn.storeValue = function () {
return this.each(function () { return this.each(function () {
var el = $(this); var el = $(this);
el.attr('data-previous-value', el.val()); el.attr("data-previous-value", el.val());
}); });
} };
$.fn.insertIntoSortedList = function (list, compare) { $.fn.insertIntoSortedList = function (list, compare) {
var newChild = this, inserted = false; var newChild = this,
inserted = false;
list.children().each(function () { list.children().each(function () {
if (compare(newChild, $(this)) < 1) { if (compare(newChild, $(this)) < 1) {
newChild.insertBefore(this); newChild.insertBefore(this);
@ -171,7 +178,7 @@
}); });
if (!inserted) newChild.appendTo(list); if (!inserted) newChild.appendTo(list);
return this; return this;
} };
function handleSaveError(xhr, action) { function handleSaveError(xhr, action) {
try { try {
@ -180,7 +187,7 @@
var data = {}; var data = {};
} }
if(typeof data.errors != 'undefined') { if (typeof data.errors != "undefined") {
$.jGrowl("Error " + action + ": " + data.errors.join(", ")); $.jGrowl("Error " + action + ": " + data.errors.join(", "));
} else { } else {
$.jGrowl("We had trouble " + action + " just now. Try again?"); $.jGrowl("We had trouble " + action + " just now. Try again?");
@ -195,45 +202,50 @@
} }
function compareItemsByName(a, b) { function compareItemsByName(a, b) {
return a.find('span.name').text().localeCompare(b.find('span.name').text()); return a.find("span.name").text().localeCompare(b.find("span.name").text());
} }
function findList(owned, id, item) { function findList(owned, id, item) {
if (id) { if (id) {
return $('#closet-list-' + id); return $("#closet-list-" + id);
} else { } else {
return $("div.closet-hangers-group[data-owned=" + owned + "] div.closet-list.unlisted"); return $(
"div.closet-hangers-group[data-owned=" +
owned +
"] div.closet-list.unlisted",
);
} }
} }
function updateListHangersCount(el) { function updateListHangersCount(el) {
el.attr('data-hangers-count', el.find('div.object').length); el.attr("data-hangers-count", el.find("div.object").length);
} }
function moveItemToList(item, owned, listId) { function moveItemToList(item, owned, listId) {
var newList = findList(owned, listId, item); var newList = findList(owned, listId, item);
var oldList = item.closest('div.closet-list'); var oldList = item.closest("div.closet-list");
var hangersWrapper = newList.find('div.closet-list-hangers'); var hangersWrapper = newList.find("div.closet-list-hangers");
item.insertIntoSortedList(hangersWrapper, compareItemsByName); item.insertIntoSortedList(hangersWrapper, compareItemsByName);
updateListHangersCount(oldList); updateListHangersCount(oldList);
updateListHangersCount(newList); updateListHangersCount(newList);
} }
function submitUpdateForm(form) { function submitUpdateForm(form) {
if(form.data('loading')) return false; if (form.data("loading")) return false;
var quantityEl = form.children("input[name=closet_hanger\[quantity\]]"); var quantityEl = form.children("input[name=closet_hanger[quantity]]");
var ownedEl = form.children("input[name=closet_hanger\[owned\]]"); var ownedEl = form.children("input[name=closet_hanger[owned]]");
var listEl = form.children("input[name=closet_hanger\[list_id\]]"); var listEl = form.children("input[name=closet_hanger[list_id]]");
var listChanged = ownedEl.hasChanged() || listEl.hasChanged(); var listChanged = ownedEl.hasChanged() || listEl.hasChanged();
if (listChanged || quantityEl.hasChanged()) { if (listChanged || quantityEl.hasChanged()) {
var objectWrapper = form.closest(".object").addClass("loading"); var objectWrapper = form.closest(".object").addClass("loading");
var newQuantity = quantityEl.val(); var newQuantity = quantityEl.val();
var quantitySpan = objectWrapper.find(".quantity span").text(newQuantity); var quantitySpan = objectWrapper.find(".quantity span").text(newQuantity);
objectWrapper.attr('data-quantity', newQuantity); objectWrapper.attr("data-quantity", newQuantity);
var data = form.serialize(); // get data before disabling inputs var data = form.serialize(); // get data before disabling inputs
objectWrapper.disableForms(); objectWrapper.disableForms();
form.data('loading', true); form.data("loading", true);
if(listChanged) moveItemToList(objectWrapper, ownedEl.val(), listEl.val()); if (listChanged)
moveItemToList(objectWrapper, ownedEl.val(), listEl.val());
$.ajax({ $.ajax({
url: form.attr("action") + ".json", url: form.attr("action") + ".json",
type: "post", type: "post",
@ -245,18 +257,23 @@
} else { } else {
objectWrapper.removeClass("loading").enableForms(); objectWrapper.removeClass("loading").enableForms();
} }
form.data('loading', false); form.data("loading", false);
}, },
success: function () { success: function () {
// Now that the move was successful, let's merge it with any // Now that the move was successful, let's merge it with any
// conflicting hangers // conflicting hangers
var id = objectWrapper.attr("data-item-id"); var id = objectWrapper.attr("data-item-id");
var conflictingHanger = findList(ownedEl.val(), listEl.val(), objectWrapper). var conflictingHanger = findList(
find("div[data-item-id=" + id + "]").not(objectWrapper); ownedEl.val(),
listEl.val(),
objectWrapper,
)
.find("div[data-item-id=" + id + "]")
.not(objectWrapper);
if (conflictingHanger.length) { if (conflictingHanger.length) {
var conflictingQuantity = parseInt( var conflictingQuantity = parseInt(
conflictingHanger.attr('data-quantity'), conflictingHanger.attr("data-quantity"),
10 10,
); );
var currentQuantity = parseInt(newQuantity, 10); var currentQuantity = parseInt(newQuantity, 10);
@ -265,7 +282,7 @@
quantitySpan.text(mergedQuantity); quantitySpan.text(mergedQuantity);
quantityEl.val(mergedQuantity); quantityEl.val(mergedQuantity);
objectWrapper.attr('data-quantity', mergedQuantity); objectWrapper.attr("data-quantity", mergedQuantity);
conflictingHanger.remove(); conflictingHanger.remove();
} }
@ -280,46 +297,53 @@
quantityEl.revertValue(); quantityEl.revertValue();
ownedEl.revertValue(); ownedEl.revertValue();
listEl.revertValue(); listEl.revertValue();
if(listChanged) moveItemToList(objectWrapper, ownedEl.val(), listEl.val()); if (listChanged)
moveItemToList(objectWrapper, ownedEl.val(), listEl.val());
quantitySpan.text(quantityEl.val()); quantitySpan.text(quantityEl.val());
handleSaveError(xhr, "updating the quantity"); handleSaveError(xhr, "updating the quantity");
} },
}); });
} }
} }
$(hangersElQuery + ' form.closet-hanger-update').live('submit', function (e) { $(hangersElQuery + " form.closet-hanger-update").live("submit", function (e) {
e.preventDefault(); e.preventDefault();
submitUpdateForm($(this)); submitUpdateForm($(this));
}); });
function editableInputs() { function editableInputs() {
return $(hangersElQuery).find( return $(hangersElQuery).find(
'input[name=closet_hanger\[quantity\]], ' + "input[name=closet_hanger[quantity]], " +
'input[name=closet_hanger\[owned\]], ' + "input[name=closet_hanger[owned]], " +
'input[name=closet_hanger\[list_id\]]' "input[name=closet_hanger[list_id]]",
) );
} }
$(hangersElQuery + 'input[name=closet_hanger\[quantity\]]').live('change', function () { $(hangersElQuery + "input[name=closet_hanger[quantity]]")
.live("change", function () {
submitUpdateForm($(this).parent()); submitUpdateForm($(this).parent());
}).storeValue(); })
.storeValue();
onHangersInit(function () { onHangersInit(function () {
editableInputs().storeValue(); editableInputs().storeValue();
}); });
$(hangersElQuery + ' div.object').live('mouseleave', function () { $(hangersElQuery + " div.object")
submitUpdateForm($(this).find('form.closet-hanger-update')); .live("mouseleave", function () {
}).liveDraggable({ submitUpdateForm($(this).find("form.closet-hanger-update"));
appendTo: '#closet-hangers', })
.liveDraggable({
appendTo: "#closet-hangers",
distance: 20, distance: 20,
helper: "clone", helper: "clone",
revert: "invalid" revert: "invalid",
}); });
$(hangersElQuery + " form.closet-hanger-destroy").live("submit", function (e) { $(hangersElQuery + " form.closet-hanger-destroy").live(
"submit",
function (e) {
e.preventDefault(); e.preventDefault();
var form = $(this); var form = $(this);
var button = form.children("input[type=submit]").val("Removing…"); var button = form.children("input[type=submit]").val("Removing…");
@ -340,12 +364,15 @@
error: function () { error: function () {
objectWrapper.removeClass("loading").enableForms(); objectWrapper.removeClass("loading").enableForms();
$.jGrowl("Error removing item. Try again?"); $.jGrowl("Error removing item. Try again?");
} },
});
}); });
},
);
$(hangersElQuery + " .select-all").live("click", function (e) { $(hangersElQuery + " .select-all").live("click", function (e) {
var checkboxes = $(this).closest(".closet-list").find(".object input[type=checkbox]"); var checkboxes = $(this)
.closest(".closet-list")
.find(".object input[type=checkbox]");
var allChecked = true; var allChecked = true;
checkboxes.each(function () { checkboxes.each(function () {
@ -355,7 +382,7 @@
} }
}); });
checkboxes.attr('checked', !allChecked); checkboxes.attr("checked", !allChecked);
updateBulkActions(); // setting the checked prop doesn't fire change events updateBulkActions(); // setting the checked prop doesn't fire change events
}); });
@ -366,7 +393,9 @@
function getCheckedIds() { function getCheckedIds() {
var checkedIds = []; var checkedIds = [];
getCheckboxes().filter(':checked').each(function() { getCheckboxes()
.filter(":checked")
.each(function () {
if (this.checked) checkedIds.push(this.id); if (this.checked) checkedIds.push(this.id);
}); });
return checkedIds; return checkedIds;
@ -375,9 +404,9 @@
getCheckboxes().live("change", updateBulkActions); getCheckboxes().live("change", updateBulkActions);
function updateBulkActions() { function updateBulkActions() {
var checkedCount = getCheckboxes().filter(':checked').length; var checkedCount = getCheckboxes().filter(":checked").length;
$('.bulk-actions').attr('data-target-count', checkedCount); $(".bulk-actions").attr("data-target-count", checkedCount);
$('.bulk-actions-target-count').text(checkedCount); $(".bulk-actions-target-count").text(checkedCount);
} }
$(".bulk-actions-move-all").bind("submit", function (e) { $(".bulk-actions-move-all").bind("submit", function (e) {
@ -385,11 +414,17 @@
e.preventDefault(); e.preventDefault();
var form = $(this); var form = $(this);
var data = form.serializeArray(); var data = form.serializeArray();
data.push({name: "return_to", value: window.location.pathname + window.location.search}); data.push({
name: "return_to",
value: window.location.pathname + window.location.search,
});
var checkedBoxes = getCheckboxes().filter(':checked'); var checkedBoxes = getCheckboxes().filter(":checked");
checkedBoxes.each(function () { checkedBoxes.each(function () {
data.push({name: "ids[]", value: $(this).closest('.object').attr('data-id')}); data.push({
name: "ids[]",
value: $(this).closest(".object").attr("data-id"),
});
}); });
$.ajax({ $.ajax({
@ -398,15 +433,21 @@
data: data, data: data,
success: function (html) { success: function (html) {
var doc = $(html); var doc = $(html);
hangersEl.html( doc.find('#closet-hangers').html() ); hangersEl.html(doc.find("#closet-hangers").html());
hangersInit(); hangersInit();
updateBulkActions(); // don't want to maintain checked; deselect em all updateBulkActions(); // don't want to maintain checked; deselect em all
doc.find('.flash').hide().insertBefore(hangersEl).show(500).delay(5000).hide(250); doc
.find(".flash")
.hide()
.insertBefore(hangersEl)
.show(500)
.delay(5000)
.hide(250);
itemsSearchField.val(""); itemsSearchField.val("");
}, },
error: function (xhr) { error: function (xhr) {
handleSaveError(xhr, "moving these items"); handleSaveError(xhr, "moving these items");
} },
}); });
}); });
@ -414,13 +455,13 @@
e.preventDefault(); e.preventDefault();
var form = $(this); var form = $(this);
var hangerIds = []; var hangerIds = [];
var checkedBoxes = getCheckboxes().filter(':checked'); var checkedBoxes = getCheckboxes().filter(":checked");
var hangerEls = $(); var hangerEls = $();
checkedBoxes.each(function () { checkedBoxes.each(function () {
hangerEls = hangerEls.add($(this).closest('.object')); hangerEls = hangerEls.add($(this).closest(".object"));
}); });
hangerEls.each(function () { hangerEls.each(function () {
hangerIds.push($(this).attr('data-id')); hangerIds.push($(this).attr("data-id"));
}); });
$.ajax({ $.ajax({
url: form.attr("action") + ".json?" + $.param({ ids: hangerIds }), url: form.attr("action") + ".json?" + $.param({ ids: hangerIds }),
@ -431,12 +472,12 @@
}, },
error: function () { error: function () {
$.jGrowl("Error removing items. Try again?"); $.jGrowl("Error removing items. Try again?");
} },
}); });
}); });
$(".bulk-actions-deselect-all").bind("click", function (e) { $(".bulk-actions-deselect-all").bind("click", function (e) {
getCheckboxes().filter(':checked').attr('checked', false); getCheckboxes().filter(":checked").attr("checked", false);
updateBulkActions(); updateBulkActions();
}); });
@ -444,7 +485,7 @@
$.fn.on = $.fn.bind; $.fn.on = $.fn.bind;
$(function () { $(function () {
$('.bulk-actions').stickUp(); $(".bulk-actions").stickUp();
}); });
function maintainCheckboxes(fn) { function maintainCheckboxes(fn) {
@ -464,7 +505,7 @@
*/ */
$('input, textarea').placeholder(); $("input, textarea").placeholder();
var itemsSearchForm = $("#closet-hangers-items-search[data-current-user-id]"); var itemsSearchForm = $("#closet-hangers-items-search[data-current-user-id]");
var itemsSearchField = itemsSearchForm.children("input[name=q]"); var itemsSearchField = itemsSearchForm.children("input[name=q]");
@ -484,35 +525,50 @@
var closetHanger = { var closetHanger = {
owned: group.owned, owned: group.owned,
list_id: ui.item.list ? ui.item.list.id : '' list_id: ui.item.list ? ui.item.list.id : "",
}; };
if (!item.hasHanger) closetHanger.quantity = 1; if (!item.hasHanger) closetHanger.quantity = 1;
$.ajax({ $.ajax({
url: "/user/" + itemsSearchForm.data("current-user-id") + "/items/" + item.id + "/closet_hangers", url:
"/user/" +
itemsSearchForm.data("current-user-id") +
"/items/" +
item.id +
"/closet_hangers",
type: "post", type: "post",
data: {closet_hanger: closetHanger, return_to: window.location.pathname + window.location.search}, data: {
closet_hanger: closetHanger,
return_to: window.location.pathname + window.location.search,
},
complete: function () { complete: function () {
itemsSearchField.removeClass("loading"); itemsSearchField.removeClass("loading");
}, },
success: function (html) { success: function (html) {
var doc = $(html); var doc = $(html);
maintainCheckboxes(function () { maintainCheckboxes(function () {
hangersEl.html( doc.find('#closet-hangers').html() ); hangersEl.html(doc.find("#closet-hangers").html());
hangersInit(); hangersInit();
}); });
doc.find('.flash').hide().insertBefore(hangersEl).show(500).delay(5000).hide(250); doc
.find(".flash")
.hide()
.insertBefore(hangersEl)
.show(500)
.delay(5000)
.hide(250);
itemsSearchField.val(""); itemsSearchField.val("");
}, },
error: function (xhr) { error: function (xhr) {
handleSaveError(xhr, "adding the item"); handleSaveError(xhr, "adding the item");
} },
}); });
} }
}, },
source: function (input, callback) { source: function (input, callback) {
if(typeof input.term == 'string') { // user-typed query if (typeof input.term == "string") {
// user-typed query
$.getJSON("/items.json?q=" + input.term, function (data) { $.getJSON("/items.json?q=" + input.term, function (data) {
var output = []; var output = [];
var items = data.items; var items = data.items;
@ -523,68 +579,87 @@
} }
callback(output); callback(output);
}); });
} else { // item was chosen, now choose a group to insert } else {
var groupInserts = [], group; // item was chosen, now choose a group to insert
var item = input.term, itemEl, occupiedGroups, hasHanger; var groupInserts = [],
group;
var item = input.term,
itemEl,
occupiedGroups,
hasHanger;
for (var i in hangerGroups) { for (var i in hangerGroups) {
group = hangerGroups[i]; group = hangerGroups[i];
itemEl = $('div.closet-hangers-group[data-owned=' + group.owned + '] div.object[data-item-id=' + item.id + ']'); itemEl = $(
occupiedGroups = itemEl.closest('.closet-list'); "div.closet-hangers-group[data-owned=" +
hasHanger = occupiedGroups.filter('.unlisted').length > 0; group.owned +
"] div.object[data-item-id=" +
item.id +
"]",
);
occupiedGroups = itemEl.closest(".closet-list");
hasHanger = occupiedGroups.filter(".unlisted").length > 0;
groupInserts[groupInserts.length] = { groupInserts[groupInserts.length] = {
group: group, group: group,
item: item, item: item,
label: item.label, label: item.label,
hasHanger: hasHanger hasHanger: hasHanger,
} };
for (var i = 0; i < group.lists.length; i++) { for (var i = 0; i < group.lists.length; i++) {
hasHanger = occupiedGroups. hasHanger =
filter("[data-id=" + group.lists[i].id + "]").length > 0; occupiedGroups.filter("[data-id=" + group.lists[i].id + "]")
.length > 0;
groupInserts[groupInserts.length] = { groupInserts[groupInserts.length] = {
group: group, group: group,
item: item, item: item,
label: item.label, label: item.label,
list: group.lists[i], list: group.lists[i],
hasHanger: hasHanger hasHanger: hasHanger,
} };
} }
} }
callback(groupInserts); callback(groupInserts);
} }
} },
}); });
var autocompleter = itemsSearchField.data("autocomplete"); var autocompleter = itemsSearchField.data("autocomplete");
autocompleter._renderItem = function (ul, item) { autocompleter._renderItem = function (ul, item) {
var li = $("<li></li>").data("item.autocomplete", item); var li = $("<li></li>").data("item.autocomplete", item);
if(item.is_item) { // these are items from the server if (item.is_item) {
$('#autocomplete-item-tmpl').tmpl({item_name: item.label}).appendTo(li); // these are items from the server
} else if(item.list) { // these are list inserts $("#autocomplete-item-tmpl").tmpl({ item_name: item.label }).appendTo(li);
} else if (item.list) {
// these are list inserts
var listName = item.list.label; var listName = item.list.label;
if (item.hasHanger) { if (item.hasHanger) {
$('#autocomplete-already-in-collection-tmpl'). $("#autocomplete-already-in-collection-tmpl")
tmpl({collection_name: listName}).appendTo(li); .tmpl({ collection_name: listName })
.appendTo(li);
} else { } else {
$('#autocomplete-add-to-list-tmpl').tmpl({list_name: listName}). $("#autocomplete-add-to-list-tmpl")
appendTo(li); .tmpl({ list_name: listName })
.appendTo(li);
} }
li.addClass("closet-list-autocomplete-item"); li.addClass("closet-list-autocomplete-item");
} else { // these are group inserts } else {
// these are group inserts
var groupName = item.group.label; var groupName = item.group.label;
if (!item.hasHanger) { if (!item.hasHanger) {
$('#autocomplete-add-to-group-tmpl'). $("#autocomplete-add-to-group-tmpl")
tmpl({group_name: groupName.replace(/\s+$/, '')}).appendTo(li); .tmpl({ group_name: groupName.replace(/\s+$/, "") })
.appendTo(li);
} else { } else {
$('#autocomplete-already-in-collection-tmpl'). $("#autocomplete-already-in-collection-tmpl")
tmpl({collection_name: groupName}).appendTo(li); .tmpl({ collection_name: groupName })
.appendTo(li);
} }
li.addClass('closet-hangers-group-autocomplete-item'); li.addClass("closet-hangers-group-autocomplete-item");
} }
return li.appendTo(ul); return li.appendTo(ul);
} };
/* /*
@ -592,48 +667,54 @@
*/ */
var contactEl = $('#closet-hangers-contact'); var contactEl = $("#closet-hangers-contact");
var contactForm = contactEl.children('form'); var contactForm = contactEl.children("form");
var contactField = contactForm.children('select'); var contactField = contactForm.children("select");
var contactAddOption = $('<option/>', var contactAddOption = $("<option/>", {
{text: contactField.attr('data-new-text'), value: -1}); text: contactField.attr("data-new-text"),
value: -1,
});
contactAddOption.appendTo(contactField); contactAddOption.appendTo(contactField);
var currentUserId = $('meta[name=current-user-id]').attr('content'); var currentUserId = $("meta[name=current-user-id]").attr("content");
function submitContactForm() { function submitContactForm() {
var data = contactForm.serialize(); var data = contactForm.serialize();
contactForm.disableForms(); contactForm.disableForms();
$.ajax({ $.ajax({
url: contactForm.attr('action') + '.json', url: contactForm.attr("action") + ".json",
type: 'post', type: "post",
data: data, data: data,
dataType: 'json', dataType: "json",
complete: function () { complete: function () {
contactForm.enableForms(); contactForm.enableForms();
}, },
error: function (xhr) { error: function (xhr) {
handleSaveError(xhr, 'saving Neopets username'); handleSaveError(xhr, "saving Neopets username");
} },
}); });
} }
contactField.change(function (e) { contactField.change(function (e) {
if (contactField.val() < 0) { if (contactField.val() < 0) {
var newUsername = $.trim(prompt(contactField.attr('data-new-prompt'), '')); var newUsername = $.trim(
prompt(contactField.attr("data-new-prompt"), ""),
);
if (newUsername) { if (newUsername) {
$.ajax({ $.ajax({
url: '/user/' + currentUserId + '/neopets-connections', url: "/user/" + currentUserId + "/neopets-connections",
type: 'POST', type: "POST",
data: { neopets_connection: { neopets_username: newUsername } }, data: { neopets_connection: { neopets_username: newUsername } },
dataType: 'json', dataType: "json",
success: function (connection) { success: function (connection) {
var newOption = $('<option/>', {text: newUsername, var newOption = $("<option/>", {
value: connection.id}) text: newUsername,
value: connection.id,
});
newOption.insertBefore(contactAddOption); newOption.insertBefore(contactAddOption);
contactField.val(connection.id); contactField.val(connection.id);
submitContactForm(); submitContactForm();
} },
}); });
} }
} else { } else {
@ -647,8 +728,8 @@
*/ */
$('input[type=submit][data-confirm]').live('click', function (e) { $("input[type=submit][data-confirm]").live("click", function (e) {
if(!confirm(this.getAttribute('data-confirm'))) e.preventDefault(); if (!confirm(this.getAttribute("data-confirm"))) e.preventDefault();
}); });
/* /*
@ -658,23 +739,30 @@
*/ */
onHangersInit(function () { onHangersInit(function () {
$('div.closet-list').droppable({ $("div.closet-list").droppable({
accept: 'div.object', accept: "div.object",
activate: function () { activate: function () {
$(this).find('.closet-list-content').animate({opacity: 0, height: 100}, 250); $(this)
.find(".closet-list-content")
.animate({ opacity: 0, height: 100 }, 250);
}, },
activeClass: 'droppable-active', activeClass: "droppable-active",
deactivate: function () { deactivate: function () {
$(this).find('.closet-list-content').css('height', 'auto').animate({opacity: 1}, 250); $(this)
.find(".closet-list-content")
.css("height", "auto")
.animate({ opacity: 1 }, 250);
}, },
drop: function (e, ui) { drop: function (e, ui) {
var form = ui.draggable.find('form.closet-hanger-update'); var form = ui.draggable.find("form.closet-hanger-update");
form.find('input[name=closet_hanger\[list_id\]]'). form
val(this.getAttribute('data-id')); .find("input[name=closet_hanger[list_id]]")
form.find('input[name=closet_hanger\[owned\]]'). .val(this.getAttribute("data-id"));
val($(this).closest('.closet-hangers-group').attr('data-owned')); form
.find("input[name=closet_hanger[owned]]")
.val($(this).closest(".closet-hangers-group").attr("data-owned"));
submitUpdateForm(form); submitUpdateForm(form);
} },
}); });
}); });
@ -685,16 +773,21 @@
*/ */
function updateVisibilityDescription() { function updateVisibilityDescription() {
var descriptions = $(this).closest('.visibility-form'). var descriptions = $(this)
find('ul.visibility-descriptions'); .closest(".visibility-form")
.find("ul.visibility-descriptions");
descriptions.children('li.current').removeClass('current'); descriptions.children("li.current").removeClass("current");
descriptions.children('li[data-id=' + $(this).val() + ']').addClass('current'); descriptions
.children("li[data-id=" + $(this).val() + "]")
.addClass("current");
} }
function visibilitySelects() { return $('form.visibility-form select') } function visibilitySelects() {
return $("form.visibility-form select");
}
visibilitySelects().live('change', updateVisibilityDescription); visibilitySelects().live("change", updateVisibilityDescription);
onHangersInit(function () { onHangersInit(function () {
visibilitySelects().each(updateVisibilityDescription); visibilitySelects().each(updateVisibilityDescription);
@ -706,8 +799,8 @@
*/ */
$('#toggle-help').click(function () { $("#toggle-help").click(function () {
$('#closet-hangers-help').toggleClass('hidden'); $("#closet-hangers-help").toggleClass("hidden");
}); });
/* /*
@ -716,9 +809,11 @@
*/ */
$('#closet-hangers-share-box').mouseover(function () { $("#closet-hangers-share-box")
.mouseover(function () {
$(this).focus(); $(this).focus();
}).mouseout(function () { })
.mouseout(function () {
$(this).blur(); $(this).blur();
}); });
@ -730,4 +825,3 @@
hangersInit(); hangersInit();
})(); })();

View file

@ -1,8 +1,8 @@
(function () { (function () {
function setChecked() { function setChecked() {
var el = $(this); var el = $(this);
el.closest('li').toggleClass('checked', el.is(':checked')); el.closest("li").toggleClass("checked", el.is(":checked"));
} }
$('#petpage-closet-lists input').click(setChecked).each(setChecked); $("#petpage-closet-lists input").click(setChecked).each(setChecked);
})(); })();

View file

@ -1,4 +1,3 @@
$('form.button_to input[type=submit]').click(function (e) { $("form.button_to input[type=submit]").click(function (e) {
if(!confirm(this.getAttribute('data-confirm'))) e.preventDefault(); if (!confirm(this.getAttribute("data-confirm"))) e.preventDefault();
}); });

View file

@ -1,16 +1,16 @@
var DEBUG = (document.location.search.substr(0, 6) == '?debug'); var DEBUG = document.location.search.substr(0, 6) == "?debug";
/* Needed items form */ /* Needed items form */
(function () { (function () {
var UI = {}; var UI = {};
UI.form = $('#needed-items-form'); UI.form = $("#needed-items-form");
UI.alert = $('#needed-items-alert'); UI.alert = $("#needed-items-alert");
UI.pet_name_field = $('#needed-items-pet-name-field'); UI.pet_name_field = $("#needed-items-pet-name-field");
UI.pet_thumbnail = $('#needed-items-pet-thumbnail'); UI.pet_thumbnail = $("#needed-items-pet-thumbnail");
UI.pet_header = $('#needed-items-pet-header'); UI.pet_header = $("#needed-items-pet-header");
UI.reload = $('#needed-items-reload'); UI.reload = $("#needed-items-reload");
UI.pet_items = $('#needed-items-pet-items'); UI.pet_items = $("#needed-items-pet-items");
UI.item_template = $('#item-template'); UI.item_template = $("#item-template");
var current_request = { abort: function () {} }; var current_request = { abort: function () {} };
function sendRequest(options) { function sendRequest(options) {
@ -33,48 +33,51 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
cancelRequest(); cancelRequest();
sendRequest({ sendRequest({
url: UI.form.attr('action') + '.json', url: UI.form.attr("action") + ".json",
dataType: 'json', dataType: "json",
data: { name: pet_name }, data: { name: pet_name },
error: petError, error: petError,
success: function (data) { petSuccess(data, pet_name) }, success: function (data) {
complete: petComplete petSuccess(data, pet_name);
},
complete: petComplete,
}); });
UI.form.removeClass('failed').addClass('loading-pet'); UI.form.removeClass("failed").addClass("loading-pet");
} }
function petComplete() { function petComplete() {
UI.form.removeClass('loading-pet'); UI.form.removeClass("loading-pet");
} }
function petError(xhr) { function petError(xhr) {
UI.alert.text(xhr.responseText); UI.alert.text(xhr.responseText);
UI.form.addClass('failed'); UI.form.addClass("failed");
} }
function petSuccess(data, pet_name) { function petSuccess(data, pet_name) {
last_successful_pet_name = pet_name; last_successful_pet_name = pet_name;
UI.pet_thumbnail.attr('src', petThumbnailUrl(pet_name)); UI.pet_thumbnail.attr("src", petThumbnailUrl(pet_name));
UI.pet_header.empty(); UI.pet_header.empty();
$('#needed-items-pet-header-template').tmpl({pet_name: pet_name}). $("#needed-items-pet-header-template")
appendTo(UI.pet_header); .tmpl({ pet_name: pet_name })
.appendTo(UI.pet_header);
loadItems(data.query); loadItems(data.query);
} }
function petThumbnailUrl(pet_name) { function petThumbnailUrl(pet_name) {
return 'https://pets.neopets.com/cpn/' + pet_name + '/1/1.png'; return "https://pets.neopets.com/cpn/" + pet_name + "/1/1.png";
} }
/* Items */ /* Items */
function loadItems(query) { function loadItems(query) {
UI.form.addClass('loading-items'); UI.form.addClass("loading-items");
sendRequest({ sendRequest({
url: '/items/needed.json', url: "/items/needed.json",
dataType: 'json', dataType: "json",
data: query, data: query,
success: itemsSuccess success: itemsSuccess,
}); });
} }
@ -89,7 +92,7 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
UI.pet_items.empty(); UI.pet_items.empty();
UI.item_template.tmpl(items).appendTo(UI.pet_items); UI.item_template.tmpl(items).appendTo(UI.pet_items);
UI.form.removeClass('loading-items').addClass('loaded'); UI.form.removeClass("loading-items").addClass("loaded");
} }
UI.form.submit(function (e) { UI.form.submit(function (e) {
@ -105,28 +108,31 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
/* Bulk pets form */ /* Bulk pets form */
(function () { (function () {
var form = $('#bulk-pets-form'), var form = $("#bulk-pets-form"),
queue_el = form.find('ul'), queue_el = form.find("ul"),
names_el = form.find('textarea'), names_el = form.find("textarea"),
add_el = $('#bulk-pets-form-add'), add_el = $("#bulk-pets-form-add"),
clear_el = $('#bulk-pets-form-clear'), clear_el = $("#bulk-pets-form-clear"),
bulk_load_queue; bulk_load_queue;
$(document.body).addClass('js'); $(document.body).addClass("js");
bulk_load_queue = new (function BulkLoadQueue() { bulk_load_queue = new (function BulkLoadQueue() {
var RECENTLY_SENT_INTERVAL_IN_SECONDS = 30; var RECENTLY_SENT_INTERVAL_IN_SECONDS = 30;
var RECENTLY_SENT_MAX = 3; var RECENTLY_SENT_MAX = 3;
var pets = [], url = form.attr('action') + '.json', var pets = [],
recently_sent_count = 0, loading = false; url = form.attr("action") + ".json",
recently_sent_count = 0,
loading = false;
function Pet(name) { function Pet(name) {
var el = $('#bulk-pets-submission-template').tmpl({pet_name: name}). var el = $("#bulk-pets-submission-template")
appendTo(queue_el); .tmpl({ pet_name: name })
.appendTo(queue_el);
this.load = function () { this.load = function () {
el.removeClass('waiting').addClass('loading'); el.removeClass("waiting").addClass("loading");
var response_el = el.find('span.response'); var response_el = el.find("span.response");
pets.shift(); pets.shift();
loading = true; loading = true;
$.ajax({ $.ajax({
@ -135,19 +141,20 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
loadNextIfReady(); loadNextIfReady();
}, },
data: { name: name }, data: { name: name },
dataType: 'json', dataType: "json",
error: function (xhr) { error: function (xhr) {
el.removeClass('loading').addClass('failed'); el.removeClass("loading").addClass("failed");
response_el.text(xhr.responseText); response_el.text(xhr.responseText);
}, },
success: function (data) { success: function (data) {
var points = data.points; var points = data.points;
el.removeClass('loading').addClass('loaded'); el.removeClass("loading").addClass("loaded");
$('#bulk-pets-submission-success-template').tmpl({points: points}). $("#bulk-pets-submission-success-template")
appendTo(response_el); .tmpl({ points: points })
.appendTo(response_el);
}, },
type: 'post', type: "post",
url: url url: url,
}); });
recently_sent_count++; recently_sent_count++;
@ -155,17 +162,17 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
recently_sent_count--; recently_sent_count--;
loadNextIfReady(); loadNextIfReady();
}, RECENTLY_SENT_INTERVAL_IN_SECONDS * 1000); }, RECENTLY_SENT_INTERVAL_IN_SECONDS * 1000);
} };
} }
this.add = function (name) { this.add = function (name) {
name = name.replace(/^\s+|\s+$/g, ''); name = name.replace(/^\s+|\s+$/g, "");
if (name.length) { if (name.length) {
var pet = new Pet(name); var pet = new Pet(name);
pets.push(pet); pets.push(pet);
if (pets.length == 1) loadNextIfReady(); if (pets.length == 1) loadNextIfReady();
} }
} };
function loadNextIfReady() { function loadNextIfReady() {
if (!loading && recently_sent_count < RECENTLY_SENT_MAX && pets.length) { if (!loading && recently_sent_count < RECENTLY_SENT_MAX && pets.length) {
@ -175,19 +182,22 @@ var DEBUG = (document.location.search.substr(0, 6) == '?debug');
})(); })();
names_el.keyup(function () { names_el.keyup(function () {
var names = this.value.split('\n'), x = names.length - 1, i, name; var names = this.value.split("\n"),
x = names.length - 1,
i,
name;
for (i = 0; i < x; i++) { for (i = 0; i < x; i++) {
bulk_load_queue.add(names[i]); bulk_load_queue.add(names[i]);
} }
this.value = (x >= 0) ? names[x] : ''; this.value = x >= 0 ? names[x] : "";
}); });
add_el.click(function () { add_el.click(function () {
bulk_load_queue.add(names_el.val()); bulk_load_queue.add(names_el.val());
names_el.val(''); names_el.val("");
}); });
clear_el.click(function () { clear_el.click(function () {
queue_el.children('li.loaded, li.failed').remove(); queue_el.children("li.loaded, li.failed").remove();
}); });
})(); })();