Add simple notes/commands section (separate notes.php, JSON storage)
This commit is contained in:
parent
ed0a596b27
commit
156f05c2a0
3 changed files with 318 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,3 +1,4 @@
|
|||
/data/devices.json
|
||||
/data/notes.json
|
||||
/data/*.tmp
|
||||
.DS_Store
|
||||
|
|
|
|||
|
|
@ -152,6 +152,14 @@ declare(strict_types=1);
|
|||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
try {
|
||||
require __DIR__ . '/notes.php';
|
||||
} catch (Throwable $e) {
|
||||
echo '<section class="card"><p class="muted">Notes section unavailable.</p></section>';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
|
||||
<script src="assets/app.js" defer></script>
|
||||
|
|
|
|||
309
notes.php
Normal file
309
notes.php
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
function notes_path(): string
|
||||
{
|
||||
return __DIR__ . '/data/notes.json';
|
||||
}
|
||||
|
||||
function notes_load(): array
|
||||
{
|
||||
$path = notes_path();
|
||||
if (!is_file($path)) {
|
||||
return [];
|
||||
}
|
||||
$raw = @file_get_contents($path);
|
||||
if ($raw === false || trim($raw) === '') {
|
||||
return [];
|
||||
}
|
||||
$data = json_decode($raw, true);
|
||||
if (!is_array($data)) {
|
||||
return [];
|
||||
}
|
||||
$out = [];
|
||||
foreach ($data as $n) {
|
||||
if (!is_array($n)) continue;
|
||||
$text = trim((string) ($n['text'] ?? ''));
|
||||
if ($text === '') continue;
|
||||
$out[] = [
|
||||
'id' => (string) ($n['id'] ?? ''),
|
||||
'text' => $text,
|
||||
'updated' => (string) ($n['updated'] ?? ''),
|
||||
];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
function notes_save(array $notes): bool
|
||||
{
|
||||
$path = notes_path();
|
||||
$dir = dirname($path);
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0775, true);
|
||||
}
|
||||
$json = json_encode(array_values($notes), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
if ($json === false) return false;
|
||||
$tmp = $path . '.tmp';
|
||||
$ok = @file_put_contents($tmp, $json . "\n", LOCK_EX);
|
||||
if ($ok === false) return false;
|
||||
return @rename($tmp, $path);
|
||||
}
|
||||
|
||||
function notes_json(array $data, int $status = 200): never
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
function notes_id(): string
|
||||
{
|
||||
return bin2hex(random_bytes(8));
|
||||
}
|
||||
|
||||
// Handle AJAX/API requests when called directly
|
||||
$isDirect = basename((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === basename(__FILE__);
|
||||
$action = (string) ($_GET['action'] ?? $_POST['action'] ?? '');
|
||||
if ($isDirect && $action !== '') {
|
||||
try {
|
||||
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
|
||||
$input = $_POST;
|
||||
if (stripos($contentType, 'application/json') !== false) {
|
||||
$raw = file_get_contents('php://input');
|
||||
$decoded = json_decode($raw ?: '', true);
|
||||
if (is_array($decoded)) $input = $decoded;
|
||||
}
|
||||
|
||||
if ($action === 'list') {
|
||||
notes_json(['ok' => true, 'notes' => notes_load()]);
|
||||
}
|
||||
|
||||
if ($action === 'add') {
|
||||
$text = trim((string) ($input['text'] ?? ''));
|
||||
if ($text === '') notes_json(['ok' => false, 'error' => 'Note is empty.'], 400);
|
||||
if (strlen($text) > 10000) notes_json(['ok' => false, 'error' => 'Note too long (max 10000 chars).'], 400);
|
||||
$notes = notes_load();
|
||||
$note = ['id' => notes_id(), 'text' => $text, 'updated' => gmdate('c')];
|
||||
array_unshift($notes, $note);
|
||||
if (!notes_save($notes)) notes_json(['ok' => false, 'error' => 'Failed to save note.'], 500);
|
||||
notes_json(['ok' => true, 'note' => $note, 'notes' => $notes]);
|
||||
}
|
||||
|
||||
if ($action === 'edit') {
|
||||
$id = (string) ($input['id'] ?? '');
|
||||
$text = trim((string) ($input['text'] ?? ''));
|
||||
if ($id === '') notes_json(['ok' => false, 'error' => 'Missing note id.'], 400);
|
||||
if ($text === '') notes_json(['ok' => false, 'error' => 'Note is empty.'], 400);
|
||||
if (strlen($text) > 10000) notes_json(['ok' => false, 'error' => 'Note too long (max 10000 chars).'], 400);
|
||||
$notes = notes_load();
|
||||
$found = false;
|
||||
foreach ($notes as &$n) {
|
||||
if (($n['id'] ?? '') === $id) {
|
||||
$n['text'] = $text;
|
||||
$n['updated'] = gmdate('c');
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
unset($n);
|
||||
if (!$found) notes_json(['ok' => false, 'error' => 'Note not found.'], 404);
|
||||
if (!notes_save($notes)) notes_json(['ok' => false, 'error' => 'Failed to save note.'], 500);
|
||||
notes_json(['ok' => true, 'notes' => $notes]);
|
||||
}
|
||||
|
||||
if ($action === 'delete') {
|
||||
$id = (string) ($input['id'] ?? '');
|
||||
if ($id === '') notes_json(['ok' => false, 'error' => 'Missing note id.'], 400);
|
||||
$notes = notes_load();
|
||||
$before = count($notes);
|
||||
$notes = array_values(array_filter($notes, fn($n) => ($n['id'] ?? '') !== $id));
|
||||
if (count($notes) === $before) notes_json(['ok' => false, 'error' => 'Note not found.'], 404);
|
||||
if (!notes_save($notes)) notes_json(['ok' => false, 'error' => 'Failed to save note.'], 500);
|
||||
notes_json(['ok' => true, 'notes' => $notes]);
|
||||
}
|
||||
|
||||
notes_json(['ok' => false, 'error' => 'Unknown action.'], 400);
|
||||
} catch (Throwable $e) {
|
||||
notes_json(['ok' => false, 'error' => 'Server error.'], 500);
|
||||
}
|
||||
}
|
||||
|
||||
// Render mode (when included)
|
||||
if ($isDirect && $action === '') {
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "notes.php endpoint";
|
||||
return;
|
||||
}
|
||||
|
||||
$notesInitial = [];
|
||||
try {
|
||||
$notesInitial = notes_load();
|
||||
} catch (Throwable $e) {
|
||||
$notesInitial = [];
|
||||
}
|
||||
?>
|
||||
<section class="card notes-card" aria-labelledby="notes-title" id="notesSection">
|
||||
<div class="card-header">
|
||||
<h2 class="section-title" id="notes-title">Notes & Commands</h2>
|
||||
<div class="actions no-margin-top">
|
||||
<button type="button" class="button button-small" id="notesAddBtn">+ Add Note</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="notesAlert" class="alert" hidden></div>
|
||||
|
||||
<div id="notesEditor" class="notes-editor" hidden>
|
||||
<div class="field">
|
||||
<label for="notesText" id="notesEditorLabel">New note</label>
|
||||
<textarea id="notesText" rows="5" placeholder="Paste commands or notes here…"></textarea>
|
||||
<p class="hint">Stored in <code>data/notes.json</code>. Use for commands/snippets you want quick access to.</p>
|
||||
</div>
|
||||
<div class="actions no-margin-top">
|
||||
<button type="button" class="button button-primary button-small" id="notesSaveBtn">Save</button>
|
||||
<button type="button" class="button button-small" id="notesCancelBtn">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="notesList" class="notes-list" aria-live="polite"></div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.notes-card { width: 100%; }
|
||||
.notes-editor { margin-bottom: 14px; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius); background: rgba(128,128,128,.03); }
|
||||
.notes-list { display: grid; gap: 10px; }
|
||||
.note-item { border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; background: transparent; animation: card-in .2s ease both; }
|
||||
.note-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; margin-bottom: 8px; }
|
||||
.note-meta { color: var(--muted); font-size: .72rem; }
|
||||
.note-actions { display: flex; gap: 6px; flex-shrink: 0; }
|
||||
.note-icon-btn { min-height: 30px; min-width: 30px; padding: 4px 8px; font-size: .8rem; line-height: 1; }
|
||||
.note-body { margin: 0; white-space: pre-wrap; word-break: break-word; font-family: var(--mono); font-size: .82rem; line-height: 1.5; color: var(--text); background: transparent; border: 0; padding: 0; }
|
||||
.notes-empty { color: var(--muted); text-align: center; padding: 18px 8px; margin: 0; border: 1px dashed var(--line); border-radius: var(--radius); }
|
||||
@media (max-width: 560px) { .note-head { flex-direction: column; } .note-actions { width: 100%; } }
|
||||
</style>
|
||||
|
||||
<script>
|
||||
(() => {
|
||||
const API = 'notes.php';
|
||||
const listEl = document.getElementById('notesList');
|
||||
const alertEl = document.getElementById('notesAlert');
|
||||
const editor = document.getElementById('notesEditor');
|
||||
const editorLabel = document.getElementById('notesEditorLabel');
|
||||
const textEl = document.getElementById('notesText');
|
||||
const addBtn = document.getElementById('notesAddBtn');
|
||||
const saveBtn = document.getElementById('notesSaveBtn');
|
||||
const cancelBtn = document.getElementById('notesCancelBtn');
|
||||
if (!listEl) return;
|
||||
|
||||
let notes = <?php echo json_encode($notesInitial, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
|
||||
let editingId = null;
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll("'","'");
|
||||
}
|
||||
function fmt(iso) {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
return isNaN(d.getTime()) ? iso : d.toLocaleString();
|
||||
}
|
||||
function showAlert(msg, type='') {
|
||||
if (!msg) { alertEl.hidden = true; alertEl.textContent=''; alertEl.className='alert'; return; }
|
||||
alertEl.hidden = false; alertEl.textContent = msg;
|
||||
alertEl.className = 'alert' + (type ? ' is-' + type : '');
|
||||
}
|
||||
async function api(action, payload) {
|
||||
const res = await fetch(API + '?action=' + encodeURIComponent(action), {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type':'application/json','Accept':'application/json'},
|
||||
body: JSON.stringify(payload || {})
|
||||
});
|
||||
const data = await res.json().catch(() => ({ok:false,error:'Invalid response'}));
|
||||
if (!res.ok && !data.error) data.error = 'Request failed';
|
||||
return data;
|
||||
}
|
||||
function render() {
|
||||
if (!notes.length) {
|
||||
listEl.innerHTML = '<p class="notes-empty">No notes yet. Add commands or snippets you use often.</p>';
|
||||
return;
|
||||
}
|
||||
listEl.innerHTML = notes.map(n => `
|
||||
<article class="note-item" data-id="${esc(n.id)}">
|
||||
<div class="note-head">
|
||||
<div class="note-meta">${n.updated ? 'Updated ' + esc(fmt(n.updated)) : ''}</div>
|
||||
<div class="note-actions">
|
||||
<button type="button" class="button note-icon-btn" data-copy="${esc(n.id)}" title="Copy" aria-label="Copy note">Copy</button>
|
||||
<button type="button" class="button note-icon-btn" data-edit="${esc(n.id)}" title="Edit" aria-label="Edit note">Edit</button>
|
||||
<button type="button" class="button note-icon-btn button-danger" data-delete="${esc(n.id)}" title="Delete" aria-label="Delete note">Del</button>
|
||||
</div>
|
||||
</div>
|
||||
<pre class="note-body">${esc(n.text)}</pre>
|
||||
</article>
|
||||
`).join('');
|
||||
|
||||
listEl.querySelectorAll('[data-copy]').forEach(btn => btn.addEventListener('click', async () => {
|
||||
const note = notes.find(x => x.id === btn.dataset.copy);
|
||||
if (!note) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(note.text);
|
||||
showAlert('Note copied to clipboard.', 'success');
|
||||
} catch {
|
||||
showAlert('Copy failed. You can manually select and copy the text.', 'warning');
|
||||
}
|
||||
}));
|
||||
listEl.querySelectorAll('[data-edit]').forEach(btn => btn.addEventListener('click', () => {
|
||||
const note = notes.find(x => x.id === btn.dataset.edit);
|
||||
if (!note) return;
|
||||
editingId = note.id;
|
||||
editorLabel.textContent = 'Edit note';
|
||||
textEl.value = note.text;
|
||||
editor.hidden = false;
|
||||
textEl.focus();
|
||||
showAlert('');
|
||||
}));
|
||||
listEl.querySelectorAll('[data-delete]').forEach(btn => btn.addEventListener('click', async () => {
|
||||
const id = btn.dataset.delete;
|
||||
if (!confirm('Delete this note?')) return;
|
||||
btn.disabled = true;
|
||||
const data = await api('delete', {id});
|
||||
if (data.ok) { notes = data.notes || []; render(); showAlert('Note deleted.', 'success'); }
|
||||
else { btn.disabled = false; showAlert(data.error || 'Delete failed.', 'urgent'); }
|
||||
}));
|
||||
}
|
||||
|
||||
addBtn.addEventListener('click', () => {
|
||||
editingId = null;
|
||||
editorLabel.textContent = 'New note';
|
||||
textEl.value = '';
|
||||
editor.hidden = false;
|
||||
textEl.focus();
|
||||
showAlert('');
|
||||
});
|
||||
cancelBtn.addEventListener('click', () => {
|
||||
editingId = null;
|
||||
editor.hidden = true;
|
||||
textEl.value = '';
|
||||
});
|
||||
saveBtn.addEventListener('click', async () => {
|
||||
const text = textEl.value.trim();
|
||||
if (!text) { showAlert('Note is empty.', 'warning'); return; }
|
||||
saveBtn.disabled = true;
|
||||
const action = editingId ? 'edit' : 'add';
|
||||
const payload = editingId ? {id: editingId, text} : {text};
|
||||
const data = await api(action, payload);
|
||||
saveBtn.disabled = false;
|
||||
if (data.ok) {
|
||||
notes = data.notes || notes;
|
||||
editingId = null;
|
||||
editor.hidden = true;
|
||||
textEl.value = '';
|
||||
render();
|
||||
showAlert(action === 'edit' ? 'Note updated.' : 'Note added.', 'success');
|
||||
} else {
|
||||
showAlert(data.error || 'Save failed.', 'urgent');
|
||||
}
|
||||
});
|
||||
|
||||
render();
|
||||
})();
|
||||
</script>
|
||||
Loading…
Add table
Reference in a new issue