# @implements: [F-052] — Clarify-UX Emoji Buttons # @implements: [F-054] — Clarify-UX max 3/Reihe Chunking (2-Reihen-Pattern) # @implements: [F-557] — Emoji-Number Fallback: _is_numeric_choice Helper """ Gemeinsamer Button-Builder für Onboarding und Review-Flow. Extrahiert aus onboarding_review.py (P0-1), damit adapter.py und onboarding_review.py die GLEICHE Button-Konstruktion nutzen — kein Drift. Regeln: - Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣... - Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer, IMMER in separatem (letztem) Attachment - Jedes Attachment hat max 3 actions """ import hashlib import re from typing import Any, List, Optional, Tuple # Emoji-Nummern für bis zu 10 Buttons EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] # F-557: Inverse-Mapping — Emoji-Nummer → 1-basierter Index. # Die ersten 9 sind "Ziffer + U+FE0F + U+20E3" (3 Codepoints), "🔟" (U+1F51F) # ist ein EINZELNER Codepoint ohne ASCII-Ziffer. Deshalb ein explizites Mapping # statt String-Index-Arithmetik. Zusätzlich die Kompaktform ohne # Variation-Selector ("1⃣" = U+0031 U+20E3), die manche Clients senden. _EMOJI_TO_NUM: dict = {e: i + 1 for i, e in enumerate(EMOJI_NUMBERS)} _EMOJI_TO_NUM.update({f"{d}\u20e3": d for d in range(1, 10)}) # F-557: Oberes Limit — EMOJI_NUMBERS deckt 1..10 ab. Höhere Zahlen sind # out-of-range (bei Clarify mit >10 Optionen ohnehin ein UX-Problem). _MAX_CHOICE = len(EMOJI_NUMBERS) # 10 def _is_numeric_choice(text: Optional[str]) -> Optional[int]: """Extrahiert eine 1-basierte Wahl aus ``text`` oder ``None`` (F-557). Symmetrisch zu ``EMOJI_NUMBERS``: der Helper ist die Inverse der Emoji-Nummer-Generierung. Erkennt sowohl die Button-Varianten (Emoji-Keycap) als auch die Plain-Text-Fallbacks, die User in nicht-interactiven Clients (Mobile-App, Frame/Blockquote-Rendering) tippen, wenn Interactive Buttons nicht klickbar sind (P-047). Akzeptiert (Leading/Trailing-Whitespace tolerant): - "1", "2", ..., "9", "10" (rein numerisch) - "1️⃣", "2️⃣", ..., "🔟" (Emoji-Nummern, inkl. Kompaktform) - "1.", "9." (mit Punkt) - "1)", "1.)" (mit Klammer) - "1 Rüber" (führende Ziffer + Text) - "Option 1" (Wort + Zahl) Liefert ``None`` (keine Wahl): - "" / "abc" / "0" (leer, nicht-numerisch, nicht 1-basiert) - "11" (out-of-range, > EMOJI_NUMBERS-Cap) - "1 und 2", "1, 2", "1 oder 2" (Multi-Wahl — bewusst NICHT unterstützt, siehe Architektur F557 §3.3) Args: text: Die (bereits quote-gestrippte) Eingabe des Users. Returns: 1-basierter Index (1..10) oder ``None`` wenn keine eindeutige Wahl. """ if text is None: return None s = text.strip() if not s: return None # 1) Exakter Emoji-Keycap ("1️⃣" … "🔟") oder Kompaktform ("1⃣" … "9⃣"). if s in _EMOJI_TO_NUM: return _EMOJI_TO_NUM[s] # 2) "Option N" — Wort am Anfang, Zahl am Ende. m = re.match(r"^option\s+(\d{1,2})\s*$", s, re.IGNORECASE) if m: num = int(m.group(1)) return num if 1 <= num <= _MAX_CHOICE else None # 3) Führende Ziffer ("1", "1.", "1)", "1 rüber", "1 und 2"). m = re.match(r"^(\d{1,2})", s) if not m: return None num = int(m.group(1)) if not (1 <= num <= _MAX_CHOICE): return None rest = s[m.end():].strip() # "1." / "1)" / "1.)" — nur Satzzeichen-Suffix → Einzelwahl. if rest in ("", ".", ")", ".)"): return num # Multi-Wahl: Rest beginnt mit Konjunktion + Zahl oder direkt mit Zahl. if re.match(r"^(?:und|oder|and|or|,|;|\+|&)\s*\d", rest, re.IGNORECASE) or rest[0].isdigit(): return None # Sonst: führende Ziffer mit Text ("1 rüber") → Einzelwahl. return num def _make_action_id(msg_payload: str, index: int = 0) -> str: """Deterministische action_id aus msg-Payload (SHA1, 12 Zeichen). Rocket.Chat 6.x benötigt zwingend ein action_id-Feld im Button-Dict, sonst wird das gesamte actions-Array ignoriert (P-051). """ raw = f"{msg_payload}:{index}".encode() return hashlib.sha1(raw).hexdigest()[:12] def build_button_attachments( num_buttons: List[Tuple[Any, ...]], special_buttons: List[Tuple[Any, ...]], color: str = "#1d74f5", title: str = "", number_buttons: bool = True, button_style: str = "primary", ) -> List[dict]: """Baut Attachments nach Andreas' 2-Reihen-Button-Pattern. Regeln: - Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣... (Nummerierung kann via number_buttons=False deaktiviert werden) - Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer, IMMER in separatem (letztem) Attachment - Jedes Attachment hat max 3 actions P0-Fix: msg-Payload mit '::' Suffix für Button-Klick-Erkennung. num_buttons: (label, prefix) oder (label, prefix, suffix) special_buttons: (label, prefix, style) oder (label, prefix, style, suffix) Wenn suffix vorhanden: msg = f'{prefix}::{suffix}' Sonst (backward-compat): msg = prefix Args: num_buttons: Liste von (label, prefix[, suffix]) Tuples special_buttons: Liste von (label, prefix, style[, suffix]) Tuples color: Attachment-Farbe (default: "#1d74f5") title: Attachment-Titel (nur für erstes Attachment) number_buttons: Wenn False, werden Buttons NICHT nummeriert (z.B. für X-Buttons in Keywords-Edit) button_style: Rocket.Chat button style für num_buttons (default: "primary") Returns: Liste von Attachment-Dicts (jedes mit max 3 actions) """ attachments: List[dict] = [] # Nummerierte Buttons in 3er-Blöcke aufteilen for i in range(0, len(num_buttons), 3): chunk = num_buttons[i:i + 3] actions = [] for j, tup in enumerate(chunk): label = tup[0] prefix = tup[1] suffix = tup[2] if len(tup) >= 3 else None msg_payload = f"{prefix}::{suffix}" if suffix else prefix if number_buttons: num_idx = i + j emoji = EMOJI_NUMBERS[num_idx] if num_idx < len(EMOJI_NUMBERS) else str(num_idx + 1) text = f"{emoji} {label}" else: text = label actions.append({ "type": "button", "text": text, "msg": msg_payload, "msg_in_chat_window": True, "style": button_style, "action_id": _make_action_id(msg_payload, i + j), }) att = { "color": color, "actions": actions, } if i == 0 and title: att["title"] = title attachments.append(att) # Sonderschaltflächen in separatem Attachment if special_buttons: special_actions = [] for s_idx, tup in enumerate(special_buttons): label = tup[0] prefix = tup[1] style = tup[2] suffix = tup[3] if len(tup) >= 4 else None msg_payload = f"{prefix}::{suffix}" if suffix else prefix special_actions.append({ "type": "button", "text": label, "msg": msg_payload, "msg_in_chat_window": True, "style": style, "action_id": _make_action_id(msg_payload, s_idx), }) attachments.append({ "color": color, "actions": special_actions, }) return attachments