MediaWiki: Common.js

From Bharatpedia
Jump to: navigation, search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */
$(function () {
	var myElement = document.getElementById('search-box');
	myElement.innerHTML = '<div id="autocomplete" class="autocomplete">
  <input class="autocomplete-input" placeholder="Search Bharatpedia" aria-label="Search Bharatpedia"/>
  <ul class="autocomplete-result-list"></ul>
</div>';
}());
console.clear()

const wikiUrl = 'https://en.bharatpedia.org'
const params = 'action=query&list=search&format=json&origin=*'

new Autocomplete('#autocomplete', {
  
  // Search function can return a promise
  // which resolves with an array of
  // results. In this case we're using
  // the bharatpedia search API.
  search: input => {
    const url = `${wikiUrl}/api.php?${
      params
    }&srsearch=${encodeURI(input)}`

    return new Promise(resolve => {
      if (input.length < 3) {
        return resolve([])
      }

      fetch(url)
        .then(response => response.json())
        .then(data => {
          const results = data.query.search.map((result, index) => {
            return { ...result, index }
          })
          resolve(results)
        })
    })
  },
  
  // Control the rendering of result items.
  // Let's show the title and snippet
  // from the bharatpedia results
  renderResult: (result, props) => {
    let group = ''
    if (result.index % 3 === 0) {
      group = `<li class="group">Group</li>`
    }
    return `
      ${group}
      <li ${props}>
        <div class="wiki-title">
          ${result.title}
        </div>
        <div class="wiki-snippet">
          ${result.snippet}
        </div>
      </li>
    `
  },
  
  // bharatpedia returns a format like this:
  //
  // {
  //   pageid: 12345,
  //   title: 'Article title',
  //   ...
  // }
  // 
  // We want to display the title
  getResultValue: result => result.title,

  // Open the selected article in
  // a new window
  onSubmit: result => {
    window.open(`${wikiUrl}/wiki/${
      encodeURI(result.title)
    }`)
  }
})