//
// Copyright 2025 DXOS.org
//
import React, { useCallback } from 'react';
import { DXN } from '@dxos/keys';
import { Button, Clipboard, Input } from '@dxos/react-ui';
import { SyntaxHighlighter, createElement } from '@dxos/react-ui-syntax-highlighter';
/**
 * Renders a JSON object with navigatable DXN links.
 */
export const ObjectViewer = ({ object, id, onNavigate }) => {
    const text = JSON.stringify(object, null, 2);
    const rowRenderer = ({ rows, stylesheet, useInlineStyles, }) => {
        /**
         * Changes the "dxn:..." span to an anchor tag that navigates to the object.
         */
        const addDxnLinks = (node) => {
            if (isDxnSpanNode(node)) {
                node.tagName = 'a';
                node.properties ??= { className: [] };
                node.properties.className.push('underline', 'cursor-pointer');
                node.properties.onClick = () => {
                    onNavigate?.(DXN.parse(node.children[0].value.slice(1, -1)));
                };
            }
            else {
                node.children?.forEach(addDxnLinks);
            }
        };
        rows.forEach(addDxnLinks);
        return rows.map((row, index) => {
            return createElement({
                node: row,
                stylesheet,
                style: {},
                useInlineStyles,
                key: index,
            });
        });
    };
    const handleCopy = useCallback(() => {
        void navigator.clipboard.writeText(JSON.stringify(object, null, 2));
    }, [object]);
    return (React.createElement(React.Fragment, null,
        id && (React.createElement(Clipboard.Provider, null,
            React.createElement("div", { className: 'flex flex-col' },
                React.createElement(Input.Root, null,
                    React.createElement("div", { role: 'none', className: 'flex flex-col gap-1' },
                        React.createElement("div", { role: 'none', className: 'flex gap-1' },
                            React.createElement(Input.TextInput, { disabled: true, value: id }),
                            React.createElement(Clipboard.IconButton, { value: id }),
                            React.createElement(Button, { value: id, onClick: handleCopy }, "Copy JSON"))))))),
        React.createElement(SyntaxHighlighter, { language: 'json', classNames: 'text-sm', renderer: rowRenderer }, text)));
};
const isDxnSpanNode = (node) => {
    return (node.type === 'element' &&
        node.tagName === 'span' &&
        node.children?.length === 1 &&
        node.children[0].type === 'text' &&
        typeof node.children[0].value === 'string' &&
        node.children[0].value.match(/^"(dxn:[^"]+)"$/));
};
//# sourceMappingURL=ObjectViewer.js.map