-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin-reference-library.js
More file actions
488 lines (425 loc) · 18.4 KB
/
Copy pathadmin-reference-library.js
File metadata and controls
488 lines (425 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
* admin-reference-library.js - Prompts & Reinforcers library manager (admin/BCBA)
*
* Agent B output. IIFE-scoped. Reads/mutates window.MOCK.prompts_library and
* window.MOCK.reinforcers_library in memory (mock mode). Arfa wires real API later.
* No PHI. No real API calls on this page. Toast via ARFA_API.toast.
* DO NOT EDIT shared files (style.css, app.js, mock-data.js, api-client.js).
*/
(function () {
'use strict';
// ── Config ────────────────────────────────────────────────────────────────
const PAGE_SIZE = 25;
const PROMPT_CATEGORIES = [
{ value: 'physical-fading', label: 'Physical fading' },
{ value: 'physical', label: 'Physical' },
{ value: 'gestural', label: 'Gestural' },
{ value: 'verbal', label: 'Verbal' },
{ value: 'visual', label: 'Visual' },
{ value: 'fading', label: 'Fading' },
{ value: 'chaining', label: 'Chaining' },
{ value: 'independent', label: 'Independent' },
];
const REINFORCER_CATEGORIES = [
{ value: 'edible-schedule', label: 'Edible schedule' },
{ value: 'edible', label: 'Edible' },
{ value: 'social', label: 'Social' },
{ value: 'tangible', label: 'Tangible' },
{ value: 'token', label: 'Token' },
{ value: 'activity', label: 'Activity' },
{ value: 'negative', label: 'Negative reinforcement' },
{ value: 'natural', label: 'Natural consequence' },
];
// ── State ─────────────────────────────────────────────────────────────────
let activeTab = 'prompts'; // 'prompts' | 'reinforcers'
let searchQuery = { prompts: '', reinforcers: '' };
let currentPage = { prompts: 1, reinforcers: 1 };
let pendingDelete = null; // { lib, id, rowEl } - tracks in-row confirm
// ── Helpers ───────────────────────────────────────────────────────────────
function getLibrary(lib) {
if (!window.MOCK) return [];
return lib === 'prompts'
? (window.MOCK.prompts_library || [])
: (window.MOCK.reinforcers_library || []);
}
function setLibrary(lib, arr) {
if (!window.MOCK) return;
if (lib === 'prompts') window.MOCK.prompts_library = arr;
else window.MOCK.reinforcers_library = arr;
}
function getCategoryLabel(lib, value) {
const cats = lib === 'prompts' ? PROMPT_CATEGORIES : REINFORCER_CATEGORIES;
const found = cats.find(c => c.value === value);
return found ? found.label : value;
}
function truncate(str, max) {
if (!str) return '-';
return str.length > max ? str.slice(0, max) + '…' : str;
}
function generateId(lib) {
const prefix = lib === 'prompts' ? 'prompt' : 'rein';
return `${prefix}-${Date.now().toString(36)}`;
}
function nowLabel() {
const d = new Date();
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
function filterLibrary(lib) {
const q = (searchQuery[lib] || '').toLowerCase().trim();
const all = getLibrary(lib);
if (!q) return all;
return all.filter(item =>
(item.name || '').toLowerCase().includes(q) ||
(item.category || '').toLowerCase().includes(q) ||
getCategoryLabel(lib, item.category).toLowerCase().includes(q)
);
}
// ── Render list ───────────────────────────────────────────────────────────
function renderList(lib) {
const contentEl = document.getElementById(`arl-${lib}-content`);
const paginationEl = document.getElementById(`arl-pagination-${lib}`);
if (!contentEl) return;
const filtered = filterLibrary(lib);
const total = filtered.length;
const page = currentPage[lib];
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const safePage = Math.min(page, totalPages);
currentPage[lib] = safePage;
const start = (safePage - 1) * PAGE_SIZE;
const slice = filtered.slice(start, start + PAGE_SIZE);
// Empty state
if (total === 0) {
const isSearching = (searchQuery[lib] || '').trim().length > 0;
contentEl.innerHTML = `
<div class="arl-empty">
<div class="arl-empty-icon">${isSearching ? '🔍' : '📚'}</div>
<div class="arl-empty-title">${isSearching ? 'No matches found' : 'Library is empty'}</div>
<div class="arl-empty-sub">${isSearching
? `No ${lib === 'prompts' ? 'prompts' : 'reinforcers'} match "${searchQuery[lib]}".`
: `No ${lib === 'prompts' ? 'prompt strategies' : 'reinforcer types'} in the library yet.`
}</div>
${!isSearching ? `<button class="btn btn-primary" id="arl-empty-add-${lib}" style="min-height:44px;">Add Your First</button>` : ''}
</div>
`;
if (!isSearching) {
const addBtn = document.getElementById(`arl-empty-add-${lib}`);
if (addBtn) addBtn.addEventListener('click', () => openEditor(lib, null));
}
if (paginationEl) paginationEl.style.display = 'none';
return;
}
// Table
const rows = slice.map(item => `
<tr data-id="${item.id}" data-lib="${lib}">
<td class="arl-cell-name">${item.name || '-'}</td>
<td class="arl-cell-category">
<span class="arl-category-badge">${getCategoryLabel(lib, item.category)}</span>
</td>
<td class="arl-cell-def">${truncate(item.definition, 80)}</td>
<td class="arl-cell-actions" id="arl-actions-${item.id}">
<button class="arl-btn-edit" data-action="edit" data-id="${item.id}" data-lib="${lib}"
aria-label="Edit ${item.name}">Edit</button>
<button class="arl-btn-delete" data-action="delete" data-id="${item.id}" data-lib="${lib}"
aria-label="Delete ${item.name}">Delete</button>
</td>
</tr>
`).join('');
contentEl.innerHTML = `
<div class="arl-table-wrap">
<table class="arl-table" aria-label="${lib === 'prompts' ? 'Prompts' : 'Reinforcers'} library">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Category</th>
<th scope="col">Definition</th>
<th scope="col" style="text-align:right;">Actions</th>
</tr>
</thead>
<tbody id="arl-tbody-${lib}">
${rows}
</tbody>
</table>
</div>
`;
// Wire action buttons
contentEl.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', e => {
const action = btn.dataset.action;
const id = btn.dataset.id;
const blib = btn.dataset.lib;
if (action === 'edit') openEditor(blib, id);
if (action === 'delete') promptDelete(blib, id, btn.closest('tr'));
});
});
// Pagination
if (paginationEl) {
if (totalPages <= 1) {
paginationEl.style.display = 'none';
} else {
paginationEl.style.display = 'flex';
renderPagination(lib, safePage, totalPages, total, start, paginationEl);
}
}
}
function renderPagination(lib, page, totalPages, total, start, el) {
const end = Math.min(start + PAGE_SIZE, total);
el.innerHTML = `
<span class="arl-page-info">Showing ${start + 1}-${end} of ${total}</span>
<button class="arl-page-btn" data-page="${page - 1}" ${page <= 1 ? 'disabled' : ''}
aria-label="Previous page">← Prev</button>
`;
// Page number buttons (show max 7)
const maxBtns = 7;
let lo = Math.max(1, page - Math.floor(maxBtns / 2));
let hi = Math.min(totalPages, lo + maxBtns - 1);
if (hi - lo < maxBtns - 1) lo = Math.max(1, hi - maxBtns + 1);
for (let p = lo; p <= hi; p++) {
const btn = document.createElement('button');
btn.className = 'arl-page-btn' + (p === page ? ' arl-page-current' : '');
btn.dataset.page = p;
btn.textContent = p;
btn.setAttribute('aria-label', `Page ${p}`);
if (p === page) btn.setAttribute('aria-current', 'page');
el.appendChild(btn);
}
const nextBtn = document.createElement('button');
nextBtn.className = 'arl-page-btn';
nextBtn.dataset.page = page + 1;
nextBtn.textContent = 'Next →';
nextBtn.setAttribute('aria-label', 'Next page');
if (page >= totalPages) nextBtn.disabled = true;
el.appendChild(nextBtn);
el.querySelectorAll('[data-page]').forEach(btn => {
btn.addEventListener('click', () => {
const p = parseInt(btn.dataset.page, 10);
if (!isNaN(p) && p >= 1 && p <= totalPages) {
currentPage[lib] = p;
renderList(lib);
el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
});
});
}
// ── Delete with inline confirmation ──────────────────────────────────────
function promptDelete(lib, id, rowEl) {
// Cancel any prior pending delete
cancelPendingDelete();
const actionsCell = document.getElementById(`arl-actions-${id}`);
if (!actionsCell) return;
pendingDelete = { lib, id, rowEl, actionsCell };
const original = actionsCell.innerHTML;
actionsCell.innerHTML = `
<div class="arl-confirm-row">
Delete?
<button class="arl-confirm-yes" id="arl-confirm-yes-${id}" aria-label="Confirm delete">Yes, delete</button>
<button class="arl-confirm-no" id="arl-confirm-no-${id}" aria-label="Cancel delete">Cancel</button>
</div>
`;
actionsCell._originalHTML = original;
document.getElementById(`arl-confirm-yes-${id}`).addEventListener('click', () => {
commitDelete(lib, id);
});
document.getElementById(`arl-confirm-no-${id}`).addEventListener('click', () => {
cancelPendingDelete();
});
}
function cancelPendingDelete() {
if (pendingDelete && pendingDelete.actionsCell && pendingDelete.actionsCell._originalHTML) {
pendingDelete.actionsCell.innerHTML = pendingDelete.actionsCell._originalHTML;
// Re-wire the restored buttons
pendingDelete.actionsCell.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', () => {
const action = btn.dataset.action;
const id = btn.dataset.id;
const lib = btn.dataset.lib;
if (action === 'edit') openEditor(lib, id);
if (action === 'delete') promptDelete(lib, id, btn.closest('tr'));
});
});
}
pendingDelete = null;
}
function commitDelete(lib, id) {
const arr = getLibrary(lib);
const item = arr.find(i => i.id === id);
const newArr = arr.filter(i => i.id !== id);
setLibrary(lib, newArr);
pendingDelete = null;
renderList(lib);
ARFA_API.toast(`"${item ? item.name : id}" deleted`, 'info');
}
// ── Editor modal ──────────────────────────────────────────────────────────
function openEditor(lib, id) {
const overlay = document.getElementById('arl-modal-overlay');
const titleEl = document.getElementById('arl-modal-title');
const idInput = document.getElementById('arl-edit-id');
const libInput = document.getElementById('arl-edit-lib');
const nameInput = document.getElementById('arl-edit-name');
const catSelect = document.getElementById('arl-edit-category');
const defTa = document.getElementById('arl-edit-definition');
const charHint = document.getElementById('arl-char-hint');
if (!overlay) return;
const isEdit = !!id;
titleEl.textContent = isEdit
? `Edit ${lib === 'prompts' ? 'Prompt' : 'Reinforcer'}`
: `Add ${lib === 'prompts' ? 'Prompt' : 'Reinforcer'}`;
idInput.value = id || '';
libInput.value = lib;
// Populate category options
const cats = lib === 'prompts' ? PROMPT_CATEGORIES : REINFORCER_CATEGORIES;
catSelect.innerHTML = cats.map(c =>
`<option value="${c.value}">${c.label}</option>`
).join('');
if (isEdit) {
const item = getLibrary(lib).find(i => i.id === id);
if (item) {
nameInput.value = item.name || '';
catSelect.value = item.category || cats[0].value;
defTa.value = item.definition || '';
}
} else {
nameInput.value = '';
catSelect.value = cats[0].value;
defTa.value = '';
}
// Char counter
function updateCharHint() {
const len = defTa.value.length;
charHint.textContent = `${len} / 200`;
charHint.classList.toggle('arl-over', len > 200);
}
updateCharHint();
defTa.addEventListener('input', updateCharHint);
overlay.style.display = 'flex';
requestAnimationFrame(() => nameInput.focus());
}
function closeEditor() {
const overlay = document.getElementById('arl-modal-overlay');
if (overlay) overlay.style.display = 'none';
}
function saveEditor() {
const idInput = document.getElementById('arl-edit-id');
const libInput = document.getElementById('arl-edit-lib');
const nameInput = document.getElementById('arl-edit-name');
const catSelect = document.getElementById('arl-edit-category');
const defTa = document.getElementById('arl-edit-definition');
const lib = libInput.value;
const id = idInput.value;
const name = nameInput.value.trim();
if (!name) {
nameInput.focus();
ARFA_API.toast('Name is required', 'warning');
return;
}
const arr = getLibrary(lib);
const isEdit = !!id;
if (isEdit) {
const idx = arr.findIndex(i => i.id === id);
if (idx !== -1) {
arr[idx] = {
...arr[idx],
name: name,
category: catSelect.value,
definition: defTa.value.trim(),
updated_at: nowLabel(),
};
}
setLibrary(lib, arr);
ARFA_API.toast(`"${name}" updated`, 'success');
} else {
const newItem = {
id: generateId(lib),
name: name,
category: catSelect.value,
definition: defTa.value.trim(),
created_at: nowLabel(),
updated_at: nowLabel(),
};
arr.push(newItem);
setLibrary(lib, arr);
// Jump to last page to show newly added item
const filtered = filterLibrary(lib);
currentPage[lib] = Math.ceil(filtered.length / PAGE_SIZE) || 1;
ARFA_API.toast(`"${name}" added`, 'success');
}
closeEditor();
renderList(lib);
}
// ── Tab switching ─────────────────────────────────────────────────────────
function switchTab(tab) {
activeTab = tab;
document.querySelectorAll('.arl-tab').forEach(btn => {
const isActive = btn.dataset.tab === tab;
btn.classList.toggle('arl-tab-active', isActive);
btn.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
const panels = {
prompts: document.getElementById('arl-panel-prompts'),
reinforcers: document.getElementById('arl-panel-reinforcers'),
};
Object.entries(panels).forEach(([key, el]) => {
if (el) el.style.display = key === tab ? '' : 'none';
});
cancelPendingDelete();
renderList(tab);
}
// ── Search wiring ─────────────────────────────────────────────────────────
function wireSearch(lib) {
const input = document.getElementById(`arl-search-${lib}`);
if (!input) return;
input.addEventListener('input', () => {
searchQuery[lib] = input.value;
currentPage[lib] = 1;
renderList(lib);
});
}
// ── Init ──────────────────────────────────────────────────────────────────
function init() {
// Tab buttons
document.querySelectorAll('.arl-tab').forEach(btn => {
btn.addEventListener('click', () => switchTab(btn.dataset.tab));
});
// Add New buttons
const addPromptBtn = document.getElementById('arl-add-prompt');
const addReinforcerBtn = document.getElementById('arl-add-reinforcer');
if (addPromptBtn) addPromptBtn.addEventListener('click', () => openEditor('prompts', null));
if (addReinforcerBtn) addReinforcerBtn.addEventListener('click', () => openEditor('reinforcers', null));
// Modal close / cancel / save
const closeBtn = document.getElementById('arl-modal-close');
const cancelBtn = document.getElementById('arl-modal-cancel');
const saveBtn = document.getElementById('arl-modal-save');
const overlay = document.getElementById('arl-modal-overlay');
if (closeBtn) closeBtn.addEventListener('click', closeEditor);
if (cancelBtn) cancelBtn.addEventListener('click', closeEditor);
if (saveBtn) saveBtn.addEventListener('click', saveEditor);
// Close modal on overlay backdrop click
if (overlay) {
overlay.addEventListener('click', e => {
if (e.target === overlay) closeEditor();
});
}
// Close modal on Escape
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
if (overlay && overlay.style.display !== 'none') closeEditor();
}
});
// Wire search inputs
wireSearch('prompts');
wireSearch('reinforcers');
// Dismiss pending delete on outside click
document.addEventListener('click', e => {
if (pendingDelete && !e.target.closest(`#arl-actions-${pendingDelete.id}`)) {
cancelPendingDelete();
}
});
// Initial render
renderList('prompts');
}
// ── Boot ──────────────────────────────────────────────────────────────────
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();