292 lines
10 KiB
JavaScript
292 lines
10 KiB
JavaScript
/* global $, axios, i18next, isI18nReady, initSelect2, initPagination, removeAllChildNodes, currentPagePath, DateUtils, bindKeys, setVisibleAdvancedSearch */
|
|
// eslint-disable-next-line no-unused-vars
|
|
/* global isAdvancedSearchButtonPressedOddTimes:writable */
|
|
|
|
// Sorting, pagination, searching and filtering shared by /admin/slovarji and /ogled-virov.
|
|
const PAGE_CONFIG = {
|
|
'/admin/slovarji': {
|
|
apiUrl: '/api/v1/dictionaries/listAllDictionaries',
|
|
rowActionHref: id => `/admin/slovarji/${id}/podatki`,
|
|
rowActionIcon: '/images/u_edit-alt.svg',
|
|
rowActionLabelKey: 'Uredi'
|
|
},
|
|
'/ogled-virov': {
|
|
apiUrl: '/api/v1/dictionaries/listAllViewableDictionaries',
|
|
rowActionHref: id => `/ogled-virov/${id}/podatki`,
|
|
rowActionIcon: '/images/eye.svg',
|
|
rowActionLabelKey: 'Podatki'
|
|
}
|
|
}
|
|
|
|
const pageConfig = PAGE_CONFIG[currentPagePath]
|
|
|
|
if (pageConfig) {
|
|
;(function () {
|
|
const SORT_COLUMNS = [
|
|
'id',
|
|
'name',
|
|
'status',
|
|
'timeCreated',
|
|
'timeModified'
|
|
]
|
|
|
|
const resultsListEl = document.getElementById('page-results')
|
|
const headerButtons = {
|
|
id: document.getElementById('sortById'),
|
|
name: document.getElementById('sortByName'),
|
|
status: document.getElementById('sortByStatus'),
|
|
timeCreated: document.getElementById('sortByTimeCreated'),
|
|
timeModified: document.getElementById('sortByTimeModified')
|
|
}
|
|
const headerIcons = {
|
|
id: document.getElementById('idImg'),
|
|
name: document.getElementById('nameImg'),
|
|
status: document.getElementById('statusImg'),
|
|
timeCreated: document.getElementById('timeCreatedImg'),
|
|
timeModified: document.getElementById('timeModifiedImg')
|
|
}
|
|
|
|
const searchInput = document.getElementById('dict-name-search')
|
|
const searchBtn = document.getElementById('search-dictionaries')
|
|
const applyFiltersBtn = document.getElementById('apply-filters')
|
|
const clearFiltersBtn = document.getElementById('clear-filters')
|
|
|
|
const initialParams = new URL(location).searchParams
|
|
let currentPage = +initialParams.get('p') > 0 ? +initialParams.get('p') : 1
|
|
let sortBy = SORT_COLUMNS.includes(initialParams.get('sort'))
|
|
? initialParams.get('sort')
|
|
: 'id'
|
|
let sortDir = initialParams.get('dir') === 'asc' ? 'asc' : 'desc'
|
|
let nameQuery = initialParams.get('q') || ''
|
|
let primaryDomainIds = initialParams.getAll('pd')
|
|
let secondaryDomainIds = initialParams.getAll('sd')
|
|
let languageIds = initialParams.getAll('lang')
|
|
let statuses = initialParams.getAll('status')
|
|
let latestRequestId = 0
|
|
|
|
const updatePager = initPagination('pagination', onPageChange, currentPage)
|
|
|
|
bindSortHeaderListeners()
|
|
bindFilterListeners()
|
|
initFilterSelect2()
|
|
bindKeys('#dict-name-search')
|
|
if (
|
|
primaryDomainIds.length ||
|
|
secondaryDomainIds.length ||
|
|
languageIds.length ||
|
|
statuses.length
|
|
) {
|
|
// scripts.js unconditionally force-closes the panel on every page load
|
|
// (setVisibleAdvancedSearch(false), run once #advanced-search exists),
|
|
// which would otherwise override the server-rendered "open" state from
|
|
// the Pug `class` condition on #admin-dict-filter-panel. Explicitly
|
|
// reopen it here (this file loads after scripts.js) and keep the
|
|
// shared open/close counter in sync so the *next* click closes it.
|
|
isAdvancedSearchButtonPressedOddTimes = true
|
|
setVisibleAdvancedSearch(true)
|
|
}
|
|
window.addEventListener('popstate', onPopState)
|
|
|
|
function bindSortHeaderListeners() {
|
|
SORT_COLUMNS.forEach(column => {
|
|
headerButtons[column].addEventListener('click', () =>
|
|
onSortClick(column)
|
|
)
|
|
})
|
|
}
|
|
|
|
async function onSortClick(column) {
|
|
if (sortBy === column) {
|
|
sortDir = sortDir === 'asc' ? 'desc' : 'asc'
|
|
} else {
|
|
sortBy = column
|
|
sortDir = 'asc'
|
|
}
|
|
currentPage = 1
|
|
updateSortIndicators()
|
|
await fetchAndRender()
|
|
}
|
|
|
|
function updateSortIndicators() {
|
|
SORT_COLUMNS.forEach(column => {
|
|
const icon = headerIcons[column]
|
|
if (column === sortBy) {
|
|
icon.classList.remove('invisible')
|
|
icon.src =
|
|
sortDir === 'asc'
|
|
? '/images/arrow_drop_up.svg'
|
|
: '/images/arrow_drop_down.svg'
|
|
} else {
|
|
icon.classList.add('invisible')
|
|
}
|
|
})
|
|
}
|
|
|
|
async function onPageChange(newPage) {
|
|
currentPage = newPage
|
|
await fetchAndRender()
|
|
}
|
|
|
|
function initFilterSelect2() {
|
|
isI18nReady.then(t => {
|
|
initSelect2('.select-admin-domain-primary', t('Področje'))
|
|
initSelect2('.select-admin-domain-secondary', t('Podpodročje'))
|
|
initSelect2('.select-admin-language', t('Jezik'))
|
|
initSelect2('.select-admin-status', t('Status'))
|
|
})
|
|
}
|
|
|
|
function bindFilterListeners() {
|
|
// Opening/closing #admin-dict-filter-panel itself is handled globally
|
|
// by scripts.js (initAdvancedSearch('#advanced-search')), since the
|
|
// panel reuses the #advanced-search id and .advanced-search-root class
|
|
// from /slovarji's advanced-search dropdown.
|
|
searchBtn.addEventListener('click', onApplyFilters)
|
|
searchInput.addEventListener('keydown', event => {
|
|
if (event.key === 'Enter') {
|
|
event.preventDefault()
|
|
onApplyFilters()
|
|
}
|
|
})
|
|
applyFiltersBtn.addEventListener('click', onApplyFilters)
|
|
clearFiltersBtn.addEventListener('click', onClearFilters)
|
|
}
|
|
|
|
async function onApplyFilters() {
|
|
nameQuery = searchInput.value.trim()
|
|
primaryDomainIds = $('#filter-domain-primary').val() || []
|
|
secondaryDomainIds = $('#filter-domain-secondary').val() || []
|
|
languageIds = $('#filter-language').val() || []
|
|
statuses = $('#filter-status').val() || []
|
|
currentPage = 1
|
|
await fetchAndRender()
|
|
}
|
|
|
|
async function onClearFilters() {
|
|
nameQuery = ''
|
|
primaryDomainIds = []
|
|
secondaryDomainIds = []
|
|
languageIds = []
|
|
statuses = []
|
|
syncFilterControls()
|
|
currentPage = 1
|
|
await fetchAndRender()
|
|
}
|
|
|
|
function syncFilterControls() {
|
|
searchInput.value = nameQuery
|
|
$('#filter-domain-primary').val(primaryDomainIds).trigger('change')
|
|
$('#filter-domain-secondary').val(secondaryDomainIds).trigger('change')
|
|
$('#filter-language').val(languageIds).trigger('change')
|
|
$('#filter-status').val(statuses).trigger('change')
|
|
}
|
|
|
|
async function fetchAndRender(updateHistory = true) {
|
|
// Guards against out-of-order responses: if a newer request has been
|
|
// issued (e.g. rapid sort-click then back-navigation) by the time this
|
|
// one resolves, its response is stale and must not overwrite the UI.
|
|
const requestId = ++latestRequestId
|
|
try {
|
|
const { page, numberOfAllPages, results } = await getData(
|
|
currentPage
|
|
)
|
|
if (requestId !== latestRequestId) return
|
|
currentPage = page
|
|
removeAllChildNodes(resultsListEl)
|
|
renderResults(results)
|
|
updatePager(page, numberOfAllPages)
|
|
if (updateHistory) updateUrlAndHistory()
|
|
} catch (error) {
|
|
if (requestId !== latestRequestId) return
|
|
let message = i18next.t('Prišlo je do napake.')
|
|
if (error.response?.data) {
|
|
message = error.response.data
|
|
} else if (error.request) {
|
|
message = i18next.t('Strežnik ni dosegljiv. Poskusite kasneje.')
|
|
}
|
|
alert(message)
|
|
updatePager()
|
|
}
|
|
}
|
|
|
|
function buildQueryParams(page) {
|
|
const params = new URLSearchParams()
|
|
params.set('p', page)
|
|
params.set('sort', sortBy)
|
|
params.set('dir', sortDir)
|
|
if (nameQuery) params.set('q', nameQuery)
|
|
primaryDomainIds.forEach(id => params.append('pd', id))
|
|
secondaryDomainIds.forEach(id => params.append('sd', id))
|
|
languageIds.forEach(id => params.append('lang', id))
|
|
statuses.forEach(value => params.append('status', value))
|
|
return params
|
|
}
|
|
|
|
async function getData(page) {
|
|
const url = `${pageConfig.apiUrl}?${buildQueryParams(page)}`
|
|
const { data } = await axios.get(url)
|
|
return data
|
|
}
|
|
|
|
function renderResults(results) {
|
|
results.forEach(result => {
|
|
const rowEl = document.createElement('tr')
|
|
const td1 = document.createElement('td')
|
|
const td2 = document.createElement('td')
|
|
const td3 = document.createElement('td')
|
|
const td4 = document.createElement('td')
|
|
const td5 = document.createElement('td')
|
|
const td6 = document.createElement('td')
|
|
const aEl = document.createElement('a')
|
|
const imgEl = document.createElement('img')
|
|
const spanEl = document.createElement('span')
|
|
td1.textContent = result.id
|
|
td2.textContent = result.name
|
|
td3.textContent = statusLabel(result.status)
|
|
td4.textContent = DateUtils.formatDateTime(result.timeCreated)
|
|
td5.textContent = DateUtils.formatDateTime(result.timeModified)
|
|
aEl.classList.add('image-link')
|
|
aEl.type = 'link'
|
|
aEl.href = pageConfig.rowActionHref(result.id)
|
|
imgEl.src = pageConfig.rowActionIcon
|
|
imgEl.alt = i18next.t(pageConfig.rowActionLabelKey)
|
|
spanEl.className = 'normal-gray ms-1'
|
|
spanEl.textContent = i18next.t(pageConfig.rowActionLabelKey)
|
|
td6.append(aEl)
|
|
aEl.append(imgEl, spanEl)
|
|
rowEl.append(td1, td2, td3, td4, td5, td6)
|
|
resultsListEl.appendChild(rowEl)
|
|
})
|
|
}
|
|
|
|
function statusLabel(status) {
|
|
if (status === 'closed') return i18next.t('zaprt')
|
|
if (status === 'reviewed') return i18next.t('v predogledu')
|
|
return i18next.t('odprt')
|
|
}
|
|
|
|
function updateUrlAndHistory() {
|
|
const newUrl = new URL(location)
|
|
newUrl.search = buildQueryParams(currentPage).toString()
|
|
history.pushState(null, '', newUrl)
|
|
}
|
|
|
|
function onPopState() {
|
|
const params = new URL(location).searchParams
|
|
currentPage = +params.get('p') > 0 ? +params.get('p') : 1
|
|
sortBy = SORT_COLUMNS.includes(params.get('sort'))
|
|
? params.get('sort')
|
|
: 'id'
|
|
sortDir = params.get('dir') === 'asc' ? 'asc' : 'desc'
|
|
nameQuery = params.get('q') || ''
|
|
primaryDomainIds = params.getAll('pd')
|
|
secondaryDomainIds = params.getAll('sd')
|
|
languageIds = params.getAll('lang')
|
|
statuses = params.getAll('status')
|
|
updateSortIndicators()
|
|
syncFilterControls()
|
|
fetchAndRender(false)
|
|
}
|
|
})()
|
|
}
|