From 5ef1b16e40bef5a08666eff73f11f9309dcf5884 Mon Sep 17 00:00:00 2001 From: "David T. Macknet" Date: Thu, 19 Sep 2024 15:16:58 -0700 Subject: [PATCH] Create shared.js The files in this project use functions from shared.js, which was previously missing. SharedHelpers is defined. This provides the following functions: AddAntiForgeryToken StripCurrency StripWhitespace ColorScale DateTimeInit Resizable CaptureHtml CaptureChart SubstringMatcher simpleGrid: item[cellName] = SharedHelpers.StripCurrency($cell.text().trim()); numericTableWidget: var numericValue = SharedHelpers.StripCurrency(SharedHelpers.StripWhitespace(value)); editableTableWidget: source: SharedHelpers.SubstringMatcher(data) --- src/js/shared.js | 4820 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4820 insertions(+) create mode 100644 src/js/shared.js diff --git a/src/js/shared.js b/src/js/shared.js new file mode 100644 index 0000000..d33f62b --- /dev/null +++ b/src/js/shared.js @@ -0,0 +1,4820 @@ +$(document).ajaxError(function (e, jqxhr, settings, exception) { + e.stopPropagation(); + if (jqxhr != null) { + + var error = ""; + + if (jqxhr.responseJSON != null) { + if (jqxhr.responseJSON.Error != null) { + error = jqxhr.responseJSON.Error; + } else { + var errors = jqxhr.responseJSON; + + $.each(errors, function (key, item) { + error += "\\\\ " + item.errors[0] + " \\\\ \n"; + }); + alert(error); + } + } else if (jqxhr.statusText) { + error = jqxhr.statusText; + } else { + error = "An error occurred trying to submit your data. Please try again and, if the problem persists, contact support."; + } + + toastr.error(error); + } +}); +(function ($) { + $.fn.changeElementType = function (newType) { + var attrs = {}; + + $.each(this[0].attributes, function (idx, attr) { + attrs[attr.nodeName] = attr.nodeValue; + }); + + this.replaceWith(function () { + return $("<" + newType + "/>", attrs).append($(this).contents()); + }); + } +})(jQuery); +$(document).ready(function () { + // Wire up the close button + $(".exit").click(function () { window.open('', '_self', '').close(); }); +}); +$(document).ready(function () { + //Custom Sorting + jQuery.extend(jQuery.fn.dataTableExt.oSort, { + "jsPrefix-pre": function (a) { + if (a.trim().toLowerCase().substring(0, 2) === "js") { + return 2; + } + return 1; + }, + + "jsPrefix-asc": function (a, b) { + return ((a < b) ? -1 : ((a > b) ? 1 : 0)); + }, + + "jsPrefix-desc": function (a, b) { + return ((a < b) ? 1 : ((a > b) ? -1 : 0)); + } + }); + + // Checkbox Sorting + $.fn.dataTable.ext.order["dom-checkbox"] = function (settings, col) { + return this.api().column(col, { order: "index" }).nodes().map(function (td, i) { + return $("input", td).prop("checked") ? "1" : "0"; + }); + }; +}); + + +function getDaySuffix(day) { + switch (day) { + case 1: + case 21: + case 31: + return "st"; + case 2: + case 22: + return "nd"; + case 3: + case 23: + return "rd"; + default: + return "th"; + } +} +jQuery(document).ready(function () { + SharedHelpers.DateTimeInit(); +}); + + +$(document).ready(function () { + $("#mainContent").css("margin-top", $(".navbar").height() - 50); +}); +function randomIntFromInterval(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} + +$(document).ready(function () { + if (randomIntFromInterval(1, 10) === 1) { + var geckoNumber = randomIntFromInterval(2, 7); + if (new Date().getDay() === 5) { //Friday for geckos, not for geckoes + $(".GeckoAnchor").addClass('gecko' + geckoNumber); + } + geckoNumber = randomIntFromInterval(1, 7); + } + var geckoSpecial = 1; + $("#gecko").click(function () { + $("#gecko").removeClass('gecko1 gecko2 gecko3 gecko4 gecko5 gecko6 gecko7') + .addClass('gecko' + geckoSpecial); + if (geckoSpecial == 7) { geckoSpecial = 1; } else { geckoSpecial++; }; + }); +}); +$(document).ready(function () { + var url = window.location.pathname; + + if (localStorage[url] === "true") { + $('.row-offcanvas').addClass('active'); + } else { + $('.row-offcanvas').removeClass('active'); + } + + $('[data-toggle="offcanvas"]').click(function () { + $('.row-offcanvas').toggleClass('active'); + + var visible = $('.row-offcanvas.active').length > 0; + var url = window.location.pathname; + localStorage[url] = visible; + }); +}); +$(document).ready(function () { + // Wire up the print button + $(".print").click(function () { + $(".unprintable").toggle(false); + $(".printonly").toggle(true); + $(".page-header").toggle(false); + $(".left-sidebar").toggle(false); + $(".header").toggle(false); + $("body").css("padding-top", "0"); + }); +}); +$(document).ready(function () { + // Enable Reload button + $(".reloadWindow").click(function () { + location.reload(true); + }); +}); +$(document).ready(function () { + // Allow Multiline Text boxes to be resized + SharedHelpers.Resizable(); +}); +var SharedHelpers = function ($) { + return { + AddAntiForgeryToken: function (data) { + data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(); + return data; + }, + StripCurrency: function (text) { + return text.replace(/\,/g, '').replace('$', '').replace('\u00A3', ''); //\u00A3 == '£' + }, + StripWhitespace: function (text) { + return text.replace(/\s/g, ''); + }, + ColorScale: ["#3498db", "#1E824C", "#9b59b6", "#1abc9c", "#34495e", "#f1c40f", "#e67e22", "#FF6BE1", "#7f8c8d", "#BE90D4"], + DateTimeInit: function () { + $('.datetime').datetimepicker({ + format: 'd M Y H:i', + validateOnBlur: true, + hours12: false, + //startDate: new Date(), + scrollInput: false + }); + + $('.date').datetimepicker({ + format: 'd M Y', + formatDate: 'd M Y', + validateOnBlur: true, + closeOnDateSelect: true, + timepicker: false, + //startDate: new Date(), + scrollInput: false + }); + }, + Resizable: function () { + $(".resizable").resizable(); + }, + CaptureHtml: function (targetId) { + $(".capture").click(function () { + html2canvas($("#" + targetId), { + onrendered: function (canvas) { + canvas.toBlob(function (blob) { + var filename = $(".page-header").text().trim(); + if (!filename) { + filename = "@ViewBag.Title"; + } + saveAs(blob, filename + ".png"); + }); + } + }); + }); + }, + CaptureChart: function (targetId, filename, captureSelector) { + if (!captureSelector) { + captureSelector = ".capture"; + } + + $(captureSelector).click(function () { + if (!filename) { + filename = $(".page-header").text().trim() !== "" + ? $(".page-header").text().trim() + : "@ViewBag.Title"; + } + + svgenie.save("#" + targetId, { name: filename + ".png" }); + }); + }, + SubstringMatcher: function (strs) { + return function findMatches(q, cb) { + + // an array that will be populated with substring matches + var matches = []; + + // regex used to determine if a string contains the substring `q` + var substrRegex = new RegExp(q, 'i'); + + // iterate through the pool of strings and for any string that + // contains the substring `q`, add it to the `matches` array + $.each(strs, function (i, str) { + if (substrRegex.test(str)) { + matches.push(str); + } + }); + + cb(matches); + }; + } + }; +}(jQuery); + +toastr.options = { + "positionClass": "toast-bottom-right" +}; +/* + * possible uses of dropdown: sort: $.editableTable.dropdownSort.ID + */ + +; (function ($, window, document, undefined) { + + var EditableTable = function (options) { + 'use strict'; + var DATE_FORMAT = 'DD MMM YYYY', + ARROW_LEFT = 37, + ARROW_UP = 38, + ARROW_RIGHT = 39, + ARROW_DOWN = 40, + ENTER = 13, + ESC = 27, + TAB = 9, + EMPTY_STRING = ''; + + var tableEditors = []; + + var init = function ($tbl) { + $tbl.each(function () { + var getColumnName = function (activeCell) { + if (activeCell) { + var colIndex = activeCell.parent().children().index(activeCell); + + return activeCell + .parents('table') + .find('thead tr th:eq(' + colIndex + ')') + .attr('name'); + } + }; + var buildDefaultOptions = function () { + var opts = $.extend({}, options.defaultOptions); + opts.editor = opts.editor.clone(); + return opts; + }, + activeOptions = $.extend(buildDefaultOptions(), options), + deletedClass = activeOptions.deletedClass || 'danger', + editedClass = activeOptions.editedClass || 'success', + element = $(this), + editor, + active, + setActiveText = function () { + var currentValue = editor.val(), + originalContent = active.html(), + originalValue = active.text().trim(), + originalAndCurrent = [currentValue, originalValue], + evt = $.Event('change', originalAndCurrent); + + if (originalValue === currentValue || editor.hasClass('error')) { + //if (activeOptions.markCellEdited) { + // active.removeClass(editedClass); + //} else if (activeOptions.markRowEdited) { + // active.parents('tr').each(function() { + // $(this).removeClass(editedClass); + // }); + //}; + return true; + }; + + // if empty overwrite all text, otherwise update only the text content (node type = 3) and not any hidden elements + if (originalValue === EMPTY_STRING) { + active.text(currentValue); + } else { + active.contents().filter(function () { + return this.nodeType === 3; + }).last().replaceWith(currentValue); + } + + active.trigger(evt, originalAndCurrent); + if (evt.result === false) { + active.html(originalContent); + } else if (activeOptions.url) { + var cellValue = {}; + var colName = active.attr('name') || getColumnName(active); + + cellValue[colName] = active.text().trim(); + + //serialize to get hidden inputs + var cellObject = $.extend({}, active.data(), cellValue); + + $.ajax({ + type: 'POST', + url: activeOptions.url, + dataType: 'json', + data: { 'postObject': cellObject }, + success: function () { + active.removeClass('error blank ' + deletedClass).addClass(editedClass); + if (typeof activeOptions.callback === "function") { + activeOptions.callback(); + } + }, + error: function () { + active.removeClass(editedClass).addClass(deletedClass); + active.html(originalContent); + active.trigger(evt, originalAndCurrent); + } + }); + } + return true; + }, + movement = function (cell, keycode) { + if (keycode === ARROW_RIGHT) { + return cell.next('td'); + } else if (keycode === ARROW_LEFT) { + return cell.prev('td'); + } else if (keycode === ARROW_UP) { + return cell.parent().prev().children().eq(cell.index()); + } else if (keycode === ARROW_DOWN) { + return cell.parent().next().children().eq(cell.index()); + } + return []; + }, + columnIsReadOnly = function (activeCell) { + var colIndex = activeCell.parent().children().index(activeCell); + var colHeader = activeCell + .parents('table') + .find('thead tr th:eq(' + colIndex + ')'); + return colHeader.attr('readonly') && !colHeader.is('[readonly="false"]'); + }, + cellIsReadOnly = function (activeCell) { + return activeCell.attr('readonly') && !activeCell.is('[readonly="false"]'); + }, + buildEditors = function () { + var eds = { 'default': activeOptions.editor }; + if (options && options.types) { + $.each(options.types, function (index, obj) { + if (obj) { + switch (obj.type) { + case 'dropdown': + + // construct select list + var sel = $('