@partrunner-ai/ui 2.2.4 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6343,6 +6343,765 @@ function PresetOption({
6343
6343
  );
6344
6344
  }
6345
6345
 
6346
+ // src/commentText.ts
6347
+ var TOKEN_RE = /<@(u|a):([0-9A-Za-z_-]+)>/g;
6348
+ function parseCommentBody(body, mentions = []) {
6349
+ const names = new Map(mentions.map((m) => [`${m.kind}:${m.id.toLowerCase()}`, m.name]));
6350
+ const segments = [];
6351
+ let last = 0;
6352
+ for (const match of body.matchAll(TOKEN_RE)) {
6353
+ const index = match.index ?? 0;
6354
+ if (index > last) segments.push({ type: "text", text: body.slice(last, index) });
6355
+ const kind = match[1] === "u" ? "user" : "agent";
6356
+ const id = match[2] ?? "";
6357
+ const name = names.get(`${kind}:${id.toLowerCase()}`) ?? (kind === "agent" ? id : "alguien");
6358
+ segments.push({ type: "mention", kind, id, name });
6359
+ last = index + match[0].length;
6360
+ }
6361
+ if (last < body.length) segments.push({ type: "text", text: body.slice(last) });
6362
+ return segments;
6363
+ }
6364
+ function commentPlainText(body, mentions = []) {
6365
+ return parseCommentBody(body, mentions).map((s) => s.type === "text" ? s.text : `@${s.name}`).join("");
6366
+ }
6367
+ function serializeCommentDraft(text, picked) {
6368
+ const unique = /* @__PURE__ */ new Map();
6369
+ for (const m of picked) unique.set(`${m.kind}:${m.id}`, m);
6370
+ const ordered = [...unique.values()].sort((a, b) => b.name.length - a.name.length);
6371
+ if (ordered.length === 0) return text;
6372
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6373
+ const pattern = new RegExp(`@(${ordered.map((m) => escape(m.name)).join("|")})(?![\\p{L}\\p{N}_])`, "gu");
6374
+ const byName = new Map(ordered.map((m) => [m.name, m]));
6375
+ return text.replace(pattern, (whole, name) => {
6376
+ const m = byName.get(name);
6377
+ if (!m) return whole;
6378
+ return m.kind === "user" ? `<@u:${m.id}>` : `<@a:${m.id}>`;
6379
+ });
6380
+ }
6381
+ function commentDraftFromBody(body, mentions = []) {
6382
+ const picked = [];
6383
+ const text = parseCommentBody(body, mentions).map((s) => {
6384
+ if (s.type === "text") return s.text;
6385
+ picked.push({ kind: s.kind, id: s.id, name: s.name });
6386
+ return `@${s.name}`;
6387
+ }).join("");
6388
+ return { text, picked };
6389
+ }
6390
+ function activeMentionQuery(text, caret) {
6391
+ const before = text.slice(0, caret);
6392
+ const at = before.lastIndexOf("@");
6393
+ if (at < 0) return null;
6394
+ if (at > 0 && !/\s/.test(before[at - 1] ?? "")) return null;
6395
+ const query = before.slice(at + 1);
6396
+ if (query.length > 40 || /[\n@]/.test(query) || /\s{2}/.test(query)) return null;
6397
+ return { start: at, query };
6398
+ }
6399
+ function mergeCommentMessages(current, changes) {
6400
+ if (changes.length === 0) return current;
6401
+ const byId = new Map(current.map((m) => [m.id, m]));
6402
+ for (const m of changes) byId.set(m.id, m);
6403
+ return [...byId.values()].sort(
6404
+ (a, b) => a.createdAt === b.createdAt ? a.id.localeCompare(b.id) : a.createdAt < b.createdAt ? -1 : 1
6405
+ );
6406
+ }
6407
+ var cx = (...parts) => parts.filter(Boolean).join(" ");
6408
+ var QUICK_REACTIONS = ["\u{1F44D}", "\u2764\uFE0F", "\u{1F602}", "\u{1F62E}", "\u{1F64F}", "\u2705", "\u{1F440}", "\u{1F525}"];
6409
+ var MAX_FILES = 10;
6410
+ var timeFormat = new Intl.DateTimeFormat("es-MX", { hour: "2-digit", minute: "2-digit" });
6411
+ var dayFormat = new Intl.DateTimeFormat("es-MX", { weekday: "long", day: "numeric", month: "long" });
6412
+ function dayKey(iso) {
6413
+ const d = new Date(iso);
6414
+ return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
6415
+ }
6416
+ function dayLabel(iso) {
6417
+ const d = new Date(iso);
6418
+ const today = /* @__PURE__ */ new Date();
6419
+ const yesterday = new Date(today);
6420
+ yesterday.setDate(today.getDate() - 1);
6421
+ if (dayKey(iso) === dayKey(today.toISOString())) return "Hoy";
6422
+ if (dayKey(iso) === dayKey(yesterday.toISOString())) return "Ayer";
6423
+ const label = dayFormat.format(d);
6424
+ return label.charAt(0).toUpperCase() + label.slice(1);
6425
+ }
6426
+ function fileSize(bytes) {
6427
+ if (bytes < 1024) return `${bytes} B`;
6428
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
6429
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
6430
+ }
6431
+ var isInlineImage = (mime) => ["image/jpeg", "image/png", "image/webp", "image/gif"].includes(mime);
6432
+ function MessageBody({ message }) {
6433
+ const segments = react.useMemo(() => parseCommentBody(message.body, message.mentions), [message.body, message.mentions]);
6434
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__text", children: segments.map(
6435
+ (s, i) => s.type === "text" ? /* @__PURE__ */ jsxRuntime.jsx(react.Fragment, { children: s.text }, i) : /* @__PURE__ */ jsxRuntime.jsxs("span", { className: cx("pr-comments__mention", s.kind === "agent" && "pr-comments__mention--agent"), children: [
6436
+ "@",
6437
+ s.name
6438
+ ] }, i)
6439
+ ) });
6440
+ }
6441
+ function Attachments({
6442
+ attachments,
6443
+ attachmentHref
6444
+ }) {
6445
+ if (attachments.length === 0) return null;
6446
+ const images = attachments.filter((a) => isInlineImage(a.mimeType));
6447
+ const files = attachments.filter((a) => !isInlineImage(a.mimeType));
6448
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__attachments", children: [
6449
+ images.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__images", children: images.map((a) => /* @__PURE__ */ jsxRuntime.jsx("a", { href: attachmentHref(a.id), target: "_blank", rel: "noreferrer", className: "pr-comments__image", children: /* @__PURE__ */ jsxRuntime.jsx(
6450
+ "img",
6451
+ {
6452
+ src: attachmentHref(a.id),
6453
+ alt: a.fileName,
6454
+ loading: "lazy",
6455
+ width: a.width ?? void 0,
6456
+ height: a.height ?? void 0
6457
+ }
6458
+ ) }, a.id)) }),
6459
+ files.map((a) => /* @__PURE__ */ jsxRuntime.jsxs("a", { href: attachmentHref(a.id, { download: true }), className: "pr-comments__file", download: a.fileName, children: [
6460
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { size: 16, "aria-hidden": true }),
6461
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__file-name", children: a.fileName }),
6462
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__file-size", children: fileSize(a.sizeBytes) })
6463
+ ] }, a.id))
6464
+ ] });
6465
+ }
6466
+ function MessageRow({
6467
+ message,
6468
+ own,
6469
+ canWrite,
6470
+ highlighted,
6471
+ attachmentHref,
6472
+ onReply,
6473
+ onJumpTo,
6474
+ onReact,
6475
+ onEdit,
6476
+ onDelete
6477
+ }) {
6478
+ const [picker, setPicker] = react.useState(false);
6479
+ const [editing, setEditing] = react.useState(null);
6480
+ const [confirmDelete, setConfirmDelete] = react.useState(false);
6481
+ const [busy, setBusy] = react.useState(false);
6482
+ const isAgent = message.author.kind === "agent";
6483
+ const writing = isAgent && (message.status === "pending" || message.status === "streaming");
6484
+ const canAct = canWrite && !message.deleted && message.status === "sent";
6485
+ const saveEdit = async () => {
6486
+ if (!editing || !onEdit) return;
6487
+ setBusy(true);
6488
+ try {
6489
+ await onEdit(message.id, serializeCommentDraft(editing.text, editing.picked));
6490
+ setEditing(null);
6491
+ } finally {
6492
+ setBusy(false);
6493
+ }
6494
+ };
6495
+ const remove = async () => {
6496
+ if (!onDelete) return;
6497
+ setBusy(true);
6498
+ try {
6499
+ await onDelete(message.id);
6500
+ } finally {
6501
+ setBusy(false);
6502
+ setConfirmDelete(false);
6503
+ }
6504
+ };
6505
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6506
+ "li",
6507
+ {
6508
+ id: `pr-comment-${message.id}`,
6509
+ className: cx("pr-comments__row", own && "pr-comments__row--own", highlighted && "pr-comments__row--highlight"),
6510
+ children: [
6511
+ !own && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__avatar", children: isAgent ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__agent-avatar", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Bot, { size: 16 }) }) : /* @__PURE__ */ jsxRuntime.jsx(Avatar, { name: message.author.name, src: message.author.avatarUrl ?? void 0, size: "sm", decorative: true }) }),
6512
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__bubble-wrap", children: [
6513
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cx("pr-comments__bubble", isAgent && "pr-comments__bubble--agent"), children: [
6514
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__meta", children: [
6515
+ !own && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__author", children: message.author.name }),
6516
+ isAgent && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__badge", children: "IA" }),
6517
+ /* @__PURE__ */ jsxRuntime.jsx("time", { className: "pr-comments__time", dateTime: message.createdAt, children: timeFormat.format(new Date(message.createdAt)) }),
6518
+ message.editedAt && !message.deleted && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__edited", children: "editado" })
6519
+ ] }),
6520
+ message.replyTo && /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", className: "pr-comments__quote", onClick: () => onJumpTo(message.replyTo.id), children: [
6521
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__quote-author", children: message.replyTo.authorName }),
6522
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__quote-text", children: message.replyTo.deleted ? "Mensaje eliminado" : message.replyTo.excerpt || (message.replyTo.hasAttachments ? "Archivo" : "") })
6523
+ ] }),
6524
+ message.deleted ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__text pr-comments__text--deleted", children: "Mensaje eliminado" }) : editing ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__edit", children: [
6525
+ /* @__PURE__ */ jsxRuntime.jsx(
6526
+ "textarea",
6527
+ {
6528
+ className: "pr-comments__edit-input",
6529
+ value: editing.text,
6530
+ "aria-label": "Editar mensaje",
6531
+ autoFocus: true,
6532
+ rows: 3,
6533
+ onChange: (e) => setEditing({ ...editing, text: e.target.value }),
6534
+ onKeyDown: (e) => {
6535
+ if (e.key === "Escape") setEditing(null);
6536
+ if (e.key === "Enter" && !e.shiftKey) {
6537
+ e.preventDefault();
6538
+ void saveEdit();
6539
+ }
6540
+ }
6541
+ }
6542
+ ),
6543
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__edit-actions", children: [
6544
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pr-comments__link", onClick: () => setEditing(null), disabled: busy, children: "Cancelar" }),
6545
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pr-comments__link pr-comments__link--strong", onClick: saveEdit, disabled: busy, children: "Guardar" })
6546
+ ] })
6547
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
6548
+ message.body && /* @__PURE__ */ jsxRuntime.jsx(MessageBody, { message }),
6549
+ writing && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pr-comments__typing", "aria-label": "Escribiendo", children: [
6550
+ /* @__PURE__ */ jsxRuntime.jsx("span", {}),
6551
+ /* @__PURE__ */ jsxRuntime.jsx("span", {}),
6552
+ /* @__PURE__ */ jsxRuntime.jsx("span", {})
6553
+ ] }),
6554
+ isAgent && message.status === "failed" && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__failed", children: "No se pudo completar la respuesta." }),
6555
+ /* @__PURE__ */ jsxRuntime.jsx(Attachments, { attachments: message.attachments, attachmentHref })
6556
+ ] })
6557
+ ] }),
6558
+ !message.deleted && message.reactions.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__reactions", children: message.reactions.map((r) => /* @__PURE__ */ jsxRuntime.jsxs(
6559
+ "button",
6560
+ {
6561
+ type: "button",
6562
+ className: cx("pr-comments__reaction", r.mine && "pr-comments__reaction--mine"),
6563
+ "aria-pressed": r.mine,
6564
+ title: r.names.join(", "),
6565
+ disabled: !canWrite || !onReact,
6566
+ onClick: () => onReact?.(message.id, r.emoji, !r.mine),
6567
+ children: [
6568
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "aria-hidden": true, children: r.emoji }),
6569
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__reaction-count", children: r.count })
6570
+ ]
6571
+ },
6572
+ r.emoji
6573
+ )) }),
6574
+ confirmDelete && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__confirm", role: "group", "aria-label": "Confirmar borrado", children: [
6575
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xBFBorrar este mensaje?" }),
6576
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pr-comments__link", onClick: () => setConfirmDelete(false), disabled: busy, children: "No" }),
6577
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pr-comments__link pr-comments__link--danger", onClick: remove, disabled: busy, children: "S\xED, borrar" })
6578
+ ] }),
6579
+ picker && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__picker", role: "group", "aria-label": "Reaccionar", children: QUICK_REACTIONS.map((emoji) => /* @__PURE__ */ jsxRuntime.jsx(
6580
+ "button",
6581
+ {
6582
+ type: "button",
6583
+ className: "pr-comments__picker-item",
6584
+ "aria-label": `Reaccionar con ${emoji}`,
6585
+ onClick: () => {
6586
+ const mine = message.reactions.find((r) => r.emoji === emoji)?.mine ?? false;
6587
+ void onReact?.(message.id, emoji, !mine);
6588
+ setPicker(false);
6589
+ },
6590
+ children: emoji
6591
+ },
6592
+ emoji
6593
+ )) })
6594
+ ] }),
6595
+ canAct && !editing && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__actions", children: [
6596
+ /* @__PURE__ */ jsxRuntime.jsx(IconButton, { size: "sm", compact: true, variant: "ghost", label: "Responder", icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CornerUpLeft, { size: 14 }), onClick: () => onReply(message) }),
6597
+ onReact && /* @__PURE__ */ jsxRuntime.jsx(
6598
+ IconButton,
6599
+ {
6600
+ size: "sm",
6601
+ compact: true,
6602
+ variant: "ghost",
6603
+ label: "Reaccionar",
6604
+ icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.SmilePlus, { size: 14 }),
6605
+ "aria-expanded": picker,
6606
+ onClick: () => setPicker((v) => !v)
6607
+ }
6608
+ ),
6609
+ own && onEdit && message.author.kind === "user" && /* @__PURE__ */ jsxRuntime.jsx(
6610
+ IconButton,
6611
+ {
6612
+ size: "sm",
6613
+ compact: true,
6614
+ variant: "ghost",
6615
+ label: "Editar",
6616
+ icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { size: 14 }),
6617
+ onClick: () => setEditing(commentDraftFromBody(message.body, message.mentions))
6618
+ }
6619
+ ),
6620
+ own && onDelete && message.author.kind === "user" && /* @__PURE__ */ jsxRuntime.jsx(IconButton, { size: "sm", compact: true, variant: "ghost", label: "Borrar", icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Trash2, { size: 14 }), onClick: () => setConfirmDelete(true) })
6621
+ ] })
6622
+ ]
6623
+ }
6624
+ );
6625
+ }
6626
+ function Composer({
6627
+ replyTo,
6628
+ onCancelReply,
6629
+ onSend,
6630
+ onSearchMentions,
6631
+ onUpload,
6632
+ placeholder,
6633
+ droppedFiles,
6634
+ onDroppedFilesTaken,
6635
+ inputRef
6636
+ }) {
6637
+ const [text, setText] = react.useState("");
6638
+ const [picked, setPicked] = react.useState([]);
6639
+ const [files, setFiles] = react.useState([]);
6640
+ const [sending, setSending] = react.useState(false);
6641
+ const [sendError, setSendError] = react.useState(null);
6642
+ const [mention, setMention] = react.useState(null);
6643
+ const [candidates, setCandidates] = react.useState([]);
6644
+ const [active, setActive] = react.useState(0);
6645
+ const fileInput = react.useRef(null);
6646
+ const listId = react.useId();
6647
+ const seq = react.useRef(0);
6648
+ react.useEffect(() => {
6649
+ if (!mention || !onSearchMentions) {
6650
+ setCandidates([]);
6651
+ return;
6652
+ }
6653
+ const ticket = ++seq.current;
6654
+ const timer = setTimeout(() => {
6655
+ onSearchMentions(mention.query).then((found) => {
6656
+ if (ticket === seq.current) {
6657
+ setCandidates(found.slice(0, 8));
6658
+ setActive(0);
6659
+ }
6660
+ }).catch(() => {
6661
+ if (ticket === seq.current) setCandidates([]);
6662
+ });
6663
+ }, 150);
6664
+ return () => clearTimeout(timer);
6665
+ }, [mention, onSearchMentions]);
6666
+ const addFiles = react.useCallback(
6667
+ (list) => {
6668
+ if (!onUpload || list.length === 0) return;
6669
+ const room = MAX_FILES - files.length;
6670
+ for (const file of list.slice(0, Math.max(room, 0))) {
6671
+ const localId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
6672
+ setFiles((prev) => [...prev, { localId, fileName: file.name, status: "uploading" }]);
6673
+ onUpload(file).then(
6674
+ (attachment) => setFiles((prev) => prev.map((f) => f.localId === localId ? { ...f, status: "done", attachment } : f))
6675
+ ).catch(
6676
+ (err) => setFiles(
6677
+ (prev) => prev.map(
6678
+ (f) => f.localId === localId ? { ...f, status: "error", error: err instanceof Error ? err.message : "No se pudo subir" } : f
6679
+ )
6680
+ )
6681
+ );
6682
+ }
6683
+ },
6684
+ [files.length, onUpload]
6685
+ );
6686
+ react.useEffect(() => {
6687
+ if (droppedFiles.length > 0) {
6688
+ addFiles(droppedFiles);
6689
+ onDroppedFilesTaken();
6690
+ }
6691
+ }, [droppedFiles, addFiles, onDroppedFilesTaken]);
6692
+ const pendingCaret = react.useRef(null);
6693
+ react.useLayoutEffect(() => {
6694
+ const el = inputRef.current;
6695
+ if (!el) return;
6696
+ el.style.height = "auto";
6697
+ el.style.height = `${Math.min(el.scrollHeight, 180)}px`;
6698
+ if (pendingCaret.current !== null) {
6699
+ const pos = pendingCaret.current;
6700
+ pendingCaret.current = null;
6701
+ el.focus();
6702
+ el.setSelectionRange(pos, pos);
6703
+ }
6704
+ }, [text, inputRef]);
6705
+ const updateText = (value, caret) => {
6706
+ setText(value);
6707
+ setSendError(null);
6708
+ setMention(onSearchMentions ? activeMentionQuery(value, caret) : null);
6709
+ };
6710
+ const choose = (candidate) => {
6711
+ if (!mention) return;
6712
+ const el = inputRef.current;
6713
+ const caret = el?.selectionStart ?? text.length;
6714
+ const inserted = `@${candidate.name} `;
6715
+ const next = text.slice(0, mention.start) + inserted + text.slice(caret);
6716
+ setText(next);
6717
+ setPicked((prev) => [...prev, { kind: candidate.kind, id: candidate.id, name: candidate.name }]);
6718
+ setMention(null);
6719
+ pendingCaret.current = mention.start + inserted.length;
6720
+ };
6721
+ const uploading = files.some((f) => f.status === "uploading");
6722
+ const ready = files.filter((f) => f.status === "done" && f.attachment);
6723
+ const canSend = !sending && !uploading && (text.trim().length > 0 || ready.length > 0);
6724
+ const send = async () => {
6725
+ if (!canSend) return;
6726
+ setSending(true);
6727
+ setSendError(null);
6728
+ try {
6729
+ await onSend({
6730
+ body: serializeCommentDraft(text.trim(), picked),
6731
+ replyTo: replyTo?.id ?? null,
6732
+ attachmentIds: ready.map((f) => f.attachment.id)
6733
+ });
6734
+ setText("");
6735
+ setPicked([]);
6736
+ setFiles([]);
6737
+ onCancelReply();
6738
+ } catch (err) {
6739
+ setSendError(err instanceof Error ? err.message : "No se pudo enviar el mensaje.");
6740
+ } finally {
6741
+ setSending(false);
6742
+ }
6743
+ };
6744
+ const onKeyDown = (e) => {
6745
+ if (mention && candidates.length > 0) {
6746
+ if (e.key === "ArrowDown") {
6747
+ e.preventDefault();
6748
+ setActive((i) => (i + 1) % candidates.length);
6749
+ return;
6750
+ }
6751
+ if (e.key === "ArrowUp") {
6752
+ e.preventDefault();
6753
+ setActive((i) => (i - 1 + candidates.length) % candidates.length);
6754
+ return;
6755
+ }
6756
+ if (e.key === "Enter" || e.key === "Tab") {
6757
+ e.preventDefault();
6758
+ const candidate = candidates[active];
6759
+ if (candidate) choose(candidate);
6760
+ return;
6761
+ }
6762
+ if (e.key === "Escape") {
6763
+ e.preventDefault();
6764
+ setMention(null);
6765
+ return;
6766
+ }
6767
+ }
6768
+ if (e.key === "Escape" && replyTo) onCancelReply();
6769
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
6770
+ e.preventDefault();
6771
+ void send();
6772
+ }
6773
+ };
6774
+ const onPaste = (e) => {
6775
+ const pasted = Array.from(e.clipboardData.files);
6776
+ if (pasted.length > 0 && onUpload) {
6777
+ e.preventDefault();
6778
+ addFiles(pasted);
6779
+ }
6780
+ };
6781
+ const showSuggestions = mention !== null && candidates.length > 0;
6782
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__composer", children: [
6783
+ replyTo && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__replying", children: [
6784
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__replying-text", children: [
6785
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "pr-comments__quote-author", children: [
6786
+ "Respondiendo a ",
6787
+ replyTo.author.name
6788
+ ] }),
6789
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__quote-text", children: commentPlainText(replyTo.body, replyTo.mentions) || (replyTo.attachments.length > 0 ? "Archivo" : "") })
6790
+ ] }),
6791
+ /* @__PURE__ */ jsxRuntime.jsx(IconButton, { size: "sm", compact: true, variant: "ghost", label: "Cancelar respuesta", icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { size: 14 }), onClick: onCancelReply })
6792
+ ] }),
6793
+ files.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "pr-comments__pending", children: files.map((f) => /* @__PURE__ */ jsxRuntime.jsxs("li", { className: cx("pr-comments__pending-file", f.status === "error" && "pr-comments__pending-file--error"), children: [
6794
+ f.status === "uploading" ? /* @__PURE__ */ jsxRuntime.jsx(Spinner, { size: "sm" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { size: 14, "aria-hidden": true }),
6795
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__file-name", title: f.error ?? f.fileName, children: f.status === "error" ? `${f.fileName}: ${f.error}` : f.fileName }),
6796
+ /* @__PURE__ */ jsxRuntime.jsx(
6797
+ IconButton,
6798
+ {
6799
+ size: "sm",
6800
+ compact: true,
6801
+ variant: "ghost",
6802
+ label: `Quitar ${f.fileName}`,
6803
+ icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { size: 12 }),
6804
+ onClick: () => setFiles((prev) => prev.filter((p) => p.localId !== f.localId))
6805
+ }
6806
+ )
6807
+ ] }, f.localId)) }),
6808
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__input-row", children: [
6809
+ onUpload && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
6810
+ /* @__PURE__ */ jsxRuntime.jsx(
6811
+ IconButton,
6812
+ {
6813
+ size: "sm",
6814
+ variant: "ghost",
6815
+ label: "Adjuntar archivos",
6816
+ icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Paperclip, { size: 16 }),
6817
+ disabled: files.length >= MAX_FILES,
6818
+ onClick: () => fileInput.current?.click()
6819
+ }
6820
+ ),
6821
+ /* @__PURE__ */ jsxRuntime.jsx(
6822
+ "input",
6823
+ {
6824
+ ref: fileInput,
6825
+ type: "file",
6826
+ multiple: true,
6827
+ hidden: true,
6828
+ accept: "image/*,.pdf,.xlsx,.xls,.docx,.doc,.csv,.txt",
6829
+ onChange: (e) => {
6830
+ addFiles(Array.from(e.target.files ?? []));
6831
+ e.target.value = "";
6832
+ }
6833
+ }
6834
+ )
6835
+ ] }),
6836
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-comments__input-wrap", children: [
6837
+ /* @__PURE__ */ jsxRuntime.jsx(
6838
+ "textarea",
6839
+ {
6840
+ ref: inputRef,
6841
+ className: "pr-comments__input",
6842
+ rows: 1,
6843
+ value: text,
6844
+ placeholder,
6845
+ "aria-label": "Escribe un comentario",
6846
+ role: "combobox",
6847
+ "aria-expanded": showSuggestions,
6848
+ "aria-controls": showSuggestions ? listId : void 0,
6849
+ "aria-autocomplete": "list",
6850
+ "aria-activedescendant": showSuggestions ? `${listId}-${active}` : void 0,
6851
+ onChange: (e) => updateText(e.target.value, e.target.selectionStart),
6852
+ onKeyDown,
6853
+ onPaste,
6854
+ onBlur: () => setTimeout(() => setMention(null), 150)
6855
+ }
6856
+ ),
6857
+ showSuggestions && /* @__PURE__ */ jsxRuntime.jsx("ul", { id: listId, role: "listbox", className: "pr-comments__suggestions", children: candidates.map((c, i) => /* @__PURE__ */ jsxRuntime.jsxs(
6858
+ "li",
6859
+ {
6860
+ id: `${listId}-${i}`,
6861
+ role: "option",
6862
+ "aria-selected": i === active,
6863
+ className: cx("pr-comments__suggestion", i === active && "pr-comments__suggestion--active"),
6864
+ onMouseDown: (e) => {
6865
+ e.preventDefault();
6866
+ choose(c);
6867
+ },
6868
+ children: [
6869
+ c.kind === "agent" ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__agent-avatar", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Bot, { size: 14 }) }) : /* @__PURE__ */ jsxRuntime.jsx(Avatar, { name: c.name, src: c.avatarUrl ?? void 0, size: "xs", decorative: true }),
6870
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__suggestion-name", children: c.name }),
6871
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "pr-comments__suggestion-hint", children: c.kind === "agent" ? c.description ?? "Agente IA" : c.email })
6872
+ ]
6873
+ },
6874
+ `${c.kind}:${c.id}`
6875
+ )) })
6876
+ ] }),
6877
+ /* @__PURE__ */ jsxRuntime.jsx(
6878
+ IconButton,
6879
+ {
6880
+ size: "sm",
6881
+ variant: "primary",
6882
+ label: "Enviar",
6883
+ icon: sending ? /* @__PURE__ */ jsxRuntime.jsx(Spinner, { size: "sm", tone: "inherit" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.SendHorizontal, { size: 16 }),
6884
+ disabled: !canSend,
6885
+ onClick: send
6886
+ }
6887
+ )
6888
+ ] }),
6889
+ sendError && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__error", role: "alert", children: sendError })
6890
+ ] });
6891
+ }
6892
+ var FOLLOW_LABEL = {
6893
+ none: "Seguir",
6894
+ following: "Siguiendo",
6895
+ muted: "Silenciado"
6896
+ };
6897
+ function CommentThread({
6898
+ messages,
6899
+ viewerId,
6900
+ canWrite,
6901
+ loading = false,
6902
+ error = null,
6903
+ hasMore = false,
6904
+ loadingOlder = false,
6905
+ onLoadOlder,
6906
+ lastReadAt = null,
6907
+ follow,
6908
+ onFollowChange,
6909
+ attachmentHref,
6910
+ onSend,
6911
+ onEdit,
6912
+ onDelete,
6913
+ onReact,
6914
+ onSearchMentions,
6915
+ onUpload,
6916
+ title = "Comentarios",
6917
+ emptyText = "Todav\xEDa no hay comentarios. Escribe el primero; con @ etiquetas a alguien.",
6918
+ placeholder = "Escribe un comentario\u2026 usa @ para etiquetar",
6919
+ className
6920
+ }) {
6921
+ const listRef = react.useRef(null);
6922
+ const inputRef = react.useRef(null);
6923
+ const [replyTo, setReplyTo] = react.useState(null);
6924
+ const [highlight, setHighlight] = react.useState(null);
6925
+ const [dragging, setDragging] = react.useState(false);
6926
+ const [dropped, setDropped] = react.useState([]);
6927
+ const nearBottom = react.useRef(true);
6928
+ const lastId = messages[messages.length - 1]?.id;
6929
+ const firstId = messages[0]?.id;
6930
+ const prevFirst = react.useRef(void 0);
6931
+ const prevHeight = react.useRef(0);
6932
+ react.useLayoutEffect(() => {
6933
+ const el = listRef.current;
6934
+ if (!el) return;
6935
+ if (prevFirst.current && firstId !== prevFirst.current && prevHeight.current) {
6936
+ el.scrollTop += el.scrollHeight - prevHeight.current;
6937
+ } else if (nearBottom.current) {
6938
+ el.scrollTop = el.scrollHeight;
6939
+ }
6940
+ prevFirst.current = firstId;
6941
+ prevHeight.current = el.scrollHeight;
6942
+ }, [firstId, lastId, messages]);
6943
+ const firstUnread = react.useMemo(() => {
6944
+ if (!lastReadAt) return null;
6945
+ return messages.find((m) => m.createdAt > lastReadAt && m.author.userId !== viewerId && !m.deleted)?.id ?? null;
6946
+ }, [lastReadAt, firstId]);
6947
+ const jumpTo = (id) => {
6948
+ const target = document.getElementById(`pr-comment-${id}`);
6949
+ if (!target) return;
6950
+ target.scrollIntoView({ block: "center", behavior: "smooth" });
6951
+ setHighlight(id);
6952
+ setTimeout(() => setHighlight((h) => h === id ? null : h), 1600);
6953
+ };
6954
+ const reply = (message) => {
6955
+ setReplyTo(message);
6956
+ inputRef.current?.focus();
6957
+ };
6958
+ const dropProps = canWrite && onUpload ? {
6959
+ onDragOver: (e) => {
6960
+ if (Array.from(e.dataTransfer.types).includes("Files")) {
6961
+ e.preventDefault();
6962
+ setDragging(true);
6963
+ }
6964
+ },
6965
+ onDragLeave: (e) => {
6966
+ if (e.currentTarget === e.target) setDragging(false);
6967
+ },
6968
+ onDrop: (e) => {
6969
+ e.preventDefault();
6970
+ setDragging(false);
6971
+ setDropped(Array.from(e.dataTransfer.files));
6972
+ }
6973
+ } : {};
6974
+ let lastDay = "";
6975
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx("pr-comments", dragging && "pr-comments--dragging", className), "aria-label": "Comentarios", ...dropProps, children: [
6976
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: "pr-comments__header", children: [
6977
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "pr-comments__title", children: title }),
6978
+ onFollowChange && follow && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__follow", role: "group", "aria-label": "Avisos de esta conversaci\xF3n", children: ["following", "none", "muted"].map((state) => /* @__PURE__ */ jsxRuntime.jsxs(
6979
+ "button",
6980
+ {
6981
+ type: "button",
6982
+ className: cx("pr-comments__follow-option", follow === state && "pr-comments__follow-option--active"),
6983
+ "aria-pressed": follow === state,
6984
+ title: state === "following" ? "Te avisamos de cada mensaje nuevo" : state === "muted" ? "S\xF3lo te avisamos si te etiquetan" : "Te avisamos si te etiquetan; al etiquetarte empiezas a seguirla",
6985
+ onClick: () => follow !== state && onFollowChange(state),
6986
+ children: [
6987
+ state === "following" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.BellRing, { size: 14, "aria-hidden": true }) : state === "muted" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.BellOff, { size: 14, "aria-hidden": true }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Bell, { size: 14, "aria-hidden": true }),
6988
+ FOLLOW_LABEL[state]
6989
+ ]
6990
+ },
6991
+ state
6992
+ )) })
6993
+ ] }),
6994
+ /* @__PURE__ */ jsxRuntime.jsxs(
6995
+ "div",
6996
+ {
6997
+ ref: listRef,
6998
+ className: "pr-comments__list",
6999
+ onScroll: (e) => {
7000
+ const el = e.currentTarget;
7001
+ nearBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
7002
+ },
7003
+ children: [
7004
+ hasMore && onLoadOlder && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__older", children: /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", className: "pr-comments__link", onClick: onLoadOlder, disabled: loadingOlder, children: loadingOlder ? "Cargando\u2026" : "Ver mensajes anteriores" }) }),
7005
+ loading && messages.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pr-comments__empty", children: /* @__PURE__ */ jsxRuntime.jsx(Spinner, { size: "md" }) }) : messages.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__empty", children: emptyText }) : /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "pr-comments__messages", children: messages.map((m) => {
7006
+ const day = dayKey(m.createdAt);
7007
+ const showDay = day !== lastDay;
7008
+ lastDay = day;
7009
+ const own = m.author.kind === "user" && viewerId !== null && m.author.userId === viewerId;
7010
+ return /* @__PURE__ */ jsxRuntime.jsxs(react.Fragment, { children: [
7011
+ showDay && /* @__PURE__ */ jsxRuntime.jsx("li", { className: "pr-comments__day", "aria-hidden": true, children: /* @__PURE__ */ jsxRuntime.jsx("span", { children: dayLabel(m.createdAt) }) }),
7012
+ m.id === firstUnread && /* @__PURE__ */ jsxRuntime.jsx("li", { className: "pr-comments__unread", children: /* @__PURE__ */ jsxRuntime.jsx("span", { children: "Nuevos" }) }),
7013
+ /* @__PURE__ */ jsxRuntime.jsx(
7014
+ MessageRow,
7015
+ {
7016
+ message: m,
7017
+ own,
7018
+ canWrite,
7019
+ highlighted: highlight === m.id,
7020
+ attachmentHref,
7021
+ onReply: reply,
7022
+ onJumpTo: jumpTo,
7023
+ onReact,
7024
+ onEdit,
7025
+ onDelete
7026
+ }
7027
+ )
7028
+ ] }, m.id);
7029
+ }) })
7030
+ ]
7031
+ }
7032
+ ),
7033
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__error", role: "alert", children: error }),
7034
+ canWrite ? /* @__PURE__ */ jsxRuntime.jsx(
7035
+ Composer,
7036
+ {
7037
+ replyTo,
7038
+ onCancelReply: () => setReplyTo(null),
7039
+ onSend,
7040
+ onSearchMentions,
7041
+ onUpload,
7042
+ placeholder,
7043
+ droppedFiles: dropped,
7044
+ onDroppedFilesTaken: () => setDropped([]),
7045
+ inputRef
7046
+ }
7047
+ ) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pr-comments__readonly", children: "Puedes leer estos comentarios, pero no tienes permiso para escribir." })
7048
+ ] });
7049
+ }
7050
+
7051
+ // src/commentImage.ts
7052
+ var RESIZABLE = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
7053
+ var MAX_SIDE = 2560;
7054
+ var SHRINK_ABOVE_BYTES = 1.5 * 1024 * 1024;
7055
+ function loadImage(file) {
7056
+ return new Promise((resolve, reject) => {
7057
+ const url = URL.createObjectURL(file);
7058
+ const img = new Image();
7059
+ img.onload = () => {
7060
+ URL.revokeObjectURL(url);
7061
+ resolve(img);
7062
+ };
7063
+ img.onerror = () => {
7064
+ URL.revokeObjectURL(url);
7065
+ reject(new Error("image_decode_failed"));
7066
+ };
7067
+ img.src = url;
7068
+ });
7069
+ }
7070
+ async function prepareCommentFile(file) {
7071
+ if (!RESIZABLE.has(file.type) || typeof document === "undefined") {
7072
+ return { file, width: null, height: null };
7073
+ }
7074
+ let img;
7075
+ try {
7076
+ img = await loadImage(file);
7077
+ } catch {
7078
+ return { file, width: null, height: null };
7079
+ }
7080
+ const width = img.naturalWidth;
7081
+ const height = img.naturalHeight;
7082
+ const longSide = Math.max(width, height);
7083
+ if (file.size <= SHRINK_ABOVE_BYTES && longSide <= MAX_SIDE) {
7084
+ return { file, width, height };
7085
+ }
7086
+ const scale = Math.min(1, MAX_SIDE / longSide);
7087
+ const canvas = document.createElement("canvas");
7088
+ canvas.width = Math.round(width * scale);
7089
+ canvas.height = Math.round(height * scale);
7090
+ const ctx = canvas.getContext("2d");
7091
+ if (!ctx) return { file, width, height };
7092
+ ctx.fillStyle = "#ffffff";
7093
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
7094
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
7095
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.85));
7096
+ if (!blob || blob.size >= file.size) return { file, width, height };
7097
+ const name = file.name.replace(/\.[^.]+$/, "") + ".jpg";
7098
+ return {
7099
+ file: new File([blob], name, { type: "image/jpeg", lastModified: file.lastModified }),
7100
+ width: canvas.width,
7101
+ height: canvas.height
7102
+ };
7103
+ }
7104
+
6346
7105
  exports.AlertDialogAction = AlertDialogAction;
