Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.34 KB | None | 0 0
  1. /*
  2. * Load contacts and filter by categories.
  3. */
  4. ( function() {
  5. 'use strict';
  6.  
  7. // Variables.
  8. const filterForm = document.getElementById( 'filter-contacts' );
  9. const contactWrapper = document.getElementById( 'contact-section' );
  10. const htmlOutput = document.getElementById( 'js-contact-replace' );
  11. const cityField = document.getElementById( 'select-office' );
  12. const areaField = document.getElementById( 'select-area' );
  13. const searchField = document.getElementById( 'search-contacts' );
  14.  
  15. // Filtering and search REST url.
  16. const restUrl = '/wp-json/wp/v2/contact?_embed&per_page=100';
  17.  
  18. // Set empty contacts array and fetch all the data in there.
  19. const contacts = [];
  20.  
  21. // Add loading class.
  22. contactWrapper.classList.add( 'loading' );
  23.  
  24. // Fetch info from REST API.
  25. fetch( restUrl )
  26. .then( function( response ) {
  27. const contentType = response.headers.get( 'content-type' );
  28. const totalCount = response.headers.get( 'x-wp-total' );
  29. const pages = response.headers.get( 'x-wp-totalpages' );
  30.  
  31. if ( contentType && contentType.includes( 'application/json' ) ) {
  32. loadMore( totalCount, pages );
  33. return response.json();
  34. }
  35. throw new TypeError( 'Oops, the format is not JSON.' );
  36. });
  37.  
  38. // Load contact info, 100 contacts at one time.
  39. function loadMore( totalCount, pages ) {
  40. const restUrl = '/wp-json/wp/v2/contact?_embed&per_page=100';
  41.  
  42. // Loop all pages, which was counted from the first REST API fetch.
  43. for ( let i = 1; i <= pages; i++ ) {
  44. fetch( restUrl + '&page=' + i )
  45. .then( blob => blob.json() )
  46. .then( function( data ) {
  47.  
  48. // Add data to contacts array.
  49. contacts.push( ...data );
  50.  
  51. // When all data have been loaded, init first filtering and remove 'loading' class.
  52. if ( contacts.length == totalCount ) {
  53. filterByCategory();
  54. contactWrapper.classList.remove( 'loading' );
  55. }
  56. });
  57. }
  58. }
  59.  
  60. // Template for contact cards.
  61. function contactsTemplate( item, itemTitle, itemJobTitle, itemPhone ) {
  62.  
  63. // Get featured image if it's exist. Default img set in functions.php
  64. let featuredImg = 0 !== item.featured_media ? item._embedded['wp:featuredmedia'][0]['media_details']['sizes']['valteri-small']['source_url'] : ValteriContacts.defaultImg;
  65.  
  66. // Get other data.
  67. let title = '' == itemTitle ? item.title.rendered : itemTitle;
  68. let jobTitle = '' == itemTitle ? item.contact_meta_fields._valteri_contact_job_title[0]: itemJobTitle;
  69. let email = item.contact_meta_fields._valteri_contact_email[0];
  70. let phone = '' == itemPhone ? item.contact_meta_fields._valteri_contact_phone[0]: itemPhone;
  71. let cat = item._embedded['wp:term'][0][0]['name'];
  72. let area = item._embedded['wp:term'][1][0]['name'];
  73. let info = item.contact_meta_fields._valteri_contact_info[0];
  74.  
  75. // Add article.
  76. return `<article class="hentry contact">
  77. <div class="entry-inner-wrapper entry-inner-contact">
  78. <header class="entry-header">
  79. <p class="entry-author">
  80. <img class="attachment-valteri-small size-valteri-small wp-post-image" src="${featuredImg}" alt="">
  81. </p>
  82. <h2 class="entry-title heading-medium">${title}</h2>
  83. </header>
  84. <div class="entry-summary">
  85. <ul class="border-list no-margin-bottom">
  86. <li>${jobTitle}</li>
  87. <li><a href="mailto:${email}">${email}</a></li>
  88. <li>${ValteriContacts.phone} ${phone}</li>
  89. <li>${cat}</li>
  90. <li>${area}</li>
  91. <li>${info}</li>
  92. </ul>
  93. </div>
  94. </div>
  95. </article>`;
  96. }
  97.  
  98. // Filter by area category.
  99. function filterByCategory() {
  100.  
  101. // Get field values.
  102. const office = cityField.value;
  103. const area = areaField.value;
  104.  
  105. // Sent as empty.
  106. const title = '';
  107. const jobTitle = '';
  108. const phone = '';
  109.  
  110. // Filter by field values.
  111. const filteredArray = contacts.filter( contact => ( contact.contact_cat[0] == office && contact.contact_area[0] == area ) );
  112. console.log( filteredArray );
  113.  
  114. // Sort by name.
  115. const sortArray = filteredArray.sort( ( a, b ) => a.title.rendered > b.title.rendered ? 1 : -1 );
  116.  
  117. // Empty previous output.
  118. htmlOutput.innerHTML = '';
  119.  
  120. // Clear search field.
  121. searchField.value = '';
  122.  
  123. // If we have data, lets load it.
  124. if ( 0 < sortArray.length ) {
  125. const html = sortArray.map( contact => {
  126. return contactsTemplate( contact, title, jobTitle, phone );
  127. }).join( '' );
  128.  
  129. htmlOutput.innerHTML = html;
  130.  
  131. // Let screen reader announce the success message.
  132. wp.a11y.speak( ValteriContacts.found, 'assertive' );
  133. } else {
  134. const notFound = `<p class="contacts-not-found center-block">${ValteriContacts.notFound}</p>`;
  135. htmlOutput.innerHTML = notFound;
  136.  
  137. // Let screen reader announce the not found message.
  138. wp.a11y.speak( ValteriContacts.notFound, 'assertive' );
  139. }
  140. }
  141.  
  142. // Find search match results.
  143. function findMatches( wordToMatch, contacts ) {
  144. return contacts.filter( search => {
  145.  
  146. // What was searched.
  147. const regex = new RegExp( wordToMatch, 'gi' );
  148. return search.title.rendered.match( regex ) || search.contact_meta_fields._valteri_contact_job_title[0].match( regex ) || search.contact_meta_fields._valteri_contact_phone[0].match( regex );
  149. });
  150. }
  151.  
  152. // Display search results.
  153. function displayMatches() {
  154.  
  155. // Find matches.
  156. const matchArray = findMatches( this.value, contacts );
  157.  
  158. // Sort alphabetically.
  159. const sortArray = matchArray.sort( ( a, b ) => a.title.rendered > b.title.rendered ? 1 : -1 );
  160.  
  161. //
  162. const html = sortArray.map( contact => {
  163. const regex = new RegExp( this.value, 'gi' );
  164.  
  165. // Add highlight <span>.
  166. const title = contact.title.rendered.replace( regex, `<span class="highlight">${this.value}</span>` );
  167. const jobTitle = contact.contact_meta_fields._valteri_contact_job_title[0].replace( regex, `<span class="highlight">${this.value}</span>` );
  168. const phone = contact.contact_meta_fields._valteri_contact_phone[0].replace( regex, `<span class="highlight">${this.value}</span>` );
  169. return contactsTemplate( contact, title, jobTitle, phone );
  170. }).join( '' );
  171.  
  172. // Add contact cards, empty first just in case.
  173. htmlOutput.innerHTML = '';
  174. htmlOutput.innerHTML = html;
  175. }
  176.  
  177. // Filter by selected category.
  178. cityField.addEventListener( 'change', filterByCategory );
  179. areaField.addEventListener( 'change', filterByCategory );
  180.  
  181. // Filter by search.
  182. searchField.addEventListener( 'change', displayMatches );
  183. searchField.addEventListener( 'keyup', displayMatches );
  184.  
  185. }() );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement