Commit awal: prototipe UI SIAKAD Untan
This commit is contained in:
@@ -0,0 +1,763 @@
|
||||
import Alpine from 'alpinejs';
|
||||
import $ from 'jquery';
|
||||
import select2 from 'select2';
|
||||
|
||||
window.Alpine = Alpine;
|
||||
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): <dialog> 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));
|
||||
});
|
||||
|
||||
/*
|
||||
* 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');
|
||||
},
|
||||
}));
|
||||
|
||||
/*
|
||||
* 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', (config) => ({
|
||||
chart: null,
|
||||
|
||||
init() {
|
||||
this.build();
|
||||
window.addEventListener('themechange', () => this.build());
|
||||
},
|
||||
|
||||
async build() {
|
||||
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.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 (<details class="nav-group">): buka/tutup dianimasikan (tinggi + opacity) lewat Web Animations.
|
||||
* Tanpa JS atau saat gerak dikurangi, <details> berperilaku bawaan.
|
||||
*/
|
||||
document.addEventListener('click', (event) => {
|
||||
const summary = event.target.closest?.('details.nav-group > summary');
|
||||
if (!summary) return;
|
||||
|
||||
// Sidebar mode ikon: klik grup memperluas sidebar dan membuka grup itu
|
||||
if (document.documentElement.classList.contains('sidebar-collapsed') && window.matchMedia('(width >= 60rem)').matches) {
|
||||
event.preventDefault();
|
||||
window.dispatchEvent(new CustomEvent('sidebar:expand'));
|
||||
summary.parentElement.open = true;
|
||||
return;
|
||||
}
|
||||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||
|
||||
const group = summary.parentElement;
|
||||
const items = group.querySelector(':scope > .nav-group__items');
|
||||
if (!items || !items.animate) return;
|
||||
event.preventDefault();
|
||||
|
||||
const running = items.getAnimations();
|
||||
const from = running.length ? items.getBoundingClientRect().height : null;
|
||||
running.forEach((animation) => animation.cancel());
|
||||
|
||||
const opening = group.dataset.closing === '1' || !group.open;
|
||||
const options = { duration: 440, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' };
|
||||
items.style.overflow = 'hidden';
|
||||
const finish = () => { items.style.overflow = ''; };
|
||||
|
||||
if (opening) {
|
||||
delete group.dataset.closing;
|
||||
group.open = true;
|
||||
const to = items.getBoundingClientRect().height;
|
||||
items.animate({ height: [`${from ?? 0}px`, `${to}px`], opacity: [from ? 1 : 0, 1] }, options).onfinish = finish;
|
||||
} else {
|
||||
group.dataset.closing = '1';
|
||||
const start = from ?? items.getBoundingClientRect().height;
|
||||
items.animate({ height: [`${start}px`, '0px'], opacity: [1, 0] }, options).onfinish = () => {
|
||||
finish();
|
||||
if (group.dataset.closing === '1') { group.open = false; delete group.dataset.closing; }
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Select2 untuk semua <select> formulir (form.select dan <select class="field__select">): pencarian pada
|
||||
* daftar panjang, tombol hapus (allowClear) dan placeholder "Pilih {nama kolom}". Pemilihan diteruskan ke
|
||||
* x-model/x-on:change Alpine lewat event bawaan; perubahan dari Alpine disinkronkan balik ke tampilan.
|
||||
* Atribut: data-no-clear (tanpa tombol hapus), data-no-select2 (biarkan <select> bawaan).
|
||||
*/
|
||||
const SELECT2_ID = {
|
||||
noResults: () => 'Data tidak ditemukan',
|
||||
searching: () => 'Mencari...',
|
||||
loadingMore: () => 'Memuat data lainnya...',
|
||||
errorLoading: () => 'Data tidak dapat dimuat',
|
||||
};
|
||||
|
||||
const labelOf = (el) => {
|
||||
const label = el.id ? document.querySelector(`label[for="${CSS.escape(el.id)}"]`) : null;
|
||||
if (!label) return '';
|
||||
const copy = label.cloneNode(true);
|
||||
copy.querySelectorAll('.field__optional, .visually-hidden').forEach((node) => node.remove());
|
||||
return copy.textContent.replace(/\s+/g, ' ').replace(/\*$/, '').trim();
|
||||
};
|
||||
|
||||
const enhanceSelect = (el) => {
|
||||
if (el.dataset.select2Ready || el.hasAttribute('data-no-select2') || el.multiple || el.closest('template')) return;
|
||||
el.dataset.select2Ready = '1';
|
||||
|
||||
const noClear = el.hasAttribute('data-no-clear') || el.required || el.disabled;
|
||||
// Select2 butuh opsi kosong sebagai tempat placeholder; tambahkan bila belum ada (nilai terpilih dipertahankan)
|
||||
if (!noClear && ![...el.options].some((option) => option.value === '')) {
|
||||
const current = el.value;
|
||||
el.insertBefore(new Option('', ''), el.firstChild);
|
||||
el.value = current;
|
||||
}
|
||||
|
||||
const hasEmpty = [...el.options].some((option) => option.value === '');
|
||||
const name = labelOf(el);
|
||||
const placeholder = name ? `Pilih ${name}` : 'Pilih...';
|
||||
const $el = $(el);
|
||||
|
||||
$el.select2({
|
||||
width: '100%',
|
||||
placeholder: hasEmpty ? placeholder : undefined,
|
||||
allowClear: !noClear && hasEmpty,
|
||||
language: SELECT2_ID,
|
||||
minimumResultsForSearch: el.options.length > 8 ? 0 : Infinity,
|
||||
dropdownCssClass: 'select2-glass',
|
||||
selectionCssClass: 'select2-glass',
|
||||
});
|
||||
|
||||
// Select2 -> Alpine: x-model dan x-on:change mendengar event bawaan
|
||||
let bridging = false;
|
||||
$el.on('change.bridge', () => {
|
||||
if (bridging) return;
|
||||
bridging = true;
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
bridging = false;
|
||||
});
|
||||
|
||||
// Alpine -> Select2: nilai model yang berubah (mis. Atur ulang) menyegarkan tampilan
|
||||
const model = [...el.attributes].find((attribute) => attribute.name.startsWith('x-model'));
|
||||
if (model) {
|
||||
Alpine.effect(() => {
|
||||
const value = Alpine.evaluate(el, model.value);
|
||||
const next = value === null || value === undefined ? '' : String(value);
|
||||
// x-model sudah mengubah nilai <select> asli; Select2 tetap perlu menyegarkan tampilannya
|
||||
Alpine.nextTick(() => {
|
||||
if (String($el.val() ?? '') !== next) $el.val(next);
|
||||
$el.trigger('change.select2');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Saat dropdown dibuka, kolom cari langsung fokus (bila ada)
|
||||
$el.on('select2:open', () => {
|
||||
document.querySelector('.select2-container--open .select2-search__field')?.focus({ preventScroll: true });
|
||||
});
|
||||
};
|
||||
|
||||
const enhanceAllSelects = (root = document) => {
|
||||
root.querySelectorAll('select.field__select, select[data-select2]').forEach(enhanceSelect);
|
||||
};
|
||||
|
||||
document.addEventListener('alpine:initialized', () => {
|
||||
enhanceAllSelects();
|
||||
// <select> yang muncul belakangan (x-if, x-for)
|
||||
new MutationObserver((records) => {
|
||||
records.forEach((record) => record.addedNodes.forEach((node) => {
|
||||
if (!(node instanceof Element)) return;
|
||||
if (node.matches('select.field__select, select[data-select2]')) enhanceSelect(node);
|
||||
else enhanceAllSelects(node);
|
||||
}));
|
||||
}).observe(document.body, { childList: true, subtree: true });
|
||||
});
|
||||
|
||||
Alpine.start();
|
||||
Reference in New Issue
Block a user