6347
7106
  exports.AlertDialogCancel = AlertDialogCancel;
6348
7107
  exports.AlertDialogContent = AlertDialogContent;
@@ -6366,6 +7125,7 @@ exports.CardTitle = CardTitle;
6366
7125
  exports.Checkbox = Checkbox;
6367
7126
  exports.CheckboxGroup = CheckboxGroup;
6368
7127
  exports.Combobox = Combobox;
7128
+ exports.CommentThread = CommentThread;
6369
7129
  exports.ConfirmDialog = ConfirmDialog;
6370
7130
  exports.CopyField = CopyField;
6371
7131
  exports.DataTable = DataTable;
@@ -6469,17 +7229,24 @@ exports.ToolbarGroup = ToolbarGroup;
6469
7229
  exports.ToolbarSpacer = ToolbarSpacer;
6470
7230
  exports.Tooltip = Tooltip;
6471
7231
  exports.ValidationSummary = ValidationSummary;
7232
+ exports.activeMentionQuery = activeMentionQuery;
6472
7233
  exports.avatarInitials = avatarInitials;
7234
+ exports.commentDraftFromBody = commentDraftFromBody;
7235
+ exports.commentPlainText = commentPlainText;
6473
7236
  exports.formatCalendarDate = formatCalendarDate;
6474
7237
  exports.formatDateRange = formatDateRange;
6475
7238
  exports.isCalendarDate = isCalendarDate;
6476
7239
  exports.isSameDateRange = isSameDateRange;
6477
7240
  exports.isValidDateRange = isValidDateRange;
6478
7241
  exports.menuStyle = menuStyle;
7242
+ exports.mergeCommentMessages = mergeCommentMessages;
6479
7243
  exports.parseCalendarDate = parseCalendarDate;
7244
+ exports.parseCommentBody = parseCommentBody;
7245
+ exports.prepareCommentFile = prepareCommentFile;
6480
7246
  exports.registerDialogLayerPortal = registerDialogLayerPortal;
6481
7247
  exports.resolveActiveNavigationHref = resolveActiveNavigationHref;
6482
7248
  exports.serializeCalendarDate = serializeCalendarDate;
7249
+ exports.serializeCommentDraft = serializeCommentDraft;
6483
7250
  exports.toneFromString = toneFromString;
6484
7251
  exports.useAnchoredMenu = useAnchoredMenu;
6485
7252
  //# sourceMappingURL=index.cjs.map