import copy import json from nicegui import ui from state import AppState from utils import save_json, get_file_mtime, KEY_HISTORY_TREE, KEY_PROMPT_HISTORY def render_raw_editor(state: AppState): data = state.data_cache file_path = state.file_path ui.label(f'Raw Editor: {file_path.name}').classes('text-h6') hide_history = ui.checkbox( 'Hide History (Safe Mode)', value=True, ) @ui.refreshable def render_editor(): # Prepare display data if hide_history.value: display_data = copy.deepcopy(data) display_data.pop(KEY_HISTORY_TREE, None) display_data.pop(KEY_PROMPT_HISTORY, None) else: display_data = data try: json_str = json.dumps(display_data, indent=4, ensure_ascii=False) except Exception as e: ui.notify(f'Error serializing JSON: {e}', type='negative') json_str = '{}' text_area = ui.textarea( 'JSON Content', value=json_str, ).classes('w-full font-mono').props('outlined rows=30') ui.separator() def do_save(): try: input_data = json.loads(text_area.value) # Merge hidden history back in if safe mode if hide_history.value: if KEY_HISTORY_TREE in data: input_data[KEY_HISTORY_TREE] = data[KEY_HISTORY_TREE] if KEY_PROMPT_HISTORY in data: input_data[KEY_PROMPT_HISTORY] = data[KEY_PROMPT_HISTORY] save_json(file_path, input_data) data.clear() data.update(input_data) state.last_mtime = get_file_mtime(file_path) ui.notify('Raw JSON Saved Successfully!', type='positive') render_editor.refresh() except json.JSONDecodeError as e: ui.notify(f'Invalid JSON Syntax: {e}', type='negative') except Exception as e: ui.notify(f'Unexpected Error: {e}', type='negative') ui.button('Save Raw Changes', icon='save', on_click=do_save).props( 'color=primary' ).classes('w-full') hide_history.on_value_change(lambda _: render_editor.refresh()) render_editor()