Edit selected record
Select a table row or a 3D object.
'''
_CLIENT = r'''
(() => {
const boot=JSON.parse(document.getElementById('oracle7-interaction').textContent), fields=document.getElementById('o7-fields');
let state=boot.state, selected=null;
const message=(text,error=false)=>{const p=document.getElementById('o7-message');p.textContent=text;p.dataset.error=String(error);};
function selection(id){
selected=id==null?null:String(id); const row=state.rows.find(r=>String(r[state.identity])===selected);
document.getElementById('o7-selection').textContent=row?'Selected: '+selected:'Select a table row or a 3D object.';
fields.replaceChildren(); document.getElementById('o7-save').disabled=!row;
if(row) for(const col of state.editable){
const label=document.createElement('label');label.textContent=col;
const input=document.createElement('input');input.name=col;input.dataset.original=JSON.stringify(row[col]);
const type=state.types[col].type;input.type=type==='boolean'?'checkbox':(type==='number'||type==='integer'?'number':'text');
if(input.type==='checkbox')input.checked=row[col]===true||String(row[col]).toLowerCase()==='true';else input.value=row[col]??'';
if(input.type==='number')input.step=type==='integer'?'1':'any';
input.disabled=!(state.permissions[selected]||[]).includes(col);label.append(input);fields.append(label);
}
document.querySelectorAll('tr[data-id]').forEach(tr=>tr.classList.toggle('sel',tr.dataset.id===selected));
const target=document.getElementById('o7-target');target.replaceChildren();
for(const row of state.rows){const option=document.createElement('option');option.value=String(row[state.identity]);option.textContent=option.value;target.append(option);}
const list=document.getElementById('o7-edges');list.replaceChildren();
for(const edge of state.edges.filter(e=>e.source===selected||e.target===selected)){
const item=document.createElement('li');item.textContent=edge.source+' → '+edge.target+(edge.label?' ('+edge.label+')':'')+' ';
const remove=document.createElement('button');remove.type='button';remove.textContent='Remove';
remove.addEventListener('click',()=>action({action:'edge_remove',source:edge.source,target:edge.target}));item.append(remove);list.append(item);
}
}
function render(){
const table=document.querySelector('main table');if(table){table.replaceChildren();const head=document.createElement('tr');
for(const col of state.columns){const th=document.createElement('th');th.textContent=col;head.append(th);}table.append(head);
for(const row of state.rows){const tr=document.createElement('tr');tr.dataset.id=String(row[state.identity]);tr.tabIndex=0;
for(const col of state.columns){const td=document.createElement('td');td.textContent=row[col]==null?'':String(row[col]);tr.append(td);}table.append(tr);}}
const recordPayload=document.getElementById('oracle7-rows');if(recordPayload)recordPayload.textContent=JSON.stringify(state.rows);
document.getElementById('o7-relations').hidden=!state.relationships;
const records=state.rows.map(r=>({id:String(r[state.identity]),v:state.value==null||r[state.value]==null||r[state.value]===''?null:Number(r[state.value])}));
if(window.__o7setRecords)window.__o7setRecords(records);
if(window.__o7setEdges)window.__o7setEdges(state.edges);
selection(selected);if(selected&&window.__o7select)window.__o7select(selected);
window.__o7interaction.state=state;window.dispatchEvent(new CustomEvent('oracle7:state',{detail:state}));
}
async function action(payload){try{
const response=await fetch('/_oracle7/action',{method:'POST',headers:{'Content-Type':'application/json','X-Oracle7-Token':boot.token},body:JSON.stringify({...payload,version:state.version})});
const next=await response.json();if(!response.ok)throw new Error(next.error||'Save failed');state=next;render();message('Saved. Table and scene refreshed.');return state;
}catch(error){message(error.message,true);throw error;}}
async function refresh(){const response=await fetch('/_oracle7/state',{cache:'no-store'});const next=await response.json();if(!response.ok)throw new Error(next.error);state=next;render();return state;}
document.getElementById('o7-edit-form').addEventListener('submit',event=>{event.preventDefault();const changes={};
for(const input of fields.querySelectorAll('input:not(:disabled)')){const value=input.type==='checkbox'?input.checked:input.value;
const original=JSON.parse(input.dataset.original);if(String(value)!==String(original??''))changes[input.name]=value;}
if(!Object.keys(changes).length)return message('No values changed.');action({action:'update',id:selected,changes}).catch(()=>{});
});
document.getElementById('o7-edge-form').addEventListener('submit',event=>{event.preventDefault();if(!selected)return message('Select a record first.',true);
action({action:'edge_add',source:selected,target:document.getElementById('o7-target').value,label:document.getElementById('o7-edge-label').value}).catch(()=>{});});
document.getElementById('o7-refresh').addEventListener('click',()=>refresh().then(()=>message('Refreshed.')).catch(e=>message(e.message,true)));
document.addEventListener('click',event=>{const tr=event.target.closest('tr[data-id]');if(tr){selection(tr.dataset.id);if(window.__o7select)window.__o7select(tr.dataset.id);}});
document.addEventListener('keydown',event=>{if(event.key==='Enter'&&event.target.matches('tr[data-id]')){selection(event.target.dataset.id);if(window.__o7select)window.__o7select(selected);}});
window.addEventListener('oracle7:select',event=>selection(event.detail.id));
window.addEventListener('oracle7:scene-ready',()=>render());
window.__o7interaction={state,select:selection,refresh,save:changes=>action({action:'update',id:selected,changes}),
addEdge:(source,target,label='')=>action({action:'edge_add',source,target,label}),removeEdge:(source,target)=>action({action:'edge_remove',source,target})};
render();
})();
'''
def runtime_source():
return _RUNTIME.strip() + '\n\n_I_PANEL = ' + repr(_PANEL) + '\n_I_CLIENT = ' + repr(_CLIENT) + '\n'
source_snapshot = PS.source_snapshot
_source_key = PS._source_key
ProjectSourceError = PS.SourceError
exec(runtime_source())
def _kind(values, parse_strings=True):
present = [v for v in values if v is not None and v != '']
nullable = len(present) != len(values)
if present and all(isinstance(v, bool) for v in present):
return {'type': 'boolean', 'nullable': nullable}
if any(isinstance(v, str) for v in present):
if not parse_strings or any(re.match(r'^[+-]?0\d+', v) for v in present if isinstance(v, str)):
return {'type': 'string' if all(isinstance(v, str) for v in present) else 'structured', 'nullable': nullable}
try:
numbers = [float(v) for v in present if not isinstance(v, bool)]
if present and len(numbers) == len(present) and all(_i_math.isfinite(v) for v in numbers):
return {'type': 'integer' if all(v.is_integer() for v in numbers) else 'number', 'nullable': nullable}
except (ValueError, TypeError, OverflowError):
pass
if any(isinstance(v, (list, dict)) for v in present):
return {'type': 'structured', 'nullable': nullable}
return {'type': 'string', 'nullable': nullable}
def plan_interaction(root, source, rows=None, identity=None, editable=None, edges=None):
"""Bind editable cells and explicit relations, or say precisely what is missing."""
columns, all_rows = PS.source_snapshot(source, root)
rows = all_rows if rows is None else rows
identity = identity or ('id' if 'id' in columns else columns[0] if columns else None)
if not identity or identity not in columns:
raise InteractionError('name a stable identity column from the source records')
_i_index(all_rows, identity)
_i_index(rows, identity)
reserved = {identity}
def keys(graph):
if graph.get('op') in ('join', 'lookup'):
reserved.update(c for pair in graph['keys'] for c in pair)
keys(graph['left']); keys(graph['right'])
elif graph.get('op') == 'union':
for child in graph['inputs']: keys(child)
keys(source)
_origin_columns, origin_rows = _i_origins(source, root)
types = {c: _kind([r.get(c) for r in all_rows], parse_strings=all(
origin.get(c, ('',))[0].lower().endswith('.csv') or not isinstance(row.get(c), str)
for row, origin in origin_rows)) for c in columns}
allowed = [c for c in columns if c not in reserved and types[c]['type'] != 'structured']
if editable is not None:
requested = [editable] if isinstance(editable, str) else list(editable)
invalid = [c for c in requested if c not in allowed]
if invalid:
raise InteractionError('these fields have no safe editable binding: %s; identities, join keys and derived values remain fixed' % ', '.join(invalid))
allowed = requested
view_columns = list(dict.fromkeys(c for row in rows for c in row)) or columns
if any(c not in view_columns for c in allowed):
raise InteractionError('retain the editable fields in the displayed records')
if edges:
edges = dict(edges)
if not all(isinstance(edges.get(k), str) and edges[k] for k in ('file', 'from', 'to')):
raise InteractionError('name the relationship file and its from/to identity columns')
if _i_path(root, edges['file']) in {_i_path(root, f) for f in _i_files(source)}:
raise InteractionError('give relationships their own edge table; a record source cannot also be its edge storage')
binding = {'v': 1, 'source': source, 'identity': identity, 'editable': allowed, 'columns': view_columns,
'types': {c: types[c] for c in allowed}, 'edges': edges,
'value': next((c for c in view_columns if c != identity and c in types and types[c]['type'] in ('integer', 'number')), None)}
interactive_state(binding, lambda: rows, root)
return binding