|
|
@@ -3,7 +3,7 @@ import { Link, useSearchParams } from 'react-router-dom'
|
|
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
|
|
import {
|
|
|
Plus, Search, Pencil, ChevronLeft, ChevronRight, Database,
|
|
|
- Copy, ArrowUp, ArrowDown, ArrowUpDown, RefreshCw,
|
|
|
+ Copy, ArrowUp, ArrowDown, ArrowUpDown, RefreshCw, Lock, Bot, User,
|
|
|
} from 'lucide-react'
|
|
|
import { api } from '@/api/client'
|
|
|
import { useAuthStore } from '@/stores/authStore'
|
|
|
@@ -13,7 +13,7 @@ import { ConfirmDialog } from '@/components/ConfirmDialog'
|
|
|
import { JsonEditor } from '@/components/JsonEditor'
|
|
|
import { RelationLinks } from '@/components/RelationLinks'
|
|
|
import { DeleteImpactDialog } from '@/components/DeleteImpactDialog'
|
|
|
-import { ApiError } from '@/types'
|
|
|
+import { ApiError, DB_METADATA_FIELDS } from '@/types'
|
|
|
import type { CollectionMeta } from '@/types'
|
|
|
|
|
|
// ─── Filter op types ──────────────────────────────────────────────────────────
|
|
|
@@ -240,12 +240,295 @@ function FilterBar({
|
|
|
)
|
|
|
}
|
|
|
|
|
|
+// ─── Database metadata ────────────────────────────────────────────────────────
|
|
|
+
|
|
|
+const META_KEYS: readonly string[] = DB_METADATA_FIELDS
|
|
|
+
|
|
|
+function isMetaKey(key: string): boolean {
|
|
|
+ return META_KEYS.includes(key)
|
|
|
+}
|
|
|
+
|
|
|
+// Split a document the database handed back into the metadata it ATTACHED and
|
|
|
+// the body that is actually stored.
|
|
|
+//
|
|
|
+// These are not two views of one thing: the body is what a write sends and the
|
|
|
+// metadata is what every read overwrites. Showing them mixed invites a user to
|
|
|
+// edit a reserved key, and this service strips reserved keys from a write body,
|
|
|
+// so that edit would be accepted, discarded, and look like it worked.
|
|
|
+function splitDocument(doc: Record<string, unknown>): {
|
|
|
+ meta: Record<string, unknown>
|
|
|
+ body: Record<string, unknown>
|
|
|
+} {
|
|
|
+ const meta: Record<string, unknown> = {}
|
|
|
+ const body: Record<string, unknown> = {}
|
|
|
+ for (const [k, v] of Object.entries(doc)) {
|
|
|
+ if (isMetaKey(k)) meta[k] = v
|
|
|
+ else body[k] = v
|
|
|
+ }
|
|
|
+ return { meta, body }
|
|
|
+}
|
|
|
+
|
|
|
+// Remove any reserved key a user typed into the editor by hand.
|
|
|
+//
|
|
|
+// The panel keeps them out of the editor, but the editor is free-form JSON and
|
|
|
+// nothing stops someone typing `_version` into it. The server would strip it
|
|
|
+// anyway; stripping here as well is what lets the UI SAY so, instead of the
|
|
|
+// write quietly differing from what the user wrote.
|
|
|
+function stripMetadata(doc: Record<string, unknown>): {
|
|
|
+ body: Record<string, unknown>
|
|
|
+ removed: string[]
|
|
|
+} {
|
|
|
+ const { meta, body } = splitDocument(doc)
|
|
|
+ return { body, removed: Object.keys(meta) }
|
|
|
+}
|
|
|
+
|
|
|
+// Document timestamps are epoch MILLISECONDS by default - but a collection can
|
|
|
+// be configured for NANOSECONDS (`CollectionConfig::timestampPrecision`), and
|
|
|
+// `migrateCollectionTimestamps()` converts rows one at a time, so a single
|
|
|
+// collection can legitimately hold both at once. No route of ours reports a
|
|
|
+// collection's configured precision, so the value itself is the only evidence
|
|
|
+// available, and the discriminator used here is the database's OWN: its
|
|
|
+// migration skips already-converted rows on a 10^15 threshold.
|
|
|
+//
|
|
|
+// Guessing wrong is not a cosmetic error. A nanosecond value rendered as
|
|
|
+// milliseconds lands in the year 58000 and reads as corrupted data.
|
|
|
+const NS_THRESHOLD = 1e15
|
|
|
+
|
|
|
+function isNanoseconds(raw: number): boolean {
|
|
|
+ return raw >= NS_THRESHOLD
|
|
|
+}
|
|
|
+
|
|
|
+function epochToMillis(raw: number): number {
|
|
|
+ return isNanoseconds(raw) ? raw / 1e6 : raw
|
|
|
+}
|
|
|
+
|
|
|
+function formatEpoch(raw: number): string {
|
|
|
+ try {
|
|
|
+ const d = new Date(epochToMillis(raw))
|
|
|
+ if (Number.isNaN(d.getTime())) return '(not a renderable time)'
|
|
|
+ return d.toLocaleString()
|
|
|
+ } catch {
|
|
|
+ return '(not a renderable time)'
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+function relativeToNow(ms: number): string {
|
|
|
+ const delta = ms - Date.now()
|
|
|
+ const abs = Math.abs(delta)
|
|
|
+ const units: Array<[number, string]> = [
|
|
|
+ [86400000, 'day'], [3600000, 'hour'], [60000, 'minute'], [1000, 'second'],
|
|
|
+ ]
|
|
|
+ for (const [size, name] of units) {
|
|
|
+ if (abs >= size) {
|
|
|
+ const n = Math.round(abs / size)
|
|
|
+ const plural = n === 1 ? '' : 's'
|
|
|
+ return delta >= 0 ? `in ${n} ${name}${plural}` : `${n} ${name}${plural} ago`
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return delta >= 0 ? 'in under a second' : 'under a second ago'
|
|
|
+}
|
|
|
+
|
|
|
+function asNumber(v: unknown): number | null {
|
|
|
+ if (typeof v === 'number' && Number.isFinite(v)) return v
|
|
|
+ if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v)
|
|
|
+ return null
|
|
|
+}
|
|
|
+
|
|
|
+function MetaRow({ label, hint, children }: {
|
|
|
+ label: string
|
|
|
+ hint?: React.ReactNode
|
|
|
+ children: React.ReactNode
|
|
|
+}) {
|
|
|
+ return (
|
|
|
+ <div className="px-3 py-2">
|
|
|
+ <div className="flex items-baseline justify-between gap-4">
|
|
|
+ <dt className="text-[11px] uppercase tracking-wider text-slate-500 shrink-0 font-mono">{label}</dt>
|
|
|
+ <dd className="text-xs text-slate-200 text-right break-all">{children}</dd>
|
|
|
+ </div>
|
|
|
+ {hint && <p className="mt-1 text-[11px] text-slate-500 text-right">{hint}</p>}
|
|
|
+ </div>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+// A timestamp, shown BOTH ways on purpose: the local time is what a human
|
|
|
+// reads and the raw value is what a caller puts in a `?filter=` - so showing
|
|
|
+// only one of them makes the other a separate lookup.
|
|
|
+function TimestampValue({ raw }: { raw: number }) {
|
|
|
+ const ns = isNanoseconds(raw)
|
|
|
+ return (
|
|
|
+ <span className="inline-flex flex-col items-end gap-0.5">
|
|
|
+ <span>{formatEpoch(raw)}</span>
|
|
|
+ <span className="font-mono text-[11px] text-slate-500">
|
|
|
+ {raw}
|
|
|
+ <span className="ml-1 text-slate-600">{ns ? 'ns' : 'ms'}</span>
|
|
|
+ </span>
|
|
|
+ </span>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+// `fn:<project>/<function-id>` identifies the FUNCTION that wrote the row, and
|
|
|
+// the function id is the half that carries the information: a consumer depends
|
|
|
+// on that granularity as their only after-the-fact attribution channel, which
|
|
|
+// is why it is rendered whole and never shortened to the project.
|
|
|
+function WriterValue({ value }: { value: unknown }) {
|
|
|
+ const s = typeof value === 'string' ? value : JSON.stringify(value)
|
|
|
+ if (typeof s === 'string' && s.startsWith('fn:')) {
|
|
|
+ return (
|
|
|
+ <span className="inline-flex items-center gap-1.5 justify-end">
|
|
|
+ <Bot size={12} className="text-indigo-400 shrink-0" />
|
|
|
+ <span className="font-mono text-indigo-300">{s}</span>
|
|
|
+ </span>
|
|
|
+ )
|
|
|
+ }
|
|
|
+ return (
|
|
|
+ <span className="inline-flex items-center gap-1.5 justify-end">
|
|
|
+ <User size={12} className="text-slate-500 shrink-0" />
|
|
|
+ <span className="font-mono">{s || <span className="text-slate-600">-</span>}</span>
|
|
|
+ </span>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+// `_expires_at` has THREE readings, not two, and the third is the one that
|
|
|
+// looks like a bug when it is not:
|
|
|
+//
|
|
|
+// absent - no expiry. Never zero, and never "unknown".
|
|
|
+// future - the row will be swept at that time.
|
|
|
+// PAST - the row is past its deadline AND IS STILL HERE. Expiry is lazy:
|
|
|
+// the sweep runs on its own schedule, so a row sitting past its
|
|
|
+// expiry is ordinary, not evidence of a fault. It is also the row
|
|
|
+// that must be left OUT of a restore, since a restored row carries
|
|
|
+// no TTL and would come back immortal.
|
|
|
+function ExpiryValue({ present, raw }: { present: boolean; raw: number | null }) {
|
|
|
+ if (!present) {
|
|
|
+ return <span className="text-slate-400">no expiry</span>
|
|
|
+ }
|
|
|
+ if (raw === null) {
|
|
|
+ return <span className="text-amber-300">present but not a number</span>
|
|
|
+ }
|
|
|
+ const ms = epochToMillis(raw)
|
|
|
+ const expired = ms <= Date.now()
|
|
|
+ return (
|
|
|
+ <span className="inline-flex flex-col items-end gap-0.5">
|
|
|
+ <span className={expired ? 'text-amber-300' : 'text-slate-200'}>
|
|
|
+ {formatEpoch(raw)} ({relativeToNow(ms)})
|
|
|
+ </span>
|
|
|
+ <span className="font-mono text-[11px] text-slate-500">{raw} ms</span>
|
|
|
+ {expired && (
|
|
|
+ <span className="text-[11px] text-amber-400/90">
|
|
|
+ past its expiry and still stored - the sweep runs on its own schedule
|
|
|
+ </span>
|
|
|
+ )}
|
|
|
+ </span>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
+// The read-only half of a document.
|
|
|
+function DocumentMetaPanel({ meta, onCopy }: {
|
|
|
+ meta: Record<string, unknown>
|
|
|
+ onCopy: (text: string, label: string) => void
|
|
|
+}) {
|
|
|
+ if (Object.keys(meta).length === 0) return null
|
|
|
+
|
|
|
+ const id = meta['_id']
|
|
|
+ const version = asNumber(meta['_version'])
|
|
|
+ const createdAt = asNumber(meta['_created_at'])
|
|
|
+ const updatedAt = asNumber(meta['_updated_at'])
|
|
|
+ // Membership, not truthiness: ABSENT means "no expiry", and a present value
|
|
|
+ // can legitimately be in the past. `meta['_expires_at'] ? ...` would collapse
|
|
|
+ // both of those into the same rendering.
|
|
|
+ const expiresPresent = Object.prototype.hasOwnProperty.call(meta, '_expires_at')
|
|
|
+ const expiresAt = asNumber(meta['_expires_at'])
|
|
|
+
|
|
|
+ // Anything the database starts attaching that this UI does not know about
|
|
|
+ // yet. Listed rather than dropped: a field nobody renders is how a reader
|
|
|
+ // learns the server moved ahead of the UI.
|
|
|
+ const known = ['_id', '_version', '_created_at', '_updated_at', '_created_by', '_updated_by', '_expires_at']
|
|
|
+ const extra = Object.entries(meta).filter(([k]) => !known.includes(k))
|
|
|
+
|
|
|
+ return (
|
|
|
+ <div className="rounded-lg border border-slate-700/40 bg-slate-900/40" data-testid="doc-meta-panel">
|
|
|
+ <div className="flex items-center gap-2 border-b border-slate-700/40 px-3 py-2">
|
|
|
+ <Lock size={12} className="text-slate-500" />
|
|
|
+ <span className="text-xs font-semibold text-slate-300">Database metadata</span>
|
|
|
+ <span className="text-[11px] text-slate-500">
|
|
|
+ read-only - attached by the database, never part of the stored body
|
|
|
+ </span>
|
|
|
+ </div>
|
|
|
+
|
|
|
+ <dl className="divide-y divide-slate-700/30">
|
|
|
+ {id !== undefined && (
|
|
|
+ <MetaRow label="_id" hint="the document's identity; it is taken from the URL on a write, never from the body">
|
|
|
+ <span className="inline-flex items-center gap-1.5 justify-end">
|
|
|
+ <span className="font-mono">{String(id)}</span>
|
|
|
+ <button
|
|
|
+ onClick={() => onCopy(String(id), 'Document ID')}
|
|
|
+ className="p-1 rounded text-slate-500 hover:text-slate-200 hover:bg-slate-700/50 transition"
|
|
|
+ aria-label="Copy document ID"
|
|
|
+ title="Copy ID"
|
|
|
+ >
|
|
|
+ <Copy size={11} />
|
|
|
+ </button>
|
|
|
+ </span>
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ {version !== null && (
|
|
|
+ <MetaRow label="_version" hint="the value a conditional write passes as ?if_version=">
|
|
|
+ <span className="font-mono">{version}</span>
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ {createdAt !== null && (
|
|
|
+ <MetaRow label="_created_at">
|
|
|
+ <TimestampValue raw={createdAt} />
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ {updatedAt !== null && (
|
|
|
+ <MetaRow label="_updated_at">
|
|
|
+ <TimestampValue raw={updatedAt} />
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ {meta['_created_by'] !== undefined && (
|
|
|
+ <MetaRow label="_created_by" hint="a function writes as fn:<project>/<function-id>">
|
|
|
+ <WriterValue value={meta['_created_by']} />
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ {meta['_updated_by'] !== undefined && (
|
|
|
+ <MetaRow label="_updated_by">
|
|
|
+ <WriterValue value={meta['_updated_by']} />
|
|
|
+ </MetaRow>
|
|
|
+ )}
|
|
|
+
|
|
|
+ <MetaRow
|
|
|
+ label="_expires_at"
|
|
|
+ hint={expiresPresent ? undefined : 'the field is absent, which means no expiry - it is never reported as zero'}
|
|
|
+ >
|
|
|
+ <ExpiryValue present={expiresPresent} raw={expiresAt} />
|
|
|
+ </MetaRow>
|
|
|
+
|
|
|
+ {extra.map(([k, v]) => (
|
|
|
+ <MetaRow key={k} label={k} hint="reserved by the database; this UI has no specific rendering for it yet">
|
|
|
+ <span className="font-mono">{JSON.stringify(v)}</span>
|
|
|
+ </MetaRow>
|
|
|
+ ))}
|
|
|
+ </dl>
|
|
|
+ </div>
|
|
|
+ )
|
|
|
+}
|
|
|
+
|
|
|
// ─── Document editor modal ────────────────────────────────────────────────────
|
|
|
|
|
|
interface DocEditorModalProps {
|
|
|
open: boolean
|
|
|
title: string
|
|
|
+ /// The STORED BODY only. The database's own fields are rendered separately
|
|
|
+ /// and read-only, so the editor cannot be used to write one.
|
|
|
initialJson: string
|
|
|
+ /// The database's attached fields for this document, empty for a new one.
|
|
|
+ meta: Record<string, unknown>
|
|
|
// Present only when editing an existing document; enables the relation links
|
|
|
// and the delete-impact preview.
|
|
|
project?: string
|
|
|
@@ -254,13 +537,14 @@ interface DocEditorModalProps {
|
|
|
onClose: () => void
|
|
|
onSave: (parsed: Record<string, unknown>) => Promise<void>
|
|
|
onDelete?: () => void
|
|
|
+ onCopy: (text: string, label: string) => void
|
|
|
saving: boolean
|
|
|
}
|
|
|
|
|
|
function DocEditorModal({
|
|
|
- open, title, initialJson,
|
|
|
+ open, title, initialJson, meta,
|
|
|
project, collection, docId,
|
|
|
- onClose, onSave, onDelete, saving,
|
|
|
+ onClose, onSave, onDelete, onCopy, saving,
|
|
|
}: DocEditorModalProps) {
|
|
|
const [json, setJson] = useState(initialJson)
|
|
|
const [jsonValid, setJsonValid] = useState(true)
|
|
|
@@ -286,6 +570,8 @@ function DocEditorModal({
|
|
|
<>
|
|
|
<Modal open={open} title={title} onClose={onClose}>
|
|
|
<div className="flex flex-col gap-4">
|
|
|
+ <DocumentMetaPanel meta={meta} onCopy={onCopy} />
|
|
|
+
|
|
|
<JsonEditor
|
|
|
value={json}
|
|
|
onChange={setJson}
|
|
|
@@ -300,7 +586,11 @@ function DocEditorModal({
|
|
|
{project && collection && docId && jsonValid && (() => {
|
|
|
let parsed: Record<string, unknown> = {}
|
|
|
try { parsed = JSON.parse(json) as Record<string, unknown> } catch { return null }
|
|
|
- return <RelationLinks project={project} collection={collection} doc={parsed} />
|
|
|
+ // The WHOLE document, metadata included. The editor now holds only
|
|
|
+ // the body, and a relation is free to be declared on a field this
|
|
|
+ // split moved out of it - so passing the body alone would silently
|
|
|
+ // stop resolving those links.
|
|
|
+ return <RelationLinks project={project} collection={collection} doc={{ ...meta, ...parsed }} />
|
|
|
})()}
|
|
|
|
|
|
<div className="flex items-center justify-between pt-1">
|
|
|
@@ -372,13 +662,21 @@ interface ResultsTableProps {
|
|
|
sortField: string
|
|
|
sortDesc: boolean
|
|
|
onSortById: () => void
|
|
|
+ /// Whether a filter was in force for this result. An empty collection and a
|
|
|
+ /// filter that matched nothing are different facts, and one message for both
|
|
|
+ /// makes the reader guess which they are looking at.
|
|
|
+ filtered: boolean
|
|
|
}
|
|
|
|
|
|
-function ResultsTable({ docs, onRowClick, onCopy, sortField, sortDesc, onSortById }: ResultsTableProps) {
|
|
|
+function ResultsTable({ docs, onRowClick, onCopy, sortField, sortDesc, onSortById, filtered }: ResultsTableProps) {
|
|
|
if (docs.length === 0) {
|
|
|
return (
|
|
|
<div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center">
|
|
|
- <p className="text-slate-400 text-sm">No documents found.</p>
|
|
|
+ <p className="text-slate-400 text-sm" data-testid="docs-empty">
|
|
|
+ {filtered
|
|
|
+ ? 'No documents match this filter. The collection may still hold documents.'
|
|
|
+ : 'This collection holds no documents.'}
|
|
|
+ </p>
|
|
|
</div>
|
|
|
)
|
|
|
}
|
|
|
@@ -473,7 +771,10 @@ type ModalMode = 'new' | 'edit'
|
|
|
interface ModalState {
|
|
|
mode: ModalMode
|
|
|
docId: string
|
|
|
+ /// The stored body, which is the only part a write sends.
|
|
|
json: string
|
|
|
+ /// The database's attached fields, rendered read-only.
|
|
|
+ meta: Record<string, unknown>
|
|
|
}
|
|
|
|
|
|
export default function Documents() {
|
|
|
@@ -516,7 +817,7 @@ export default function Documents() {
|
|
|
|
|
|
// Modal state
|
|
|
const [modalOpen, setModalOpen] = useState(false)
|
|
|
- const [modalState, setModalState] = useState<ModalState>({ mode: 'new', docId: '', json: '{}' })
|
|
|
+ const [modalState, setModalState] = useState<ModalState>({ mode: 'new', docId: '', json: '{}', meta: {} })
|
|
|
const [saving, setSaving] = useState(false)
|
|
|
|
|
|
// Auto-select first collection on project change
|
|
|
@@ -546,13 +847,20 @@ export default function Documents() {
|
|
|
|
|
|
const docs = findData?.documents ?? []
|
|
|
const docCount = findData?.count ?? null
|
|
|
+ // `total` is the exact number of rows matching the filters, computed server
|
|
|
+ // side BEFORE pagination - not an estimate and not a page count.
|
|
|
+ const totalMatching = findData?.total ?? null
|
|
|
|
|
|
- // Pagination — the API returns a page of results (no grand total), so we use
|
|
|
- // the full-page heuristic: a full page means there is probably a next page.
|
|
|
const limitNum = parseInt(limit, 10) || 50
|
|
|
const offsetNum = parseInt(offset, 10) || 0
|
|
|
const canPrev = offsetNum > 0
|
|
|
- const canNext = docs.length >= limitNum
|
|
|
+ // `has_more` is the server's own answer and it is emitted unconditionally,
|
|
|
+ // so an ABSENT field means one thing only: a server older than the release
|
|
|
+ // that added it. That is the single case the old full-page heuristic is
|
|
|
+ // still right for, and it is wrong whenever the last page happens to be
|
|
|
+ // exactly full - which offered a Next button onto an empty page.
|
|
|
+ const hasMoreReported = findData?.has_more
|
|
|
+ const canNext = hasMoreReported ?? docs.length >= limitNum
|
|
|
|
|
|
const invalidateDocs = () => {
|
|
|
void queryClient.invalidateQueries({ queryKey: ['documents', currentProject, effectiveCollection] })
|
|
|
@@ -600,7 +908,13 @@ export default function Documents() {
|
|
|
try {
|
|
|
const full = await api.getDocument(currentProject, effectiveCollection, openId)
|
|
|
if (cancelled) return
|
|
|
- setModalState({ mode: 'edit', docId: openId, json: JSON.stringify(full, null, 2) })
|
|
|
+ const split = splitDocument(full)
|
|
|
+ setModalState({
|
|
|
+ mode: 'edit',
|
|
|
+ docId: openId,
|
|
|
+ json: JSON.stringify(split.body, null, 2),
|
|
|
+ meta: split.meta,
|
|
|
+ })
|
|
|
setModalOpen(true)
|
|
|
} catch (err) {
|
|
|
if (!cancelled) push(`Could not open ${openId}: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
|
|
|
@@ -640,10 +954,15 @@ export default function Documents() {
|
|
|
const id = docId(doc)
|
|
|
try {
|
|
|
const fullDoc = await api.getDocument(currentProject, effectiveCollection, id)
|
|
|
+ // The editor gets the BODY; the database's own fields go to the
|
|
|
+ // read-only panel. Editing one of them would be accepted here and
|
|
|
+ // discarded by the server, which is the worst of both.
|
|
|
+ const split = splitDocument(fullDoc)
|
|
|
setModalState({
|
|
|
mode: 'edit',
|
|
|
docId: id,
|
|
|
- json: JSON.stringify(fullDoc, null, 2),
|
|
|
+ json: JSON.stringify(split.body, null, 2),
|
|
|
+ meta: split.meta,
|
|
|
})
|
|
|
setModalOpen(true)
|
|
|
} catch (err) {
|
|
|
@@ -656,12 +975,23 @@ export default function Documents() {
|
|
|
const handleSave = async (parsed: Record<string, unknown>) => {
|
|
|
if (!currentProject || !effectiveCollection) return
|
|
|
setSaving(true)
|
|
|
+ // Reserved keys never reach the request. The server strips them anyway, so
|
|
|
+ // sending one would be accepted and silently discarded - the user would see
|
|
|
+ // a successful save and an unchanged value. Stripping here lets the UI name
|
|
|
+ // what it dropped instead.
|
|
|
+ const { body, removed } = stripMetadata(parsed)
|
|
|
+ if (removed.length > 0) {
|
|
|
+ push(
|
|
|
+ `${removed.join(', ')} ${removed.length === 1 ? 'is' : 'are'} attached by the database and cannot be written - left out of this save.`,
|
|
|
+ 'info',
|
|
|
+ )
|
|
|
+ }
|
|
|
try {
|
|
|
if (modalState.mode === 'new') {
|
|
|
- await api.insertDocument(currentProject, effectiveCollection, parsed)
|
|
|
+ await api.insertDocument(currentProject, effectiveCollection, body)
|
|
|
push('Document inserted.', 'success')
|
|
|
} else {
|
|
|
- await api.putDocument(currentProject, effectiveCollection, modalState.docId, parsed)
|
|
|
+ await api.putDocument(currentProject, effectiveCollection, modalState.docId, body)
|
|
|
push('Document saved.', 'success')
|
|
|
}
|
|
|
setModalOpen(false)
|
|
|
@@ -759,9 +1089,10 @@ export default function Documents() {
|
|
|
<p className="text-slate-400 text-sm mt-1">
|
|
|
Project: <span className="text-slate-300 font-mono">{currentProject}</span>
|
|
|
{docCount !== null && (
|
|
|
- <span className="ml-2 text-slate-500">
|
|
|
+ <span className="ml-2 text-slate-500" data-testid="docs-count">
|
|
|
— showing {docCount.toLocaleString()}
|
|
|
{(canNext || offsetNum > 0) && ` (rows ${(offsetNum + 1).toLocaleString()}–${(offsetNum + docs.length).toLocaleString()})`}
|
|
|
+ {totalMatching !== null && ` of ${totalMatching.toLocaleString()} matching`}
|
|
|
</span>
|
|
|
)}
|
|
|
</p>
|
|
|
@@ -779,7 +1110,7 @@ export default function Documents() {
|
|
|
</button>
|
|
|
<button
|
|
|
onClick={() => {
|
|
|
- setModalState({ mode: 'new', docId: '', json: '{}' })
|
|
|
+ setModalState({ mode: 'new', docId: '', json: '{}', meta: {} })
|
|
|
setModalOpen(true)
|
|
|
}}
|
|
|
disabled={!effectiveCollection}
|
|
|
@@ -862,6 +1193,7 @@ export default function Documents() {
|
|
|
sortField={sortField}
|
|
|
sortDesc={sortDesc}
|
|
|
onSortById={toggleSortById}
|
|
|
+ filtered={appliedQs.includes('filter=')}
|
|
|
/>
|
|
|
)}
|
|
|
|
|
|
@@ -870,6 +1202,12 @@ export default function Documents() {
|
|
|
<div className="flex items-center justify-between text-sm">
|
|
|
<span className="text-slate-500 text-xs">
|
|
|
Page {Math.floor(offsetNum / limitNum) + 1}
|
|
|
+ {totalMatching !== null && ` of ${Math.max(1, Math.ceil(totalMatching / limitNum)).toLocaleString()}`}
|
|
|
+ {hasMoreReported === undefined && (
|
|
|
+ <span className="ml-2 text-slate-600" title="This server does not report has_more; the Next button is a guess from a full page.">
|
|
|
+ (page count estimated)
|
|
|
+ </span>
|
|
|
+ )}
|
|
|
</span>
|
|
|
<div className="flex items-center gap-2">
|
|
|
<button
|
|
|
@@ -899,12 +1237,14 @@ export default function Documents() {
|
|
|
open={modalOpen}
|
|
|
title={modalState.mode === 'new' ? 'New Document' : `Edit Document — ${modalState.docId}`}
|
|
|
initialJson={modalState.json}
|
|
|
+ meta={modalState.meta}
|
|
|
project={modalState.mode === 'edit' ? currentProject : undefined}
|
|
|
collection={modalState.mode === 'edit' ? effectiveCollection : undefined}
|
|
|
docId={modalState.mode === 'edit' ? modalState.docId : undefined}
|
|
|
onClose={() => setModalOpen(false)}
|
|
|
onSave={(parsed) => handleSave(parsed)}
|
|
|
onDelete={modalState.mode === 'edit' ? () => void handleDelete() : undefined}
|
|
|
+ onCopy={(text, label) => void handleCopy(text, label)}
|
|
|
saving={saving}
|
|
|
/>
|
|
|
</div>
|