edu-senex/edu/js/cheatsheets.js

74 Zeilen
3,6 KiB
JavaScript

'use strict';
var CheatSheets = {
render: function(params) {
var el = document.getElementById('content');
if (params[0]) { this.renderSingle(el, params[0]); return; }
el.textContent = 'Lade Cheat Sheets...';
var self = this;
API.get('/cheatsheets').then(function(data) { self.renderList(el, data.cheatsheets); })
.catch(function(e) { el.textContent = e.message; });
},
renderList: function(el, sheets) {
var groups = {};
sheets.forEach(function(s) {
var cat = s.category || 'Sonstige';
if (!groups[cat]) groups[cat] = [];
groups[cat].push(s);
});
var h = '<div class="page-header"><h1>Cheat Sheets</h1><p>' + sheets.length + ' Referenzkarten</p></div>';
h += '<div class="search-bar"><input type="search" id="sheet-search" placeholder="Suchen..."></div>';
h += '<div id="sheet-list">';
Object.keys(groups).forEach(function(cat) {
h += '<h3 style="margin:16px 0 8px;color:var(--text-secondary)">' + Markdown.esc(cat) + '</h3><div class="sheet-grid">';
groups[cat].forEach(function(s) {
h += '<div class="sheet-card" data-slug="' + s.slug + '"><div class="sheet-title">' + Markdown.esc(s.title) + '</div>';
h += '<div class="sheet-cat">' + Markdown.esc(s.category) + '</div></div>';
});
h += '</div>';
});
h += '</div>';
el.innerHTML = h;
el.querySelectorAll('.sheet-card').forEach(function(card) {
card.addEventListener('click', function() { location.hash = '#/cheatsheets/' + card.dataset.slug; });
});
var self = this;
var searchTimer;
document.getElementById('sheet-search').addEventListener('input', function() {
clearTimeout(searchTimer);
var q = this.value;
searchTimer = setTimeout(function() {
if (q.length < 2) {
API.get('/cheatsheets').then(function(data) { self.renderList(el, data.cheatsheets); });
} else {
API.get('/cheatsheets/search?q=' + encodeURIComponent(q)).then(function(data) {
var list = document.getElementById('sheet-list');
if (!list) return;
var lh = '<div class="sheet-grid">';
data.cheatsheets.forEach(function(s) {
lh += '<div class="sheet-card" data-slug="' + s.slug + '"><div class="sheet-title">' + Markdown.esc(s.title) + '</div><div class="sheet-cat">' + Markdown.esc(s.category) + '</div></div>';
});
lh += '</div>';
if (data.cheatsheets.length === 0) lh = '<div class="empty-state">Keine Treffer</div>';
list.innerHTML = lh;
list.querySelectorAll('.sheet-card').forEach(function(card) {
card.addEventListener('click', function() { location.hash = '#/cheatsheets/' + card.dataset.slug; });
});
}).catch(function() {});
}
}, 300);
});
},
renderSingle: function(el, slug) {
el.textContent = 'Lade...';
API.get('/cheatsheets/' + slug).then(function(data) {
var s = data.cheatsheet;
var h = '<a href="#/cheatsheets" class="back-link">&larr; Zurueck zu Cheat Sheets</a>';
h += '<div class="sheet-content">' + Markdown.render(s.content_md) + '</div>';
el.innerHTML = h;
}).catch(function(e) { el.textContent = e.message; });
}
};