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, $); /* * Laci navigasi (layouts.app). Di bawah 60rem sidebar menjadi laci di luar layar; * tanpa JS sidebar tampil biasa di atas konten, jadi tidak ada yang hilang. */ Alpine.data('appShell', () => ({ open: false, narrow: false, collapsed: document.documentElement.classList.contains('sidebar-collapsed'), init() { const query = window.matchMedia('(width < 60rem)'); const sync = () => { this.narrow = query.matches; if (!this.narrow) this.close(false); }; sync(); query.addEventListener('change', sync); this.$watch('open', (isOpen) => { document.documentElement.classList.toggle('drawer-open', isOpen); }); // Sidebar desktop: mode ikon saja (diingat di peramban) this.$watch('collapsed', (value) => { document.documentElement.classList.toggle('sidebar-collapsed', value); try { localStorage.setItem('siakad-sidebar', value ? 'collapsed' : 'expanded'); } catch (e) {} this.syncTitles(); }); this.syncTitles(); window.addEventListener('sidebar:expand', () => { this.collapsed = false; }); }, get menuLabel() { if (this.narrow) return this.open ? 'Tutup menu' : 'Buka menu'; return this.collapsed ? 'Perluas sidebar' : 'Kecilkan sidebar'; }, // Saat hanya ikon yang tampak, nama menu muncul sebagai tooltip bawaan syncTitles() { this.$nextTick(() => { this.$root.querySelectorAll('.sidebar .nav-item, .sidebar .nav-group > summary, .sidebar__user, .sidebar__foot .btn').forEach((el) => { if (this.collapsed) { const label = el.querySelector('.nav-item__label-text, .nav-group__label-text, .sidebar__name-text, .btn > span:not(.btn__spinner)'); const text = (label ?? el).textContent.trim().replace(/\s+/g, ' '); if (text) el.setAttribute('title', text); } else if (!el.classList.contains('sidebar__user')) { el.removeAttribute('title'); } }); }); }, get locked() { return this.open && this.narrow; }, toggle() { if (!this.narrow) { this.collapsed = !this.collapsed; return; } this.open ? this.close() : this.show(); }, // Geser ke kiri pada laci untuk menutupnya swipeFrom: null, swipeStart(event) { this.swipeFrom = event.touches[0].clientX; }, swipeEnd(event) { if (this.swipeFrom === null) return; const dx = event.changedTouches[0].clientX - this.swipeFrom; this.swipeFrom = null; if (dx < -60) this.close(false); }, show() { this.open = true; this.$nextTick(() => this.$refs.close?.focus()); }, close(restoreFocus = true) { if (!this.open) return; this.open = false; if (restoreFocus) this.$nextTick(() => this.$refs.menu?.focus()); }, })); /* Tampil/sembunyikan kata sandi (form.field type="password"). */ Alpine.data('passwordField', () => ({ show: false, toggle() { this.show = !this.show; }, })); /* * Toast (ui.flash). Satu penyimpanan bersama: pesan sesi dari server (seed) dan pesan klien * lewat window.toast(tone, message) atau $dispatch('toast', { tone, message }). */ const TOAST_NAMES = { info: 'Informasi', success: 'Berhasil', warning: 'Peringatan', danger: 'Galat' }; const TOAST_TONES = Object.keys(TOAST_NAMES); Alpine.store('toasts', { items: [], seq: 0, seed(messages) { document.documentElement.classList.add('toasts-ready'); (messages || []).forEach((message) => this.push(message)); }, push({ tone = 'info', message = '', duration = null } = {}) { if (!message) return; const safeTone = TOAST_TONES.includes(tone) ? tone : 'info'; const assertive = safeTone === 'danger'; this.items.push({ id: ++this.seq, tone: safeTone, name: TOAST_NAMES[safeTone], message: String(message), assertive, // Galat dan peringatan diberi waktu baca lebih lama duration: duration ?? (safeTone === 'danger' || safeTone === 'warning' ? 10000 : 6000), }); }, remove(id) { this.items = this.items.filter((item) => item.id !== id); }, }); window.toast = (tone, message, options = {}) => Alpine.store('toasts').push({ tone, message, ...options }); window.addEventListener('toast', (event) => Alpine.store('toasts').push(event.detail || {})); // Satu toast: hilang sendiri, jeda saat disorot atau difokus, tombol tutup Alpine.data('toastItem', (item) => ({ open: true, timer: null, remaining: item.duration, startedAt: 0, init() { this.start(); }, start() { clearTimeout(this.timer); this.startedAt = Date.now(); this.timer = setTimeout(() => this.dismiss(), this.remaining); }, pause() { if (!this.timer) return; clearTimeout(this.timer); this.timer = null; this.remaining = Math.max(1500, this.remaining - (Date.now() - this.startedAt)); }, resume() { if (this.timer || !this.open) return; if (this.$el.matches(':hover') || this.$el.matches(':focus-within')) return; this.start(); }, dismiss() { clearTimeout(this.timer); this.timer = null; this.open = false; setTimeout(() => Alpine.store('toasts').remove(item.id), 260); }, })); /* Dialog konfirmasi (ui.confirm): modal, fokus awal di Batal, fokus kembali ke pemicu. */ Alpine.data('confirmDialog', () => ({ show() { this.$refs.dialog.showModal(); this.$refs.cancel.focus(); }, close() { this.$refs.dialog.close(); }, // Klik di tirai (target = dialog itu sendiri) menutup; klik di isi tidak backdrop(event) { if (event.target === this.$refs.dialog) this.close(); }, restore() { this.$refs.trigger?.focus(); }, })); /* * Status sibuk untuk setiap formulir: tombol kirim menampilkan pemintal dan * kirim ganda ditahan. Formulir yang tidak ingin ini memberi atribut data-no-busy. */ /* * Label sibuk: selama tombol memuat, teksnya menjadi "Memproses..." (pemintal tampil di depannya) dan * lebarnya dikunci agar tata letak tidak melompat. Teks asli dikembalikan setelah selesai. * Ganti teksnya per tombol dengan atribut data-busy-text. */ const markBusy = (el, busy) => { const label = [...el.children].find((child) => child.tagName === 'SPAN' && !child.classList.contains('btn__spinner')); const swappable = label && !el.classList.contains('btn--icon') && !label.hasAttribute('x-text'); if (busy) { if (el.hasAttribute('data-busy-label')) return; el.style.minWidth = `${el.offsetWidth}px`; el.setAttribute('data-busy-label', swappable ? label.textContent : ''); if (swappable) label.textContent = el.getAttribute('data-busy-text') || 'Memproses...'; } else { if (!el.hasAttribute('data-busy-label')) return; const original = el.getAttribute('data-busy-label'); if (swappable && original !== '') label.textContent = original; el.removeAttribute('data-busy-label'); el.style.minWidth = ''; } }; /* * Tombol aksi non-formulir (Tambah, Cetak, Lihat, Hapus, Atur ulang, dan sebagainya): pemintal singkat * sebagai umpan balik bahwa klik diterima. Berlaku untuk semua `.btn`; kecuali tombol buka/tutup, * batal, dan yang memberi atribut data-no-busy. */ const pulseBusy = (button, ms = 800) => { if (button.hasAttribute('data-busy')) return; markBusy(button, true); button.setAttribute('data-busy', ''); button.setAttribute('aria-busy', 'true'); button.setAttribute('aria-disabled', 'true'); setTimeout(() => { button.removeAttribute('data-busy'); button.removeAttribute('aria-busy'); button.removeAttribute('aria-disabled'); markBusy(button, false); }, ms); }; document.addEventListener('click', (event) => { if (event.defaultPrevented || event.button !== 0) return; const button = event.target instanceof Element ? event.target.closest('button.btn') : null; if (!button || button.disabled || button.type === 'submit' || button.closest('.sidebar')) return; if (button.hasAttribute('data-no-busy') || button.hasAttribute('data-busy') || button.getAttribute('aria-disabled') === 'true') return; if (button.matches('[aria-expanded], [aria-controls], [aria-haspopup], [x-ref="cancel"], .sidebar__close, .topbar__menu')) return; // Tombol aksi memberi label; pemintal hanya untuk tombol yang benar-benar melakukan sesuatu pulseBusy(button); }); const setBusy = (form, busy) => { form.toggleAttribute('data-busy', busy); form.querySelectorAll('[type="submit"]').forEach((button) => { markBusy(button, busy); button.toggleAttribute('data-busy', busy); busy ? button.setAttribute('aria-disabled', 'true') : button.removeAttribute('aria-disabled'); }); }; document.addEventListener('submit', (event) => { const form = event.target; if (!(form instanceof HTMLFormElement) || form.hasAttribute('data-no-busy')) return; if (form.hasAttribute('data-busy')) { event.preventDefault(); return; } // Menunggu handler lain yang mungkin membatalkan pengiriman setTimeout(() => { if (!event.defaultPrevented) setBusy(form, true); else if (event.submitter instanceof HTMLElement) pulseBusy(event.submitter); }, 0); }); // Kembali lewat tombol back (bfcache): jangan biarkan tombol terkunci 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
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
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. 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 * memberi atribut data-no-busy. Semua kembali normal bila halaman dipulihkan dari bfcache. */ const progressBar = () => { let el = document.getElementById('nav-progress'); if (!el) { el = document.createElement('div'); el.id = 'nav-progress'; el.setAttribute('aria-hidden', 'true'); document.body.appendChild(el); } return el; }; let loadingLink = null; let loadingTimer = null; const stopLoading = () => { clearTimeout(loadingTimer); document.getElementById('nav-progress')?.classList.remove('is-running'); if (loadingLink) { loadingLink.removeAttribute('data-loading'); loadingLink.removeAttribute('aria-busy'); if (loadingLink.classList.contains('btn')) { loadingLink.removeAttribute('data-busy'); markBusy(loadingLink, false); } loadingLink = null; } }; const startLoading = (link) => { stopLoading(); // Menu sidebar: tanpa pemintal/penguncian, cukup bilah kemajuan di atas halaman if (link.closest('.sidebar')) { const quiet = progressBar(); quiet.classList.remove('is-running'); void quiet.offsetWidth; quiet.classList.add('is-running'); loadingTimer = setTimeout(stopLoading, 15000); return; } loadingLink = link; link.setAttribute('data-loading', ''); link.setAttribute('aria-busy', 'true'); if (link.classList.contains('btn')) { if (!link.querySelector('.btn__spinner')) { const spinner = document.createElement('span'); spinner.className = 'btn__spinner'; spinner.setAttribute('aria-hidden', 'true'); link.prepend(spinner); } markBusy(link, true); link.setAttribute('data-busy', ''); } const bar = progressBar(); bar.classList.remove('is-running'); void bar.offsetWidth; // mulai ulang animasi bar.classList.add('is-running'); // Pengaman: unduhan atau navigasi yang dibatalkan tidak menyisakan pemintal selamanya loadingTimer = setTimeout(stopLoading, 15000); }; 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 || link.hasAttribute('data-no-busy') || link.hasAttribute('download')) return; if (link.target && link.target !== '_self') return; if (link === loadingLink) { event.preventDefault(); // klik ganda saat memuat return; } let url; try { url = new URL(link.href, location.href); } catch { return; } if (!/^https?:$/.test(url.protocol) || url.origin !== location.origin) return; if (url.hash && url.pathname === location.pathname && url.search === location.search) return; startLoading(link); }); window.addEventListener('pageshow', (event) => { if (event.persisted) stopLoading(); }); /* * Pencarian menu sidebar (menu Operator yang panjang): menyembunyikan butir yang tidak cocok * dan membuka kelompok yang berisi hasil; mengembalikan keadaan buka semula bila dikosongkan. */ Alpine.data('menuFilter', () => ({ q: '', memo: null, find() { const list = this.$el.closest('.sidebar__list'); const groups = [...list.querySelectorAll('details.nav-group')]; const items = [...list.querySelectorAll('.nav-item[data-menu]')]; const q = this.q.trim().toLowerCase(); if (this.memo === null) this.memo = groups.map((group) => group.open); if (!q) { items.forEach((item) => (item.hidden = false)); groups.forEach((group, i) => { group.hidden = false; group.open = this.memo[i]; }); this.memo = null; return; } items.forEach((item) => (item.hidden = !item.textContent.toLowerCase().includes(q))); // Dari dalam ke luar: subgrup dulu, lalu grup induknya [...groups].reverse().forEach((group) => { const has = group.querySelector('.nav-item[data-menu]:not([hidden])') !== null; group.hidden = !has; group.open = has; }); }, })); /* * Tabel halaman SIM Akademik (operator.satu.list): pencarian, filter kolom, halaman, pilih baris. * Semua pada data contoh di sisi klien; tombol ubah/hapus hanya memberi pemberitahuan prototipe. */ Alpine.data('satuTable', (config) => ({ rows: config.rows, cols: config.filterCols, values: config.filterCols.map(() => ''), q: '', per: 10, page: 1, picked: [], get filtered() { const q = this.q.trim().toLowerCase(); return this.rows.filter((row) => { const okFilter = this.cols.every((col, i) => col === null || this.values[i] === '' || row.cells[col].v === this.values[i]); const okSearch = !q || row.cells.some((cell) => cell.v.toLowerCase().includes(q)); return okFilter && okSearch; }); }, get pages() { return Math.max(1, Math.ceil(this.filtered.length / this.per)); }, get view() { return this.filtered.slice((this.page - 1) * this.per, this.page * this.per); }, 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)); }, reset() { this.page = 1; this.picked = []; }, clear() { this.values = this.cols.map(() => ''); this.q = ''; this.reset(); }, go(page) { this.page = Math.min(Math.max(1, page), this.pages); }, 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'); }, })); /* * Tabel berformat SATU di atas baris yang sudah dirender server (x-satu.datatable): pencarian, jumlah data per halaman, * dan pager bekerja dengan menyembunyikan baris , jadi sel berisi tautan, formulir, atau input tetap utuh dan * tetap terkirim bersama formulir pembungkusnya. Baris dengan sel colspan (keadaan kosong) tidak dihitung. */ Alpine.data('satuDom', (config = {}) => ({ // Awalan dt: komponen ini bersarang di dalam x-data formulir lain, jadi nama tidak boleh menabrak (mis. total). dtQ: '', dtPer: config.per ?? 10, dtPage: 1, dtItems: [], init() { this.dtItems = [...this.$root.querySelectorAll('tbody > tr')] .filter((tr) => !tr.querySelector('td[colspan]')) .map((el) => ({ el, text: el.textContent.toLowerCase().replace(/\s+/g, ' ') })); this.$watch('dtQ', () => this.dtReset()); this.$watch('dtPer', () => this.dtReset()); this.dtApply(); }, get dtMatches() { const q = this.dtQ.trim().toLowerCase(); return q ? this.dtItems.filter((item) => item.text.includes(q)) : this.dtItems; }, get dtTotal() { return this.dtMatches.length; }, get dtPages() { return Math.max(1, Math.ceil(this.dtTotal / this.dtPer)); }, get dtWindow() { const start = Math.max(1, Math.min(this.dtPage - 2, this.dtPages - 4)); return Array.from({ length: Math.min(5, this.dtPages) }, (_, i) => start + i); }, dtReset() { this.dtPage = 1; this.dtApply(); }, dtGo(page) { this.dtPage = Math.min(Math.max(1, page), this.dtPages); this.dtApply(); }, dtApply() { const visible = new Set(this.dtMatches.slice((this.dtPage - 1) * this.dtPer, this.dtPage * this.dtPer)); this.dtItems.forEach((item) => { item.el.hidden = !visible.has(item); }); }, })); /* * Laporan berdata asli: setiap perubahan parameter menjalankan laporan ke server (JSON) dan hasilnya tampil * berhalaman; kolom bisa berbeda per parameter, jadi tabel dirender dinamis. Tautan Unduh/Cetak memuat parameter * terkini. Alamat halaman ikut diperbarui (replaceState) agar bisa dibagikan. * config: { url, downloadUrl, printUrl, params: [{name, type, required, reload}], values: { nama: '' | bool }, perPage, per }. */ Alpine.data('laporanReport', (config) => ({ values: { ...config.values }, params: config.params, per: config.per, result: null, error: null, loading: false, page: 1, controller: null, timer: null, init() { this.load(); }, // Semua parameter wajib sudah terisi get ready() { return this.params.every((p) => !p.required || (this.values[p.name] !== '' && this.values[p.name] !== null && this.values[p.name] !== undefined)); }, get query() { const params = new URLSearchParams(); Object.entries(this.values).forEach(([name, value]) => { // Kotak centang hanya dikirim saat dicentang if (value === '' || value === null || value === undefined || value === false) return; params.set(name, value === true ? '1' : String(value)); }); return params.toString(); }, get downloadHref() { return this.ready ? `${config.downloadUrl}?${this.query}` : '#'; }, get printHref() { return this.ready ? `${config.printUrl}?${this.query}` : '#'; }, get window() { const pages = this.result?.last_page ?? 1; const page = this.result?.page ?? 1; const start = Math.max(1, Math.min(page - 2, pages - 4)); return Array.from({ length: Math.min(5, pages) }, (_, i) => start + i); }, cell(value) { return value === null || value === undefined || value === '' ? '–' : value; }, // Parameter atau jumlah per halaman berubah: kembali ke halaman 1 refresh() { this.page = 1; this.load(); }, go(page) { this.page = Math.min(Math.max(1, page), this.result?.last_page ?? 1); this.load(); }, async load() { clearTimeout(this.timer); if (!this.ready) { this.controller?.abort(); this.result = null; this.error = null; this.loading = false; return; } // 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 params = `${this.query}${this.query ? '&' : ''}page=${this.page}&per=${this.per}`; const started = performance.now(); try { const response = await fetch(`${config.url}?${params}`, { headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, signal: controller.signal, }); const data = await response.json().catch(() => null); if (!response.ok || !data) { this.result = null; this.error = data?.message || 'Laporan tidak dapat dimuat. Muat ulang halaman lalu coba lagi.'; return; } this.error = null; this.result = data; this.page = data.page; window.history.replaceState(null, '', `${window.location.pathname}${this.query ? `?${this.query}` : ''}`); console.info(`[SIAKAD] GET ${config.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 laporan', error); this.result = null; this.error = 'Laporan tidak dapat dimuat. Periksa koneksi lalu coba lagi.'; } finally { if (this.controller === controller) this.loading = false; } }, })); /* * 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, // Opsional: tautan Lihat per baris ("__ID__" diganti id) dan penghapusan sungguhan (POST {ids}) viewUrl: config.viewUrl ?? null, destroyUrl: config.destroyUrl ?? null, token: config.token ?? '', pending: [], // Opsional: formulir tambah/ubah lewat modal ({storeUrl, updateUrl, fields:[{name, default}]}); baris memberi row.form form: config.form ?? null, editing: null, formData: {}, // Modal Lihat: kolom tabel dan baris yang sedang dilihat columns: config.columns ?? [], viewing: null, startView(row) { this.viewing = row; this.$refs.detail?.showModal(); }, 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); }, startInsert() { if (!this.form) return this.demo('Tambah'); this.editing = 'new'; this.formData = Object.fromEntries(this.form.fields.map((f) => [f.name, Array.isArray(f.default) ? [...f.default] : f.default])); this.openForm(); }, startEdit(row) { if (!this.form || !row.form) return this.demo('Ubah'); this.editing = row.id; this.formData = Object.fromEntries(this.form.fields.map((f) => [f.name, Array.isArray(row.form[f.name]) ? [...row.form[f.name]] : (row.form[f.name] ?? (Array.isArray(f.default) ? [] : ''))])); this.openForm(); }, openForm() { const dialog = this.$refs.form; if (dialog && !dialog.open) dialog.showModal(); this.$nextTick(() => dialog?.querySelector('input:not([type=hidden]), select, textarea')?.focus()); }, closeForm() { this.$refs.form?.close(); }, formBackdrop(event) { if (event.target === this.$refs.form) this.closeForm(); }, async save() { if (!this.form || this.loading || this.editing === null) return; const isNew = this.editing === 'new'; const url = isNew ? this.form.storeUrl : this.form.updateUrl.replace('__ID__', encodeURIComponent(this.editing)); const body = Object.fromEntries(Object.entries(this.formData).map(([k, v]) => [k, v === '' ? null : v])); this.loading = true; try { const response = await fetch(url, { method: isNew ? 'POST' : 'PUT', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.token, 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify(body), }); const data = await response.json().catch(() => null); if (!response.ok) { const first = data?.errors ? Object.values(data.errors).flat()[0] : null; throw new Error(first || data?.message || 'Data tidak dapat disimpan. Muat ulang halaman lalu coba lagi.'); } console.info(`[SIAKAD] ${isNew ? 'POST' : 'PUT'} ${url}`, { hasil: data?.message }); window.toast('success', data?.message || 'Data disimpan.'); this.closeForm(); this.loading = false; this.load(isNew ? 1 : this.page); } catch (error) { window.toast('danger', error.message); this.loading = false; } }, 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]) => { // Kotak centang: hanya dikirim saat dicentang if (value === '' || value === null || value === false) return; params.set(name, value === true ? '1' : 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` }); // Halaman terakhir baru saja kosong (mis. setelah hapus): pindah ke halaman terakhir yang masih ada if (data.rows.length === 0 && data.page > Math.max(1, data.last_page)) { queueMicrotask(() => this.load(Math.max(1, data.last_page))); } } 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.`); }, link(row) { return this.viewUrl ? this.viewUrl.replace('__ID__', encodeURIComponent(row.id)) : '#'; }, remove() { if (!this.picked.length) { window.toast('warning', 'Pilih data yang akan dihapus terlebih dahulu.'); return; } this.askRemove(this.picked); }, askRemove(ids) { if (!this.destroyUrl) { this.demo('Hapus'); return; } this.pending = [...ids]; const dialog = this.$refs.dialog; if (dialog && !dialog.open) dialog.showModal(); }, closeDialog() { this.$refs.dialog?.close(); }, backdrop(event) { if (event.target === this.$refs.dialog) this.closeDialog(); }, async confirmRemove() { const ids = [...this.pending]; if (!ids.length) return; this.loading = true; try { const response = await fetch(this.destroyUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.token, 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify({ ids }), }); const data = await response.json().catch(() => null); if (!response.ok) throw new Error(data?.message || 'Data tidak dapat dihapus. Muat ulang halaman lalu coba lagi.'); console.info(`[SIAKAD] POST ${this.destroyUrl}`, { ids: ids.length, hasil: data?.message }); window.toast('success', data?.message || 'Data dihapus.'); this.closeDialog(); this.loading = false; this.load(this.page); } catch (error) { console.error('[SIAKAD] Gagal menghapus', error); window.toast('danger', error.message); this.loading = false; } }, })); /* * Detail mahasiswa dan pegawai (Portal operator): biodata per bagian yang bisa diubah di tempat. Tiap bagian punya nilai * isian (values) dan teks tampil (display); Simpan mengirim PUT JSON untuk satu bagian lalu memakai nilai segar dari server. * config: { tab, saveUrl ("__SECTION__"), token, values: { bagian: { kolom: nilai } }, display: { bagian: { kolom: teks } } }. */ Alpine.data('bioDetail', (config) => ({ tab: config.tab, values: config.values, display: config.display, editing: null, form: {}, saving: false, reloading: false, // Nama lengkap dari bagian pribadi: gelar depan + nama, gelar belakang setelah koma (mahasiswa tidak punya gelar) get nama() { const v = this.values.pribadi ?? {}; const name = [String(v.gelardepan ?? '').trim(), String(v.nama ?? '').trim()].filter(Boolean).join(' '); const back = String(v.gelarbelakang ?? '').trim().replace(/^[,\s]+/, ''); return back ? name + ', ' + back : name; }, // Inisial seperti ui.avatar: gelar bertitik dan bagian setelah koma dilewati get initials() { const words = this.nama.split(',')[0].trim().split(/\s+/).filter(Boolean); const plain = words.filter((word) => !word.endsWith('.')); const use = plain.length ? plain : words; return ((use[0]?.[0] ?? '?') + (use.length > 1 ? use[use.length - 1][0] : '')).toUpperCase(); }, show(key) { this.tab = key; }, edit(key) { this.tab = key; this.editing = key; this.form = { ...this.values[key] }; this.$nextTick(() => this.$refs['panel-' + key]?.querySelector('input:not([type=hidden]), select, textarea')?.focus()); }, cancel() { this.editing = null; }, async save() { const key = this.editing; if (key === null || this.saving) return; const url = config.saveUrl.replace('__SECTION__', encodeURIComponent(key)); this.saving = true; try { const response = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': config.token, 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify(this.form), }); const data = await response.json().catch(() => null); if (!response.ok) { const first = data?.errors ? Object.values(data.errors).flat()[0] : null; throw new Error(first || data?.message || 'Biodata tidak dapat disimpan. Muat ulang halaman lalu coba lagi.'); } console.info(`[SIAKAD] PUT ${url}`, { hasil: data.message }); // Data akademik mengubah ringkasan di atas halaman: muat ulang (pesan tampil lewat sesi); tombol tetap sibuk if (data.reload) { this.reloading = true; window.location.reload(); return; } this.values[key] = data.values; // Gabung: keterangan hanya-baca (bukan isian) di display tetap dipertahankan this.display[key] = { ...this.display[key], ...data.display }; this.editing = null; window.toast('success', data.message); } catch (error) { window.toast('danger', error.message); } finally { if (!this.reloading) this.saving = false; } }, })); /* * Kegiatan Akademik (Portal operator, akun DB lama): tabel jenis kegiatan dengan tambah/ubah sebaris dan hapus * berdialog. Baris disaring dan dihalamankan di sisi klien (jumlahnya puluhan); setiap simpan mengirim JSON dan * memakai daftar segar dari server. */ Alpine.data('satuKegiatan', (config) => ({ rows: config.rows, urls: config.urls, token: config.token, ready: config.ready, q: '', per: config.per, page: 1, editing: null, form: { kode: '', nama: '', warna: '' }, saving: false, pending: null, get filtered() { const q = this.q.trim().toLowerCase(); if (q === '') return this.rows; return this.rows.filter((row) => [row.kode, row.nama, row.warna ?? ''].some((value) => String(value).toLowerCase().includes(q))); }, get pages() { return Math.max(1, Math.ceil(this.filtered.length / this.per)); }, get view() { const start = (this.page - 1) * this.per; return this.filtered.slice(start, start + this.per); }, 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); }, reset() { this.page = 1; }, go(page) { this.page = Math.min(Math.max(1, page), this.pages); }, startInsert() { this.editing = 'new'; this.form = { kode: '', nama: '', warna: '' }; this.$nextTick(() => this.$refs.nama?.focus()); }, startEdit(row) { this.editing = row.id; this.form = { kode: row.kode, nama: row.nama, warna: row.warna ?? '' }; this.$nextTick(() => this.$refs.nama?.focus()); }, cancel() { this.editing = null; }, async request(url, method, body) { const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': this.token, 'X-Requested-With': 'XMLHttpRequest' }, body: body === undefined ? undefined : JSON.stringify(body), }); const data = await response.json().catch(() => null); if (!response.ok) { const first = data?.errors ? Object.values(data.errors).flat()[0] : null; throw new Error(first || data?.message || 'Permintaan gagal. Muat ulang halaman lalu coba lagi.'); } console.info(`[SIAKAD] ${method} ${url}`, { hasil: data?.message }); return data; }, async save() { if (this.saving || this.editing === null) return; if (this.form.nama.trim() === '') { window.toast('warning', 'Nama kegiatan akademik wajib diisi.'); this.$refs.nama?.focus(); return; } const isNew = this.editing === 'new'; const url = isNew ? this.urls.store : this.urls.update.replace('__ID__', this.editing); const body = { kode: this.form.kode.trim() || null, nama: this.form.nama.trim(), warna: this.form.warna.trim() || null }; this.saving = true; try { const data = await this.request(url, isNew ? 'POST' : 'PUT', body); this.rows = data.rows; this.editing = null; window.toast('success', data.message); } catch (error) { window.toast('danger', error.message); } finally { this.saving = false; } }, askRemove(row) { this.pending = row; const dialog = this.$refs.dialog; if (dialog && !dialog.open) dialog.showModal(); }, closeDialog() { this.$refs.dialog?.close(); }, backdrop(event) { if (event.target === this.$refs.dialog) this.closeDialog(); }, async confirmRemove() { if (!this.pending || this.saving) return; this.saving = true; try { const data = await this.request(this.urls.destroy.replace('__ID__', this.pending.id), 'DELETE'); this.rows = data.rows; if (this.page > this.pages) this.page = this.pages; window.toast('success', data.message); this.closeDialog(); } catch (error) { window.toast('danger', error.message); } finally { this.saving = false; } }, })); /* * 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. */ if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; if (!location.hash) window.scrollTo(0, 0); /* * Grafik (ui.chart): Chart.js dimuat malas hanya bila ada grafik di halaman. Warna dibaca dari token CSS. */ Alpine.data('themeToggle', () => ({ dark: document.documentElement.dataset.theme === 'dark', toggle(event) { const mode = this.dark ? 'light' : 'dark'; const apply = () => { this.dark = mode === 'dark'; document.documentElement.dataset.theme = mode; try { localStorage.setItem('siakad-theme', mode); } catch (e) { /* penyimpanan tidak tersedia */ } window.dispatchEvent(new CustomEvent('themechange', { detail: { mode } })); }; const calm = window.matchMedia('(prefers-reduced-motion: reduce)').matches; if (calm || typeof document.startViewTransition !== 'function') { apply(); return; } // Peralihan halus: tangkapan layar lama memudar dan tema baru menyingkap dari tombol. const box = event?.currentTarget?.getBoundingClientRect(); const x = box ? box.left + box.width / 2 : window.innerWidth / 2; const y = box ? box.top + box.height / 2 : 0; const radius = Math.hypot(Math.max(x, window.innerWidth - x), Math.max(y, window.innerHeight - y)); const transition = document.startViewTransition(apply); transition.ready.then(() => { document.documentElement.animate( { clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`] }, { duration: 800, easing: 'cubic-bezier(0.4, 0, 0.2, 1)', pseudoElement: '::view-transition-new(root)' }, ); }).catch(() => {}); }, })); 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() { 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(); const palette = ['accent', 'gold', 'info', 'success', 'brand-red', 'muted'].map(token); const ink = token('muted'); const grid = token('rule'); const circular = config.type === 'doughnut'; const datasets = config.datasets.map((dataset, index) => ({ borderRadius: 8, borderWidth: circular ? 0 : 2, tension: 0.35, backgroundColor: circular ? config.labels.map((_, i) => palette[i % palette.length]) : palette[index % palette.length], borderColor: circular ? undefined : palette[index % palette.length], ...dataset, })); const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches; this.chart = new Chart(this.$refs.canvas, { type: config.type, data: { labels: config.labels, datasets }, options: { responsive: true, maintainAspectRatio: false, animation: reduce ? false : { duration: 600 }, plugins: { legend: { display: circular || datasets.length > 1, position: 'bottom', labels: { color: ink, usePointStyle: true } }, }, scales: circular ? {} : { x: { grid: { display: false }, ticks: { color: ink } }, y: { beginAtZero: true, grid: { color: grid }, ticks: { color: ink, precision: 0 } }, }, }, }); }, destroy() { this.observer?.disconnect(); Alpine.raw(this.chart)?.destroy(); }, })); /* * Nama panjang satu baris yang bergeser sampai ujung: jeda 1 dtk, geser, jeda 1 dtk di ujung, kembali, * jeda 1 dtk, ulangi. Hanya transform; tanpa gerak bila nama muat atau gerak dikurangi. */ Alpine.data('nameMarquee', () => ({ timer: null, animation: null, observer: null, init() { this.observer = new ResizeObserver(() => this.restart()); this.observer.observe(this.$el); this.restart(); }, destroy() { this.stop(); this.observer?.disconnect(); }, stop() { clearTimeout(this.timer); this.animation?.cancel(); this.animation = null; }, restart() { this.stop(); const inner = this.$refs.inner; const distance = Math.ceil(inner.scrollWidth - this.$el.clientWidth); this.$el.classList.toggle('is-clipped', distance > 0); if (distance <= 0 || window.matchMedia('(prefers-reduced-motion: reduce)').matches || !inner.animate) return; const duration = Math.min(Math.max(distance * 30, 900), 4000); const run = (target, next) => { this.animation = inner.animate( { transform: [`translateX(${target === 0 ? -distance : 0}px)`, `translateX(${target}px)`] }, { duration, easing: 'ease-in-out', fill: 'forwards' }, ); this.animation.onfinish = () => { this.timer = setTimeout(next, 1000); }; }; const forward = () => run(-distance, back); const back = () => run(0, forward); this.timer = setTimeout(forward, 1000); }, })); /* * Grup menu sidebar (