// Import the svelte-jsoneditor module import {createJSONEditor} from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/standalone.js'; /** * Initializes and displays a JSON editor using the Svelte JSON Editor. * https://github.com/josdejong/svelte-jsoneditor * @param {string} debuggerId - The ID of the container where the editor should be rendered. * @param {string} targetID - The ID of the component that will receive the response (tab manager) * @param {Object} data - The JSON data to be rendered in the editor. */ function showJson(debuggerId, targetID, data) { const containerId = `dbengine-${debuggerId}` const container = document.getElementById(containerId); if (!container) { console.error(`Container with ID '${containerId}' not found.`); return; } // Clear previous content (if any) container.innerHTML = ''; // Create and render the editor const editor = createJSONEditor({ target: container, props: { content: {json: data}, mode: 'view', // Options: 'view', 'tree', 'text' readOnly: true, onSelect: (selection) => { // Access the complete JSON const jsonContent = editor.get()?.json || {}; const {key, value} = getSelectedNodeValue(selection, jsonContent); htmx.ajax('POST', '/debugger/dbengine', { target: `#${targetID}`, headers: {"Content-Type": "application/x-www-form-urlencoded"}, swap: "outerHTML", values: { _id: debuggerId, digest: value, } }); }, }, }); console.log('Svelte JSON Editor initialized with data:', data); } /** * Retrieves the selected key and value based on the editor's selection details and JSON structure. * * @param {Object} selection - The editor's selection object. * @param {Object} jsonContent - The JSON content from the editor. * @returns {{key: string|null, value: any|null}} - The selected key and value. */ function getSelectedNodeValue(selection, jsonContent) { if (!selection || !jsonContent) { return {key: null, value: null}; } if (selection.path) { // If a full path is provided (e.g., ["items", 0, "value"]) const key = selection.path[selection.path.length - 1]; // The last item is the key const value = selection.path.reduce((current, segment) => { return current ? current[segment] : undefined; }, jsonContent); return {key, value}; } // For single key/value selections return {key: selection.key || null, value: jsonContent[selection.key] || null}; } window.showJson = showJson;