File size: 31,564 Bytes
d9b105f | 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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | """Record interaction part: a selection, typed edit and explicit relation write.
Connects a project's source shape to the existing table/three.js scene. The
writer embeds runtime_source() after project_sources.runtime_source(); generated
programs use only the standard library. Every editable cell has a source row,
and every relationship has declared endpoint columns. No first-file writeback.
"""
import re
import project_sources as PS
_RUNTIME = r'''
import csv as _i_csv
import hashlib as _i_hash
import html as _i_html
import io as _i_io
import json as _i_json
import math as _i_math
import os as _i_os
import secrets as _i_secrets
import tempfile as _i_tempfile
import threading as _i_threading
from pathlib import Path as _IPath
from http.server import BaseHTTPRequestHandler as _IHandler, ThreadingHTTPServer as _IServer
from urllib.parse import urlsplit as _i_urlsplit
_I_LOCK = _i_threading.RLock()
_I_TOKEN = _i_secrets.token_urlsafe(32)
class InteractionError(ValueError):
def __init__(self, message, status=400):
super().__init__(message)
self.status = status
def _i_path(root, filename):
base = _IPath(root).resolve()
path = (base / filename).resolve()
if base not in path.parents or path.suffix.lower() not in ('.csv', '.json', '.jsonl'):
raise InteractionError('name a CSV, JSON or JSONL file inside the project folder')
return path
def _i_files(graph):
if graph.get('op') == 'read':
return [graph['file']]
children = graph.get('inputs', []) if graph.get('op') == 'union' else [graph['left'], graph['right']]
return list(dict.fromkeys(filename for child in children for filename in _i_files(child)))
def _i_origins(graph, root):
"""Rows paired with cell origins (file, row index, original column)."""
op = graph['op']
if op == 'read':
cols, rows = source_snapshot(graph, root)
return cols, [(row, {c: (graph['file'], i, c) for c in cols}) for i, row in enumerate(rows)]
if op == 'union':
cols, result = source_snapshot(graph, root)[0], []
for child in graph['inputs']:
result.extend(_i_origins(child, root)[1])
return cols, result
lc, left = _i_origins(graph['left'], root)
rc, right = _i_origins(graph['right'], root)
left_keys, right_keys = zip(*graph['keys'])
extra = [c for c in rc if c not in right_keys]
index = {}
for row, provenance in right:
key = _source_key(row, right_keys)
if key is not None:
index.setdefault(key, []).append((row, provenance))
result = []
for row, provenance in left:
key = _source_key(row, left_keys)
matches = index.get(key, []) if key is not None else []
for other, origins in matches:
result.append((dict(row, **{c: other[c] for c in extra}),
dict(provenance, **{c: origins[c] for c in extra})))
if not matches and graph.get('how') == 'left':
result.append((dict(row, **{c: None for c in extra}), dict(provenance)))
return lc + extra, result
def _i_id(value):
if value is None or isinstance(value, (list, dict, bool)) or not str(value).strip():
raise InteractionError('each record needs a nonempty scalar identity; name a unique identity column')
if isinstance(value, float) and not _i_math.isfinite(value):
raise InteractionError('record identities must be finite values')
return str(value)
def _i_index(rows, identity):
index = {}
for row in rows:
if identity not in row:
raise InteractionError('the view does not retain identity column %s; retain it before enabling edits' % identity)
key = _i_id(row[identity])
if key in index:
raise InteractionError('identity %s occurs more than once; name a unique record identity or remove join fan-out' % key)
index[key] = row
return index
def _i_versions(binding, root):
files = _i_files(binding['source']) + ([binding['edges']['file']] if binding.get('edges') else [])
marks = {}
for filename in files:
path = _i_path(root, filename)
marks[filename] = _i_hash.sha256(path.read_bytes()).hexdigest() if path.exists() else None
return marks
def _i_version(marks):
return _i_hash.sha256(_i_json.dumps(marks, sort_keys=True).encode()).hexdigest()
def _i_edges(binding, root, all_ids):
spec = binding.get('edges')
if not spec:
return [], []
path = _i_path(root, spec['file'])
if not path.exists() and not spec.get('create'):
raise InteractionError('relationship file %s is missing; add it or explicitly ask to create relationship storage' % spec['file'])
cols, records = source_snapshot({'op': 'read', 'file': spec['file']}, root) if path.exists() else (list(dict.fromkeys([spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else []))), [])
if spec['from'] == spec['to'] or any(c not in cols for c in [spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else [])):
raise InteractionError('relationship storage needs distinct declared endpoint columns, and its declared label column')
seen, edges = set(), []
for record in records:
source, target = _i_id(record[spec['from']]), _i_id(record[spec['to']])
if source not in all_ids or target not in all_ids:
raise InteractionError('relationship %s -> %s has no corresponding record; correct its endpoints' % (source, target))
if (source, target) in seen:
raise InteractionError('relationship %s -> %s is duplicated; give each endpoint pair one record' % (source, target))
seen.add((source, target))
edges.append({'source': source, 'target': target, 'label': str(record.get(spec.get('label'), '') or '')})
return cols, edges
def _i_snapshot(binding, compute, root):
before = _i_versions(binding, root)
source_snapshot(binding['source'], root) # validate the composed source contract
_cols, joined = _i_origins(binding['source'], root)
all_rows = [row for row, _origin in joined]
all_ids = _i_index(all_rows, binding['identity'])
origins = {_i_id(row[binding['identity']]): origin for row, origin in joined}
rows = compute()
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
raise InteractionError('the editable view must return records')
visible = _i_index(rows, binding['identity'])
if any(key not in origins for key in visible):
raise InteractionError('a displayed record has no owning source row')
_edge_columns, edges = _i_edges(binding, root, all_ids)
after = _i_versions(binding, root)
if before != after:
raise InteractionError('the inputs changed while the view was read; refresh and try again', 409)
return {'rows': rows, 'origins': origins, 'all_ids': all_ids, 'edges': edges, 'marks': before,
'version': _i_version(before)}
def interactive_state(binding, compute, root='.'):
with _I_LOCK:
snap = _i_snapshot(binding, compute, root)
permissions = {key: [c for c in binding['editable'] if c in snap['origins'][key]]
for key in _i_index(snap['rows'], binding['identity'])}
return {'version': snap['version'], 'rows': snap['rows'], 'identity': binding['identity'],
'columns': binding['columns'], 'editable': binding['editable'], 'types': binding['types'],
'value': binding.get('value'), 'permissions': permissions,
'edges': snap['edges'], 'relationships': bool(binding.get('edges'))}
def _i_coerce(value, shape, column):
kind = shape['type']
if value is None or value == '':
if shape.get('nullable'):
return None if value is None else ''
if kind != 'string':
raise InteractionError('%s needs a %s value' % (column, kind))
try:
if kind == 'boolean':
if value is True or value in ('true', 'True'): return True
if value is False or value in ('false', 'False'): return False
raise ValueError()
if kind in ('integer', 'number'):
if isinstance(value, bool): raise ValueError()
number = float(value)
if not _i_math.isfinite(number) or kind == 'integer' and not number.is_integer(): raise ValueError()
return int(number) if kind == 'integer' else number
if not isinstance(value, str): raise ValueError()
return value
except (TypeError, ValueError, OverflowError):
raise InteractionError('%s needs a finite %s value' % (column, kind))
def _i_prepare(root, filename, rows, cols, expected):
path = _i_path(root, filename)
old = path.read_bytes() if path.exists() else None
actual = _i_hash.sha256(old).hexdigest() if old is not None else None
if actual != expected:
raise InteractionError('the file changed since it was read; refresh before saving', 409)
encoding = 'utf-8-sig' if old and old.startswith(b'\xef\xbb\xbf') else 'utf-8'
if path.suffix.lower() == '.csv':
output = _i_io.StringIO(newline='')
writer = _i_csv.DictWriter(output, fieldnames=cols)
writer.writeheader()
writer.writerows(rows)
content = output.getvalue()
elif path.suffix.lower() == '.jsonl':
content = ''.join(_i_json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n' for row in rows)
else:
original = _i_json.loads(old.decode(encoding)) if old is not None else []
if isinstance(original, dict):
wrapper = next((k for k, value in original.items() if isinstance(value, list)), None)
if wrapper is None:
if len(rows) != 1: raise InteractionError('a single-object JSON source must retain one record')
original = rows[0]
else:
original[wrapper] = rows
else:
original = rows
content = _i_json.dumps(original, indent=2, ensure_ascii=False, allow_nan=False) + '\n'
raw = content.encode(encoding)
return {'file': filename, 'old': old, 'raw': raw, 'before': expected,
'after': _i_hash.sha256(raw).hexdigest()}
def _i_atomic_bytes(path, content):
temporary = None
try:
path.parent.mkdir(parents=True, exist_ok=True)
with _i_tempfile.NamedTemporaryFile(mode='wb', dir=str(path.parent), delete=False) as handle:
temporary = handle.name
handle.write(content)
handle.flush()
_i_os.fsync(handle.fileno())
if path.exists():
_i_os.chmod(temporary, path.stat().st_mode)
_i_os.replace(temporary, path)
temporary = None
finally:
if temporary is not None:
_i_os.unlink(temporary)
def _i_commit(binding, compute, root, prepared, marks):
"""All values are staged first; a failed save restores only our own versions."""
written = []
expected = dict(marks)
try:
for change in prepared:
if _i_versions(binding, root) != expected:
raise InteractionError('the inputs changed while the save was prepared; refresh and try again', 409)
_i_atomic_bytes(_i_path(root, change['file']), change['raw'])
written.append(change)
expected[change['file']] = change['after']
return interactive_state(binding, compute, root)
except Exception as error:
preserved = []
for change in reversed(written):
path = _i_path(root, change['file'])
current = _i_hash.sha256(path.read_bytes()).hexdigest() if path.exists() else None
if current != change['after']:
preserved.append(change['file'])
continue
if change['old'] is None:
path.unlink()
else:
_i_atomic_bytes(path, change['old'])
if preserved:
raise InteractionError('the save could not complete; newer changes in %s were preserved, and other writes were restored; refresh before continuing' % ', '.join(preserved), 409) from error
raise InteractionError('the edit could not be completed; no changes were kept: %s' % error,
getattr(error, 'status', 400)) from error
def interactive_update(binding, compute, payload, root='.'):
if not isinstance(payload, dict):
raise InteractionError('send an action object')
with _I_LOCK:
snap = _i_snapshot(binding, compute, root)
if payload.get('version') != snap['version']:
raise InteractionError('these records changed; refresh before saving your edit', 409)
action = payload.get('action')
if action == 'update':
identity = _i_id(payload.get('id'))
if identity not in _i_index(snap['rows'], binding['identity']):
raise InteractionError('select a record currently shown in this view')
changes = payload.get('changes')
if not isinstance(changes, dict) or not changes:
raise InteractionError('give the fields and values to change')
provenance, pending = snap['origins'][identity], {}
for column in changes:
if column not in binding['editable'] or column not in provenance:
raise InteractionError('%s is not an editable source field for this record' % column)
for column, value in changes.items():
filename, index, original_column = provenance[column]
if filename not in pending:
pending[filename] = source_snapshot({'op': 'read', 'file': filename}, root)
cols, rows = pending[filename]
coerced = _i_coerce(value, binding['types'][column], column)
original = _i_coerce(rows[index][original_column], binding['types'][column], column)
if coerced == original and type(coerced) is type(original):
continue
rows[index][original_column] = ('' if coerced is None else str(coerced)) if filename.lower().endswith('.csv') else coerced
prepared = []
for filename, (cols, rows) in pending.items():
original_rows = source_snapshot({'op': 'read', 'file': filename}, root)[1]
if rows != original_rows:
prepared.append(_i_prepare(root, filename, rows, cols, snap['marks'][filename]))
elif action in ('edge_add', 'edge_remove'):
spec = binding.get('edges')
if not spec: raise InteractionError('this view has no declared relationship storage')
source, target = _i_id(payload.get('source')), _i_id(payload.get('target'))
if source not in snap['all_ids'] or target not in snap['all_ids']:
raise InteractionError('both relationship endpoints must identify existing records')
path = _i_path(root, spec['file'])
if path.exists():
cols, rows = source_snapshot({'op': 'read', 'file': spec['file']}, root)
else:
cols, rows = list(dict.fromkeys([spec['from'], spec['to']] + ([spec['label']] if spec.get('label') else []))), []
matches = [i for i, row in enumerate(rows) if (_i_id(row[spec['from']]), _i_id(row[spec['to']])) == (source, target)]
if action == 'edge_add':
if matches: raise InteractionError('that relationship already exists')
if any(c not in (spec['from'], spec['to'], spec.get('label')) for c in cols):
raise InteractionError('relationship storage has extra required fields; declare their values before adding a relationship')
row = {spec['from']: snap['all_ids'][source][binding['identity']], spec['to']: snap['all_ids'][target][binding['identity']]}
if spec.get('label'):
label = payload.get('label', '')
if not isinstance(label, str): raise InteractionError('a relationship label must be text')
row[spec['label']] = label
rows.append(row)
else:
if not matches: raise InteractionError('that relationship no longer exists; refresh', 409)
rows.pop(matches[0])
prepared = [_i_prepare(root, spec['file'], rows, cols, snap['marks'][spec['file']])]
else:
raise InteractionError('choose update, edge_add or edge_remove')
return _i_commit(binding, compute, root, prepared, snap['marks'])
def interactive_page(page, binding, compute, root='.'):
state = interactive_state(binding, compute, root)
bootstrap = _i_json.dumps({'state': state, 'token': _I_TOKEN}, ensure_ascii=False, allow_nan=False).replace('<', '\\u003c')
panel = _I_PANEL + '<script type="application/json" id="oracle7-interaction">' + bootstrap + '</script><script>' + _I_CLIENT + '</script>'
return page.replace('</main>', panel + '</main>', 1) if '</main>' in page else page + panel
def interactive_handler(render, binding, compute, root='.'):
class Handler(_IHandler):
def log_message(self, *_args): pass
def send_json(self, status, value):
body = _i_json.dumps(value, ensure_ascii=False, allow_nan=False).encode('utf-8')
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(body)))
self.end_headers(); self.wfile.write(body)
def valid_host(self):
return self.headers.get('Host') in ('127.0.0.1:%d' % self.server.server_port, 'localhost:%d' % self.server.server_port)
def do_GET(self):
if not self.valid_host(): return self.send_json(403, {'error': 'use this project on its local address'})
try:
path = _i_urlsplit(self.path).path
if path == '/_oracle7/state': return self.send_json(200, interactive_state(binding, compute, root))
if path not in ('/', '/index.html'): return self.send_json(404, {'error': 'no such project resource'})
body = interactive_page(render(), binding, compute, root).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(body)))
self.end_headers(); self.wfile.write(body)
except (InteractionError, ProjectSourceError, OSError, ValueError) as error:
self.send_json(getattr(error, 'status', 400), {'error': str(error)})
def do_POST(self):
if not self.valid_host(): return self.send_json(403, {'error': 'use this project on its local address'})
if _i_urlsplit(self.path).path != '/_oracle7/action': return self.send_json(404, {'error': 'no such project action'})
expected_origin = 'http://' + self.headers.get('Host', '')
if self.headers.get('Origin') != expected_origin or self.headers.get('X-Oracle7-Token') != _I_TOKEN:
return self.send_json(403, {'error': 'open this project page before saving changes'})
try:
size = int(self.headers.get('Content-Length', '0'))
if size <= 0 or size > 65536: raise InteractionError('the action must be between 1 and 65536 bytes', 413)
if self.headers.get('Content-Type', '').split(';')[0] != 'application/json': raise InteractionError('send a JSON action', 415)
payload = _i_json.loads(self.rfile.read(size))
self.send_json(200, interactive_update(binding, compute, payload, root))
except (InteractionError, ProjectSourceError, OSError, ValueError, TypeError) as error:
self.send_json(getattr(error, 'status', 400), {'error': str(error)})
return Handler
def serve_interactive(port, render, binding, compute, root='.'):
server = _IServer(('127.0.0.1', port), interactive_handler(render, binding, compute, root))
try: server.serve_forever()
finally: server.server_close()
'''
_PANEL = '''<section id="oracle7-editor" aria-label="Record editor"><h2>Edit selected record</h2>
<p id="o7-selection">Select a table row or a 3D object.</p><form id="o7-edit-form"><div id="o7-fields"></div>
<button type="submit" id="o7-save" disabled>Save changes</button><button type="button" id="o7-refresh">Refresh</button></form>
<div id="o7-relations" hidden><h3>Relationships</h3><form id="o7-edge-form"><label>Connect selected record to <select id="o7-target"></select></label>
<label>Label <input id="o7-edge-label" type="text"></label><button type="submit">Add relationship</button></form><ul id="o7-edges"></ul></div>
<p id="o7-message" role="status" aria-live="polite"></p></section>
<style>#oracle7-editor{padding:20px 0;border-top:1px solid currentColor}#o7-fields{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:12px}
#oracle7-editor label{display:flex;gap:6px;flex-direction:column}#oracle7-editor input,#oracle7-editor select{font:inherit;max-width:24em}
#oracle7-editor button{font:inherit;margin:4px 8px 4px 0;cursor:pointer}#o7-edge-form{display:flex;gap:12px;align-items:end;flex-wrap:wrap}</style>'''
_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
|