const StellarTimeline = { reactions: { '+1': '👍', '-1': '👎', 'laugh': '😀', 'hooray': '🎉', 'confused': '😕', 'heart': '❤️', 'rocket': '🚀', 'eyes': '👀' }, requestAPI: (url, callback, timeout) => { let retryTimes = 5; function request() { return new Promise((resolve, reject) => { let status = 0; // 0 等待 1 完成 2 超时 let timer = setTimeout(() => { if (status === 0) { status = 2; timer = null; reject('请求超时'); if (retryTimes == 0) { timeout(); } } }, 5000); fetch(url).then(function(response) { if (status !== 2) { clearTimeout(timer); resolve(response); timer = null; status = 1; } if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }).then(function(data) { retryTimes = 0; callback(data); }).catch(function(error) { if (retryTimes > 0) { retryTimes -= 1; setTimeout(() => { request(); }, 5000); } else { timeout(); } }); }); } request(); }, layoutDiv: (cfg) => { const el = $(cfg.el)[0]; $(el).append('
'); StellarTimeline.requestAPI(cfg.api, function(data) { $(el).find('.loading-wrap').remove(); const query = new URL(cfg.api).search; const arr = data.content || data; var users = []; const filter = el.getAttribute('user'); if (filter && filter.length > 0) { users = filter.split(","); } var hide = []; const hideStr = el.getAttribute('hide'); if (hideStr && hideStr.length > 0) { hide = hideStr.split(","); } arr.forEach((item, i) => { if (item.user && item.user.login && users.length > 0) { if (!users.includes(item.user.login)) { return; } } var cell = '
'; cell += '
'; if (!users.length && item.user && !hide.includes('user')) { cell += ''; } let date = new Date(item.created_at); cell += '

' + date.toString().replace(/\sGMT([^.]*)/i, "") + '

'; cell += '
'; cell += '
'; if (!hide.includes('title')) { cell += '

'; cell += ''; cell += item.title || item.name || item.tag_name; cell += ''; cell += '

'; } cell += marked.parse(item.body || ''); if (!hide.includes('footer')) { cell += ''; } cell += '
'; cell += '
'; $(el).append(cell); }); }, function() { $(el).find('.loading-wrap svg').remove(); $(el).find('.loading-wrap').append(''); $(el).find('.loading-wrap').addClass('error'); }); }, } $(function () { const els = document.getElementsByClassName('stellar-timeline-api'); for (var i = 0; i < els.length; i++) { const el = els[i]; const api = el.getAttribute('api'); if (api == null) { continue; } var obj = new Object(); obj.el = el; obj.api = api; StellarTimeline.layoutDiv(obj); } });