[Operator] Integrasi view laman Dashboard, Mahasiswa, dan Pegawai
This commit is contained in:
+297
-3
@@ -1,8 +1,10 @@
|
||||
import Alpine from 'alpinejs';
|
||||
import morph from '@alpinejs/morph';
|
||||
import $ from 'jquery';
|
||||
import select2 from 'select2';
|
||||
|
||||
window.Alpine = Alpine;
|
||||
Alpine.plugin(morph);
|
||||
window.$ = window.jQuery = $;
|
||||
select2(window, $);
|
||||
|
||||
@@ -284,6 +286,189 @@ window.addEventListener('pageshow', (event) => {
|
||||
if (event.persisted) document.querySelectorAll('form[data-busy]').forEach((form) => setBusy(form, false));
|
||||
});
|
||||
|
||||
/*
|
||||
* Muat di tempat: formulir GET dan tautan yang hanya mengganti query halaman yang sama (filter, pencarian,
|
||||
* tab, halaman tabel, pilihan kelas/semester) diambil lewat fetch, lalu isi <main> ditukar. Alamat di
|
||||
* peramban tidak berubah; setiap permintaan dicatat di konsol. Query yang terbawa saat halaman dibuka
|
||||
* (tautan dari halaman lain, kembali setelah simpan) dihapus dari bilah alamat. Respons yang bukan
|
||||
* halaman ini (unduhan, galat, sesi habis) dibuka sebagai navigasi biasa. Lewati dengan data-no-remote.
|
||||
* Tanpa X-Requested-With: Laravel tetap mencatat alamat terakhir, jadi back() setelah validasi gagal
|
||||
* kembali ke filter yang sedang dipakai.
|
||||
*/
|
||||
const remoteMain = () => document.querySelector('main#isi');
|
||||
const samePage = (url) => url.origin === location.origin && url.pathname === location.pathname && !url.hash;
|
||||
let remoteRequest = null;
|
||||
|
||||
if (remoteMain() && location.search) history.replaceState(history.state, '', location.pathname + location.hash);
|
||||
|
||||
// Fokus dipulihkan lewat id (kolom cari, pilihan Select2) agar keyboard tidak kehilangan tempat
|
||||
const focusKey = () => {
|
||||
const el = document.activeElement;
|
||||
if (!(el instanceof HTMLElement) || !remoteMain()?.contains(el)) return null;
|
||||
const select = el.closest('.select2-container')?.previousElementSibling;
|
||||
if (select?.id) return { id: select.id, select2: true };
|
||||
return el.id ? { id: el.id, select2: false } : null;
|
||||
};
|
||||
|
||||
const restoreFocus = (key) => {
|
||||
const el = key && document.getElementById(key.id);
|
||||
if (!el) return;
|
||||
const target = key.select2 ? el.nextElementSibling?.querySelector('.select2-selection') : el;
|
||||
target?.focus({ preventScroll: true });
|
||||
if (target instanceof HTMLInputElement && /^(search|text)$/.test(target.type)) target.setSelectionRange(target.value.length, target.value.length);
|
||||
};
|
||||
|
||||
/*
|
||||
* Isi <main> diperbarui dengan morph: hanya teks dan atribut yang berbeda yang diubah, jadi kartu tidak
|
||||
* dirender ulang (tanpa animasi masuk) dan state Alpine (mis. tab terpilih) bertahan. Komponen yang
|
||||
* ekspresi x-data-nya berubah diganti utuh agar mulai dengan data baru. <canvas> dibiarkan: grafik
|
||||
* memperbarui dirinya dari data-chart. Select2 dilepas lalu dipasang lagi dalam satu tugas (tanpa kedip).
|
||||
*/
|
||||
const releaseSelect = (el) => {
|
||||
$(el).off('.bridge select2:open').select2('destroy');
|
||||
delete el.dataset.select2Ready;
|
||||
};
|
||||
|
||||
const freshValue = (el, to) => {
|
||||
if (el.tagName === 'SELECT') return (to.querySelector('option[selected]') ?? to.querySelector('option'))?.value ?? '';
|
||||
if (el.tagName === 'TEXTAREA') return to.textContent;
|
||||
return to.getAttribute('value') ?? '';
|
||||
};
|
||||
|
||||
/*
|
||||
* Angka berhitung dari nilai lama ke nilai baru (elemen [data-count], mis. nilai ui.stat dan teks ui.meter).
|
||||
* Format Indonesia: titik ribuan, koma desimal. Bila susunan teks di luar angka berbeda (mis. "–" menjadi
|
||||
* "3,25"), teks langsung diganti. Tanpa hitungan saat gerak dikurangi.
|
||||
*/
|
||||
const NUMBER = /\d{1,3}(?:\.\d{3})+(?:,\d+)?|\d+(?:,\d+)?/g;
|
||||
const parseNumber = (text) => Number(text.replace(/\./g, '').replace(',', '.'));
|
||||
|
||||
const countTo = (el, from, to) => {
|
||||
cancelAnimationFrame(el._countFrame);
|
||||
const start = from.match(NUMBER) ?? [];
|
||||
const end = to.match(NUMBER) ?? [];
|
||||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches || !end.length || from.replace(NUMBER, '#') !== to.replace(NUMBER, '#')) {
|
||||
el.textContent = to;
|
||||
return;
|
||||
}
|
||||
const formats = end.map((token) => {
|
||||
const digits = (token.split(',')[1] ?? '').length;
|
||||
return new Intl.NumberFormat('id-ID', { minimumFractionDigits: digits, maximumFractionDigits: digits, useGrouping: token.includes('.') || parseNumber(token) < 1000 });
|
||||
});
|
||||
const parts = to.split(NUMBER);
|
||||
const began = performance.now();
|
||||
const frame = (now) => {
|
||||
const t = Math.min((now - began) / 700, 1);
|
||||
const eased = 1 - (1 - t) ** 3;
|
||||
el.textContent = t === 1 ? to : parts.reduce((text, part, i) => {
|
||||
if (i === end.length) return text + part;
|
||||
const a = parseNumber(start[i]);
|
||||
const b = parseNumber(end[i]);
|
||||
return text + part + formats[i].format(a + (b - a) * eased);
|
||||
}, '');
|
||||
if (t < 1) el._countFrame = requestAnimationFrame(frame);
|
||||
};
|
||||
el._countFrame = requestAnimationFrame(frame);
|
||||
};
|
||||
|
||||
const morphMain = (main, fresh) => {
|
||||
$(main).find('select').filter((_, el) => $(el).data('select2')).each((_, el) => releaseSelect(el));
|
||||
const replaced = [];
|
||||
const controls = [];
|
||||
const counts = [];
|
||||
|
||||
Alpine.morph(main, fresh, {
|
||||
updating(el, to, childrenOnly, skip) {
|
||||
if (el.nodeType !== 1) return;
|
||||
if (el.tagName === 'CANVAS') return skip();
|
||||
if (el.hasAttribute('data-count') && el.textContent.trim() !== to.textContent.trim()) {
|
||||
counts.push([el, el.textContent.trim(), to.textContent.trim()]);
|
||||
return skip();
|
||||
}
|
||||
if (el.hasAttribute('x-data') && el.getAttribute('x-data') !== to.getAttribute('x-data')) {
|
||||
replaced.push([el, to.cloneNode(true)]);
|
||||
return skip();
|
||||
}
|
||||
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && el.type !== 'file' && el !== document.activeElement) controls.push([el, to]);
|
||||
},
|
||||
});
|
||||
|
||||
// Nilai yang pernah diubah pengguna tidak mengikuti atribut value/selected: samakan dengan halaman baru
|
||||
controls.forEach(([el, to]) => {
|
||||
if (el.type === 'checkbox' || el.type === 'radio') el.checked = to.hasAttribute('checked');
|
||||
else if (el.value !== freshValue(el, to)) el.value = freshValue(el, to);
|
||||
});
|
||||
replaced.forEach(([el, clone]) => el.replaceWith(clone));
|
||||
counts.forEach(([el, from, to]) => countTo(el, from, to));
|
||||
enhanceAllSelects(main);
|
||||
};
|
||||
|
||||
const visit = async (url, link = null) => {
|
||||
const main = remoteMain();
|
||||
remoteRequest?.abort();
|
||||
const controller = new AbortController();
|
||||
remoteRequest = controller;
|
||||
const label = `${url.pathname}${url.search}`;
|
||||
const started = performance.now();
|
||||
const key = focusKey();
|
||||
startLoading(link ?? main);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { headers: { Accept: 'text/html' }, signal: controller.signal });
|
||||
const html = (response.headers.get('Content-Type') ?? '').includes('text/html') ? await response.text() : '';
|
||||
const page = html ? new DOMParser().parseFromString(html, 'text/html') : null;
|
||||
const fresh = page?.querySelector('main#isi');
|
||||
if (!response.ok || !fresh || new URL(response.url).pathname !== location.pathname) {
|
||||
console.warn(`[SIAKAD] GET ${label}`, { status: response.status, lanjut: 'navigasi biasa' });
|
||||
location.assign(response.redirected ? response.url : url);
|
||||
return;
|
||||
}
|
||||
if (remoteRequest !== controller) return;
|
||||
|
||||
morphMain(main, fresh);
|
||||
document.title = page.title;
|
||||
console.info(`[SIAKAD] GET ${label}`, { status: response.status, waktu: `${Math.round(performance.now() - started)} ms` });
|
||||
// Alpine dan Select2 memasang isi baru lewat MutationObserver; fokus menyusul setelahnya
|
||||
setTimeout(() => restoreFocus(key), 0);
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
console.error(`[SIAKAD] GET ${label} gagal`, error);
|
||||
window.toast('danger', 'Data tidak dapat dimuat. Periksa koneksi lalu coba lagi.');
|
||||
} finally {
|
||||
if (remoteRequest === controller) {
|
||||
remoteRequest = null;
|
||||
stopLoading();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
|
||||
if (!link || !remoteMain()?.contains(link) || link.closest('[data-no-remote]') || link.hasAttribute('download')) return;
|
||||
if (link.target && link.target !== '_self') return;
|
||||
let url;
|
||||
try { url = new URL(link.href, location.href); } catch { return; }
|
||||
if (!samePage(url)) return;
|
||||
event.preventDefault();
|
||||
visit(url, link);
|
||||
});
|
||||
|
||||
document.addEventListener('submit', (event) => {
|
||||
const form = event.target;
|
||||
if (event.defaultPrevented || !(form instanceof HTMLFormElement) || !remoteMain()?.contains(form) || form.closest('[data-no-remote]')) return;
|
||||
if ((form.getAttribute('method') ?? '').toLowerCase() !== 'get') return;
|
||||
const url = new URL(form.getAttribute('action') || location.pathname, location.href);
|
||||
if (!samePage(url)) return;
|
||||
event.preventDefault();
|
||||
const params = new URLSearchParams();
|
||||
for (const [name, value] of new FormData(form, event.submitter)) {
|
||||
if (typeof value === 'string' && value !== '') params.append(name, value);
|
||||
}
|
||||
url.search = params.toString();
|
||||
visit(url);
|
||||
});
|
||||
|
||||
/*
|
||||
* Pindah halaman lewat tautan (menu, tombol tautan, tab): tautan yang diklik menampilkan pemintal,
|
||||
* bilah kemajuan tipis tampil di atas halaman, dan ketukan ganda ditahan. Tautan yang tidak ingin ini
|
||||
@@ -477,6 +662,97 @@ Alpine.data('satuTable', (config) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
/*
|
||||
* Tabel SATU berisi data asli: tampilan sama dengan satuTable, tetapi filter, pencarian, dan halaman diminta
|
||||
* ke server lewat fetch (JSON), sehingga alamat halaman tidak berubah. Ringkasan permintaan dicatat di konsol.
|
||||
* config: { url, filters: { nama: '' }, data: { rows, page, last_page, total, per_page } }.
|
||||
*/
|
||||
Alpine.data('satuRemoteTable', (config) => ({
|
||||
url: config.url,
|
||||
values: { ...config.filters },
|
||||
q: '',
|
||||
per: config.data.per_page,
|
||||
page: config.data.page,
|
||||
pages: config.data.last_page,
|
||||
total: config.data.total,
|
||||
view: config.data.rows,
|
||||
loading: false,
|
||||
picked: [],
|
||||
controller: null,
|
||||
|
||||
get window() {
|
||||
const start = Math.max(1, Math.min(this.page - 2, this.pages - 4));
|
||||
return Array.from({ length: Math.min(5, this.pages) }, (_, i) => start + i);
|
||||
},
|
||||
|
||||
get allPicked() {
|
||||
return this.view.length > 0 && this.view.every((row) => this.picked.includes(row.id));
|
||||
},
|
||||
|
||||
// Filter, kata cari, atau jumlah per halaman berubah: kembali ke halaman 1
|
||||
search() {
|
||||
this.load(1);
|
||||
},
|
||||
|
||||
go(page) {
|
||||
const next = Math.min(Math.max(1, page), this.pages);
|
||||
if (next !== this.page) this.load(next);
|
||||
},
|
||||
|
||||
async load(page) {
|
||||
const params = new URLSearchParams({ page: String(page), per: String(this.per) });
|
||||
if (this.q.trim() !== '') params.set('q', this.q.trim());
|
||||
Object.entries(this.values).forEach(([name, value]) => {
|
||||
if (value !== '' && value !== null) params.set(name, value);
|
||||
});
|
||||
|
||||
// Permintaan lama dibatalkan agar hasil yang terlambat tidak menimpa yang terbaru
|
||||
this.controller?.abort();
|
||||
const controller = new AbortController();
|
||||
this.controller = controller;
|
||||
this.loading = true;
|
||||
const started = performance.now();
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.url}?${params}`, {
|
||||
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
|
||||
signal: controller.signal,
|
||||
});
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok || !data || !Array.isArray(data.rows)) {
|
||||
throw new Error(data?.message || 'Data tidak dapat dimuat. Muat ulang halaman lalu coba lagi.');
|
||||
}
|
||||
|
||||
Object.assign(this, { view: data.rows, page: data.page, pages: data.last_page, total: data.total, per: data.per_page });
|
||||
this.picked = [];
|
||||
console.info(`[SIAKAD] GET ${this.url}?${params}`, { total: data.total, halaman: `${data.page}/${data.last_page}`, waktu: `${Math.round(performance.now() - started)} ms` });
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
console.error('[SIAKAD] Gagal memuat data', error);
|
||||
window.toast('danger', error.message);
|
||||
} finally {
|
||||
if (this.controller === controller) this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
toggleAll() {
|
||||
const ids = this.view.map((row) => row.id);
|
||||
this.picked = this.allPicked ? this.picked.filter((id) => !ids.includes(id)) : [...new Set([...this.picked, ...ids])];
|
||||
},
|
||||
|
||||
demo(label) {
|
||||
window.toast('info', `${label}: tampilan prototipe, tidak ada data yang diubah.`);
|
||||
},
|
||||
|
||||
remove() {
|
||||
if (!this.picked.length) {
|
||||
window.toast('warning', 'Pilih data yang akan dihapus terlebih dahulu.');
|
||||
return;
|
||||
}
|
||||
this.demo('Hapus');
|
||||
},
|
||||
}));
|
||||
|
||||
/*
|
||||
* Muat ulang selalu mulai dari atas: tanpa ini peramban memulihkan posisi gulir lama dan halaman
|
||||
* tampak "bergeser" saat tinggi isi (grafik, huruf) berubah sesudah dimuat.
|
||||
@@ -521,16 +797,33 @@ Alpine.data('themeToggle', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
Alpine.data('chartCanvas', (config) => ({
|
||||
Alpine.data('chartCanvas', () => ({
|
||||
chart: null,
|
||||
observer: null,
|
||||
|
||||
init() {
|
||||
this.build();
|
||||
window.addEventListener('themechange', () => this.build());
|
||||
// Muat di tempat mengganti data-chart: batang/garis bergerak ke nilai baru tanpa menggambar ulang grafik
|
||||
this.observer = new MutationObserver(() => this.refresh());
|
||||
this.observer.observe(this.$el, { attributes: true, attributeFilter: ['data-chart'] });
|
||||
},
|
||||
|
||||
refresh() {
|
||||
const config = JSON.parse(this.$el.dataset.chart);
|
||||
const chart = Alpine.raw(this.chart);
|
||||
if (!chart || config.type === 'doughnut' || chart.config.type !== config.type || chart.data.datasets.length !== config.datasets.length) {
|
||||
this.build();
|
||||
return;
|
||||
}
|
||||
chart.data.labels = config.labels;
|
||||
config.datasets.forEach((dataset, index) => Object.assign(chart.data.datasets[index], { label: dataset.label, data: dataset.data }));
|
||||
chart.update();
|
||||
},
|
||||
|
||||
async build() {
|
||||
this.chart?.destroy();
|
||||
const config = JSON.parse(this.$el.dataset.chart);
|
||||
Alpine.raw(this.chart)?.destroy();
|
||||
const { default: Chart } = await import('chart.js/auto');
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
const token = (name) => css.getPropertyValue(`--color-${name}`).trim();
|
||||
@@ -569,7 +862,8 @@ Alpine.data('chartCanvas', (config) => ({
|
||||
},
|
||||
|
||||
destroy() {
|
||||
this.chart?.destroy();
|
||||
this.observer?.disconnect();
|
||||
Alpine.raw(this.chart)?.destroy();
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user