forms.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. $(document).ready(function() {
  2. // Pagination
  3. $('select#per_page').change(function() {
  4. this.form.submit();
  5. });
  6. // "Toggle" checkbox for object lists (PK column)
  7. $('input:checkbox.toggle').click(function() {
  8. $(this).closest('table').find('input:checkbox[name=pk]:visible').prop('checked', $(this).prop('checked'));
  9. // Show the "select all" box if present
  10. if ($(this).is(':checked')) {
  11. $('#select_all_box').removeClass('hidden');
  12. } else {
  13. $('#select_all').prop('checked', false);
  14. }
  15. });
  16. // Uncheck the "toggle" and "select all" checkboxes if an item is unchecked
  17. $('input:checkbox[name=pk]').click(function (event) {
  18. if (!$(this).attr('checked')) {
  19. $('input:checkbox.toggle, #select_all').prop('checked', false);
  20. }
  21. });
  22. // Enable hidden buttons when "select all" is checked
  23. $('#select_all').click(function() {
  24. if ($(this).is(':checked')) {
  25. $('#select_all_box').find('button').prop('disabled', '');
  26. } else {
  27. $('#select_all_box').find('button').prop('disabled', 'disabled');
  28. }
  29. });
  30. // Slugify
  31. function slugify(s, num_chars) {
  32. s = s.replace(/[^\-\.\w\s]/g, ''); // Remove unneeded chars
  33. s = s.replace(/^[\s\.]+|[\s\.]+$/g, ''); // Trim leading/trailing spaces
  34. s = s.replace(/[\-\.\s]+/g, '-'); // Convert spaces and decimals to hyphens
  35. s = s.toLowerCase(); // Convert to lowercase
  36. return s.substring(0, num_chars); // Trim to first num_chars chars
  37. }
  38. var slug_field = $('#id_slug');
  39. if (slug_field) {
  40. var slug_source = $('#id_' + slug_field.attr('slug-source'));
  41. var slug_length = slug_field.attr('maxlength');
  42. if (slug_field.val()) {
  43. slug_field.attr('_changed', true);
  44. }
  45. slug_field.change(function() {
  46. $(this).attr('_changed', true);
  47. });
  48. slug_source.on('keyup change', function() {
  49. if (slug_field && !slug_field.attr('_changed')) {
  50. slug_field.val(slugify($(this).val(), (slug_length ? slug_length : 50)));
  51. }
  52. });
  53. $('button.reslugify').click(function() {
  54. slug_field.val(slugify(slug_source.val(), (slug_length ? slug_length : 50)));
  55. });
  56. }
  57. // Bulk edit nullification
  58. $('input:checkbox[name=_nullify]').click(function() {
  59. $('#id_' + this.value).toggle('disabled');
  60. });
  61. // Set formaction and submit using a link
  62. $('a.formaction').click(function(event) {
  63. event.preventDefault();
  64. var form = $(this).closest('form');
  65. form.attr('action', $(this).attr('href'));
  66. form.submit();
  67. });
  68. // Parse URLs which may contain variable references to other field values
  69. function parseURL(url) {
  70. var filter_regex = /\{\{([a-z_]+)\}\}/g;
  71. var match;
  72. var rendered_url = url;
  73. var filter_field;
  74. while (match = filter_regex.exec(url)) {
  75. filter_field = $('#id_' + match[1]);
  76. var custom_attr = $('option:selected', filter_field).attr('api-value');
  77. if (custom_attr) {
  78. rendered_url = rendered_url.replace(match[0], custom_attr);
  79. } else if (filter_field.val()) {
  80. rendered_url = rendered_url.replace(match[0], filter_field.val());
  81. } else if (filter_field.attr('data-null-option')) {
  82. rendered_url = rendered_url.replace(match[0], 'null');
  83. }
  84. }
  85. return rendered_url
  86. }
  87. // Assign color picker selection classes
  88. function colorPickerClassCopy(data, container) {
  89. if (data.element) {
  90. // Swap the style
  91. $(container).attr('style', $(data.element).attr("style"));
  92. }
  93. return data.text;
  94. }
  95. // Color Picker
  96. $('.netbox-select2-color-picker').select2({
  97. allowClear: true,
  98. placeholder: "---------",
  99. theme: "bootstrap",
  100. templateResult: colorPickerClassCopy,
  101. templateSelection: colorPickerClassCopy,
  102. width: "off"
  103. });
  104. // Static choice selection
  105. $('.netbox-select2-static').select2({
  106. allowClear: true,
  107. placeholder: "---------",
  108. theme: "bootstrap",
  109. width: "off"
  110. });
  111. // API backed selection
  112. // Includes live search and chained fields
  113. // The `multiple` setting may be controlled via a data-* attribute
  114. $('.netbox-select2-api').select2({
  115. allowClear: true,
  116. placeholder: "---------",
  117. theme: "bootstrap",
  118. width: "off",
  119. ajax: {
  120. delay: 500,
  121. url: function(params) {
  122. var element = this[0];
  123. var url = parseURL(element.getAttribute("data-url"));
  124. if (url.includes("{{")) {
  125. // URL is not fully rendered yet, abort the request
  126. return false;
  127. }
  128. return url;
  129. },
  130. data: function(params) {
  131. var element = this[0];
  132. // Paging. Note that `params.page` indexes at 1
  133. var offset = (params.page - 1) * 50 || 0;
  134. // Base query params
  135. var parameters = {
  136. q: params.term,
  137. limit: 50,
  138. offset: offset,
  139. };
  140. // Allow for controlling the brief setting from within APISelect
  141. parameters.brief = ( $(element).is('[data-full]') ? undefined : true );
  142. // filter-for fields from a chain
  143. var attr_name = "data-filter-for-" + $(element).attr("name");
  144. var form = $(element).closest('form');
  145. var filter_for_elements = form.find("select[" + attr_name + "]");
  146. filter_for_elements.each(function(index, filter_for_element) {
  147. var param_name = $(filter_for_element).attr(attr_name);
  148. var is_required = $(filter_for_element).attr("required");
  149. var is_nullable = $(filter_for_element).attr("data-null-option");
  150. var is_visible = $(filter_for_element).is(":visible");
  151. var value = $(filter_for_element).val();
  152. if (param_name && is_visible) {
  153. if (value) {
  154. parameters[param_name] = value;
  155. } else if (is_required && is_nullable) {
  156. parameters[param_name] = "null";
  157. }
  158. }
  159. });
  160. // Additional query params
  161. $.each(element.attributes, function(index, attr){
  162. if (attr.name.includes("data-additional-query-param-")){
  163. var param_name = attr.name.split("data-additional-query-param-")[1];
  164. $.each($.parseJSON(attr.value), function(index, value) {
  165. if (param_name in parameters) {
  166. if (Array.isArray(parameters[param_name])) {
  167. parameters[param_name].push(value);
  168. } else {
  169. parameters[param_name] = [parameters[param_name], value];
  170. }
  171. } else {
  172. parameters[param_name] = value;
  173. }
  174. });
  175. }
  176. });
  177. // This will handle params with multiple values (i.e. for list filter forms)
  178. return $.param(parameters, true);
  179. },
  180. processResults: function (data) {
  181. var element = this.$element[0];
  182. $(element).children('option').attr('disabled', false);
  183. var results = data.results;
  184. results = results.reduce((results,record,idx) => {
  185. record.text = record[element.getAttribute('display-field')] || record.name;
  186. if (record._depth) {
  187. // Annotate hierarchical depth for MPTT objects
  188. record.text = '--'.repeat(record._depth) + ' ' + record.text;
  189. }
  190. record.id = record[element.getAttribute('value-field')] || record.id;
  191. if(element.getAttribute('disabled-indicator') && record[element.getAttribute('disabled-indicator')]) {
  192. // The disabled-indicator equated to true, so we disable this option
  193. record.disabled = true;
  194. }
  195. if( record.group !== undefined && record.group !== null && record.site !== undefined && record.site !== null ) {
  196. results[record.site.name + ":" + record.group.name] = results[record.site.name + ":" + record.group.name] || { text: record.site.name + " / " + record.group.name, children: [] };
  197. results[record.site.name + ":" + record.group.name].children.push(record);
  198. }
  199. else if( record.group !== undefined && record.group !== null ) {
  200. results[record.group.name] = results[record.group.name] || { text: record.group.name, children: [] };
  201. results[record.group.name].children.push(record);
  202. }
  203. else if( record.site !== undefined && record.site !== null ) {
  204. results[record.site.name] = results[record.site.name] || { text: record.site.name, children: [] };
  205. results[record.site.name].children.push(record);
  206. }
  207. else if ( (record.group !== undefined || record.group == null) && (record.site !== undefined || record.site === null) ) {
  208. results['global'] = results['global'] || { text: 'Global', children: [] };
  209. results['global'].children.push(record);
  210. }
  211. else {
  212. results[idx] = record
  213. }
  214. return results;
  215. },Object.create(null));
  216. results = Object.values(results);
  217. // Handle the null option, but only add it once
  218. if (element.getAttribute('data-null-option') && data.previous === null) {
  219. results.unshift({
  220. id: 'null',
  221. text: element.getAttribute('data-null-option')
  222. });
  223. }
  224. // Check if there are more results to page
  225. var page = data.next !== null;
  226. return {
  227. results: results,
  228. pagination: {
  229. more: page
  230. }
  231. };
  232. }
  233. }
  234. });
  235. // Flatpickr selectors
  236. $('.date-picker').flatpickr({
  237. allowInput: true
  238. });
  239. $('.datetime-picker').flatpickr({
  240. allowInput: true,
  241. enableSeconds: true,
  242. enableTime: true,
  243. time_24hr: true
  244. });
  245. $('.time-picker').flatpickr({
  246. allowInput: true,
  247. enableSeconds: true,
  248. enableTime: true,
  249. noCalendar: true,
  250. time_24hr: true
  251. });
  252. // API backed tags
  253. var tags = $('#id_tags.tagfield');
  254. if (tags.length > 0 && tags.val().length > 0){
  255. tags = $('#id_tags.tagfield').val().split(/,\s*/);
  256. } else {
  257. tags = [];
  258. }
  259. tag_objs = $.map(tags, function (tag) {
  260. return {
  261. id: tag,
  262. text: tag,
  263. selected: true
  264. }
  265. });
  266. // Replace the django issued text input with a select element
  267. $('#id_tags.tagfield').replaceWith('<select name="tags" id="id_tags" class="form-control tagfield"></select>');
  268. $('#id_tags.tagfield').select2({
  269. tags: true,
  270. data: tag_objs,
  271. multiple: true,
  272. allowClear: true,
  273. placeholder: "Tags",
  274. theme: "bootstrap",
  275. width: "off",
  276. ajax: {
  277. delay: 250,
  278. url: netbox_api_path + "extras/tags/",
  279. data: function(params) {
  280. // Paging. Note that `params.page` indexes at 1
  281. var offset = (params.page - 1) * 50 || 0;
  282. var parameters = {
  283. q: params.term,
  284. brief: 1,
  285. limit: 50,
  286. offset: offset,
  287. };
  288. return parameters;
  289. },
  290. processResults: function (data) {
  291. var results = $.map(data.results, function (obj) {
  292. // If tag contains space add double quotes
  293. if (/\s/.test(obj.name))
  294. obj.name = '"' + obj.name + '"'
  295. return {
  296. id: obj.name,
  297. text: obj.name
  298. }
  299. });
  300. // Check if there are more results to page
  301. var page = data.next !== null;
  302. return {
  303. results: results,
  304. pagination: {
  305. more: page
  306. }
  307. };
  308. }
  309. }
  310. });
  311. $('#id_tags.tagfield').closest('form').submit(function(event){
  312. // django-taggit can only accept a single comma seperated string value
  313. var value = $('#id_tags.tagfield').val();
  314. if (value.length > 0){
  315. var final_tags = value.join(', ');
  316. $('#id_tags.tagfield').val(null).trigger('change');
  317. var option = new Option(final_tags, final_tags, true, true);
  318. $('#id_tags.tagfield').append(option).trigger('change');
  319. }
  320. });
  321. if( $('select#id_mode').length > 0 ) {
  322. $('select#id_mode').on('change', function () {
  323. if ($(this).val() == '') {
  324. $('select#id_untagged_vlan').val();
  325. $('select#id_untagged_vlan').trigger('change');
  326. $('select#id_tagged_vlans').val([]);
  327. $('select#id_tagged_vlans').trigger('change');
  328. $('select#id_untagged_vlan').parent().parent().hide();
  329. $('select#id_tagged_vlans').parent().parent().hide();
  330. }
  331. else if ($(this).val() == 'access') {
  332. $('select#id_tagged_vlans').val([]);
  333. $('select#id_tagged_vlans').trigger('change');
  334. $('select#id_untagged_vlan').parent().parent().show();
  335. $('select#id_tagged_vlans').parent().parent().hide();
  336. }
  337. else if ($(this).val() == 'tagged') {
  338. $('select#id_untagged_vlan').parent().parent().show();
  339. $('select#id_tagged_vlans').parent().parent().show();
  340. }
  341. else if ($(this).val() == 'tagged-all') {
  342. $('select#id_tagged_vlans').val([]);
  343. $('select#id_tagged_vlans').trigger('change');
  344. $('select#id_untagged_vlan').parent().parent().show();
  345. $('select#id_tagged_vlans').parent().parent().hide();
  346. }
  347. });
  348. $('select#id_mode').trigger('change');
  349. }
  350. // Scroll up an offset equal to the first nav element if a hash is present
  351. // Cannot use '#navbar' because it is not always visible, like in small windows
  352. function headerOffsetScroll() {
  353. if (window.location.hash) {
  354. // Short wait needed to allow the page to scroll to the element
  355. setTimeout(function() {
  356. window.scrollBy(0, -$('nav').height())
  357. }, 10);
  358. }
  359. }
  360. // Account for the header height when hash-scrolling
  361. window.addEventListener('load', headerOffsetScroll);
  362. window.addEventListener('hashchange', headerOffsetScroll);
  363. // Offset between the preview window and the window edges
  364. const IMAGE_PREVIEW_OFFSET_X = 20;
  365. const IMAGE_PREVIEW_OFFSET_Y = 10;
  366. // Preview an image attachment when the link is hovered over
  367. $('a.image-preview').on('mouseover', function(e) {
  368. // Twice the offset to account for all sides of the picture
  369. var maxWidth = window.innerWidth - (e.clientX + (IMAGE_PREVIEW_OFFSET_X * 2));
  370. var maxHeight = window.innerHeight - (e.clientY + (IMAGE_PREVIEW_OFFSET_Y * 2));
  371. var img = $('<img>').attr('id', 'image-preview-window').css({
  372. display: 'none',
  373. position: 'absolute',
  374. maxWidth: maxWidth + 'px',
  375. maxHeight: maxHeight + 'px',
  376. left: e.pageX + IMAGE_PREVIEW_OFFSET_X + 'px',
  377. top: e.pageY + IMAGE_PREVIEW_OFFSET_Y + 'px',
  378. boxShadow: '0 0px 12px 3px rgba(0, 0, 0, 0.4)',
  379. });
  380. // Remove any existing preview windows and add the current one
  381. $('#image-preview-window').remove();
  382. $('body').append(img);
  383. // Once loaded, show the preview if the image is indeed an image
  384. img.on('load', function(e) {
  385. if (e.target.complete && e.target.naturalWidth) {
  386. $('#image-preview-window').fadeIn('fast');
  387. }
  388. });
  389. // Begin loading
  390. img.attr('src', e.target.href);
  391. });
  392. // Fade the image out; it will be deleted when another one is previewed
  393. $('a.image-preview').on('mouseout', function() {
  394. $('#image-preview-window').fadeOut('fast');
  395. });
  396. // Rearrange options within a <select> list
  397. $('#move-option-up').bind('click', function() {
  398. var select_id = '#' + $(this).attr('data-target');
  399. $(select_id + ' option:selected').each(function () {
  400. var newPos = $(select_id + ' option').index(this) - 1;
  401. if (newPos > -1) {
  402. $(select_id + ' option').eq(newPos).before("<option value='" + $(this).val() + "' selected='selected'>" + $(this).text() + "</option>");
  403. $(this).remove();
  404. }
  405. });
  406. });
  407. $('#move-option-down').bind('click', function() {
  408. var select_id = '#' + $(this).attr('data-target');
  409. var countOptions = $(select_id + ' option').length;
  410. var countSelectedOptions = $(select_id + ' option:selected').length;
  411. $(select_id + ' option:selected').each(function () {
  412. var newPos = $(select_id + ' option').index(this) + countSelectedOptions;
  413. if (newPos < countOptions) {
  414. $(select_id + ' option').eq(newPos).after("<option value='" + $(this).val() + "' selected='selected'>" + $(this).text() + "</option>");
  415. $(this).remove();
  416. }
  417. });
  418. });
  419. $('#select-all-options').bind('click', function() {
  420. var select_id = '#' + $(this).attr('data-target');
  421. $(select_id + ' option').prop('selected',true);
  422. });
  423. });