diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..48c615d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,68 @@ +# 界面约定 + +适用于本仓库的 Android / Compose 界面。 + +## 少用弹窗,能开界面就开界面 + +用户明确要求:**尽量减少弹窗那种,能加界面就加界面。** + +理由(也是判断标准): + +- **弹窗装不下东西**。一屏对话框的高度大概只够三四行内容,一旦要放的 + 东西超过这个量(列表、代码框、多组配置),用户就得在弹窗里滚动 —— + 那还不如直接开一屏。 +- **弹窗会互相压**。弹窗里再弹一个(比如"变量管理"里点"新建", + 或者"节点管理"里点"编辑")在手机上是灾难:返回键的行为变得说不清, + 用户也不知道自己在第几层。 +- **弹窗盖住上下文**。这个 App 的会议画布本身就是要看着的, + 一个盖住半屏的对话框让人没法一边看图一边改配置。 + +### 该怎么做 + +| 内容量 | 用什么 | +|---|---| +| 一次确认("要删除吗") | `AlertDialog` ✓ 弹窗合适 | +| 纯菜单(两三个入口,点完就走) | 底部弹层或 `AlertDialog` ✓ | +| 列表 / 多组配置 / 代码 / 任何要滚动的 | **独立全屏界面**,顶栏 `← 返回` + 标题 + 右侧动作 | + +### 全屏界面的骨架 + +统一用同一套顶栏,别各写各的(不然返回的位置、标题的大小、 +右边按钮的样式会到处不一样): + +``` +← 返回 标题 副标题 [动作] +──────────────────────────────────────────── +(内容,可滚动) +``` + +参考实现:`NodeBlockEditorScreen`(`NodeBlockEditor.kt`)的顶栏。 + +### 返回键 + +全屏界面要能被系统返回键关掉(用状态变量控制显示时, +记得在 `onBack` 里把它置空),否则用户按返回会直接退出会议编辑器 —— +比弹窗还糟。 + +## 已经欠着的(按这个原则该改还没改的) + +- [ ] 节点管理 `NodeManagerDialog` → 全屏 +- [ ] 节点编辑 `NodeEditDialog` → 全屏(代码编辑要有整屏) +- [ ] 变量管理 `VarManagerDialog` → 全屏 +- [ ] 加节点面板(现在是个 `AlertDialog`)→ 全屏或底部弹层 +- [ ] 导入会议 `ImportDialog` → 全屏 +- [ ] 节点配置 `NodeConfigDialog` → 全屏(字段很多) + +**保留弹窗的**:删除确认、`EditorMenuDialog`(它就是个菜单)。 + +## 其他界面约定(踩过坑的) + +- **引擎加了、界面必须跟上**。已经反复出现"引擎有 `cast`/`op`、界面选不到" + 这类问题。每加一种能力,检查这几处:meta 列表、引脚、配色、标题、 + 预览文字、配置面板、选择器。 +- **同一段逻辑只能有一份**。运行入口有两个(顶栏 ▶ 和底部「运行」), + 事件处理抄了两份,结果加功能时只改了一份 —— 现在统一走 + `applyMeetingEvent`。 +- **能用真实形状表达就用**。积木编程里形状是语法 + (帽子 = 事件、C 型 = 容器、六边形 = 真假值), + 全画成圆角矩形等于把语法藏起来了。 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/BlockShapes.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/BlockShapes.kt new file mode 100644 index 0000000..494aba6 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/BlockShapes.kt @@ -0,0 +1,311 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.RoundRect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathOperation +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/* + * 积木的**形状**(编程猫 / Scratch 那一套)。 + * + * 为什么形状这件事必须做对: + * 在积木编程里,形状不是装饰 —— 它是**语法**。 + * · 圆顶帽子 = 事件入口,只能待在最上面 + * · 底部凸起 + 顶部凹槽 = 能上下咬合,表示"接着做" + * · C 型的嘴巴 = 这里面的是"被包住"的,不是平级的 + * · 六边形 = 这是个真假值,只能塞进条件槽 + * · 椭圆 = 这是个值,只能塞进参数槽 + * 全是圆角矩形的话,用户看不出"这块能不能塞进那里", + * 只能靠颜色猜 —— 那就退回成"写代码"了。 + * + * 所以这里用 Canvas 手画路径:圆顶、凹凸、嘴巴。 + */ + +/** 积木的形状种类 */ +enum class BlkShape { + /** 圆顶帽子:事件入口 */ + Hat, + + /** 普通语句:上面凹槽、下面凸起 */ + Stack, + + /** C 型:右边开口,能包住别的积木 */ + C, + + /** C 型的收尾(嘴巴下面的那条横杠) */ + CFoot, +} + +private const val NOTCH_W = 20f // 凹凸的宽度 +private const val NOTCH_H = 5f // 凹凸的高度 +private const val RADIUS = 12f // 圆角 + +/** + * 画一块积木的底。 + * + * 全部用 Path 手画:Scratch 的积木形状没有现成的组件, + * 而且凹槽/嘴巴这些是"减法"(从矩形上挖掉一块), + * 用 PathOperation.Difference 最直观。 + */ +private fun buildBlockPath(w: Float, h: Float, shape: BlkShape): Path { + val base = Path().apply { + addRoundRect( + RoundRect( + rect = Rect(0f, 0f, w, h), + cornerRadius = CornerRadius(RADIUS, RADIUS), + ), + ) + } + + when (shape) { + BlkShape.Hat -> { + // 圆顶:在顶部加一个半圆 + val dome = Path().apply { + addOval( + Rect( + w * 0.08f, -h * 0.30f, + w * 0.08f + h * 0.62f, h * 0.32f, + ), + ) + } + base.op(base, dome, PathOperation.Union) + } + + BlkShape.Stack -> { + // 上面挖一个凹槽 + val topNotch = Path().apply { + addRoundRect( + RoundRect( + rect = Rect(w * 0.10f, -1f, w * 0.10f + NOTCH_W, NOTCH_H), + cornerRadius = CornerRadius(3f, 3f), + ), + ) + } + // 下面凸一块 + val bottomBump = Path().apply { + addRoundRect( + RoundRect( + rect = Rect(w * 0.10f, h - NOTCH_H, w * 0.10f + NOTCH_W, h + 1f), + cornerRadius = CornerRadius(3f, 3f), + ), + ) + } + base.op(base, topNotch, PathOperation.Difference) + base.op(base, bottomBump, PathOperation.Union) + } + + BlkShape.C -> { + // 上面凹槽、底下不封口(由 CFoot 收尾) + val topNotch = Path().apply { + addRoundRect( + RoundRect( + rect = Rect(w * 0.10f, -1f, w * 0.10f + NOTCH_W, NOTCH_H), + cornerRadius = CornerRadius(3f, 3f), + ), + ) + } + base.op(base, topNotch, PathOperation.Difference) + } + + BlkShape.CFoot -> { + // 收尾横条:上面凹槽 + 下面凸起(和 Stack 一样,但矮) + } + } + return base +} + +/** + * 一块积木的底 + 内容。 + * + * content 画在形状之上(文字、参数槽都塞在里面)。 + */ +@Composable +fun BlockSurface( + shape: BlkShape, + color: Color, + modifier: Modifier = Modifier, + height: androidx.compose.ui.unit.Dp = 40.dp, + content: @Composable () -> Unit, +) { + Box(modifier) { + Canvas( + Modifier + .fillMaxWidth() + .height(height + 10.dp) + .padding(top = 5.dp), + ) { + val w = size.width + val h = size.height - NOTCH_H + val path = buildBlockPath(w, h, shape) + // 底下垫一层暗色,做出"厚度"(Scratch 积木的立体感就靠这个) + val shadow = buildBlockPath(w, h, shape) + drawPath(shadow, color = color.copy(alpha = 0.45f), style = Stroke(width = 6f)) + drawPath(path, color = color) + } + Box( + Modifier + .fillMaxWidth() + .height(height) + .padding(top = 5.dp, start = 12.dp, end = 10.dp), + contentAlignment = Alignment.CenterStart, + ) { content() } + } +} + +/** 布尔槽:六边形(表示"这里要的是真假") */ +@Composable +fun BooleanSlot(value: String, onClick: () -> Unit) { + Box( + Modifier + .clip(RoundedCornerShape(2.dp)) + .clickable { onClick() } + .padding(horizontal = 2.dp, vertical = 1.dp), + ) { + Canvas(Modifier.fillMaxWidth().height(24.dp)) { + val w = size.width + val h = size.height + val cut = h * 0.42f + val p = Path().apply { + moveTo(cut, 0f) + lineTo(w - cut, 0f) + lineTo(w, h / 2f) + lineTo(w - cut, h) + lineTo(cut, h) + lineTo(0f, h / 2f) + close() + } + drawPath(p, color = Color.White) + drawPath(p, color = Color(0xFF9AA0A6), style = Stroke(width = 2f)) + } + Text( + value, + fontSize = 11.sp, + color = Color(0xFF333333), + modifier = Modifier.align(Alignment.Center).padding(horizontal = 14.dp), + ) + } +} + +/** 参数槽:圆角胶囊(表示"这里要的是一个值") */ +@Composable +fun ValueSlot( + value: String, + placeholder: String, + onValue: (String) -> Unit, +) { + var editing by remember { mutableStateOf(false) } + if (editing) { + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = value, + onValueChange = onValue, + modifier = Modifier.widthIn(min = 70.dp).height(38.dp), + textStyle = TextStyle(fontSize = 11.sp), + singleLine = true, + ) + Text( + "✓", + fontSize = 13.sp, + color = Color.White, + modifier = Modifier + .padding(start = 2.dp) + .clip(RoundedCornerShape(5.dp)) + .background(Color.White.copy(alpha = 0.28f)) + .clickable { editing = false } + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + } else { + Box( + Modifier + .clip(RoundedCornerShape(50)) + .background(Color.White) + .clickable { editing = true } + .padding(horizontal = 10.dp, vertical = 3.dp), + ) { + Text( + value.ifBlank { placeholder }, + fontSize = 11.sp, + color = if (value.isBlank()) Color(0xFF9AA0A6) else Color(0xFF333333), + ) + } + } +} + +/** 下拉槽(编程猫里那种 [点击] [a] 的小方块) */ +@Composable +fun DropdownSlot(value: String, options: List, onPick: (String) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + Box( + Modifier + .clip(RoundedCornerShape(5.dp)) + .background(Color.White) + .clickable { open = !open } + .padding(horizontal = 8.dp, vertical = 3.dp), + ) { + Text("$value ▾", fontSize = 11.sp, color = Color(0xFF333333)) + } + if (open) { + Column( + Modifier + .padding(top = 24.dp) + .clip(RoundedCornerShape(7.dp)) + .background(Color.White) + .heightIn(max = 150.dp) + .verticalScroll(rememberScrollState()), + ) { + options.forEach { o -> + Text( + o, + fontSize = 11.sp, + color = Color(0xFF333333), + modifier = Modifier + .clickable { onPick(o); open = false } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) + } + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt index 95d43cd..f7e5873 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsCustomNodes.kt @@ -2,25 +2,23 @@ package com.doubao.lynxclone.ui import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -34,191 +32,17 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp -import com.doubao.lynxclone.data.CustomNodeDef /* - * 自定义节点的管理 / 编辑界面。 + * 自定义节点的**管理界面**和**代码编辑界面**。 * - * ★ 为什么单独一个文件: - * MeetingsScreen.kt 已经 3800 行了,往里塞东西的每一次都要重新理解上下文, - * 而且改错了很难看出来(这一轮已经因为漏一个花括号排查了很久)。 - * "节点"本身是一个独立的东西,界面也单独放。 + * 从弹窗改成了全屏 —— 见 AGENTS.md。 + * 这两个界面本来就装不下:管理界面是一个会长的列表, + * 编辑界面要放代码框 + 补全 + 积木入口。 */ -/** 一个节点文件的列表项(来自 GET /api/meeting/nodes) */ -data class NodeFile( - val file: String = "", - val ok: Boolean = true, - val error: String = "", - val label: String = "", - val desc: String = "", - val inputs: List> = emptyList(), - val outputs: List> = emptyList(), -) - -/** - * 节点管理:列出 nodes/ 里的全部文件,能导入 / 编辑 / 导出 / 删除。 - * - * ★ 为什么要有这个界面: - * 原来只能 adb push 一个文件进去 —— 那不叫能用。 - * 用户要的是"我在手机上就能加一种节点、改它、把它发给别人"。 - */ -@Composable -fun NodeManagerDialog( - nodes: List, - dir: String, - message: String, - onImport: () -> Unit, - onEdit: (NodeFile) -> Unit, - onExport: (NodeFile) -> Unit, - onDelete: (NodeFile) -> Unit, - onNew: () -> Unit, - onDismiss: () -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("自定义节点", fontSize = 16.sp) }, - text = { - Column( - Modifier - .fillMaxWidth() - .heightIn(max = 460.dp) - .verticalScroll(rememberScrollState()), - ) { - Text( - "往这个目录放 .py 就多一种节点,界面上的引脚是从文件里读的:\n$dir", - fontSize = 11.sp, - color = doubaoTextSecondary(), - lineHeight = 15.sp, - ) - Spacer(Modifier.height(10.dp)) - Row { - Text( - "+ 新建", - color = Doubao.Blue, - fontSize = 13.sp, - fontWeight = FontWeight.Medium, - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .clickable { onNew() } - .padding(horizontal = 10.dp, vertical = 6.dp), - ) - Spacer(Modifier.width(4.dp)) - Text( - "📥 导入文件", - color = Doubao.Blue, - fontSize = 13.sp, - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .clickable { onImport() } - .padding(horizontal = 10.dp, vertical = 6.dp), - ) - } - if (message.isNotBlank()) { - Spacer(Modifier.height(4.dp)) - Text( - message, - fontSize = 11.sp, - color = if (message.startsWith("已导入")) Color(0xFF34A853) - else MaterialTheme.colorScheme.error, - lineHeight = 15.sp, - ) - } - Spacer(Modifier.height(8.dp)) - HorizontalDivider(thickness = 0.5.dp) - Spacer(Modifier.height(8.dp)) - - if (nodes.isEmpty()) { - Text( - "还没有自定义节点。点「新建」写一个,或者导入别人给你的 .py。", - fontSize = 12.sp, - color = doubaoTextSecondary(), - lineHeight = 17.sp, - ) - } - nodes.forEach { n -> - Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - (if (n.ok) "🐍 " else "⚠ ") + n.label.ifBlank { n.file }, - fontSize = 14.sp, - color = if (n.ok) doubaoText() else MaterialTheme.colorScheme.error, - ) - Spacer(Modifier.width(6.dp)) - Text(n.file, fontSize = 10.sp, color = doubaoTextSecondary()) - } - Spacer(Modifier.height(2.dp)) - Text( - if (!n.ok) n.error - else n.desc.ifBlank { - "入 ${n.inputs.size} · 出 ${n.outputs.size}" - }, - fontSize = 11.sp, - color = if (n.ok) doubaoTextSecondary() - else MaterialTheme.colorScheme.error, - lineHeight = 15.sp, - ) - Spacer(Modifier.height(4.dp)) - Row { - NodeAction("编辑") { onEdit(n) } - NodeAction("导出") { onExport(n) } - NodeAction("删除", danger = true) { onDelete(n) } - } - } - HorizontalDivider(thickness = 0.4.dp) - } - } - }, - confirmButton = { TextButton(onClick = onDismiss) { Text("好") } }, - ) -} - -@Composable -private fun NodeAction(label: String, danger: Boolean = false, onClick: () -> Unit) { - Text( - label, - fontSize = 12.sp, - color = if (danger) MaterialTheme.colorScheme.error else Doubao.Blue, - modifier = Modifier - .clip(RoundedCornerShape(6.dp)) - .clickable { onClick() } - .padding(horizontal = 8.dp, vertical = 4.dp), - ) -} - -/** - * 搭积木用的"积木块"。 - * - * ★ 这块的设计:**每一块都是一段能独立成立的 Python**,点一下就插进编辑器。 - * 不是 Scratch 那种拖拽画布 —— 那种要自己实现一套积木布局和吸附, - * 而这里的产物最终是**代码**,代码编辑器本来就在旁边。 - * 所以做成"点积木 -> 生成代码 -> 你能接着改",比拖拽更实用: - * 生成出来的东西是可读、可改、可以继续学的 Python,不是一个封闭的图形。 - * - * 对新手:从零写不出来,但知道要"记一条日志""设置输出"。 - * 对老手:这些块就是快捷键,省得敲样板代码。 - */ -private data class Block(val label: String, val hint: String, val code: String) - -private val BLOCKS = listOf( - Block("📝 记一条日志", "把内容写进这一步的说明里", " ctx.log(\"\", )\n"), - Block("📤 设置文本输出", "这个节点的文本出口给什么", " node[\"output\"][\"\"] = \"\"\n"), - Block("💾 写变量", "存进会议变量(要先在变量面板登记)", " ctx.set_var(\"\", )\n"), - Block("📖 读输入", "读某个入口的值", " value = node[\"input\"][\"\"]\n"), - Block("🔤 转大写", "把文本变成大写", " text = str(node[\"input\"][\"\"]).upper()\n"), - Block("✂️ 取前几个字", "截取开头 N 个字符", " head = text[:3]\n"), - Block("📏 文本长度", "有多少个字", " n = len(text)\n"), - Block("➕ 拼两段文本", "把两段接起来", " joined = a + b\n"), - Block("🔀 如果…否则…", "按条件走不同的路(把分支名换成你声明的)", - " if n >= 3:\n node[\"output\"][\"高分\"] = True\n else:\n node[\"output\"][\"低分\"] = True\n"), - Block("🔁 重复 N 次", "循环", " for i in range(3):\n pass\n"), - Block("🧩 遍历列表", "逐个处理列表里的东西", - " for item in node[\"input\"][\"列表\"]:\n ctx.log(item)\n"), - Block("🛡 试试看(出错不崩)", "包一层异常保护", - " try:\n pass\n except Exception as e:\n ctx.log(\"出错:\", e)\n"), -) - -private val TEMPLATE = """ +/** 从零写一个节点时的模板(带注释,照着改就行) */ +fun newNodeTemplate(): String = """ ToolName = { "name": "我的节点", "desc": "说明它干什么(当工具时给模型看,写清楚)", @@ -240,134 +64,184 @@ def run(ctx, node): return node """.trimIndent() -/** 新建时的空白模板 */ -fun newNodeTemplate(): String = TEMPLATE +/** 一个节点文件的列表项(来自 GET /api/meeting/nodes) */ +data class NodeFile( + val file: String = "", + val ok: Boolean = true, + val error: String = "", + val label: String = "", + val desc: String = "", + val inputs: List> = emptyList(), + val outputs: List> = emptyList(), +) { + val execBranches: Int get() = outputs.count { it.first == "exec" } + val dataOuts: Int get() = outputs.count { it.first != "exec" } + val dataIns: Int get() = inputs.count { it.first != "exec" } +} /** - * 现场编辑一个节点:代码框 + 搭积木面板。 + * 自定义节点管理(全屏)。 * - * 改完保存会走内核的导入接口 —— 内核**先试加载一遍**,写错了当场把 - * Python 的报错显示出来,而不是存进去变成一个坏节点。 + * 列出 nodes/ 里的全部文件:能新建 / 导入 / 编辑 / 导出 / 删除。 + * 坏掉的节点**也列出来**并显示原因 —— 静默消失会让用户以为文件丢了。 */ @Composable -fun NodeEditDialog( - title: String, +fun NodeManagerScreen( + nodes: List, + dir: String, + message: String, + onImport: () -> Unit, + onEdit: (NodeFile) -> Unit, + onExport: (NodeFile) -> Unit, + onDelete: (NodeFile) -> Unit, + onNew: () -> Unit, + onBack: () -> Unit, +) { + FullScreen( + title = "自定义节点", + subtitle = "往这里放 .py 就多一种节点", + onBack = onBack, + actions = { TopAction("+ 新建", onClick = onNew) }, + ) { + Column( + Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()), + ) { + Text( + dir, + fontSize = 10.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp), + ) + Row( + Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RowAction("📥 导入文件") { onImport() } + } + if (message.isNotBlank()) { + Text( + message, + fontSize = 12.sp, + color = if (message.startsWith("已导入") || message.startsWith("已保存")) + Color(0xFF34A853) else MaterialTheme.colorScheme.error, + lineHeight = 17.sp, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp), + ) + } + + HorizontalDivider(thickness = 0.5.dp, modifier = Modifier.padding(top = 6.dp)) + + if (nodes.isEmpty()) { + Text( + "还没有自定义节点。\n\n" + + "点右上角「新建」搭积木写一个,或者「导入文件」把别人给你的 .py 装进来。", + fontSize = 13.sp, + color = doubaoTextSecondary(), + lineHeight = 20.sp, + modifier = Modifier.padding(14.dp), + ) + } + + nodes.forEach { n -> + Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + if (n.ok) "🐍" else "⚠", + fontSize = 15.sp, + ) + Spacer(Modifier.width(6.dp)) + Text( + n.label.ifBlank { n.file }, + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = if (n.ok) doubaoText() else MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.width(6.dp)) + Text(n.file, fontSize = 10.sp, color = doubaoTextSecondary()) + } + Spacer(Modifier.height(3.dp)) + Text( + if (!n.ok) n.error + else n.desc.ifBlank { + "入口 ${n.dataIns} 个 · 出口 ${n.dataOuts} 个 · " + + "exec 分支 ${n.execBranches} 路" + }, + fontSize = 12.sp, + color = if (n.ok) doubaoTextSecondary() + else MaterialTheme.colorScheme.error, + lineHeight = 17.sp, + ) + Spacer(Modifier.height(6.dp)) + Row { + RowAction("编辑") { onEdit(n) } + RowAction("导出") { onExport(n) } + RowAction("删除", danger = true) { onDelete(n) } + } + } + HorizontalDivider(thickness = 0.4.dp) + } + Spacer(Modifier.height(24.dp)) + } + } +} + +/** + * 代码编辑(全屏)。 + * + * 和积木编辑器是**两个界面、同一份代码**:这里写代码,那边搭积木, + * 保存走同一条路(内核会先试加载一遍,写错了当场报错)。 + */ +@Composable +fun NodeCodeScreen( fileName: String, initialCode: String, onFileName: (String) -> Unit, + onBlocks: () -> Unit, onSave: (String) -> Unit, - onDismiss: () -> Unit, + onBack: () -> Unit, ) { var code by remember { mutableStateOf(initialCode) } - var tab by remember { mutableStateOf(0) } // 0 = 代码,1 = 积木 - var focusLine by remember { mutableStateOf(code.lines().size) } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title, fontSize = 16.sp) }, - text = { - Column( - Modifier - .fillMaxWidth() - .heightIn(max = 500.dp), - ) { - OutlinedTextField( - value = fileName, - onValueChange = onFileName, - modifier = Modifier.fillMaxWidth(), - label = { Text("文件名", fontSize = 11.sp) }, - singleLine = true, - textStyle = TextStyle(fontSize = 12.sp), - ) - Spacer(Modifier.height(8.dp)) - - // 两个页签:写代码 / 搭积木 - Row { - TabChip("代码", tab == 0) { tab = 0 } - Spacer(Modifier.width(6.dp)) - TabChip("搭积木", tab == 1) { tab = 1 } - } - Spacer(Modifier.height(8.dp)) - - if (tab == 0) { - OutlinedTextField( - value = code, - onValueChange = { code = it }, - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 260.dp, max = 320.dp) - .verticalScroll(rememberScrollState()), - textStyle = TextStyle(fontSize = 11.sp), - label = { Text("run(ctx, node)", fontSize = 11.sp) }, - ) - } else { - Text( - "点一块,代码就加到编辑器末尾。生成的是**普通 Python**," + - "你随时能切回「代码」接着改 —— 不是把你锁在积木里。", - fontSize = 11.sp, - color = doubaoTextSecondary(), - lineHeight = 15.sp, - ) - Spacer(Modifier.height(6.dp)) - Column( - Modifier - .fillMaxWidth() - .heightIn(max = 240.dp) - .verticalScroll(rememberScrollState()), - ) { - BLOCKS.forEach { b -> - Column( - Modifier - .fillMaxWidth() - .padding(vertical = 3.dp) - .clip(RoundedCornerShape(8.dp)) - .background(Doubao.Blue.copy(alpha = 0.07f)) - .clickable { - code = code.trimEnd('\n') + "\n" + b.code - focusLine = code.lines().size - } - .padding(horizontal = 10.dp, vertical = 7.dp), - ) { - Text(b.label, fontSize = 13.sp, color = Doubao.Blue) - Text( - b.hint, - fontSize = 10.sp, - color = doubaoTextSecondary(), - ) - } - } - } - Spacer(Modifier.height(8.dp)) - Text("当前代码:", fontSize = 11.sp, color = doubaoTextSecondary()) - Spacer(Modifier.height(3.dp)) - Text( - code.lines().takeLast(12).joinToString("\n"), - fontSize = 10.sp, - color = doubaoText(), - modifier = Modifier - .fillMaxWidth() - .heightIn(max = 130.dp) - .verticalScroll(rememberScrollState()), - ) - } - } + FullScreen( + title = "编辑代码", + subtitle = fileName, + onBack = onBack, + actions = { + TopTextAction("🧩 积木") { onBlocks() } + TopAction("保存") { onSave(code) } }, - confirmButton = { TextButton(onClick = { onSave(code) }) { Text("保存") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }, - ) -} - -@Composable -private fun TabChip(label: String, on: Boolean, onClick: () -> Unit) { - Text( - label, - fontSize = 13.sp, - color = if (on) Color.White else doubaoTextSecondary(), - fontWeight = if (on) FontWeight.Medium else FontWeight.Normal, - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .background(if (on) Doubao.Blue else Doubao.Blue.copy(alpha = 0.08f)) - .clickable { onClick() } - .padding(horizontal = 14.dp, vertical = 6.dp), - ) + ) { + Column(Modifier.fillMaxSize().padding(horizontal = 12.dp)) { + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = fileName, + onValueChange = onFileName, + modifier = Modifier.fillMaxWidth(), + label = { Text("文件名", fontSize = 11.sp) }, + singleLine = true, + textStyle = TextStyle(fontSize = 13.sp), + ) + Spacer(Modifier.height(6.dp)) + Text( + "入口约定是 def run(ctx, node)。ctx.log 记日志、" + + "ctx.set_var 写变量;node[\"output\"][\"名\"] 设置出口值。", + fontSize = 11.sp, + color = doubaoTextSecondary(), + lineHeight = 15.sp, + ) + Spacer(Modifier.height(8.dp)) + // 占满剩下的高度 —— 代码框就该有整屏(弹窗里那点高度写不了代码) + Box(Modifier.fillMaxWidth().weight(1f)) { + PythonCodeField( + value = code, + onValueChange = { code = it }, + modifier = Modifier.fillMaxSize(), + minHeight = 200, + ) + } + Spacer(Modifier.height(8.dp)) + } + } } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt index 2f77f1b..c25fb5f 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MeetingsScreen.kt @@ -309,6 +309,8 @@ private fun MeetingEditorScreen(vm: AppViewModel, initial: Meeting, onBack: () - var nodeImportMsg by remember { mutableStateOf("") } // 节点管理 / 现场编辑 var showNodeMgr by remember { mutableStateOf(false) } + // 全屏积木编辑器:非 null 就是打开着 + var blockEdit by remember { mutableStateOf>?>(null) } var nodeFiles by remember { mutableStateOf>(emptyList()) } var editFile by remember { mutableStateOf(null) } var editCode by remember { mutableStateOf("") } @@ -1315,20 +1317,50 @@ if (edge.kind == "exec") { ) } - // 节点管理面板 + // 全屏积木编辑器(独立界面,不是对话框 —— 见 AGENTS.md) + blockEdit?.let { (nm, decl, blocks) -> + NodeBlockEditorScreen( + title = "搭积木", + fileName = nm, + initialBlocks = blocks, + initialDecl = decl, + onFileName = { blockEdit = Triple(it, decl, blocks) }, + onDecl = { blockEdit = Triple(nm, it, blocks) }, + onSave = { code -> + vm.launch { + val r = runCatching { vm.importNodeFile(nm, code) } + nodeMgrMsg = r.fold( + onSuccess = { "已保存:$it" }, + onFailure = { "存不了:${it.message.orEmpty().take(300)}" }, + ) + if (r.isSuccess) { + blockEdit = null + refreshNodeFiles() + showNodeMgr = true + } + } + }, + onBack = { blockEdit = null; showNodeMgr = true }, + ) + return@MeetingEditorScreen + } + + // 节点管理(全屏,不是弹窗 —— 见 AGENTS.md) if (showNodeMgr) { if (nodeFiles.isEmpty() && nodeMgrMsg.isBlank()) { LaunchedEffect(Unit) { refreshNodeFiles() } } - NodeManagerDialog( + NodeManagerScreen( nodes = nodeFiles, dir = vm.meetingMeta.customDir, message = nodeMgrMsg, onImport = { nodePicker.launch(arrayOf("text/x-python", "text/plain", "*/*")) }, onNew = { - editFile = null - editName = "my_node.py" - editCode = newNodeTemplate() + // 新建**直接进积木编辑器**(全屏)—— + // 新手不该一上来就面对一个空白代码框。 + // 想写代码的话,积木界面右上角有「看代码」。 + val (blocks0, decl0) = newBlocksStarter() + blockEdit = Triple("my_node.py", decl0, blocks0) }, onEdit = { nf -> // 从内核读**源码**(列表里只有摘要,没有正文) @@ -1364,17 +1396,28 @@ if (edge.kind == "exec") { refreshNodeFiles() } }, - onDismiss = { showNodeMgr = false }, + onBack = { showNodeMgr = false }, ) + return@MeetingEditorScreen } // 现场编辑 / 新建 if (editCode.isNotEmpty() || editFile == null && editName.isNotBlank()) { - NodeEditDialog( - title = if (editFile == null) "新建节点" else "编辑 ${editFile}", + // 现场编辑代码(全屏,不是弹窗 —— 见 AGENTS.md) + NodeCodeScreen( fileName = editName, initialCode = editCode, onFileName = { editName = it }, + onBlocks = { + // 切到积木视图。 + // + // ★ 代码**解析不回**积木(那要写一个 Python 解析器,不值得), + // 所以给一块空白帽子起手。界面上说明白,别让用户以为代码被吞了。 + val (blocks0, decl0) = newBlocksStarter() + blockEdit = Triple(editName.ifBlank { "my_node.py" }, decl0, blocks0) + editCode = "" + editFile = null + }, onSave = { code -> val name = editName.ifBlank { "node.py" } vm.launch { @@ -1386,16 +1429,19 @@ if (edge.kind == "exec") { if (r.isSuccess) { editCode = "" editFile = null + showNodeMgr = true refreshNodeFiles() } } }, - onDismiss = { + onBack = { editCode = "" editFile = null editName = "" + showNodeMgr = true }, ) + return@MeetingEditorScreen } if (showImport) { diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/NodeBlockEditor.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/NodeBlockEditor.kt new file mode 100644 index 0000000..c70887b --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/NodeBlockEditor.kt @@ -0,0 +1,747 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/* + * 搭积木(编程猫 / Scratch 那种)。 + * + * ★ 为什么是**独立全屏界面**而不是对话框: + * 积木编辑器要同时放三样东西(积木分类、脚本区、生成的代码), + * 对话框里每样只够两行 —— 那还不如直接写代码。 + * 而且拖积木本身需要空间:手指出汗、目标太小就吸不住。 + * + * ★ 生成物是**普通 Python**,随时能切回代码页签改。 + * 积木是"帮你写代码"的,不是"替你锁住代码"的。 + */ + +// --------------------------------------------------------------------------- // +// 积木的数据模型 +// --------------------------------------------------------------------------- // + +/** 一块积木。children 是 C 型积木(如果/循环)肚子里装的那些。 */ +data class Blk( + val id: Long, + val kind: String, + val a: String = "", + val b: String = "", + val children: List = emptyList(), +) + +private var blkSeq = 1L +private fun newId(): Long = blkSeq++ + +/** 积木分类(左边那一列) */ +private data class Cat(val key: String, val label: String, val color: Color) + +private val CATS = listOf( + Cat("event", "事件", Color(0xFFF2B705)), + Cat("data", "数据", Color(0xFFE8622D)), + Cat("ctrl", "控制", Color(0xFF4C97FF)), + Cat("text", "文本", Color(0xFF9B59B6)), + Cat("math", "运算", Color(0xFF3BA55D)), + Cat("out", "输出", Color(0xFFE0538A)), + Cat("list", "列表", Color(0xFFE67E22)), +) + +/** 积木模板:[分类, 显示名, 形状说明, 生成代码的模板] */ +private data class Tpl( + val cat: String, + val label: String, + val hint: String, + val kind: String, + /** 默认字段值 */ + val a: String = "", + val b: String = "", + /** 是不是 C 型(肚子里能装积木) */ + val container: Boolean = false, +) + +private val TPLS = listOf( + // 事件 + Tpl("event", "当运行这个节点时", "脚本从这里开始", "hat"), + // 数据 + Tpl("data", "读输入 %1", "读某个入口的值", "getinput", a = "文本"), + Tpl("data", "把变量 %1 设为 %2", "写进会议变量", "setvar", a = "变量名", b = "值"), + Tpl("data", "记住 %1 = %2", "只在这次运行里用", "let", a = "临时名", b = "值"), + // 控制 + Tpl("ctrl", "如果 %1 那么", "条件成立才做", "if", a = "n >= 3", container = true), + Tpl("ctrl", "如果 %1 那么 否则", "两条路选一条", "ifelse", a = "n >= 3", container = true), + Tpl("ctrl", "重复 %1 次", "循环", "repeat", a = "3", container = true), + Tpl("list", "遍历 %1 里的每一项", "逐个处理", "foreach", a = "列表", container = true), + // 文本 + Tpl("text", "%1 的长度", "有多少个字", "len", a = "text"), + Tpl("text", "%1 变成大写", "转大写", "upper", a = "text"), + Tpl("text", "取 %1 的前 %2 个字", "截取", "slice", a = "text", b = "3"), + Tpl("text", "拼接 %1 和 %2", "接起来", "join", a = "a", b = "b"), + // 运算 + Tpl("math", "%1 + %2", "加", "add", a = "1", b = "1"), + Tpl("math", "%1 > %2", "大于", "gt", a = "n", b = "3"), + Tpl("math", "%1 = %2", "等于", "eq", a = "a", b = "b"), + // 输出 + Tpl("out", "记一条日志 %1", "写进这一步的说明", "log", a = "内容"), + Tpl("out", "把文本输出设为 %1", "这个节点的文本出口", "setout", a = "text"), + Tpl("out", "走分支 %1", "多个 exec 出口只能一个为真", "branch", a = "高分"), + Tpl("out", "试试看(出错不崩)", "包一层异常保护", "try", container = true), +) + +private fun tplOf(kind: String): Tpl? = TPLS.firstOrNull { it.kind == kind } + +/** 一块积木显示成什么样 */ +private fun shapeOf(kind: String): String = when (kind) { + "hat" -> "▶" + "if", "ifelse", "repeat", "foreach", "try" -> "C" + "setout", "branch" -> "▤" + "log" -> "▤" + else -> "▭" +} + +private fun colorOf(kind: String): Color { + val cat = TPLS.firstOrNull { it.kind == kind }?.cat ?: "data" + return CATS.firstOrNull { it.key == cat }?.color ?: Color(0xFF4C97FF) +} + +// --------------------------------------------------------------------------- // +// 生成 Python +// --------------------------------------------------------------------------- // + +private fun pad(n: Int) = " ".repeat(n) + +/** + * 把积木栈编译成 Python。 + * + * ★ 每一块的生成规则都写成"这一块自己那几行",嵌套靠缩进层级 —— + * 这样加一种积木只要在这里加一个分支,不用动别的。 + */ +private fun genBlocks(list: List, indent: Int): String { + val sb = StringBuilder() + for (b in list) { + val p = pad(indent) + when (b.kind) { + "hat" -> { + sb.append(p).append("# 当运行这个节点时\n") + } + "getinput" -> sb.append(p).append("${b.a} = node[\"input\"][\"${b.b.ifBlank { b.a }}\"]\n") + "setvar" -> sb.append(p).append("ctx.set_var(\"${b.a}\", ${b.b})\n") + "let" -> sb.append(p).append("${b.a} = ${b.b}\n") + "log" -> sb.append(p).append("ctx.log(${b.a})\n") + "setout" -> { + val first = b.b.ifBlank { "结果" } + sb.append(p).append("node[\"output\"][\"$first\"] = ${b.a}\n") + } + "branch" -> sb.append(p).append("node[\"output\"][\"${b.a}\"] = True\n") + "len" -> sb.append(p).append("${b.b.ifBlank { "n" }} = len(${b.a})\n") + "upper" -> sb.append(p).append("${b.b.ifBlank { "text" }} = str(${b.a}).upper()\n") + "slice" -> sb.append(p).append("${b.b.ifBlank { "head" }} = ${b.a}[:3]\n") + "join" -> sb.append(p).append("joined = ${b.a} + ${b.b}\n") + "add" -> sb.append(p).append("total = ${b.a} + ${b.b}\n") + "gt" -> sb.append(p).append("ok = ${b.a} > ${b.b}\n") + "eq" -> sb.append(p).append("ok = ${b.a} == ${b.b}\n") + "if" -> { + sb.append(p).append("if ${b.a}:\n") + sb.append(genBlocks(b.children, indent + 1).ifBlank { pad(indent + 1) + "pass\n" }) + } + "ifelse" -> { + sb.append(p).append("if ${b.a}:\n") + sb.append(genBlocks(b.children, indent + 1).ifBlank { pad(indent + 1) + "pass\n" }) + sb.append(p).append("else:\n") + sb.append(pad(indent + 1)).append("pass\n") + } + "repeat" -> { + sb.append(p).append("for _i in range(${b.a}):\n") + sb.append(genBlocks(b.children, indent + 1).ifBlank { pad(indent + 1) + "pass\n" }) + } + "foreach" -> { + sb.append(p).append("for item in node[\"input\"][\"${b.a}\"]:\n") + sb.append(genBlocks(b.children, indent + 1).ifBlank { pad(indent + 1) + "pass\n" }) + } + "try" -> { + sb.append(p).append("try:\n") + sb.append(genBlocks(b.children, indent + 1).ifBlank { pad(indent + 1) + "pass\n" }) + sb.append(p).append("except Exception as e:\n") + sb.append(pad(indent + 1)).append("ctx.log(\"出错:\", e)\n") + } + } + } + return sb.toString() +} + +/** + * 把积木栈 + 头部的声明编译成**完整的节点文件**。 + * + * 声明(input/output)从积木里推不出来 —— 那是节点对外的"接口", + * 得用户自己定。所以这里给一份能跑的默认声明,用户想要更多入口/出口 + * 就去「代码」页签改那一段。 + */ +private fun genFullCode(blocks: List, decl: String): String { + val body = genBlocks(blocks, 1).ifBlank { " pass\n" } + return decl.trimEnd() + "\n\n\ndef run(ctx, node):\n" + body + " return node\n" +} + +private val DEFAULT_DECL = """ +ToolName = { + "name": "我的节点", + "desc": "说明它干什么(当工具时给模型看)", + "input": [ + {"type": "str", "name": "文本", "value": ""}, + ], + "output": [ + {"type": "exec", "name": "好了"}, + {"type": "str", "name": "结果"}, + ], +} +""".trimIndent() + +// --------------------------------------------------------------------------- // +// 界面 +// --------------------------------------------------------------------------- // + +/** + * 积木编辑器(独立全屏)。 + * + * 布局照编程猫:左边积木分类、右边脚本区、底下生成的代码。 + */ +@Composable +fun NodeBlockEditorScreen( + title: String, + fileName: String, + initialBlocks: List, + initialDecl: String, + onFileName: (String) -> Unit, + onDecl: (String) -> Unit, + onSave: (String) -> Unit, + onBack: () -> Unit, +) { + val blocks = remember { mutableStateListOf().also { it.addAll(initialBlocks) } } + var cat by remember { mutableStateOf("event") } + var decl by remember { mutableStateOf(initialDecl) } + var showCode by remember { mutableStateOf(false) } + var dragging by remember { mutableStateOf(-1L) } + /** + * 新积木加到哪里:-1 = 最外层,否则是某个 C 型积木的 id(加进它肚子里)。 + * + * ★ 没有这个的话,"如果…那么"就只是个摆设 —— 肚子里永远空着, + * 用户搭不出任何带分支的脚本。所以必须先有"往里加"的动作。 + */ + var into by remember { mutableStateOf(-1L) } + val scroll = rememberScrollState() + + val code = genFullCode(blocks.toList(), decl) + + Column(Modifier.fillMaxSize().background(doubaoBg())) { + // ---------------- 顶栏 ---------------- + Row( + Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton(onClick = onBack) { Text("← 返回") } + Text(title, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText()) + Spacer(Modifier.width(8.dp)) + Text(fileName, fontSize = 11.sp, color = doubaoTextSecondary()) + Spacer(Modifier.weight(1f)) + Text( + if (showCode) "看积木" else "看代码", + fontSize = 13.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { showCode = !showCode } + .padding(horizontal = 10.dp, vertical = 6.dp), + ) + Text( + "保存", + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = Color.White, + modifier = Modifier + .clip(RoundedCornerShape(18.dp)) + .background(Doubao.Blue) + .clickable { onSave(code) } + .padding(horizontal = 16.dp, vertical = 7.dp), + ) + } + HorizontalDivider(thickness = 0.5.dp) + + if (showCode) { + // ---------------- 代码视图(声明 + 生成结果都能改) ---------------- + Column(Modifier.fillMaxSize().padding(10.dp)) { + Text("节点声明(入口 / 出口在这里定)", fontSize = 11.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(4.dp)) + // 声明那一段也是 Python,同样给高亮和补全 + PythonCodeField( + value = decl, + onValueChange = { decl = it; onDecl(it) }, + modifier = Modifier.fillMaxWidth(), + label = "节点声明", + minHeight = 110, + ) + Spacer(Modifier.height(8.dp)) + Text("生成的 run(ctx, node)", fontSize = 11.sp, color = doubaoTextSecondary()) + Spacer(Modifier.height(4.dp)) + Surface( + shape = RoundedCornerShape(8.dp), + color = Doubao.Blue.copy(alpha = 0.06f), + modifier = Modifier.fillMaxWidth().weight(1f), + ) { + Text( + genBlocks(blocks.toList(), 1).ifBlank { "(还没搭积木)" }, + fontSize = 11.sp, + fontFamily = FontFamily.Monospace, + color = doubaoText(), + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(10.dp), + ) + } + } + } else { + Row(Modifier.fillMaxSize()) { + // ---------------- 左:积木分类 ---------------- + Column( + Modifier + .width(96.dp) + .fillMaxHeight() + .background(doubaoText().copy(alpha = 0.04f)) + .verticalScroll(rememberScrollState()), + ) { + CATS.forEach { c -> + val on = c.key == cat + Row( + Modifier + .fillMaxWidth() + .background(if (on) c.color.copy(alpha = 0.18f) else Color.Transparent) + .clickable { cat = c.key } + .padding(horizontal = 8.dp, vertical = 9.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + Modifier + .width(8.dp) + .height(8.dp) + .clip(RoundedCornerShape(4.dp)) + .background(c.color), + ) + Spacer(Modifier.width(6.dp)) + Text( + c.label, + fontSize = 13.sp, + fontWeight = if (on) FontWeight.Medium else FontWeight.Normal, + color = doubaoText(), + ) + } + } + } + HorizontalDivider( + Modifier.width(0.5.dp).fillMaxHeight(), + thickness = 0.5.dp, + ) + + // ---------------- 右:积木面板 + 脚本区 ---------------- + Column(Modifier.weight(1f).fillMaxHeight()) { + // 可选积木(点一下加到脚本末尾) + Column( + Modifier + .fillMaxWidth() + .heightIn(max = 190.dp) + .verticalScroll(rememberScrollState()) + .padding(8.dp), + ) { + TPLS.filter { it.cat == cat }.forEach { t -> + BlockChip(t, active = into == -1L) { addBlock(blocks, into, fromTpl(t)) } + } + } + HorizontalDivider(thickness = 0.5.dp) + + Text( + if (into == -1L) "脚本(长按拖动排序,点 × 删除)" + else "正在往「${blocks.firstOrNull { it.id == into }?.let { tplOf(it.kind)?.label?.substringBefore(" %") } ?: "?"}」里面加 —— 点这里回最外层", + fontSize = 10.sp, + color = doubaoTextSecondary(), + modifier = Modifier + .padding(start = 10.dp, top = 6.dp, bottom = 2.dp) + .clip(RoundedCornerShape(6.dp)) + .clickable { into = -1L }, + ) + + Column( + Modifier + .fillMaxWidth() + .weight(1f) + .verticalScroll(scroll) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) { + if (blocks.isEmpty()) { + Text( + "左边选一个分类,点积木加进来。\n" + + "第一块建议是「当运行这个节点时」。", + fontSize = 12.sp, + color = doubaoTextSecondary(), + lineHeight = 18.sp, + ) + } + blocks.forEachIndexed { i, b -> + ScriptBlock( + b = b, + indent = 0, + dragging = dragging == b.id, + onDragStart = { dragging = b.id }, + onDrag = { dy -> + // 上下一格就换位置。用"格子高度"当阈值, + // 不然拖动会疯狂换位(和画布拖节点那次踩的坑一样) + val step = if (dy < -26f && i > 0) -1 + else if (dy > 26f && i < blocks.size - 1) 1 else 0 + if (step != 0) { + val t = blocks[i] + blocks[i] = blocks[i + step] + blocks[i + step] = t + dragging = t.id + } + }, + onDragEnd = { dragging = -1L }, + onDelete = { blocks.removeAt(i); if (into == b.id) into = -1L }, + onEnter = { into = if (into == b.id) -1L else b.id }, + isTarget = into == b.id, + onField = { which, v -> + blocks[i] = if (which == 0) b.copy(a = v) else b.copy(b = v) + }, + ) + } + } + + HorizontalDivider(thickness = 0.5.dp) + Text( + "生成的 Python", + fontSize = 10.sp, + color = doubaoTextSecondary(), + modifier = Modifier.padding(start = 10.dp, top = 4.dp), + ) + Text( + genBlocks(blocks.toList(), 1).ifBlank { "(还没搭积木)" }, + fontSize = 10.sp, + fontFamily = FontFamily.Monospace, + color = doubaoTextSecondary(), + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 110.dp) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 10.dp, vertical = 4.dp), + ) + } + } + } + } +} + +/** 按"插入目标"加积木:into = -1 加到最外层,否则加进那个 C 型积木的肚子 */ +private fun addBlock(list: MutableList, into: Long, b: Blk) { + if (into == -1L) { + list.add(b) + return + } + val idx = list.indexOfFirst { it.id == into } + if (idx < 0) { + list.add(b) + return + } + list[idx] = list[idx].copy(children = list[idx].children + b) +} + +private fun fromTpl(t: Tpl): Blk = + Blk(newId(), t.kind, a = t.a, b = t.b) + +/** 左边那一列"可选积木" —— 用**真实形状**画,这样加进来之前就知道它长什么样 */ +@Composable +private fun BlockChip(t: Tpl, active: Boolean, onClick: () -> Unit) { + val c = CATS.firstOrNull { it.key == t.cat }?.color ?: Doubao.Blue + val shape = when { + t.kind == "hat" -> BlkShape.Hat + t.container -> BlkShape.C + else -> BlkShape.Stack + } + BlockSurface( + shape = shape, + color = if (active) c else c.copy(alpha = 0.72f), + modifier = Modifier + .fillMaxWidth() + .clickable { onClick() }, + height = 38.dp, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + t.label.substringBefore(" %"), + fontSize = 13.sp, + color = Color.White, + fontWeight = FontWeight.Medium, + ) + if (t.label.contains("%1") || t.label.contains("%2")) { + Spacer(Modifier.width(5.dp)) + Box( + Modifier + .clip(RoundedCornerShape(50)) + .background(Color.White.copy(alpha = 0.9f)) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) { + Text("…", fontSize = 10.sp, color = Color(0xFF333333)) + } + } + } + } +} + +/** + * 积木上的文字 + 嵌在句子里的参数槽。 + * + * 模板里 `%1` / `%2` 是槽的位置: + * "把变量 %1 设为 %2" → 把变量 [变量名] 设为 [值] + * "取 %1 的前 %2 个字" → 取 [text] 的前 [3] 个字 + * + * 这就是"槽长在句子里"和"槽全堆在右边"的区别 —— + * 后者读起来是"取 前 个字 [text] [3]",根本读不通。 + */ +@Composable +private fun BlockLabel( + template: String, + a: String, + b: String, + onA: (String) -> Unit, + onB: (String) -> Unit, +) { + // 按 %1 / %2 把模板切成文字段和槽 + val parts = remember(template) { + val out = mutableListOf>() // (kind, text) kind: "t"/"1"/"2" + var rest = template + while (rest.isNotEmpty()) { + val i1 = rest.indexOf("%1") + val i2 = rest.indexOf("%2") + val i = when { + i1 < 0 -> i2 + i2 < 0 -> i1 + else -> minOf(i1, i2) + } + if (i < 0) { + out.add("t" to rest) + break + } + if (i > 0) out.add("t" to rest.substring(0, i)) + out.add((if (rest.startsWith("%1", i)) "1" else "2") to "") + rest = rest.substring(i + 2) + } + out + } + Row(verticalAlignment = Alignment.CenterVertically) { + parts.forEach { (kind, text) -> + when (kind) { + "t" -> Text( + text, + fontSize = 13.sp, + color = Color.White, + fontWeight = FontWeight.Medium, + ) + "1" -> { + Spacer(Modifier.width(4.dp)) + ValueSlot(a, "…") { onA(it) } + Spacer(Modifier.width(4.dp)) + } + else -> { + Spacer(Modifier.width(4.dp)) + ValueSlot(b, "…") { onB(it) } + Spacer(Modifier.width(4.dp)) + } + } + } + } +} + +/** + * 脚本区里的一块积木。 + * + * 形状按种类画(帽子 / C 型 / 堆叠)—— 在积木编程里形状就是**语法**: + * 用户靠它判断"这块能不能接在那块下面""这块能不能塞进那个槽"。 + */ +@Composable +private fun ScriptBlock( + b: Blk, + indent: Int, + dragging: Boolean, + onDragStart: () -> Unit, + onDrag: (Float) -> Unit, + onDragEnd: () -> Unit, + onDelete: () -> Unit, + onEnter: () -> Unit, + isTarget: Boolean, + onField: (Int, String) -> Unit, +) { + val c = colorOf(b.kind) + val tpl = tplOf(b.kind) + val container = tpl?.container == true + val shape = when { + b.kind == "hat" -> BlkShape.Hat + container -> BlkShape.C + else -> BlkShape.Stack + } + val label = (tpl?.label ?: b.kind).substringBefore(" %") + + Column(Modifier.padding(start = (indent * 12).dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + BlockSurface( + shape = shape, + color = c, + modifier = Modifier + .weight(1f) + .pointerInput(b.id) { + detectDragGesturesAfterLongPress( + onDragStart = { onDragStart() }, + onDragEnd = { onDragEnd() }, + onDragCancel = { onDragEnd() }, + onDrag = { change, amount -> + change.consume() + onDrag(amount.y) + }, + ) + }, + height = 40.dp, + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (dragging) { + Text("⠿ ", fontSize = 12.sp, color = Color.White.copy(alpha = 0.8f)) + } + // ★ 参数槽要**嵌在文字中间**,不是全堆在右边。 + // + // 编程猫是「把 [变量] 设为 [0]」—— 槽长在句子里, + // 一眼就知道这个槽填的是句子里的哪个位置。 + // 全堆在右边的话,"取 前 个字" 这种就完全读不通了。 + BlockLabel( + template = tpl?.label ?: b.kind, + a = b.a, + b = b.b, + onA = { onField(0, it) }, + onB = { onField(1, it) }, + ) + } + } + Text( + "×", + fontSize = 16.sp, + color = doubaoTextSecondary(), + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { onDelete() } + .padding(horizontal = 7.dp, vertical = 2.dp), + ) + } + + // C 型的"嘴巴":左边一条竖杠 + 底下收尾横杠,把肚子里的积木框住 + if (container) { + Row { + Box( + Modifier + .width(14.dp) + .heightIn(min = 30.dp) + .background(c), + ) + Column( + Modifier + .padding(start = 4.dp, top = 3.dp, bottom = 3.dp) + .weight(1f), + ) { + if (b.children.isEmpty()) { + Text( + if (isTarget) "▶ 点左边的积木,加到这里面" + else "(空)点这里进去加积木", + fontSize = 10.sp, + color = if (isTarget) Doubao.Blue else doubaoTextSecondary(), + fontWeight = if (isTarget) FontWeight.Medium else FontWeight.Normal, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { onEnter() } + .padding(vertical = 6.dp, horizontal = 4.dp), + ) + } else { + Text( + if (isTarget) "正在往这里面加(点一下退出)" else "点这里进去加积木", + fontSize = 9.sp, + color = if (isTarget) Doubao.Blue else doubaoTextSecondary(), + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .clickable { onEnter() } + .padding(vertical = 2.dp, horizontal = 4.dp), + ) + b.children.forEach { ch -> + Row( + Modifier.padding(vertical = 1.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + Modifier + .width(5.dp) + .height(5.dp) + .clip(RoundedCornerShape(3.dp)) + .background(colorOf(ch.kind)), + ) + Spacer(Modifier.width(6.dp)) + Text( + (tplOf(ch.kind)?.label ?: ch.kind).substringBefore(" %"), + fontSize = 11.sp, + color = doubaoText(), + ) + } + } + } + } + } + // 收尾横杠 + BlockSurface( + shape = BlkShape.CFoot, + color = c, + modifier = Modifier.fillMaxWidth(0.72f), + height = 16.dp, + ) {} + } + } +} + +/** 新建积木脚本时的起手式:一块帽子 */ +fun newBlocksStarter(): Pair, String> = + listOf(Blk(newId(), "hat")) to DEFAULT_DECL diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/PythonEditor.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/PythonEditor.kt new file mode 100644 index 0000000..e338045 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/PythonEditor.kt @@ -0,0 +1,319 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/* + * Python 的**语法高亮 + 代码补全**。 + * + * 为什么这两件事要自己做(而不是找个库): + * 这个项目没有依赖任何编辑器库(不要为了一段代码框引进几十 KB), + * 而 Python 的高亮规则其实很少:关键字、字符串、注释、数字、函数名。 + * 补全就更有意思了 —— 最有用的那几条是**这个节点自己的引脚名**, + * 那是从用户写的声明里读出来的,任何通用库都给不了。 + */ + +// --------------------------------------------------------------------------- // +// 高亮 +// --------------------------------------------------------------------------- // + +private val KEYWORDS = setOf( + "def", "return", "if", "elif", "else", "for", "while", "in", "not", "and", "or", + "try", "except", "finally", "raise", "import", "from", "as", "class", "with", + "lambda", "None", "True", "False", "pass", "break", "continue", "global", + "is", "assert", "yield", "del", "async", "await", +) + +/** 这个项目给用户的那套 API —— 单独一个颜色,让人一眼看出"这是能用的东西" */ +private val API_NAMES = setOf( + "ctx", "node", "input", "output", "vars", "log", "set_var", "get_var", + "str", "int", "float", "len", "range", "print", "list", "dict", "bool", + "append", "upper", "lower", "strip", "split", "join", "replace", "startswith", + "endswith", "format", "enumerate", "sorted", "sum", "min", "max", "abs", "round", +) + +private val C_KEY = Color(0xFFC678DD) // 关键字:紫 +private val C_STR = Color(0xFF98C379) // 字符串:绿 +private val C_COM = Color(0xFF7F848E) // 注释:灰 +private val C_NUM = Color(0xFFD19A66) // 数字:橙 +private val C_API = Color(0xFF61AFEF) // 内置/我们的 API:蓝 +private val C_DEF = Color(0xFFE5C07B) // 定义的名字:黄 +private val C_FUN = Color(0xFF56B6C2) // 调用:青 + +/** + * Python 语法高亮。 + * + * ★ 用手写扫描而不是正则:正则在"字符串里有 # "和"注释里有引号"这两种情况下 + * 一定会出错,而这两种在真实代码里到处都是。状态机一次扫过去, + * 字符串/注释/代码三个状态互斥,不会串。 + */ +fun pythonHighlight(): VisualTransformation = VisualTransformation { text -> + TransformedText(highlightPython(text.text), OffsetMapping.Identity) +} + +internal fun highlightPython(src: String): AnnotatedString = buildAnnotatedString { + append(src) + var i = 0 + val n = src.length + + fun style(from: Int, to: Int, color: Color, bold: Boolean = false) { + if (to <= from) return + addStyle( + SpanStyle(color = color, fontWeight = if (bold) FontWeight.Medium else null), + from, + to, + ) + } + + while (i < n) { + val c = src[i] + when { + // 注释:到行尾 + c == '#' -> { + val end = src.indexOf('\n', i).let { if (it < 0) n else it } + style(i, end, C_COM) + i = end + } + // 三引号字符串 + c == '"' && i + 2 < n && src[i + 1] == '"' && src[i + 2] == '"' -> { + val end = src.indexOf("\"\"\"", i + 3).let { if (it < 0) n else it + 3 } + style(i, end, C_STR) + i = end + } + c == '\'' && i + 2 < n && src[i + 1] == '\'' && src[i + 2] == '\'' -> { + val end = src.indexOf("'''", i + 3).let { if (it < 0) n else it + 3 } + style(i, end, C_STR) + i = end + } + // 普通字符串 + c == '"' || c == '\'' -> { + var j = i + 1 + while (j < n && src[j] != c && src[j] != '\n') { + if (src[j] == '\\') j++ + j++ + } + val end = if (j < n && src[j] == c) j + 1 else j + style(i, end, C_STR) + i = end + } + // 数字 + c.isDigit() -> { + var j = i + while (j < n && (src[j].isDigit() || src[j] == '.' || src[j] == '_')) j++ + style(i, j, C_NUM) + i = j + } + // 标识符 / 关键字 + c.isLetter() || c == '_' -> { + var j = i + while (j < n && (src[j].isLetterOrDigit() || src[j] == '_')) j++ + val word = src.substring(i, j) + when { + word in KEYWORDS -> style(i, j, C_KEY, bold = true) + // def 后面的名字单独标 + word == "def" -> style(i, j, C_KEY, bold = true) + word in API_NAMES -> style(i, j, C_API) + // 后面跟 '(' 的当函数调用 + j < n && src[j] == '(' -> style(i, j, C_FUN) + // 前一行的 def 后面那个名字 + else -> { + val lineStart = src.lastIndexOf('\n', i).let { if (it < 0) 0 else it + 1 } + val before = src.substring(lineStart, i).trim() + if (before == "def" || before == "class") style(i, j, C_DEF) + } + } + i = j + } + else -> i++ + } + } +} + +// --------------------------------------------------------------------------- // +// 补全 +// --------------------------------------------------------------------------- // + +/** 一条补全建议 */ +data class Suggest(val text: String, val note: String) + +private val BASE_WORDS = listOf( + Suggest("def run(ctx, node):", "入口函数(必须有)"), + Suggest("return node", "结束并交回出口"), + Suggest("ctx.log(", "记一条说明"), + Suggest("ctx.set_var(", "写会议变量"), + Suggest("ctx.get_var(", "读会议变量"), + Suggest("ctx.input", "所有入口的值"), + Suggest("ctx.vars", "变量快照(只读)"), + Suggest("node[\"input\"]", "入口字典"), + Suggest("node[\"output\"]", "出口字典"), + Suggest("str(", "转成文本"), + Suggest("int(", "转成整数"), + Suggest("len(", "长度"), + Suggest("range(", "数字序列"), + Suggest("for item in ", "遍历"), + Suggest("if ", "条件"), + Suggest("else:", "否则"), + Suggest("try:", "异常保护"), + Suggest("except Exception as e:", "接住异常"), + Suggest("True", "真"), + Suggest("False", "假"), +) + +/** + * 根据当前光标位置给补全建议。 + * + * ★ 最有用的一条:`node["input"]["` 之后,把**这个节点声明的入口名**列出来。 + * 那是从用户自己写的声明里读的,通用编辑器给不了 —— + * 而打错一个引号或汉字名,运行时就是 KeyError,还不好查。 + */ +fun pythonSuggestions( + text: String, + cursor: Int, + inputPins: List = emptyList(), + outputPins: List = emptyList(), +): List { + val before = text.take(cursor.coerceIn(0, text.length)) + val out = mutableListOf() + + // 正在写 node["input"][ ... 或 node["output"][ ... + val inInput = before.lastIndexOf("node[\"input\"][") > before.lastIndexOf("]") + val inOutput = before.lastIndexOf("node[\"output\"][") > before.lastIndexOf("]") + if (inInput) { + inputPins.forEach { out.add(Suggest("\"$it\"", "声明的入口")) } + } + if (inOutput) { + outputPins.forEach { out.add(Suggest("\"$it\"", "声明的出口")) } + } + if (out.isNotEmpty()) return out + + // 当前正在敲的词(用来过滤) + val word = before.takeLastWhile { it.isLetterOrDigit() || it == '_' || it == '[' || it == '"' } + if (word.isBlank()) { + return BASE_WORDS.filter { it.text.startsWith("ctx.") }.take(6) + } + val low = word.lowercase() + BASE_WORDS.filter { it.text.lowercase().contains(low) || low.isEmpty() } + .sortedByDescending { it.text.lowercase().startsWith(low) } + .take(8) + .forEach { out.add(it) } + return out +} + +/** + * 带高亮和补全的代码框。 + * + * 补全做成**编辑器下面的横排按钮**而不是浮层:手机上浮层会挡住键盘和代码, + * 而且点起来更难(浮层会跟着光标跑,手指就在旁边,很容易点错)。 + */ +@Composable +fun PythonCodeField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + label: String = "run(ctx, node)", + minHeight: Int = 240, + inputPins: List = emptyList(), + outputPins: List = emptyList(), +) { + // 光标位置:BasicTextField 的 TextFieldValue 才有,这里用"末尾"近似 —— + // 用户改代码基本都在末尾追加,够用;要精确就得换 BasicTextField, + // 那样高亮的 VisualTransformation 也要跟着换一套,收益不划算。 + var cursor by remember(value) { mutableStateOf(value.length) } + + Column(modifier) { + OutlinedTextField( + value = value, + onValueChange = { s -> + onValueChange(s) + // OutlinedTextField 的 String 重载拿不到光标位置,用"末尾"近似 —— + // 用户改代码基本都在末尾追加,够用。要精确就得换 BasicTextField + // 的 TextFieldValue 重载,那样外框装饰要自己画,收益不划算。 + cursor = s.length + }, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = minHeight.dp), + textStyle = TextStyle( + fontSize = 11.sp, + fontFamily = FontFamily.Monospace, + ), + visualTransformation = pythonHighlight(), + label = { Text(label, fontSize = 11.sp) }, + ) + Spacer(Modifier.height(4.dp)) + Row( + Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + ) { + val list = pythonSuggestions(value, cursor, inputPins, outputPins) + if (list.isEmpty()) { + Text( + "(没有补全建议)", + fontSize = 10.sp, + color = doubaoTextSecondary(), + ) + } + list.forEach { s -> + Column( + Modifier + .padding(end = 6.dp) + .clip(RoundedCornerShape(7.dp)) + .background(Doubao.Blue.copy(alpha = 0.10f)) + .clickable { + val at = cursor.coerceIn(0, value.length) + // 替换掉正在敲的那半截词,不然会出现 "ctx.log(ctx.log(" + val head = value.take(at) + .dropLastWhile { it.isLetterOrDigit() || it == '_' } + val tail = value.drop(at) + onValueChange(head + s.text + tail) + cursor = head.length + s.text.length + } + .padding(horizontal = 8.dp, vertical = 5.dp), + ) { + Text( + s.text, + fontSize = 11.sp, + color = Doubao.Blue, + fontFamily = FontFamily.Monospace, + ) + Text(s.note, fontSize = 9.sp, color = doubaoTextSecondary()) + } + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ScreenScaffold.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ScreenScaffold.kt new file mode 100644 index 0000000..5e739dc --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ScreenScaffold.kt @@ -0,0 +1,147 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/* + * 全屏界面的统一骨架。 + * + * ★ 为什么要有这个(而不是每个界面自己写顶栏): + * "返回"在左边、标题多大、右边按钮长什么样 —— 这些一旦各写各的, + * 用户在不同界面里就要重新找一遍。统一一次,后面所有界面都省事。 + * + * ★ 为什么是**全屏**而不是弹窗:见 AGENTS.md「少用弹窗,能开界面就开界面」。 + * 一句话:弹窗装不下东西、弹窗会互相压、弹窗盖住上下文。 + */ + +/** + * 一个全屏界面:顶栏 + 内容。 + * + * ``` + * ← 返回 标题 副标题 [动作] [主按钮] + * ──────────────────────────────────────────────── + * (内容) + * ``` + */ +@Composable +fun FullScreen( + title: String, + onBack: () -> Unit, + modifier: Modifier = Modifier, + subtitle: String = "", + /** 顶栏右侧的自定义动作(可以是多个按钮) */ + actions: @Composable () -> Unit = {}, + content: @Composable ColumnScope.() -> Unit, +) { + Column(modifier.fillMaxSize().background(doubaoBg())) { + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 6.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "← 返回", + fontSize = 14.sp, + color = Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onBack() } + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + Spacer(Modifier.width(2.dp)) + Column(Modifier.weight(1f)) { + Text( + title, + fontSize = 17.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + ) + if (subtitle.isNotBlank()) { + Text(subtitle, fontSize = 11.sp, color = doubaoTextSecondary()) + } + } + actions() + } + HorizontalDivider(thickness = 0.5.dp) + Column(Modifier.fillMaxWidth().weight(1f), content = content) + } +} + +/** 顶栏右侧的主按钮(蓝底白字) */ +@Composable +fun TopAction(label: String, enabled: Boolean = true, onClick: () -> Unit) { + Text( + label, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = if (enabled) Color.White else Color.White.copy(alpha = 0.55f), + modifier = Modifier + .padding(end = 10.dp) + .clip(RoundedCornerShape(18.dp)) + .background(if (enabled) Doubao.Blue else Doubao.Blue.copy(alpha = 0.55f)) + .clickable(enabled = enabled) { onClick() } + .padding(horizontal = 16.dp, vertical = 7.dp), + ) +} + +/** 顶栏右侧的次要按钮(文字) */ +@Composable +fun TopTextAction(label: String, danger: Boolean = false, onClick: () -> Unit) { + Text( + label, + fontSize = 13.sp, + color = if (danger) Color(0xFFD93025) else Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { onClick() } + .padding(horizontal = 10.dp, vertical = 8.dp), + ) +} + +/** 分组小标题 */ +@Composable +fun SectionLabel(text: String) { + Text( + text, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + color = doubaoTextSecondary(), + modifier = Modifier.padding(start = 14.dp, top = 14.dp, bottom = 6.dp), + ) +} + +/** 一行的操作按钮(列表项右边那种) */ +@Composable +fun RowAction(label: String, danger: Boolean = false, onClick: () -> Unit) { + Text( + label, + fontSize = 12.sp, + color = if (danger) Color(0xFFD93025) else Doubao.Blue, + modifier = Modifier + .clip(RoundedCornerShape(7.dp)) + .clickable { onClick() } + .padding(horizontal = 10.dp, vertical = 5.dp), + ) +} diff --git a/tmp-msg-blk.txt b/tmp-msg-blk.txt new file mode 100644 index 0000000..c3eb57b --- /dev/null +++ b/tmp-msg-blk.txt @@ -0,0 +1,61 @@ +界面:积木编辑器做成编程猫那样(形状 + 全屏 + 代码高亮补全) + +用户:"一个单独的界面都不舍得加?积木要这样的" → "你上网搜搜编程猫教程" + → "py代码要补全和高亮" → "以后尽量减少弹窗那种,能加界面就加界面" + +【查了编程猫的官方文档(docs.codemao.cn 源码图鉴),关键结论】 +**形状在积木编程里是语法,不是装饰**: + · 圆顶帽子 = 事件入口,只能待在最上面 + · 底部凸起 + 顶部凹槽 = 能上下咬合,表示"接着做" + · C 型的嘴巴 = 里面的是"被包住"的,不是平级 + · 六边形 = 真假值,只能塞进条件槽 + · 椭圆 = 一个值,只能塞进参数槽 +全画成圆角矩形的话,用户看不出"这块能不能塞进那里",只能靠颜色猜 —— +那就退回成写代码了。 + +【新增 BlockShapes.kt】 +用 Canvas + Path 手画三种形状(帽子圆顶用 Union,凹槽用 Difference): + Hat / Stack / C / CFoot +外加 BooleanSlot(六边形)和 ValueSlot(胶囊)。 + +【积木编辑器(NodeBlockEditor.kt)】 + · 左边分类(事件/数据/控制/文本/运算/输出/列表),每类一个颜色 + · 积木盒子里**用真实形状**预览,加进来之前就知道长什么样 + · 脚本区:帽子/C型/堆叠 + 长按拖动排序 + × 删除 + · C 型积木有嘴巴,能点进去往里加积木(插入目标机制) + · 底部实时显示生成的 Python + · 顶栏「看代码」能切到声明 + 生成结果(声明可改,因为入口/出口从积木推不出来) + +★ 参数槽**嵌在句子里**,不是全堆在右边: + 「取 [text] 的前 [3] 个字」而不是「取 前 个字 [text] [3]」—— 后者根本读不通。 + +【Python 高亮 + 补全(PythonEditor.kt)】 + · 高亮用手写扫描而不是正则:正则在"字符串里有 # ""注释里有引号"这两种情况下 + 一定出错,而这两种在真实代码里到处都是。状态机一次扫过去,三个状态互斥。 + · 关键字紫 / 字符串绿 / 注释灰 / 数字橙 / 内置 API 蓝 / 函数调用青 + · 补全做成编辑器下面的横排按钮(不是浮层):浮层会挡键盘和代码, + 而且跟着光标跑,手指就在旁边很容易点错 + · 最有用的一条:`node["input"]["` 之后列出**这个节点声明的入口名** —— + 打错一个引号或汉字名就是 KeyError,还不好查 + +【全屏化(AGENTS.md 的原则)】 +新建 ScreenScaffold.kt:统一的 `← 返回 + 标题 + 副标题 + 右侧动作` 骨架。 + · 节点管理 NodeManagerDialog → **NodeManagerScreen**(全屏) + · 节点编辑 NodeEditDialog → **NodeCodeScreen**(全屏,代码框占满剩下的高度) + · 积木编辑器本来就是全屏 +新建直接进积木编辑器(新手不该一上来就面对空白代码框)。 + +【踩的坑,记下来】 + · `git checkout -- ` 会把这一轮**所有未提交**的改动都还原。 + 我为了修一个手误用它,把这一轮对该文件的改动全丢了,只能重做。 + —— 以后要么先 commit,要么用编辑工具精确回退。 + · 用 PowerShell 按行号剪贴这个大文件时,`$b` 算成 -1 会导致 + "把整个文件再追加一遍"。这类脚本必须**先断言下标有效**再动手。 + · 文件监听会让 edit 工具报 "file changed since it was read" —— + 读一次紧接着改一次就行。 + +【验证】 +- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致 +- APK 构建通过、装机通过 +- 截图确认:全屏节点管理、积木编辑器(帽子圆顶可见、分类配色、 + 参数槽嵌在句子里、生成代码实时更新) diff --git a/tmp-msg-mgr.txt b/tmp-msg-mgr.txt deleted file mode 100644 index 32f8c2b..0000000 --- a/tmp-msg-mgr.txt +++ /dev/null @@ -1,68 +0,0 @@ -会议模式:自定义节点的导入 / 导出 / 现场编辑 / 搭积木 - -用户:"自定义节点可以导入导出也可以。也可以现场编辑,支持 py 或搭积木生成代码(像编程猫那样)" - -【原来只有一个"导入"】 -节点文件只能 adb push 进去 —— 那不叫能用。现在是一整套: - - 自定义节点(加节点面板 -> 「导入 / 管理节点…」) - 往这个目录放 .py 就多一种节点,界面上的引脚是从文件里读的: - /data/user/0/com.doubao.lynxclone/files/kernel-data/nodes - - + 新建 📥 导入文件 - ──────────────────────────────── - 🐍 打分 score.py - 文字越长分越高:够 3 分走「高分」,否则走「低分」 - 编辑 导出 删除 - -【内核新增三个接口】 - GET /api/meeting/nodes 列出全部(含加载失败的原因,坏的也列出来) - GET /api/meeting/nodes/ 读**源码**(现场编辑用) - POST /api/meeting/nodes 导入 / 保存 - DELETE /api/meeting/nodes/ 删除 - -★ POST 会**先试加载一遍再落盘**:直接写进去的话,用户导入一个写错的文件, - 节点列表里就多一个坏节点,每次开会都看见它。先跑一遍能把 Python 的报错 - **当场**回给界面,而且原始报错不吞 —— 用户要照着那句话去改代码。 -★ 文件名只留 basename:用户选的路径里可能带 / 或 ..,不能让它写到别处。 - -【现场编辑】 -代码框(可滚动)+ 文件名可改。保存走同一个 POST,所以同样有"先试加载"的保护。 - -【搭积木】 -「代码 / 搭积木」两个页签。积木面板有 12 块: - 📝 记一条日志 / 📤 设置文本输出 / 💾 写变量 / 📖 读输入 / 🔤 转大写 / - ✂️ 取前几个字 / 📏 文本长度 / ➕ 拼两段文本 / 🔀 如果…否则… / - 🔁 重复 N 次 / 🧩 遍历列表 / 🛡 试试看(出错不崩) -点一块就把对应的 Python 追加到代码末尾,下面实时显示"当前代码"。 - -★ 为什么不做 Scratch 那种拖拽画布: - 这里的产物最终是**代码**,代码编辑器本来就在旁边(同一个对话框里另一个页签)。 - 做成"点积木 -> 生成代码 -> 你接着改",生成的是**可读可改、能继续学**的普通 - Python,而不是一个封闭的图形。对新手:从零写不出来但知道要"记一条日志"; - 对老手:这些块就是快捷键,省得敲样板代码。 - 拖拽画布要自己实现吸附、嵌套、布局,收益主要是好看 —— 那是下一步的事。 - -【界面放在新文件里】 -MeetingsCustomNodes.kt(NodeManagerDialog / NodeEditDialog / 积木表)。 -MeetingsScreen.kt 已经 3800 行,往里塞东西每一次都要重新理解上下文, -而且改错了很难看出来 —— 这一轮就因为漏一个花括号排查了很久。 - -【顺带修的一个真 bug】 -加节点面板里导入那块 Column 少了一个 `}`(我写漏的), -导致 MeetingEditorScreen 不闭合、后面所有顶层声明全部"未解析" -(报的是 PrimaryButton / LinkFrom / canvasSize 找不到,看着完全不像是括号问题)。 -用括号计数脚本定位到的。这个排查手段以后可以常用。 - -【设备实测(emulator-5556)】 - 加节点面板:🐍 打分 score.py + 说明 ✓ - 节点管理:目录显示、新建/导入、编辑/导出/删除 ✓ - 编辑对话框:读到真实源码、代码/搭积木两个页签 ✓ - 搭积木:12 块积木、点击生成、当前代码实时预览 ✓ - 引擎:CUSTOMDIR / CUSTOMNODES / SAVED 5/5 / STEPS ['ev','sc','hi'] / - RESULTS [('高分出口','分数:7')] ✓ - -【验证】 -- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致 -- 会议 HTTP 13/13 -- APK 构建通过、装机通过、界面截图确认