import { i as e, s as t, t as n } from "./rafScheduler-CYaktF5t.js";
import { t as r } from "./chevron-right-BfEHxLF2.js";
import { t as i } from "./TopicQuickPicker-CM1HfziA.js";
import { t as a } from "./useMessagePipeline-v2mo3rKF.js";
import { h as o } from "./rosMessageTypes-CCrv3XlZ.js";
import { t as s } from "./messageBus-D2dmTOBd.js";
import { n as c } from "./time-BFgy7ftw.js";
import { t as l } from "./pickDefaultRawMessagesTopic-C8SbWmtl.js";
import u, { useCallback as d, useEffect as f, useMemo as ee, useRef as p, useState as m } from "react";
import { jsx as h, jsxs as te } from "react/jsx-runtime";
//#region src/features/panels/RawMessages/shapeTree.ts
var g = [{
	id: "log_time",
	path: "log_time",
	key: "log_time",
	depth: 0,
	expandable: !1,
	parentIsArray: !1
}, {
	id: "publish_time",
	path: "publish_time",
	key: "publish_time",
	depth: 0,
	expandable: !1,
	parentIsArray: !1
}];
function _(e) {
	if (!e || typeof e != "object") return !1;
	let t = Object.getPrototypeOf(e);
	return t === Object.prototype || t === null;
}
function v(e, t, n) {
	let r = [], i = [], a = (e) => {
		r.length < n && r.push(e);
	}, o = (e, s, c, l, u) => {
		if (r.length >= n) return;
		let d = e instanceof Uint8Array ? "u8" : e instanceof ArrayBuffer ? "ab" : Array.isArray(e) ? "arr" : _(e) ? "obj" : typeof e;
		if (i.push(`${s}:${d}`), e instanceof Uint8Array) {
			a({
				id: s,
				path: s,
				key: c,
				depth: l,
				expandable: !1,
				parentIsArray: u
			});
			return;
		}
		if (e instanceof ArrayBuffer) {
			o(new Uint8Array(e), s, c, l, u);
			return;
		}
		if (Array.isArray(e)) {
			if (a({
				id: s,
				path: s,
				key: c,
				depth: l,
				expandable: e.length > 0,
				parentIsArray: u
			}), l >= t) return;
			for (let t = 0; t < e.length; t++) if (o(e[t], `${s}.${t}`, `${t}`, l + 1, !0), r.length >= n) return;
			return;
		}
		if (_(e)) {
			let i = Object.keys(e);
			if (a({
				id: s,
				path: s,
				key: c,
				depth: l,
				expandable: i.length > 0,
				parentIsArray: u
			}), l >= t) return;
			for (let t of i) if (o(e[t], `${s}.${t}`, t, l + 1, !1), r.length >= n) return;
			return;
		}
		a({
			id: s,
			path: s,
			key: c,
			depth: l,
			expandable: !1,
			parentIsArray: u
		});
	};
	return o(e, "message", "message", 0, !1), {
		rows: r,
		signature: i.join("|")
	};
}
function ne(e, t, n) {
	let r = v(e.message, t, Math.max(0, n - g.length));
	return {
		rows: [...g, ...r.rows],
		signature: `log_time:time|publish_time:time|${r.signature}`
	};
}
//#endregion
//#region src/features/panels/RawMessages/Component.tsx
var y = 22, b = 8, re = 1200, x = 3, S = 80, ie = 1024, C = 32;
function w(e) {
	let t = "";
	for (let n = 0; n < e.length; n++) t += e[n].toString(16).padStart(2, "0");
	return t;
}
function T(e) {
	let t = 32768, n = "";
	for (let r = 0; r < e.length; r += t) n += String.fromCharCode(...e.subarray(r, Math.min(r + t, e.length)));
	return btoa(n);
}
function E(e) {
	if (!e || typeof e != "object") return !1;
	let t = Object.getPrototypeOf(e);
	return t === Object.prototype || t === null;
}
function D(e) {
	return e.split(".").filter((e) => e.length > 0);
}
function O(e) {
	return E(e) ? typeof e.sec == "number" && typeof e.nsec == "number" : !1;
}
function k(e) {
	let t = e.nsec.toString().padStart(9, "0");
	return `${e.sec}.${t} (${c(e)})`;
}
function A(e, t) {
	if (!e) return;
	if (t === "log_time") return e.receiveTime;
	if (t === "publish_time") return e.publishTime;
	if (!t || t === "message") return e.message;
	if (!t.startsWith("message.")) return;
	let n = D(t.replace(/^message\./, "")), r = e.message;
	for (let e of n) {
		if (Array.isArray(r)) {
			let t = Number(e);
			if (!Number.isInteger(t)) return;
			r = r[t];
			continue;
		}
		if (!E(r)) return;
		r = r[e];
	}
	return r;
}
function j(e, t) {
	let n = [], r = [];
	for (let i of e) {
		for (; r.length > 0 && i.depth <= r[r.length - 1];) r.pop();
		r.length > 0 || (n.push(i), i.expandable && !t.has(i.path) && r.push(i.depth));
	}
	return n;
}
function ae(e, t, n) {
	let r = Math.max(0, Math.floor(e / y) - b), i = Math.ceil(t / y) + b * 2;
	return {
		startRow: r,
		endRow: Math.min(n, r + i)
	};
}
function M(e) {
	if (e === null) return "null";
	if (typeof e == "string") {
		let t = JSON.stringify(e);
		return t.length > S ? `${t.slice(0, S)}...` : t;
	}
	if (typeof e == "number" || typeof e == "boolean") return String(e);
	if (e instanceof Uint8Array) return `Uint8Array(${e.byteLength})`;
	if (e instanceof ArrayBuffer) return `ArrayBuffer(${e.byteLength})`;
	if (Array.isArray(e)) return `Array(${e.length})`;
	if (E(e)) return `{${Object.keys(e).length} keys}`;
	if (typeof e == "bigint") return `${e.toString()}n`;
	if (typeof e == "function") return "[Function]";
	if (typeof e == "symbol") return e.toString();
	if (typeof e == "object" && e) try {
		return JSON.stringify(e);
	} catch {
		return Object.prototype.toString.call(e);
	}
	return e === void 0 ? "undefined" : Object.prototype.toString.call(e);
}
function N(e) {
	let t = Object.keys(e);
	return t.length === 0 ? "{}" : `{${t.slice(0, x).map((t) => `${JSON.stringify(t)}:${M(e[t])}`).join(",")}${t.length > x ? ",..." : ""}}`;
}
function P(e, t, n) {
	if (O(e)) return {
		text: k(e),
		kind: "number"
	};
	if (e instanceof Uint8Array) {
		let r = n?.hideBinaryHex || e.byteLength > ie ? C : Math.min(e.byteLength, t), i = e.subarray(0, r);
		return {
			text: `Uint8Array(${e.byteLength}) 0x${w(i)}${e.byteLength > i.byteLength ? "..." : ""}`,
			kind: "binary"
		};
	}
	if (e instanceof ArrayBuffer) return P(new Uint8Array(e), t, n);
	if (Array.isArray(e)) return {
		text: `Array(${e.length})`,
		kind: "array"
	};
	if (E(e)) return {
		text: N(e) ?? `{${Object.keys(e).length} keys}`,
		kind: "object"
	};
	if (e === null) return {
		text: "null",
		kind: "null"
	};
	if (typeof e == "string") return {
		text: JSON.stringify(e),
		kind: "string"
	};
	if (typeof e == "number") return {
		text: String(e),
		kind: "number"
	};
	if (typeof e == "boolean") return {
		text: e ? "true" : "false",
		kind: "boolean"
	};
	if (typeof e == "bigint") return {
		text: `${e.toString()}n`,
		kind: "unknown"
	};
	if (typeof e == "function") return {
		text: "[Function]",
		kind: "unknown"
	};
	if (typeof e == "symbol") return {
		text: e.toString(),
		kind: "unknown"
	};
	if (typeof e == "object" && e) try {
		return {
			text: JSON.stringify(e),
			kind: "unknown"
		};
	} catch {
		return {
			text: Object.prototype.toString.call(e),
			kind: "unknown"
		};
	}
	return e === void 0 ? {
		text: "undefined",
		kind: "unknown"
	} : {
		text: Object.prototype.toString.call(e),
		kind: "unknown"
	};
}
function oe(e) {
	switch (e) {
		case "string": return "rgb(163 230 53)";
		case "number": return "rgb(125 211 252)";
		case "boolean": return "rgb(196 181 253)";
		case "null": return "rgb(248 113 113)";
		case "binary": return "rgb(251 191 36)";
		case "object":
		case "array": return "rgb(203 213 225)";
		default: return "rgb(229 231 235)";
	}
}
function F(e, t) {
	if (e instanceof Uint8Array) return t === "hex" ? {
		__type: "Uint8Array",
		encoding: "hex",
		data: w(e)
	} : t === "base64" ? {
		__type: "Uint8Array",
		encoding: "base64",
		data: T(e)
	} : {
		__type: "Uint8Array",
		data: Array.from(e)
	};
	if (e instanceof ArrayBuffer) return F(new Uint8Array(e), t);
	if (Array.isArray(e)) return e.map((e) => F(e, t));
	if (E(e)) {
		let n = {};
		for (let [r, i] of Object.entries(e)) n[r] = F(i, t);
		return n;
	}
	return e;
}
async function se(e) {
	try {
		return await navigator.clipboard.writeText(e), !0;
	} catch {
		return !1;
	}
}
function ce(e, t) {
	e.textContent = t.text, e.dataset.kind !== t.kind && (e.dataset.kind = t.kind, e.style.color = oe(t.kind));
}
var le = u.memo(function({ row: e, expanded: t, onToggle: n, onCopy: i, registerValueNode: a }) {
	let o = d(() => {
		e.expandable && n(e.path);
	}, [
		n,
		e.expandable,
		e.path
	]), s = d(() => {
		i(e.path);
	}, [i, e.path]), c = d((t) => {
		a(e.path, t);
	}, [a, e.path]);
	return /* @__PURE__ */ te("div", {
		className: "group flex h-[22px] items-center border-b border-border/30",
		style: { paddingLeft: e.depth * 14 },
		children: [
			/* @__PURE__ */ h("button", {
				type: "button",
				className: `mr-1 inline-flex h-4 w-4 items-center justify-center rounded ${e.expandable ? "hover:bg-muted" : "opacity-20"}`,
				onClick: o,
				children: e.expandable ? /* @__PURE__ */ h(r, { className: `size-3 transition-transform ${t ? "rotate-90" : ""}` }) : null
			}),
			/* @__PURE__ */ te("span", {
				className: "mr-2 text-cyan-300",
				children: [e.key, ":"]
			}),
			/* @__PURE__ */ h("span", {
				ref: c,
				className: "truncate"
			}),
			/* @__PURE__ */ h("button", {
				type: "button",
				className: "ml-2 rounded px-1 text-[10px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100",
				onClick: s,
				children: "COPY"
			})
		]
	});
}), I = ({ player: r, panelId: c, topic: u, uiRefreshHz: g = 10, pauseUpdates: _ = !1, latestOnly: v = !0, maxExpandedDepth: b = 4, maxRows: x = 2e3, maxBinaryPreviewBytes: S = 256, binaryCopyFormat: ie = "uint8array", setConfig: C }) => {
	let { formatMessage: w } = t(), T = a((e) => e.sortedTopics), E = p(!1), D = ee(() => o(T.find((e) => e.name === u)?.type ?? ""), [u, T]), O = p(s.getLastMessage(u)), k = p(0), M = p(0), N = p(_), oe = p(g), I = p(v), L = p(!!s.getLastMessage(u)), R = p([]), z = p(""), B = p(new Set(["message"])), V = p(0), ue = p(240), H = p({
		startRow: 0,
		endRow: 0,
		totalRows: 0
	}), U = p({
		maxExpandedDepth: b,
		maxRows: x,
		maxBinaryPreviewBytes: S,
		isImageTopic: D
	}), W = p(null), G = p(/* @__PURE__ */ new Map()), K = p(/* @__PURE__ */ new Map()), q = p(/* @__PURE__ */ new Map()), de = p(() => {}), J = p(!1), [fe, pe] = m(() => !!s.getLastMessage(u)), [Y, me] = m(() => new Set(["message"])), [X, he] = m([]), [ge, _e] = m(""), [Z, ve] = m({
		startRow: 0,
		endRow: 0,
		totalRows: 0
	});
	f(() => {
		N.current = _;
	}, [_]), f(() => {
		oe.current = g;
	}, [g]), f(() => {
		I.current = v;
	}, [v]), f(() => {
		U.current = {
			maxExpandedDepth: b,
			maxRows: x,
			maxBinaryPreviewBytes: S,
			isImageTopic: D
		};
	}, [
		D,
		S,
		b,
		x
	]), f(() => {
		B.current = Y;
	}, [Y]), f(() => {
		R.current = X;
	}, [X]), f(() => {
		z.current = ge;
	}, [ge]), f(() => {
		if (E.current) return;
		if (u && u.trim().length > 0) {
			E.current = !0;
			return;
		}
		if (T.length === 0) return;
		let e = l(T);
		e && (E.current = !0, C((t) => ({
			...t,
			topic: e
		})));
	}, [
		C,
		u,
		T
	]), f(() => {
		if (!u || u.trim().length === 0) {
			r.unregisterSubscriptions(c);
			return;
		}
		return r.registerSubscriptions(c, [{
			topic: u,
			subscriberId: c
		}]), () => r.unregisterSubscriptions(c);
	}, [
		r,
		c,
		u
	]);
	let ye = d(() => {
		for (let [e, t] of q.current) {
			let n = G.current.get(e);
			n && ce(n, t);
		}
		q.current.clear();
	}, []), be = d((e) => {
		let t = j(R.current, B.current), { startRow: r, endRow: i } = H.current, a = t.slice(r, i), o = Math.min(a.length, re), { maxBinaryPreviewBytes: s, isImageTopic: c } = U.current;
		for (let t = 0; t < o; t++) {
			let n = a[t];
			if (!n) continue;
			let r = P(A(e, n.path), s, { hideBinaryHex: c });
			K.current.set(n.path, r), (G.current.get(n.path)?.textContent ?? null) !== r.text && q.current.set(n.path, r);
		}
		q.current.size > 0 && n(ye);
	}, [ye]), Q = d(() => {
		let e = j(R.current, B.current).length, t = {
			...ae(V.current, ue.current, e),
			totalRows: e
		};
		ve((e) => e.startRow === t.startRow && e.endRow === t.endRow && e.totalRows === t.totalRows ? e : (H.current = t, t));
	}, []), $ = d(() => {
		let e = performance.now(), t = 1e3 / Math.max(1, oe.current);
		if (N.current || k.current <= 0) return;
		if (e - M.current < t) {
			n(() => {
				de.current();
			});
			return;
		}
		k.current = 0, M.current = e;
		let r = O.current;
		if (!r) return;
		let { maxExpandedDepth: i, maxRows: a } = U.current, o = ne(r, i, a);
		if (o.signature !== z.current) {
			if (z.current = o.signature, R.current = o.rows, he(o.rows), _e(o.signature), !J.current) {
				let e = new Set(["message"]);
				for (let t of o.rows) t.depth === 1 && t.expandable && t.path.startsWith("message.") && e.add(t.path);
				B.current = e, me(e), J.current = !0;
			}
			Q(), n(() => {
				O.current && be(O.current);
			});
			return;
		}
		be(r);
	}, [Q, be]);
	f(() => {
		de.current = $;
	}), f(() => {
		!_ && k.current > 0 && n($);
	}, [$, _]), f(() => (O.current = s.getLastMessage(u), k.current = 0, M.current = performance.now(), O.current && (k.current = 1, n($)), s.subscribeTopic(u, () => {
		O.current = s.getLastMessage(u), k.current = I.current ? 1 : k.current + 1, O.current && !L.current && (L.current = !0, pe(!0)), n($);
	})), [$, u]), f(() => {
		if (!W.current) return;
		let e = null, t = new ResizeObserver((t) => {
			let r = t[0]?.contentRect.height;
			!r || r <= 0 || (ue.current = r, e?.(), e = n(Q));
		});
		return t.observe(W.current), () => {
			e?.(), t.disconnect();
		};
	}, [Q]), f(() => {
		O.current = s.getLastMessage(u), L.current = !!O.current, pe(!!O.current), _e(""), he([]), R.current = [], z.current = "", K.current.clear(), G.current.clear(), q.current.clear(), V.current = 0, H.current = {
			startRow: 0,
			endRow: 0,
			totalRows: 0
		}, ve({
			startRow: 0,
			endRow: 0,
			totalRows: 0
		}), B.current = new Set(["message"]), me(new Set(["message"])), J.current = !1, k.current = +!!O.current, M.current = performance.now(), O.current && n($);
	}, [$, u]), f(() => {
		Q();
	}, [
		Q,
		Y,
		X
	]), f(() => {
		O.current && (K.current.clear(), k.current = Math.max(k.current, 1), n($));
	}, [
		$,
		D,
		S,
		b,
		x
	]);
	let xe = ee(() => X.length === 0 ? [] : j(X, Y), [Y, X]).slice(Z.startRow, Z.endRow), Se = d((e, t) => {
		if (t) {
			G.current.set(e, t);
			let n = K.current.get(e);
			if (n == null && O.current) {
				let t = A(O.current, e), { maxBinaryPreviewBytes: r, isImageTopic: i } = U.current;
				n = P(t, r, { hideBinaryHex: i }), K.current.set(e, n);
			}
			n != null && ce(t, n);
		} else G.current.delete(e);
	}, []), Ce = d((e) => {
		me((t) => {
			let n = new Set(t);
			return n.has(e) ? n.delete(e) : n.add(e), B.current = n, n;
		});
	}, []), we = d(async (t) => {
		let n = F(A(O.current, t), ie);
		await se(typeof n == "string" || typeof n == "number" || typeof n == "boolean" ? String(n) : JSON.stringify(n, null, 2) ?? "undefined") ? e.success(w({ id: "panels.rawMessages.copy.success" }, { path: t })) : e.error(w({ id: "panels.rawMessages.copy.error" }));
	}, [ie, w]), Te = d((e) => {
		V.current = e.currentTarget.scrollTop, n(Q);
	}, [Q]);
	return /* @__PURE__ */ te("div", {
		className: "flex h-full flex-col overflow-hidden bg-background",
		children: [/* @__PURE__ */ h("div", {
			className: "shrink-0 border-b bg-muted px-2 py-1",
			children: /* @__PURE__ */ h(i, {
				value: u,
				topics: T,
				onChange: (e) => C((t) => ({
					...t,
					topic: e
				})),
				placeholder: w({ id: "panels.framework.topicPicker.placeholder" }),
				className: "min-w-0 w-full"
			})
		}), /* @__PURE__ */ h("div", {
			ref: W,
			className: "min-h-0 flex-1 overflow-auto p-2 font-mono text-[11px]",
			onScroll: Te,
			children: fe && Z.totalRows > 0 ? /* @__PURE__ */ h("div", {
				style: {
					height: Z.totalRows * y,
					position: "relative"
				},
				children: /* @__PURE__ */ h("div", {
					style: { transform: `translateY(${Z.startRow * y}px)` },
					children: xe.map((e) => /* @__PURE__ */ h(le, {
						row: e,
						expanded: Y.has(e.path),
						onToggle: Ce,
						onCopy: we,
						registerValueNode: Se
					}, e.id))
				})
			}) : /* @__PURE__ */ h("div", {
				className: "flex h-full items-center justify-center text-xs italic text-muted-foreground",
				children: "Waiting for messages..."
			})
		})]
	});
};
//#endregion
export { I as RawMessagesPanel };
