UNPKG

wcz-layout

Version:

1,926 lines • 58.6 kB
import { t as DialogsContext } from "./DialogsContext-D23fJjYR.mjs";
import { c } from "react/compiler-runtime";
import { Accordion, AccordionActions, AccordionDetails, AccordionSummary, Alert, AlertTitle, Avatar, AvatarGroup, Badge, Box, Breadcrumbs, Button, ButtonGroup, Card, CardActions, CardContent, CardHeader, CardMedia, Checkbox, Chip, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControl, FormControlLabel, FormGroup, FormHelperText, FormLabel, Grid, IconButton, ImageList, ImageListItem, ImageListItemBar, InputBase, InputLabel, LinearProgress, Link, List, ListItem, ListItemAvatar, ListItemText, ListSubheader, MenuItem, Paper, Radio, RadioGroup, Rating, Select, Skeleton, Slider, Stack, Step, StepContent, StepLabel, Stepper, Switch, Table, TableBody, TableCell, TableContainer, TableFooter, TableHead, TablePagination, TableRow, TextField, Tooltip, Typography, useEventCallback } from "@mui/material";
import dayjs from "dayjs";
import React, { Suspense, createContext, lazy, useContext, useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { z as z$1 } from "zod";
import { keyframes } from "@mui/material/styles";
import { CatchBoundary, createLink } from "@tanstack/react-router";
import { jsx, jsxs } from "react/jsx-runtime";
import { useDropzone } from "react-dropzone";
import AttachFile from "@mui/icons-material/AttachFile";
import { formatForDisplay } from "@tanstack/react-hotkeys";
import { defaultRangeExtractor } from "@tanstack/react-virtual";
import { aggregationFn_count, aggregationFn_extent, aggregationFn_first, aggregationFn_last, aggregationFn_max, aggregationFn_mean, aggregationFn_median, aggregationFn_min, aggregationFn_sum, aggregationFn_unique, aggregationFn_uniqueCount, createExpandedRowModel, createFacetedMinMaxValues, createFacetedRowModel, createFacetedUniqueValues, createFilteredRowModel, createGroupedRowModel, createPaginatedRowModel, createSortedRowModel, createTableHookContexts, filterFn_arrHas, filterFn_arrIncludes, filterFn_arrIncludesAll, filterFn_arrIncludesSome, filterFn_between, filterFn_betweenInclusive, filterFn_empty, filterFn_endsWith, filterFn_equals, filterFn_equalsString, filterFn_equalsStringSensitive, filterFn_greaterThan, filterFn_greaterThanOrEqualTo, filterFn_inDateRange, filterFn_inNumberRange, filterFn_includesString, filterFn_includesStringSensitive, filterFn_lessThan, filterFn_lessThanOrEqualTo, filterFn_notEmpty, filterFn_startsWith, filterFn_weakEquals, metaHelper, sortFn_alphanumeric, sortFn_alphanumericCaseSensitive, sortFn_basic, sortFn_datetime, sortFn_text, sortFn_textCaseSensitive, stockFeatures, tableFeatures } from "@tanstack/react-table";
import Add from "@mui/icons-material/Add";
import ArrowUpward from "@mui/icons-material/ArrowUpward";
import Refresh from "@mui/icons-material/Refresh";
import Stop from "@mui/icons-material/Stop";
import { visuallyHidden } from "@mui/utils";
import { parsePartialJSON } from "@tanstack/ai-react";
import { streamingMarkdownExtension } from "@tanstack/markdown/extensions/streaming";
import { Markdown } from "@tanstack/markdown/react";
import { toolDefinition } from "@tanstack/ai/client";
// src/hooks/useDialogs.tsx
function AlertDialog(t0) {
	const $ = c(24);
	const { open, payload, onClose } = t0;
	const { t } = useTranslation();
	const messageId = useId();
	let t1;
	if ($[0] !== onClose) {
		t1 = () => onClose();
		$[0] = onClose;
		$[1] = t1;
	} else t1 = $[1];
	let t2;
	if ($[2] !== payload.title || $[3] !== t) {
		t2 = payload.title ?? t("Layout.Dialog.Alert");
		$[2] = payload.title;
		$[3] = t;
		$[4] = t2;
	} else t2 = $[4];
	let t3;
	if ($[5] !== t2) {
		t3 = /* @__PURE__ */ jsx(DialogTitle, { children: t2 });
		$[5] = t2;
		$[6] = t3;
	} else t3 = $[6];
	let t4;
	if ($[7] !== messageId || $[8] !== payload.message) {
		t4 = /* @__PURE__ */ jsx(DialogContent, {
			id: messageId,
			children: payload.message
		});
		$[7] = messageId;
		$[8] = payload.message;
		$[9] = t4;
	} else t4 = $[9];
	let t5;
	if ($[10] !== onClose) {
		t5 = () => onClose();
		$[10] = onClose;
		$[11] = t5;
	} else t5 = $[11];
	let t6;
	if ($[12] !== t) {
		t6 = t("Layout.Dialog.Confirm");
		$[12] = t;
		$[13] = t6;
	} else t6 = $[13];
	let t7;
	if ($[14] !== t5 || $[15] !== t6) {
		t7 = /* @__PURE__ */ jsx(DialogActions, { children: /* @__PURE__ */ jsx(Button, {
			onClick: t5,
			autoFocus: true,
			children: t6
		}) });
		$[14] = t5;
		$[15] = t6;
		$[16] = t7;
	} else t7 = $[16];
	let t8;
	if ($[17] !== messageId || $[18] !== open || $[19] !== t1 || $[20] !== t3 || $[21] !== t4 || $[22] !== t7) {
		t8 = /* @__PURE__ */ jsxs(Dialog, {
			maxWidth: "xs",
			fullWidth: true,
			open,
			onClose: t1,
			role: "alertdialog",
			"aria-describedby": messageId,
			children: [
				t3,
				t4,
				t7
			]
		});
		$[17] = messageId;
		$[18] = open;
		$[19] = t1;
		$[20] = t3;
		$[21] = t4;
		$[22] = t7;
		$[23] = t8;
	} else t8 = $[23];
	return t8;
}
function ConfirmDialog(t0) {
	const $ = c(36);
	const { open, payload, onClose } = t0;
	const { t } = useTranslation();
	const messageId = useId();
	let t1;
	if ($[0] !== onClose) {
		t1 = () => onClose(false);
		$[0] = onClose;
		$[1] = t1;
	} else t1 = $[1];
	let t2;
	if ($[2] !== payload.title || $[3] !== t) {
		t2 = payload.title ?? t("Layout.Dialog.Confirm");
		$[2] = payload.title;
		$[3] = t;
		$[4] = t2;
	} else t2 = $[4];
	let t3;
	if ($[5] !== t2) {
		t3 = /* @__PURE__ */ jsx(DialogTitle, { children: t2 });
		$[5] = t2;
		$[6] = t3;
	} else t3 = $[6];
	let t4;
	if ($[7] !== messageId || $[8] !== payload.message) {
		t4 = /* @__PURE__ */ jsx(DialogContent, {
			id: messageId,
			children: payload.message
		});
		$[7] = messageId;
		$[8] = payload.message;
		$[9] = t4;
	} else t4 = $[9];
	let t5;
	if ($[10] !== onClose) {
		t5 = () => onClose(false);
		$[10] = onClose;
		$[11] = t5;
	} else t5 = $[11];
	let t6;
	if ($[12] !== payload.cancelText || $[13] !== t) {
		t6 = payload.cancelText ?? t("Layout.Dialog.Cancel");
		$[12] = payload.cancelText;
		$[13] = t;
		$[14] = t6;
	} else t6 = $[14];
	let t7;
	if ($[15] !== t5 || $[16] !== t6) {
		t7 = /* @__PURE__ */ jsx(Button, {
			onClick: t5,
			children: t6
		});
		$[15] = t5;
		$[16] = t6;
		$[17] = t7;
	} else t7 = $[17];
	let t8;
	if ($[18] !== onClose) {
		t8 = () => onClose(true);
		$[18] = onClose;
		$[19] = t8;
	} else t8 = $[19];
	let t9;
	if ($[20] !== payload.confirmText || $[21] !== t) {
		t9 = payload.confirmText ?? t("Layout.Dialog.Confirm");
		$[20] = payload.confirmText;
		$[21] = t;
		$[22] = t9;
	} else t9 = $[22];
	let t10;
	if ($[23] !== t8 || $[24] !== t9) {
		t10 = /* @__PURE__ */ jsx(Button, {
			onClick: t8,
			autoFocus: true,
			children: t9
		});
		$[23] = t8;
		$[24] = t9;
		$[25] = t10;
	} else t10 = $[25];
	let t11;
	if ($[26] !== t10 || $[27] !== t7) {
		t11 = /* @__PURE__ */ jsxs(DialogActions, { children: [t7, t10] });
		$[26] = t10;
		$[27] = t7;
		$[28] = t11;
	} else t11 = $[28];
	let t12;
	if ($[29] !== messageId || $[30] !== open || $[31] !== t1 || $[32] !== t11 || $[33] !== t3 || $[34] !== t4) {
		t12 = /* @__PURE__ */ jsxs(Dialog, {
			maxWidth: "xs",
			fullWidth: true,
			open,
			onClose: t1,
			role: "alertdialog",
			"aria-describedby": messageId,
			children: [
				t3,
				t4,
				t11
			]
		});
		$[29] = messageId;
		$[30] = open;
		$[31] = t1;
		$[32] = t11;
		$[33] = t3;
		$[34] = t4;
		$[35] = t12;
	} else t12 = $[35];
	return t12;
}
function useDialogs() {
	const $ = c(9);
	const { open, close } = useContext(DialogsContext);
	let t0;
	if ($[0] !== open) {
		t0 = (message, t1) => {
			const { ...options } = t1 === void 0 ? {} : t1;
			return open(AlertDialog, {
				...options,
				message
			});
		};
		$[0] = open;
		$[1] = t0;
	} else t0 = $[1];
	const alert = useEventCallback(t0);
	let t1;
	if ($[2] !== open) {
		t1 = (message_0, t2) => {
			const { ...options_0 } = t2 === void 0 ? {} : t2;
			return open(ConfirmDialog, {
				...options_0,
				message: message_0
			});
		};
		$[2] = open;
		$[3] = t1;
	} else t1 = $[3];
	const confirm = useEventCallback(t1);
	let t2;
	if ($[4] !== alert || $[5] !== close || $[6] !== confirm || $[7] !== open) {
		t2 = {
			alert,
			confirm,
			open,
			close
		};
		$[4] = alert;
		$[5] = close;
		$[6] = confirm;
		$[7] = open;
		$[8] = t2;
	} else t2 = $[8];
	return t2;
}
// src/components/router/RouterLink.tsx
const Component = React.forwardRef(function LinkComponent(props, reference) {
	const $ = c(3);
	let t0;
	if ($[0] !== props || $[1] !== reference) {
		t0 = /* @__PURE__ */ jsx(Link, {
			ref: reference,
			...props
		});
		$[0] = props;
		$[1] = reference;
		$[2] = t0;
	} else t0 = $[2];
	return t0;
});
const CreatedComponent = createLink(Component);
const RouterLink = (props) => {
	const $ = c(2);
	let t0;
	if ($[0] !== props) {
		t0 = /* @__PURE__ */ jsx(CreatedComponent, { ...props });
		$[0] = props;
		$[1] = t0;
	} else t0 = $[1];
	return t0;
};
// src/components/table/context.ts
const layoutTableFeatures = tableFeatures({
	...stockFeatures,
	columnMeta: metaHelper(),
	filteredRowModel: createFilteredRowModel(),
	sortedRowModel: createSortedRowModel(),
	paginatedRowModel: createPaginatedRowModel(),
	expandedRowModel: createExpandedRowModel(),
	groupedRowModel: createGroupedRowModel(),
	facetedRowModel: createFacetedRowModel(),
	facetedUniqueValues: createFacetedUniqueValues(),
	facetedMinMaxValues: createFacetedMinMaxValues(),
	filterFns: {
		arrHas: filterFn_arrHas,
		arrIncludes: filterFn_arrIncludes,
		arrIncludesAll: filterFn_arrIncludesAll,
		arrIncludesSome: filterFn_arrIncludesSome,
		between: filterFn_between,
		betweenInclusive: filterFn_betweenInclusive,
		empty: filterFn_empty,
		endsWith: filterFn_endsWith,
		equals: filterFn_equals,
		equalsString: filterFn_equalsString,
		equalsStringSensitive: filterFn_equalsStringSensitive,
		greaterThan: filterFn_greaterThan,
		greaterThanOrEqualTo: filterFn_greaterThanOrEqualTo,
		inDateRange: filterFn_inDateRange,
		inNumberRange: filterFn_inNumberRange,
		includesString: filterFn_includesString,
		includesStringSensitive: filterFn_includesStringSensitive,
		lessThan: filterFn_lessThan,
		lessThanOrEqualTo: filterFn_lessThanOrEqualTo,
		notEmpty: filterFn_notEmpty,
		startsWith: filterFn_startsWith,
		weakEquals: filterFn_weakEquals
	},
	sortFns: {
		alphanumeric: sortFn_alphanumeric,
		alphanumericCaseSensitive: sortFn_alphanumericCaseSensitive,
		basic: sortFn_basic,
		datetime: sortFn_datetime,
		text: sortFn_text,
		textCaseSensitive: sortFn_textCaseSensitive
	},
	aggregationFns: {
		sum: aggregationFn_sum,
		min: aggregationFn_min,
		max: aggregationFn_max,
		extent: aggregationFn_extent,
		mean: aggregationFn_mean,
		median: aggregationFn_median,
		unique: aggregationFn_unique,
		uniqueCount: aggregationFn_uniqueCount,
		count: aggregationFn_count,
		first: aggregationFn_first,
		last: aggregationFn_last
	}
});
const { tableContext, cellContext, headerContext, useTableContext, useCellContext, useHeaderContext } = createTableHookContexts();
// src/components/table/table/Pagination.tsx
/** A pager is for large data sets, so it offers no "All". LayoutTable starts at the lowest. */
const DEFAULT_PAGE_SIZE_OPTIONS = [
	25,
	50,
	100
];
const Pagination = ({ pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS, ...props }) => {
	"use no memo";
	const table = useTableContext();
	const { pageIndex, pageSize } = table.state.pagination;
	return /* @__PURE__ */ jsx(TablePagination, {
		component: "div",
		showFirstButton: true,
		showLastButton: true,
		...props,
		sx: [{
			flexShrink: 0,
			minHeight: 52,
			borderTop: 1,
			borderColor: "divider"
		}, ...Array.isArray(props.sx) ? props.sx : [props.sx]],
		rowsPerPageOptions: pageSizeOptions,
		count: table.getPageCount() === -1 ? -1 : table.getRowCount(),
		page: pageIndex,
		rowsPerPage: pageSize,
		onPageChange: (_, page) => table.setPageIndex(page),
		onRowsPerPageChange: (event) => table.setPagination({
			pageIndex: 0,
			pageSize: Number(event.target.value)
		})
	});
};
// src/components/table/utils.ts
/** Stable class names on every table part, for `sx` selectors like `.MuiDataGrid-*`. */
const layoutTableClasses = {
	root: "LayoutTable-root",
	main: "LayoutTable-main",
	table: "LayoutTable-table",
	toolbar: "LayoutTable-toolbar",
	toolbarLabel: "LayoutTable-toolbarLabel",
	toolbarTitle: "LayoutTable-toolbarTitle",
	toolbarSelectedCount: "LayoutTable-toolbarSelectedCount",
	toolbarDivider: "LayoutTable-toolbarDivider",
	toolbarQuickFilter: "LayoutTable-toolbarQuickFilter",
	columnsButton: "LayoutTable-columnsButton",
	columnsPanel: "LayoutTable-columnsPanel",
	filtersButton: "LayoutTable-filtersButton",
	filterPanel: "LayoutTable-filterPanel",
	columnHeaders: "LayoutTable-columnHeaders",
	columnHeaderRow: "LayoutTable-columnHeaderRow",
	columnHeader: "LayoutTable-columnHeader",
	"columnHeader--sortable": "LayoutTable-columnHeader--sortable",
	"columnHeader--sorted": "LayoutTable-columnHeader--sorted",
	"columnHeader--filtered": "LayoutTable-columnHeader--filtered",
	"columnHeader--pinnedStart": "LayoutTable-columnHeader--pinnedStart",
	"columnHeader--pinnedEnd": "LayoutTable-columnHeader--pinnedEnd",
	columnHeaderContent: "LayoutTable-columnHeaderContent",
	columnHeaderTitleContainer: "LayoutTable-columnHeaderTitleContainer",
	sortLabel: "LayoutTable-sortLabel",
	sortIndex: "LayoutTable-sortIndex",
	menuIcon: "LayoutTable-menuIcon",
	columnSeparator: "LayoutTable-columnSeparator",
	"columnSeparator--resizable": "LayoutTable-columnSeparator--resizable",
	"columnSeparator--resizing": "LayoutTable-columnSeparator--resizing",
	body: "LayoutTable-body",
	row: "LayoutTable-row",
	"row--grouped": "LayoutTable-row--grouped",
	"row--expanded": "LayoutTable-row--expanded",
	"row--pinned": "LayoutTable-row--pinned",
	cell: "LayoutTable-cell",
	"cell--selected": "LayoutTable-cell--selected",
	"cell--grouped": "LayoutTable-cell--grouped",
	"cell--aggregated": "LayoutTable-cell--aggregated",
	"cell--pinnedStart": "LayoutTable-cell--pinnedStart",
	"cell--pinnedEnd": "LayoutTable-cell--pinnedEnd",
	groupCell: "LayoutTable-groupCell",
	expandButton: "LayoutTable-expandButton",
	actionsCell: "LayoutTable-actionsCell",
	cellOffset: "LayoutTable-cellOffset",
	rowOffset: "LayoutTable-rowOffset",
	filler: "LayoutTable-filler",
	skeletonRow: "LayoutTable-skeletonRow",
	skeletonCell: "LayoutTable-skeletonCell",
	overlay: "LayoutTable-overlay",
	footer: "LayoutTable-footer",
	footerRow: "LayoutTable-footerRow",
	footerCell: "LayoutTable-footerCell",
	aggregationValue: "LayoutTable-aggregationValue",
	pagination: "LayoutTable-pagination"
};
const classNames = (...names) => names.filter(Boolean).join(" ");
const pinnedClass = (column, part) => {
	const pinned = column.getIsPinned();
	return !!pinned && layoutTableClasses[`${part}--${pinned === "start" ? "pinnedStart" : "pinnedEnd"}`];
};
const shortcutLabel = (label, hotkey) => `${label} (${formatForDisplay(hotkey)})`;
const columnLabel = (column) => {
	const meta = column.columnDef.meta;
	if (meta?.label) return meta.label;
	return typeof column.columnDef.header === "string" ? column.columnDef.header : column.id;
};
const hasColumnLabel = (column) => Boolean(column.columnDef.meta?.label) || typeof column.columnDef.header === "string";
const columnAlign = (column) => column.columnDef.meta?.align ?? (hasColumnLabel(column) ? "left" : "center");
/** The column's `meta.flex`, or 0 once the user has resized it to a fixed width. */
const columnFlex = (column) => Object.hasOwn(column.table.atoms.columnSizing.get(), column.id) ? 0 : column.columnDef.meta?.flex ?? 0;
const moveColumn = (column, delta) => {
	const { table } = column;
	const current = table.atoms.columnOrder.get();
	const order = current.length ? [...current] : table.getAllLeafColumns().map(({ id }) => id);
	const from = order.indexOf(column.id);
	const to = from + delta;
	if (from < 0 || to < 0 || to >= order.length) return;
	order.splice(to, 0, ...order.splice(from, 1));
	table.setColumnOrder(order);
};
const pinnedSx = (column, isHeader = false) => {
	const pinned = column.getIsPinned();
	if (!pinned) return {};
	return {
		position: "sticky",
		zIndex: isHeader ? 4 : 2,
		insetInlineStart: pinned === "start" ? column.getStart("start") : void 0,
		insetInlineEnd: pinned === "end" ? column.getAfter("end") : void 0,
		bgcolor: "background.paper",
		...!isHeader && {
			".MuiTableRow-root:hover > &": { backgroundImage: (theme) => `linear-gradient(${theme.palette.action.hover}, ${theme.palette.action.hover})` },
			".MuiTableRow-root.Mui-selected > &": { backgroundImage: (theme) => `linear-gradient(${theme.palette.action.selected}, ${theme.palette.action.selected})` }
		},
		...pinned === "start" && column.getIsLastColumn("start") && {
			borderInlineEnd: 1,
			borderInlineEndStyle: "solid",
			borderColor: "divider"
		},
		...pinned === "end" && column.getIsFirstColumn("end") && {
			borderInlineStart: 1,
			borderInlineStartStyle: "solid",
			borderColor: "divider"
		}
	};
};
const cellSelectionSx = (cell) => {
	if (!cell.getIsSelected()) return {};
	const edges = cell.getSelectionEdges();
	const outline = (theme) => [
		edges.top && `inset 0 2px 0 0 ${theme.palette.primary.main}`,
		edges.bottom && `inset 0 -2px 0 0 ${theme.palette.primary.main}`,
		edges.left && `inset 2px 0 0 0 ${theme.palette.primary.main}`,
		edges.right && `inset -2px 0 0 0 ${theme.palette.primary.main}`
	].filter(Boolean).join(", ") || "none";
	return {
		backgroundImage: (theme) => `linear-gradient(${theme.palette.action.selected}, ${theme.palette.action.selected})`,
		boxShadow: outline
	};
};
/** Spreadsheet TSV quoting, so a cell holding a tab or a newline stays one cell. */
const quoteTsv = (text) => /["\t\n\r]/.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
const toClipboardValue = (value) => {
	if (value == null) return "";
	if (typeof value === "string") return quoteTsv(value);
	if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return quoteTsv(String(value));
	if (value instanceof Date) return quoteTsv(value.toISOString());
	return quoteTsv(JSON.stringify(value) ?? "");
};
/**
* Serializes `table.getSelectedCellRangesData()` as TSV, which is what Excel,
* Google Sheets and LibreOffice all paste as a grid. Disjoint selection regions
* are separated by a blank line.
*/
const toClipboardText = (regions) => regions.map((rows) => rows.map((cells) => cells.map(toClipboardValue).join("	")).join("\n")).join("\n\n");
const lookaheadRange = (range, direction, lookahead) => {
	const behind = direction ? 0 : range.overscan;
	const ahead = direction ? lookahead : range.overscan;
	return defaultRangeExtractor({
		...range,
		startIndex: range.startIndex - (direction === "backward" ? ahead : behind),
		endIndex: range.endIndex + (direction === "backward" ? behind : ahead),
		overscan: 0
	});
};
// src/components/table/formatValue.ts
const formatValue = (value, dateFormat = "L LT") => {
	if (value === null || value === void 0) return "";
	if (value instanceof Date) return dayjs(value).format(dateFormat);
	if (typeof value === "string") return value;
	if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return value.toString();
	return JSON.stringify(value) ?? "";
};
// src/components/table/cells/formatters/AggregatedCell.tsx
const AggregatedCell = (t0) => {
	const $ = c(29);
	let dateFormat;
	let options;
	let props;
	let t1;
	if ($[0] !== t0) {
		({prefix: t1, options, dateFormat, ...props} = t0);
		$[0] = t0;
		$[1] = dateFormat;
		$[2] = options;
		$[3] = props;
		$[4] = t1;
	} else {
		dateFormat = $[1];
		options = $[2];
		props = $[3];
		t1 = $[4];
	}
	const prefix = t1 === void 0 ? "" : t1;
	const cell = useCellContext();
	let T0;
	let t2;
	let t3;
	let t4;
	let t5;
	let t6;
	let t7;
	let t8;
	if ($[5] !== cell || $[6] !== dateFormat || $[7] !== options || $[8] !== prefix || $[9] !== props) {
		t8 = Symbol.for("react.early_return_sentinel");
		bb0: {
			const value = cell.getValue();
			if (value === null || value === void 0 || value === "") {
				t8 = null;
				break bb0;
			}
			let t9;
			if ($[18] !== dateFormat || $[19] !== options) {
				t9 = (entry) => typeof entry === "number" ? entry.toLocaleString(void 0, options) : formatValue(entry, dateFormat);
				$[18] = dateFormat;
				$[19] = options;
				$[20] = t9;
			} else t9 = $[20];
			const format = t9;
			T0 = Typography;
			t2 = "body2";
			t3 = "text.secondary";
			t4 = true;
			t5 = props;
			t6 = prefix;
			t7 = Array.isArray(value) ? value.map(format).join(" – ") : format(value);
		}
		$[5] = cell;
		$[6] = dateFormat;
		$[7] = options;
		$[8] = prefix;
		$[9] = props;
		$[10] = T0;
		$[11] = t2;
		$[12] = t3;
		$[13] = t4;
		$[14] = t5;
		$[15] = t6;
		$[16] = t7;
		$[17] = t8;
	} else {
		T0 = $[10];
		t2 = $[11];
		t3 = $[12];
		t4 = $[13];
		t5 = $[14];
		t6 = $[15];
		t7 = $[16];
		t8 = $[17];
	}
	if (t8 !== Symbol.for("react.early_return_sentinel")) return t8;
	let t9;
	if ($[21] !== T0 || $[22] !== t2 || $[23] !== t3 || $[24] !== t4 || $[25] !== t5 || $[26] !== t6 || $[27] !== t7) {
		t9 = /* @__PURE__ */ jsxs(T0, {
			variant: t2,
			color: t3,
			noWrap: t4,
			...t5,
			children: [t6, t7]
		});
		$[21] = T0;
		$[22] = t2;
		$[23] = t3;
		$[24] = t4;
		$[25] = t5;
		$[26] = t6;
		$[27] = t7;
		$[28] = t9;
	} else t9 = $[28];
	return t9;
};
// src/lib/ai/tools/ui.ts
/**
* The MUI components the model may render, under their own names. Props pass through
* untouched, so they are MUI's official props (`ComponentProps<typeof Card>`). Add a
* component here and both tools offer it. Left out: anything that needs state, an icon,
* an overlay or a callback to work.
*/
const components = {
	Accordion,
	AccordionActions,
	AccordionDetails,
	AccordionSummary,
	Alert,
	AlertTitle,
	Avatar,
	AvatarGroup,
	Badge,
	Box,
	Breadcrumbs,
	Button,
	ButtonGroup,
	Card,
	CardActions,
	CardContent,
	CardHeader,
	CardMedia,
	Checkbox,
	Chip,
	CircularProgress,
	Divider,
	FormControl,
	FormControlLabel,
	FormGroup,
	FormHelperText,
	FormLabel,
	Grid,
	ImageList,
	ImageListItem,
	ImageListItemBar,
	InputLabel,
	LinearProgress,
	Link,
	List,
	ListItem,
	ListItemAvatar,
	ListItemText,
	ListSubheader,
	MenuItem,
	Paper,
	Radio,
	RadioGroup,
	Rating,
	Select,
	Skeleton,
	Slider,
	Stack,
	Step,
	StepContent,
	StepLabel,
	Stepper,
	Switch,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableFooter,
	TableHead,
	TableRow,
	TextField,
	Tooltip,
	Typography
};
/**
* The TanStack Charts marks a `Chart` node takes as children, under their own names. Props pass
* through untouched too: the rows as `data`, the rest the mark's official options. Only the
* names live here; the marks load with the first chart, so a chart costs nothing until one shows.
*/
const chartMarks = [
	"areaX",
	"areaY",
	"arrow",
	"bandX",
	"bandY",
	"barX",
	"barY",
	"boxX",
	"boxY",
	"cell",
	"crosshair",
	"differenceX",
	"differenceY",
	"dot",
	"frame",
	"hexagon",
	"lineX",
	"lineY",
	"linearRegressionX",
	"linearRegressionY",
	"link",
	"rect",
	"ridgelineX",
	"ridgelineY",
	"ruleX",
	"ruleY",
	"text",
	"tickX",
	"tickY",
	"vector",
	"violinX",
	"violinY",
	"waffleX",
	"waffleY"
];
/**
* `show_ui` and `ask_user`. Built on call, not at import: `wcz-layout/hooks` is imported by
* every app, and module-level calls survive tree-shaking, registry and all.
*/
function createUiTools() {
	const types = [
		...Object.keys(components),
		"Chart",
		...chartMarks
	];
	const UiNode = z$1.object({
		type: z$1.enum(types),
		props: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Official props of the MUI component (sx works), or of the TanStack Charts chart or mark. A prop can hold a node."),
		get children() {
			const child = z$1.union([
				z$1.string(),
				z$1.number(),
				UiNode
			]);
			return z$1.union([child, z$1.array(child)]).optional().describe("Text, a node, or a list of them");
		}
	});
	const uiInput = z$1.object({ ui: UiNode });
	return [toolDefinition({
		name: "show_ui",
		description: "Show Material UI (MUI v9) components in the chat. Prefer it to markdown for structured content: tables, cards, lists, key facts, statuses, steps and progress.`ui` is one node { type, props, children }: `type` is the component, `props` its official MUI props (sx works; a prop can hold a node, e.g. CardHeader avatar or Alert action), `children` text, a node or a list of them. MUI v9 has no system props: alignItems, gap, p, m and the like go in sx. Grid takes `container`, and `size` on children (e.g. { xs: 12, sm: 6 }); never `item` or `xs`. The chat can be as narrow as a phone. Callbacks do nothing; to let the user answer, use ask_user. A Chart node draws numbers that compare or change with TanStack Charts. Its props are the defineChart spec without marks: scales.x and scales.y, each { scale: 'band' for categories, 'point' for ordered labels such as months, 'linear' for numbers (the default), and the official options such as axis: { label }, grid, nice; padding and a fixed domain work too }, color ({ legend: true for several series, domain }), focus ('group-x' for lines); and the Chart's ariaLabel and height. Its children are the marks (barY, barX, lineY, areaY, dot, ruleY, text, cell, crosshair and the rest), each with props { data: the rows, then the mark's official options, channels naming fields, e.g. x: 'month', y: 'count', color: 'state' }. Bars at the same x stack; layout: { type: 'group' } puts them side by side. A line takes points: true for its dots: a dot mark of its own adds a second tooltip row. Dates are labels: there is no time scale.",
		inputSchema: uiInput
	}).client(() => ({ shown: true })), toolDefinition({
		name: "ask_user",
		description: "Ask the user with a Material UI form and wait for the answer. Same `ui` format as show_ui. Give every input a `name`: TextField (type date/number work; select: true with MenuItem children), FormControlLabel with a Checkbox, Switch or Radio `control`, RadioGroup, Slider, Rating. Add Button(s) with type 'submit'; the clicked button's name/value is included, so several buttons work as choices. Returns { [name]: value }: repeated names give arrays, unchecked boxes are left out. Never use it to confirm a tool call: tools that need approval ask the user themselves.",
		inputSchema: uiInput
	}).client()];
}
// src/components/chat/generatedUi.tsx
/** Keys that run code or swap the rendered element. Checked at every depth: slotProps nest. */
const BLOCKED = /^([oO][nN]|form[A-Z]|component$|slots$|as$|key$|ref$|dangerouslySetInnerHTML$)|(Component|Ref)$/;
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
const isNode = (value) => isRecord(value) && typeof value.type === "string" && Object.hasOwn(components, value.type);
const isChart = (value) => isRecord(value) && value.type === "Chart";
const GeneratedChart = lazy(() => import("./generatedChart-k7NEdi5Z.mjs").then(({ GeneratedChart }) => ({ default: GeneratedChart })));
const Streaming = createContext(false);
/** Drawn once the arguments are complete; its data and options reach TanStack Charts as written. */
function ChartNode(t0) {
	const $ = c(8);
	const { node } = t0;
	const streaming = useContext(Streaming);
	let t1;
	if ($[0] !== node.props) {
		t1 = isRecord(node.props) ? node.props : {};
		$[0] = node.props;
		$[1] = t1;
	} else t1 = $[1];
	const { height } = t1;
	const t2 = typeof height === "number" ? height : 280;
	let t3;
	if ($[2] !== t2) {
		t3 = /* @__PURE__ */ jsx(Skeleton, {
			variant: "rounded",
			height: t2
		});
		$[2] = t2;
		$[3] = t3;
	} else t3 = $[3];
	const placeholder = t3;
	let t4;
	if ($[4] !== node || $[5] !== placeholder || $[6] !== streaming) {
		t4 = streaming ? placeholder : /* @__PURE__ */ jsx(Suspense, {
			fallback: placeholder,
			children: /* @__PURE__ */ jsx(GeneratedChart, { node })
		});
		$[4] = node;
		$[5] = placeholder;
		$[6] = streaming;
		$[7] = t4;
	} else t4 = $[7];
	return t4;
}
/** Model-written props without blocked keys or password fields; nodes become elements. */
const toProps = (value) => {
	if (isNode(value) || isChart(value)) return renderGeneratedUi(value);
	if (Array.isArray(value)) return value.map(toProps);
	if (!isRecord(value)) return value;
	return Object.fromEntries(Object.entries(value).filter(([name, item]) => !BLOCKED.test(name) && !(name === "type" && item === "password")).map(([name, item]) => [name, toProps(item)]));
};
/** A node tree as the model wrote it. Anything that is not a known component renders nothing. */
function renderGeneratedUi(value, key) {
	if (typeof value === "string" || typeof value === "number") return value;
	if (Array.isArray(value)) return value.length === 1 ? renderGeneratedUi(value[0], key) : value.map(renderGeneratedUi);
	if (isChart(value)) return /* @__PURE__ */ jsx(ChartNode, { node: value }, key);
	if (!isNode(value)) return null;
	const Component = components[value.type];
	const { children, ...props } = isRecord(value.props) ? value.props : {};
	return /* @__PURE__ */ jsx(Component, {
		...toProps(props),
		children: renderGeneratedUi(value.children ?? children)
	}, key);
}
/** `show_ui`. Renders while the arguments still stream, so the UI builds up as the model writes it. */
function GeneratedUi(t0) {
	const $ = c(17);
	const { part } = t0;
	const { t } = useTranslation();
	let t1;
	if ($[0] !== part.arguments || $[1] !== part.input) {
		t1 = part.input ?? parsePartialJSON(part.arguments);
		$[0] = part.arguments;
		$[1] = part.input;
		$[2] = t1;
	} else t1 = $[2];
	const input = t1;
	let t2;
	if ($[3] === Symbol.for("react.memo_cache_sentinel")) {
		t2 = {
			overflowX: "auto",
			m: -.5,
			p: .5
		};
		$[3] = t2;
	} else t2 = $[3];
	let t3;
	if ($[4] !== part.arguments) {
		t3 = () => part.arguments;
		$[4] = part.arguments;
		$[5] = t3;
	} else t3 = $[5];
	let t4;
	if ($[6] !== t) {
		t4 = () => /* @__PURE__ */ jsx(Alert, {
			severity: "warning",
			children: t("Layout.Chat.RenderFailed")
		});
		$[6] = t;
		$[7] = t4;
	} else t4 = $[7];
	const t5 = part.input === void 0;
	const t6 = input?.ui;
	let t7;
	if ($[8] !== t6) {
		t7 = renderGeneratedUi(t6);
		$[8] = t6;
		$[9] = t7;
	} else t7 = $[9];
	let t8;
	if ($[10] !== t5 || $[11] !== t7) {
		t8 = /* @__PURE__ */ jsx(Streaming, {
			value: t5,
			children: t7
		});
		$[10] = t5;
		$[11] = t7;
		$[12] = t8;
	} else t8 = $[12];
	let t9;
	if ($[13] !== t3 || $[14] !== t4 || $[15] !== t8) {
		t9 = /* @__PURE__ */ jsx(Box, {
			sx: t2,
			children: /* @__PURE__ */ jsx(CatchBoundary, {
				getResetKey: t3,
				errorComponent: t4,
				children: t8
			})
		});
		$[13] = t3;
		$[14] = t4;
		$[15] = t8;
		$[16] = t9;
	} else t9 = $[16];
	return t9;
}
/** `ask_user`. Submitting sends `{ [name]: value }` back to the model as the tool's result. */
function AskUser(t0) {
	const $ = c(17);
	const { part, disabled, onAnswer } = t0;
	const answer = part.output;
	let t1;
	if ($[0] !== onAnswer) {
		t1 = (event) => {
			event.preventDefault();
			const { submitter } = event.nativeEvent;
			const values = {};
			for (const [name, value] of new FormData(event.currentTarget, submitter)) {
				const previous = values[name];
				values[name] = previous === void 0 ? value : [previous, value].flat();
			}
			onAnswer(values);
		};
		$[0] = onAnswer;
		$[1] = t1;
	} else t1 = $[1];
	const submit = t1;
	const t2 = answer === void 0 ? 1 : .6;
	const t3 = disabled ? "none" : void 0;
	let t4;
	if ($[2] !== t2 || $[3] !== t3) {
		t4 = {
			border: 0,
			m: 0,
			p: 0,
			minWidth: 0,
			opacity: t2,
			pointerEvents: t3
		};
		$[2] = t2;
		$[3] = t3;
		$[4] = t4;
	} else t4 = $[4];
	let t5;
	if ($[5] !== part) {
		t5 = /* @__PURE__ */ jsx(GeneratedUi, { part });
		$[5] = part;
		$[6] = t5;
	} else t5 = $[6];
	let t6;
	if ($[7] !== disabled || $[8] !== t4 || $[9] !== t5) {
		t6 = /* @__PURE__ */ jsx(Box, {
			component: "fieldset",
			disabled,
			sx: t4,
			children: t5
		});
		$[7] = disabled;
		$[8] = t4;
		$[9] = t5;
		$[10] = t6;
	} else t6 = $[10];
	let t7;
	if ($[11] !== answer) {
		t7 = isRecord(answer) && /* @__PURE__ */ jsx(Typography, {
			variant: "caption",
			color: "text.secondary",
			children: Object.entries(answer).map(_temp$1).join(", ")
		});
		$[11] = answer;
		$[12] = t7;
	} else t7 = $[12];
	let t8;
	if ($[13] !== submit || $[14] !== t6 || $[15] !== t7) {
		t8 = /* @__PURE__ */ jsxs(Box, {
			component: "form",
			onSubmit: submit,
			children: [t6, t7]
		});
		$[13] = submit;
		$[14] = t6;
		$[15] = t7;
		$[16] = t8;
	} else t8 = $[16];
	return t8;
}
function _temp$1(t0) {
	const [name_0, value_0] = t0;
	return `${name_0}: ${String(value_0)}`;
}
// src/lib/ai/attachments.ts
const MAX_BYTES = 10485760;
const MAX_IMAGE_SIDE = 1568;
const DOCUMENTS = {
	pdf: "application/pdf",
	docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
	xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
	rtf: "application/rtf",
	csv: "text/csv",
	md: "text/markdown",
	json: "application/json",
	html: "text/html",
	txt: "text/plain"
};
const base64 = (file) => new Promise((resolve, reject) => {
	const reader = new FileReader();
	reader.onload = () => resolve(reader.result.split(",")[1]);
	reader.onerror = () => reject(reader.error ?? /* @__PURE__ */ new Error("Cannot read the file"));
	reader.readAsDataURL(file);
});
/** An image as the model sees it: a JPEG no larger than it reads, base64. */
async function readImage(file) {
	const image = await createImageBitmap(file);
	const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(image.width, image.height));
	const canvas = document.createElement("canvas");
	canvas.width = Math.round(image.width * scale);
	canvas.height = Math.round(image.height * scale);
	const context = canvas.getContext("2d");
	if (!context) throw new Error("No canvas");
	context.fillStyle = "#fff";
	context.fillRect(0, 0, canvas.width, canvas.height);
	context.drawImage(image, 0, 0, canvas.width, canvas.height);
	return canvas.toDataURL("image/jpeg", .85).split(",")[1];
}
/**
* A file as one part of a user message, kept in the conversation and never uploaded to the file
* service. The model reads it as it is: an image of any kind the browser shows, and a document
* (PDF, Word, Excel, PowerPoint, CSV or text). Throws for a file it cannot read or a large one.
*/
async function fileToPart(file) {
	if (file.type.startsWith("image/")) return {
		type: "image",
		source: {
			type: "data",
			value: await readImage(file),
			mimeType: "image/jpeg"
		}
	};
	const extension = file.name.split(".").at(-1)?.toLowerCase() ?? "";
	const mimeType = DOCUMENTS[extension] ?? (file.type.startsWith("text/") ? "text/plain" : "");
	if (!mimeType || file.size > MAX_BYTES) throw new Error(`Cannot attach ${file.name}`);
	return {
		type: "document",
		source: {
			type: "data",
			value: await base64(file),
			mimeType
		},
		metadata: { filename: file.name }
	};
}
// src/components/chat/ChatLayout.tsx
/** One centered reading column, like ChatGPT: full width on a phone, 48rem on a desktop. */
const columnSx = {
	width: "100%",
	maxWidth: "48rem",
	mx: "auto",
	px: 2
};
const markdownSx = {
	typography: "body1",
	overflowWrap: "anywhere",
	"& > *": { my: 0 },
	"& > * + *": { mt: 2 },
	"& pre": {
		overflowX: "auto",
		p: 1.5,
		borderRadius: 2,
		bgcolor: "action.hover"
	},
	"& :not(pre) > code": {
		px: .5,
		borderRadius: 1,
		bgcolor: "action.hover"
	},
	"& table": {
		display: "block",
		overflowX: "auto",
		borderCollapse: "collapse"
	},
	"& th, & td": {
		border: 1,
		borderColor: "divider",
		px: 1,
		py: .5
	},
	"& img": { maxWidth: "100%" }
};
const markdownExtensions = [streamingMarkdownExtension()];
/** The app's own pages open in place, through the router; anything else in a new tab. */
function MarkdownLink(t0) {
	const $ = c(3);
	const { href: t1, children } = t0;
	const href = t1 === void 0 ? "" : t1;
	let t2;
	if ($[0] !== children || $[1] !== href) {
		t2 = href.startsWith("/") && !href.startsWith("//") ? /* @__PURE__ */ jsx(RouterLink, {
			to: href,
			children
		}) : /* @__PURE__ */ jsx(Link, {
			href,
			target: "_blank",
			rel: "noreferrer",
			children
		});
		$[0] = children;
		$[1] = href;
		$[2] = t2;
	} else t2 = $[2];
	return t2;
}
const markdownComponents = { a: MarkdownLink };
const shimmer = keyframes`
  from { background-position: 100% 0; }
  to { background-position: -100% 0; }
`;
/** The model is working on a reply, but nothing of it is on screen yet. */
function isReasoning({ isLoading, messages }) {
	const last = messages.at(-1);
	const part = last?.role === "assistant" ? last.parts.at(-1) : void 0;
	const streaming = part?.type === "text" && part.content !== "" || part?.type === "tool-call" && part.output === void 0;
	return isLoading && !streaming;
}
/** After a scroll event: at the bottom it follows new content, after a scroll up it stops. */
function keepsFollowing(following, previousTop, { scrollTop, scrollHeight, clientHeight }) {
	if (scrollHeight - clientHeight - scrollTop <= 1) return true;
	return scrollTop < previousTop ? false : following;
}
/** Keeps the scroll container at the bottom while content grows, unless the user scrolled up. */
function useFollowContent() {
	const $ = c(3);
	const ref = useRef(null);
	const following = useRef(true);
	let t0;
	let t1;
	if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
		t0 = () => {
			const scroller = ref.current;
			if (!scroller) return;
			let previousTop = scroller.scrollTop;
			const onScroll = () => {
				following.current = keepsFollowing(following.current, previousTop, scroller);
				previousTop = scroller.scrollTop;
			};
			const observer = new ResizeObserver(() => {
				if (!following.current) return;
				scroller.scrollTop = scroller.scrollHeight;
				previousTop = scroller.scrollTop;
			});
			scroller.addEventListener("scroll", onScroll, { passive: true });
			observer.observe(scroller);
			for (const child of scroller.children) observer.observe(child);
			return () => {
				scroller.removeEventListener("scroll", onScroll);
				observer.disconnect();
			};
		};
		t1 = [];
		$[0] = t0;
		$[1] = t1;
	} else {
		t0 = $[0];
		t1 = $[1];
	}
	useEffect(t0, t1);
	let t2;
	if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
		t2 = {
			ref,
			following
		};
		$[2] = t2;
	} else t2 = $[2];
	return t2;
}
const shimmerSx = (theme) => {
	const { text } = (theme.vars ?? theme).palette;
	return {
		alignSelf: "flex-start",
		color: "transparent",
		backgroundImage: `linear-gradient(90deg, ${text.disabled} 40%, ${text.primary} 50%, ${text.disabled} 60%)`,
		backgroundSize: "200% 100%",
		backgroundClip: "text",
		WebkitBackgroundClip: "text",
		animation: `${shimmer} 2s linear infinite`,
		"@media (prefers-reduced-motion: reduce)": { animation: "none" }
	};
};
const statusClass = "LayoutChat-status";
function Reasoning() {
	const $ = c(4);
	const { t } = useTranslation();
	let t0;
	if ($[0] !== t) {
		t0 = t("Layout.Chat.Reasoning");
		$[0] = t;
		$[1] = t0;
	} else t0 = $[1];
	let t1;
	if ($[2] !== t0) {
		t1 = /* @__PURE__ */ jsx(Typography, {
			className: statusClass,
			sx: shimmerSx,
			children: t0
		});
		$[2] = t0;
		$[3] = t1;
	} else t1 = $[3];
	return t1;
}
/** A tool's words while the model writes its input, while it runs, and once it is done. */
const activities = {
	execute_typescript: [
		"WritingCode",
		"RunningCode",
		"RanCode"
	],
	discover_tools: [
		"FindingTools",
		"FindingTools",
		"FoundTools"
	],
	__lazy__tool__discovery__: [
		"FindingTools",
		"FindingTools",
		"FoundTools"
	],
	read_page: [
		"ReadingPage",
		"ReadingPage",
		"ReadPage"
	],
	click: [
		"Clicking",
		"Clicking",
		"Clicked"
	],
	fill: [
		"Filling",
		"Filling",
		"Filled"
	],
	press_key: [
		"PressingKey",
		"PressingKey",
		"PressedKey"
	]
};
/** A tool's name as words: external_create_device is "create device". */
const words = (name) => name.replace(/^external_/, "").replaceAll("_", " ");
/** The functions a program calls, or a lookup asks for, as words: "list devices, create device". */
function functionsOf({ input, arguments: json }) {
	const { typescriptCode, toolNames } = input ?? parsePartialJSON(json) ?? {};
	const called = typeof typescriptCode === "string" ? Array.from(typescriptCode.matchAll(/external_(\w+)/g), ([, name]) => name) : [];
	const asked = Array.isArray(toolNames) ? toolNames.filter((name) => typeof name === "string") : [];
	return [...new Set([...asked, ...called].map(words))].join(", ");
}
/** What a page tool acted on, for its line: the element clicked, the values filled, the key. */
function targetOf({ input }) {
	const { name, key, fields } = input ?? {};
	const target = name ?? key ?? fields?.map(({ value }) => value).join(", ") ?? "";
	return target.length > 60 ? `${target.slice(0, 59)}…` : target;
}
function activityOf({ name, state, output }, live) {
	const [writing, running, done] = activities[name] ?? [
		"UsingTool",
		"UsingTool",
		"UsedTool"
	];
	if (output !== void 0) return state === "error" ? "ToolStopped" : done;
	if (!live) return "ToolStopped";
	return state === "awaiting-input" || state === "input-streaming" ? writing : running;
}
/** A tool's line in words, e.g. "Running code… · list devices". */
const activityText = (t, part, live) => [t(`Layout.Chat.${activityOf(part, live)}`, {
	name: words(part.name),
	target: targetOf(part)
}), functionsOf(part)].filter(Boolean).join(" · ");
/** A tool without UI of its own, as one line: what it does while it runs, then what it did. */
function ToolActivity(t0) {
	const $ = c(9);
	const { part, live } = t0;
	const { t } = useTranslation();
	const running = live && part.output === void 0;
	let t1;
	if ($[0] !== running) {
		t1 = running ? shimmerSx : { color: "text.secondary" };
		$[0] = running;
		$[1] = t1;
	} else t1 = $[1];
	let t2;
	if ($[2] !== live || $[3] !== part || $[4] !== t) {
		t2 = activityText(t, part, live);
		$[2] = live;
		$[3] = part;
		$[4] = t;
		$[5] = t2;
	} else t2 = $[5];
	let t3;
	if ($[6] !== t1 || $[7] !== t2) {
		t3 = /* @__PURE__ */ jsx(Typography, {
			variant: "body2",
			className: statusClass,
			sx: t1,
			children: t2
		});
		$[6] = t1;
		$[7] = t2;
		$[8] = t3;
	} else t3 = $[8];
	return t3;
}
/** The name a document was attached under. */
const fileNameOf = (part) => part.type === "document" ? part.metadata?.filename ?? "document" : void 0;
const srcOf = ({ source }) => source.type === "data" ? `data:${source.mimeType};base64,${source.value}` : source.value;
function ChatMessage(t0) {
	const $ = c(12);
	const { message, live, canAnswer, addToolResult } = t0;
	if (message.role === "user") {
		let t1;
		if ($[0] !== message.parts) {
			const typed = message.parts.flatMap(_temp);
			const files = message.parts.filter(_temp2);
			let t2;
			if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
				t2 = {
					alignSelf: "flex-end",
					alignItems: "flex-end",
					maxWidth: "80%"
				};
				$[2] = t2;
			} else t2 = $[2];
			t1 = /* @__PURE__ */ jsxs(Stack, {
				spacing: 1,
				sx: t2,
				children: [files.length > 0 && /* @__PURE__ */ jsx(Stack, {
					direction: "row",
					sx: {
						flexWrap: "wrap",
						justifyContent: "flex-end",
						gap: .5
					},
					children: files.map(_temp3)
				}), typed.length > 0 && /* @__PURE__ */ jsx(Typography, {
					sx: {
						px: 2,
						py: 1.25,
						borderRadius: 4.5,
						bgcolor: "action.hover",
						whiteSpace: "pre-wrap",
						overflowWrap: "anywhere"
					},
					children: typed.join("\n")
				})]
			});
			$[0] = message.parts;
			$[1] = t1;
		} else t1 = $[1];
		return t1;
	}
	let t1;
	if ($[3] !== addToolResult || $[4] !== canAnswer || $[5] !== live || $[6] !== message.parts) {
		let t2;
		if ($[8] !== addToolResult || $[9] !== canAnswer || $[10] !== live) {
			t2 = (part_1, index_0) => {
				if (part_1.type === "text") return part_1.content ? /* @__PURE__ */ jsx(Box, {
					sx: markdownSx,
					children: /* @__PURE__ */ jsx(Markdown, {
						extensions: markdownExtensions,
						components: markdownComponents,
						children: part_1.content
					})
				}, index_0) : null;
				if (part_1.type !== "tool-call") return null;
				if ((part_1.name === "show_ui" || part_1.name === "ask_user") && part_1.state === "error") return null;
				if (part_1.name === "show_ui") return /* @__PURE__ */ jsx(GeneratedUi, { part: part_1 }, part_1.id);
				if (part_1.name === "ask_user") return /* @__PURE__ */ jsx(AskUser, {
					part: part_1,
					disabled: !canAnswer || part_1.output !== void 0,
					onAnswer: (output) => void addToolResult({
						toolCallId: part_1.id,
						tool: part_1.name,
						output
					})
				}, part_1.id);
				return /* @__PURE__ */ jsx(ToolActivity, {
					part: part_1,
					live
				}, part_1.id);
			};
			$[8] = addToolResult;
			$[9] = canAnswer;
			$[10] = live;
			$[11] = t2;
		} else t2 = $[11];
		t1 = message.parts.map(t2);
		$[3] = addToolResult;
		$[4] = canAnswer;
		$[5] = live;
		$[6] = message.parts;
		$[7] = t1;
	} else t1 = $[7];
	return t1;
}
function _temp3(part_0, index) {
	return part_0.type === "image" ? /* @__PURE__ */ jsx(Box, {
		component: "img",
		src: srcOf(part_0),
		alt: "Attached image",
		sx: {
			maxWidth: "100%",
			maxHeight: 160,
			borderRadius: 3
		}
	}, index) : /* @__PURE__ */ jsx(Chip, {
		variant: "outlined",
		label: fileNameOf(part_0)
	}, index);
}
function _temp2(t0) {
	const { type } = t0;
	return type === "image" || type === "document";
}
function _temp(part) {
	return part.type === "text" ? [part.content] : [];
}
/** Confirms a server tool marked `needsApproval`; the model has said what it is about to do. */
function Approvals(t0) {
	const $ = c(7);
	const { chat } = t0;
	const { t } = useTranslation();
	let t1;
	if ($[0] !== chat.interrupts || $[1] !== chat.resuming || $[2] !== t) {
		let t2;
		if ($[4] !== chat.resuming || $[5] !== t) {
			t2 = (interrupt) => interrupt.metadata?.kind === "approval" && interrupt.status === "pending" && "resolveInterrupt" in interrupt ? /* @__PURE__ */ jsx(Alert, {
				severity: "warning",
				action: /* @__PURE__ */ jsxs(Stack, {
					direction: "row",
					spacing: 1,
					children: [/* @__PURE__ */ jsx(Button, {
						color: "inherit",
						size: "small",
						disabled: chat.resuming,
						onClick: () => interrupt.resolveInterrupt(false),
						children: t("Layout.Dialog.Cancel")
					}), /* @__PURE__ */ jsx(Button, {
						color: "inherit",
						size: "small",
						disabled: chat.resuming,
						onClick: () => interrupt.resolveInterrupt(true),
						children: t("Layout.Dialog.Confirm")
					})]
				}),
				children: t("Layout.Chat.AreYouSure")
			}, interrupt.id) : null;
			$[4] = chat.resuming;
			$[5] = t;
			$[6] = t2;
		} else t2 = $[6];
		t1 = chat.interrupts.map(t2);
		$[0] = chat.interrupts;
		$[1] = chat.resuming;
		$[2] = t;
		$[3] = t1;
	} else t1 = $[3];
	return t1;
}
const roundButtonSx = {
	bgcolor: "text.primary",
	color: "background.paper",
	"&:hover": { bgcolor: "text.secondary" }
};
/** A message waiting for the reply to end, as one line: what was typed, or the files' names. */
function queuedText(queued) {
	const content = typeof queued === "string" ? queued : queued.content;
	if (typeof content === "string") return content;
	return content.flatMap((part) => part.type === "text" ? [part.content] : fileNameOf(part) ?? []).join(" · ") || "…";
}
function ChatInput(t0) {
	const $ = c(69);
	const { chat, files, setFiles, pick, onSend } = t0;
	const { t } = useTranslation();
	const { confirm } = useDialogs();
	const [draft, setDraft] = useState("");
	let t1;
	if ($[0] !== draft || $[1] !== files.length) {
		t1 = draft.trim() !== "" || files.length > 0;
		$[0] = draft;
		$[1] = files.length;
		$[2] = t1;
	} else t1 = $[2];
	const ready = t1;
	let t2;
	if ($[3] !== chat || $[4] !== draft || $[5] !== files || $[6] !== onSend || $[7] !== ready || $[8] !== setFiles) {
		t2 = (event) => {
			event.preventDefault();
			if (!ready) return;
			onSend();
			const parts = files.map(_temp4);
			if (draft.trim()) parts.push({
				type: "text",
				content: draft.trim()
			});
			chat.sendMessage(files.length ? { content: parts } : draft.trim());
			setDraft("");
			setFiles([]);
		};
		$[3] = chat;
		$[4] = draft;
		$[5] = files;
		$[6] = onSend;
		$[7] = ready;
		$[8] = setFiles;
		$[9] = t2;
	} else t2 = $[9];
	const send = t2;
	const sendOnEnter = _temp5;
	let t3;
	if ($[10] !== chat || $[11] !== confirm || $[12] !== t) {
		t3 = async () => {
			if (await confirm(t("Layout.Chat.NewChatConfirm"))) chat.clear();
		};
		$[10] = chat;
		$[11] = confirm;
		$[12] = t;
		$[13] = t3;
	} else t3 = $[13];
	const newChat = t3;
	let t4;
	if ($[14] !== chat) {
		t4 = chat.queue.map((t5) => {
			const { id, content } = t5;
			return /* @__PURE__ */ jsx(Chip, {
				variant: "outlined",
				label: queuedText(content),
				onDelete: () => chat.cancelQueued(id),
				sx: {
					alignSelf: "flex-end",
					maxWidth: "80%"
				}
			}, id);
		});
		$[14] = chat;
		$[15] = t4;
	} else t4 = $[15];
	let t5;
	if ($[16] === Symbol.for("react.memo_cache_sentinel")) {
		t5 = {
			p: 1,
			borderRadius: 7,
			boxShadow: 2
		};
		$[16] = t5;
	} else t5 = $[16];
	let t6;
	if ($[17] !== files || $[18] !== setFiles) {
		t6 = files.length > 0 && /* @__PURE__ */ jsx(Stack, {
			direction: "row",
			sx: {
				flexWrap: "wrap",
				gap: .5,
				px: 1,
				pb: 1
			},
			children: files.map((t7, index) => {
				const { name, part: part_0 } = t7;
				return /* @__PURE__ */ jsx(Chip, {
					size: "small",
					label: name,
					avatar: part_0.type === "image" ? /* @__PURE__ */ jsx(Avatar, {
						variant: "rounded",
						src: srcOf(part_0),
						alt: ""
					}) : void 0,
					onDelete: () => setFiles(files.filter((_, at) => at !== index))
				}, index);
			})
		});
		$[17] = files;
		$[18] = setFiles;
		$[19] = t6;
	} else t6 = $[19];
	let t7;
	if ($[20] === Symbol.for("react.memo_cache_sentinel")) {
		t7 = { alignItems: "flex-end" };
		$[20] = t7;
	} else t7 = $[20];
	let t8;
	if ($[21] !== t) {
		t8 = t("Layout.Chat.NewChat");
		$[21] = t;
		$[22] = t8;
	} else t8 = $[22];
	let t9;
	if ($[23] !== newChat) {
		t9 = () => void newChat();
		$[23] = newChat;
		$[24] = t9;
	} else t9 = $[24];
	const t10 = !chat.messages.length;
	let t11;
	if ($[25] === Symbol.for("react.memo_cache_sentinel")) {
		t11 = /* @__PURE__ */ jsx(Add, {});
		$[25] = t11;
	} else t11 = $[25];
	let t12;
	if ($[26] !== t10 || $[27] !== t9) {
		t12 = /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsx(IconButton, {
			"aria-label": "New chat",
			onClick: t9,
			disabled: t10,
			children: t11
		}) });
		$[26] = t10;
		$[27] = t9;
		$[28] = t12;
	} else t12 = $[28];
	let t13;
	if ($[29] !== t12 || $[30] !== t8) {
		t13 = /* @__PURE__ */ jsx(Tooltip, {
			title: t8,
			children: t12
		});
		$[29] = t12;
		$[30] = t8;
		$[31] = t13;
	} else t13 = $[31];
	let t14;
	if ($[32] !== t) {
		t14 = t("Layout.Chat.Attach");
		$[32] = t;
		$[33] = t14;
	} else t14 = $[33];
	let t15;
	if ($[34] === Symbol.for("react.memo_cache_sentinel")) {
		t15 = /* @__PURE__ */ jsx(AttachFile, {});
		$[34] = t15;
	} else t15 = $[34];
	let t16;
	if ($[35] !== pick) {
		t16 = /* @__PURE__ */ jsx(IconButton, {
			"aria-label": "Attach files",
			onClick: pick,
			children: t15
		});
		$[35] = pick;
		$[36] = t16;
	} else t16 = $[36];
	let t17;
	if ($[37] !== t14 || $[38] !== t16) {
		t17 = /* @__PURE__ */ jsx(Tooltip, {
			title: t14,
			children: t16
		});
		$[37] = t14;
		$[38] = t16;
		$[39] = t17;
	} else t17 = $[39];
	let t18;
	if ($[40] === Symbol.for("react.memo_cache_sentinel")) {
		t18 = (event_1) => setDraft(event_1.target.value);
		$[40] = t18;
	} else t18 = $[40];
	let t19;
	if ($[41] !== t) {
		t19 = t("Layout.Chat.Message");
		$[41] = t;
		$[42] = t19;
	} else t19 = $[42];
	let t20;
	let t21;
	if ($[43] === Symbol.for("react.memo_cache_sentinel")) {
		t20 = { input: { "aria-label": "Ask anything" } };
		t21 = {
			flex: 1,
			py: 1,
			pl: .5
		};
		$[43] = t20;
		$[44] = t21;
	} else {
		t20 = $[43];
		t21 = $[44];
	}
	let t22;
	if ($[45] !== draft || $[46] !== t19) {
		t22 = /* @__PURE__ */ jsx(InputBase, {
			value: draft,
			onChange: t18,
			placeholder: t19,
			multiline: true,
			maxRows: 8,
			slotProps: t20,
			sx: t21
		});
		$[45] = draft;
		$[46] = t19;
		$[47] = t22;
	} else t22 = $[47];
	let t23;
	if ($[48] !== chat.isLoading || $[49] !== chat.stop || $[50] !== t) {
		t23 = chat.isLoading && /* @__PURE__ */ jsx(Tooltip, {
			title: t("Layout.Chat.Stop"),
			children: /* @__PURE__ */ jsx(IconButton, {
				"aria-label": "Stop",
				onClick: chat.stop,
				sx: roundButtonSx,
				children: /* @__PURE__ */ jsx(Stop, {})
			})
		});
		$[48] = chat.isLoading;
		$[49] = chat.stop;
		$[50] = t;
		$[51] = t23;
	} else t23 = $[51];
	let t24;
	if ($[52] !== chat.isLoading || $[53] !== ready || $[54] !== t) {
		t24 = (!chat.isLoading || ready) && /* @__PURE__ */ jsx(Tooltip, {
			title: t("Layout.Chat.Send"),
			children: /* @__PURE__ */ jsx(IconButton, {
				"aria-label": "Send",
				type: "submit",
				sx: roundButtonSx,
				children: /* @__PURE__ */ jsx(ArrowUpward, {})
			})
		});
		$[52] = chat.isLoading;
		$[53] = ready;
		$[54] = t;
		$[55] = t24;
	} else t24 = $[55];
	let t25;
	if ($[56] !== t13 || $[57] !== t17 || $[58] !== t22 || $[59] !== t23 || $[60] !== t24) {
		t25 = /* @__PURE__ */ jsxs(Stack, {
			direction: "row",
			spacing: .5,
			sx: t7,
			children: [
				t13,
				t17,
				t22,
				t23,
				t24
			]
		});
		$[56] = t13;
		$[57] = t17;
		$[58] = t22;
		$[59] = t23;
		$[60] = t24;
		$[61] = t25;
	} else t25 = $[61];
	let t26;
	if ($[62] !== send || $[63] !== t25 || $[64] !== t6) {
		t26 = /* @__PURE__ */ jsxs(Paper, {
			component: "form",
			variant: "outlined",
			onSubmit: send,
			onKeyDown: sendOnEnter,
			sx: t5,
			children: [t6, t25]
		});
		$[62] = send;
		$[63] = t25;
		$[64] = t6;
		$[65] = t26;
	} else t26 = $[65];
	let t27;
	if ($[66] !== t26 || $[67] !== t4) {
		t27 = /* @__PURE__ */ jsxs(Stack, {
			spacing: 1,
			children: [t4, t26]
		});
		$[66] = t26;
		$[67] = t4;
		$[68] = t27;
	} else t27 = $[68];
	return t27;
}
function _temp5(event_0) {
	if (event_0.key !== "Enter" || event_0.shiftKey || event_0.nativeEvent.isComposing) return;
	if (!(event_0.target instanceof HTMLTextAreaElement)) return;
	event_0.preventDefault();
	event_0.currentTarget.requestSubmit();
}
function _temp4(t0) {
	const { part } = t0;
	return part;
}
/** The chat screen. Give it a parent with a height (e.g. `Fullscreen`). */
function ChatLayout({ chat, sx }) {
	const { t } = useTranslation();
	const { alert } = useDialogs();
	const { ref, following } = useFollowContent();
	const [files, setFiles] = useState([]);
	const last = chat.messages.at(-1);
	const attach = async (added) => {
		for (const file of added) try {
			const part = await fileToPart(file);
			setFiles((current) => [...current, {
				name: file.name,
				part
			}]);
		} catch {
			await alert(t("Layout.Chat.FileNotRead", { name: file.name }));
		}
	};
	const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
		noClick: true,
		noKeyboard: true,
		onDrop: (dropped) => void attach(dropped)
	});
	const live = chat.isLoading || chat.interrupts.some(({ status }) => status === "pending");
	const runningTool = live ? last?.parts.findLast((part) => part.type === "tool-call" && part.output === void 0 && part.name !== "show_ui" && part.name !== "ask_user") : void 0;
	const status = isReasoning(chat) ? t("Layout.Chat.Reasoning") : runningTool ? activityText(t, runningTool, true) : "";
	return /* @__PURE__ */ jsxs(Box, {
		...getRootProps({ className: "LayoutChat-root" }),
		sx: [{
			position: "relative",
			display: "flex",
			flexDirection: "column",
			flex: 1,
			minHeight: 0,
			height: "100%"
		}, ...Array.isArray(sx) ? sx : [sx]],
		children: [
			/* @__PURE__ */ jsx("input", { ...getInputProps() }),
			/* @__PURE__ */ jsx(Box, {
				ref,
				sx: {
					flex: 1,
					minHeight: 0,
					overflowY: "auto"
				},
				children: /* @__PURE__ */ jsxs(Stack, {
					spacing: 2.5,
					sx: {
						...columnSx,
						py: 3,
						[`& > .${statusClass} + .${statusClass}`]: { mt: .5 }
					},
					children: [
						chat.messages.map((message) => /* @__PURE__ */ jsx(ChatMessage, {
							message,
							live: live && message === last,
							canAnswer: !chat.isLoading && message === last,
							addToolResult: chat.addToolResult
						}, message.id)),
						/* @__PURE__ */ jsx(Approvals, { chat }),
						isReasoning(chat) && /* @__PURE__ */ jsx(Reasoning, {}),
						chat.error && /* @__PURE__ */ jsx(Alert, {
							severity: "error",
							action: /* @__PURE__ */ jsx(Tooltip, {
								title: t("Layout.Chat.Regenerate"),
								children: /* @__PURE__ */ jsx(IconButton, {
									"aria-label": "Regenerate",
									color: "inherit",
									size: "small",
									onClick: () => void chat.reload(),
									children: /* @__PURE__ */ jsx(Refresh, { fontSize: "small" })
								})
							}),
							children: chat.error.message
						})
					]
				})
			}),
			/* @__PURE__ */ jsx(Box, {
				sx: {
					...columnSx,
					pb: 2
				},
				children: /* @__PURE__ */ jsx(ChatInput, {
					chat,
					files,
					setFiles,
					pick: open,
					onSend: () => following.current = true
				})
			}),
			isDragActive && /* @__PURE__ */ jsx(Box, {
				sx: {
					position: "absolute",
					inset: 8,
					zIndex: 2,
					display: "flex",
					alignItems: "center",
					justifyContent: "center",
					border: 2,
					borderStyle: "dashed",
					borderColor: "primary.main",
					borderRadius: 4,
					bgcolor: "background.paper",
					opacity: .92,
					pointerEvents: "none"
				},
				children: /* @__PURE__ */ jsx(Typography, {
					color: "primary",
					children: t("Layout.Chat.DropFiles")
				})
			}),
			/* @__PURE__ */ jsx(Box, {
				role: "status",
				sx: visuallyHidden,
				children: status
			})
		]
	});
}
export { tableContext as C, RouterLink as D, useTableContext as E, useDialogs as O, layoutTableFeatures as S, useHeaderContext as T, toClipboardText as _, cellSelectionSx as a, cellContext as b, columnFlex as c, layoutTableClasses as d, lookaheadRange as f, shortcutLabel as g, pinnedSx as h, formatValue as i, columnLabel as l, pinnedClass as m, createUiTools as n, classNames as o, moveColumn as p, AggregatedCell as r, columnAlign as s, ChatLayout as t, hasColumnLabel as u, DEFAULT_PAGE_SIZE_OPTIONS as v, useCellContext as w, headerContext as x, Pagination as y };

//# sourceMappingURL=ChatLayout-CkS9oyPp.mjs.map