expr_editor.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. import 'package:flutter/material.dart';
  2. import 'expr_node.dart';
  3. /// 结构化表达式的 2D 编辑器视图。
  4. ///
  5. /// 渲染方式:直接把节点树翻译成 widget 树 —— 分式用 Column(分子/横线/分母)、
  6. /// 幂用 Row + 抬高的上标、函数用 `名字[ 参数 ]`。没有自己写排版引擎,
  7. /// 因为 Flutter 的布局本来就够用,而且这样点击命中、无障碍都能白拿。
  8. class ExprEditor extends StatelessWidget {
  9. const ExprEditor({
  10. super.key,
  11. required this.doc,
  12. required this.onChanged,
  13. required this.onCaretTapped,
  14. this.fontSize = 22,
  15. });
  16. final ExprDoc doc;
  17. /// 光标或内容变化后调用,让页面刷新。
  18. final VoidCallback onChanged;
  19. /// 用户点了**光标已经所在的那个位置**(且没有选区)—— 页面据此弹出"粘贴"。
  20. final VoidCallback onCaretTapped;
  21. final double fontSize;
  22. /// 点一个节点。
  23. ///
  24. /// 三种语义:
  25. /// · 有选区时 → 扩展选区("按住选中一个,再点另一个")
  26. /// · 没选区、但点的是光标已经待着的地方 → 交给页面弹粘贴
  27. /// · 其余 → 移动光标
  28. void _tapNode(SlotPath parent, int index, bool before) {
  29. if (doc.selection != null) {
  30. doc.extendSelectionTo(parent, index);
  31. onChanged();
  32. return;
  33. }
  34. final target = SlotPath(parent.steps, before ? index : index + 1);
  35. if (doc.cursor == target) {
  36. onCaretTapped();
  37. return;
  38. }
  39. doc.cursor = target;
  40. onChanged();
  41. }
  42. /// 长按一个节点 → 选中它,工具条随之出现。
  43. void _longPressNode(SlotPath parent, int index) {
  44. doc.selectNodeAt(parent, index);
  45. onChanged();
  46. }
  47. /// 点槽的空白处:有选区就取消选区,否则光标落到槽尾。
  48. void _tapSlot(SlotPath path, SeqNode seq) {
  49. if (doc.selection != null) {
  50. doc.clearSelection();
  51. onChanged();
  52. return;
  53. }
  54. final p = SlotPath(path.steps, seq.children.length);
  55. if (doc.cursor == p) {
  56. onCaretTapped();
  57. return;
  58. }
  59. doc.cursor = p;
  60. onChanged();
  61. }
  62. @override
  63. Widget build(BuildContext context) {
  64. return SingleChildScrollView(
  65. scrollDirection: Axis.horizontal,
  66. reverse: true, // 长表达式总是把光标一侧露出来
  67. child: ConstrainedBox(
  68. constraints: BoxConstraints(
  69. minWidth: MediaQuery.sizeOf(context).width - 32,
  70. ),
  71. child: Align(
  72. alignment: Alignment.centerRight,
  73. child: Padding(
  74. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  75. child: _SlotView(
  76. doc: doc,
  77. seq: doc.root,
  78. path: SlotPath.root,
  79. size: fontSize,
  80. onTapNode: _tapNode,
  81. onLongPressNode: _longPressNode,
  82. onTapSlot: _tapSlot,
  83. ),
  84. ),
  85. ),
  86. ),
  87. );
  88. }
  89. }
  90. /// 一个槽的视图:把孩子按顺序排开,在光标位置插一根竖线。
  91. class _SlotView extends StatelessWidget {
  92. const _SlotView({
  93. required this.doc,
  94. required this.seq,
  95. required this.path,
  96. required this.size,
  97. required this.onTapNode,
  98. required this.onLongPressNode,
  99. required this.onTapSlot,
  100. });
  101. final ExprDoc doc;
  102. final SeqNode seq;
  103. final SlotPath path;
  104. final double size;
  105. final void Function(SlotPath parent, int index, bool before) onTapNode;
  106. final void Function(SlotPath parent, int index) onLongPressNode;
  107. final void Function(SlotPath path, SeqNode seq) onTapSlot;
  108. @override
  109. Widget build(BuildContext context) {
  110. final scheme = Theme.of(context).colorScheme;
  111. // 用 sameSlotAs 而不是 ==:offset 是槽内的插入位置,不属于槽的身份
  112. final focused = doc.cursor.sameSlotAs(path);
  113. final sel = doc.selection;
  114. final selectedHere = sel != null && !sel.isEmpty && sel.path.sameSlotAs(path);
  115. return GestureDetector(
  116. onTap: () => onTapSlot(path, seq),
  117. behavior: HitTestBehavior.opaque,
  118. child: Container(
  119. padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 3),
  120. // 空槽只有一个光标那么宽(2.5px),手指点不到 —— 而"点光标处弹粘贴"
  121. // 恰恰最常在空槽里用(先按 ln 再粘参数)。给个最小的可点面积。
  122. constraints: focused && seq.isEmpty
  123. ? const BoxConstraints(minWidth: 24, minHeight: 30)
  124. : null,
  125. decoration: BoxDecoration(
  126. borderRadius: BorderRadius.circular(4),
  127. color: focused ? scheme.primary.withValues(alpha: 0.06) : null,
  128. ),
  129. child: Wrap(
  130. crossAxisAlignment: WrapCrossAlignment.center,
  131. children: [
  132. for (var i = 0; i < seq.children.length; i++) ...[
  133. if (focused && doc.cursor.offset == i) _caret(scheme),
  134. _SelectedOrNot(
  135. highlighted: selectedHere && i >= sel.start && i < sel.end,
  136. child: _NodeView(
  137. doc: doc,
  138. node: seq.children[i],
  139. parent: path,
  140. index: i,
  141. size: size,
  142. onTapNode: onTapNode,
  143. onLongPressNode: onLongPressNode,
  144. onTapSlot: onTapSlot,
  145. ),
  146. ),
  147. ],
  148. if (focused && doc.cursor.offset >= seq.children.length)
  149. _caret(scheme),
  150. // 空槽给个占位,否则用户不知道能往里点
  151. if (seq.isEmpty && !focused) _placeholder(scheme),
  152. ],
  153. ),
  154. ),
  155. );
  156. }
  157. /// 光标。**常亮、不闪烁**。
  158. ///
  159. /// 之前做成 0.15~1.0 的平滑呼吸,最暗那半程看着就跟没有一样(用户反馈
  160. /// "有时能看到有时看不到")。计算器不是文本编辑器,聚焦的槽本来就有底色
  161. /// 高亮,这里再常亮一根实心竖线,位置一眼就能看到。
  162. Widget _caret(ColorScheme scheme) => Container(
  163. // 整个编辑区同时最多只有一根光标,所以固定 key 不会冲突。
  164. // 加它是为了能写"打完字光标还在不在"的回归测试 —— 这个 bug
  165. // 之前就是靠人眼看截图才发现的。
  166. key: const ValueKey('expr-caret'),
  167. width: 2.5,
  168. height: size * 1.25,
  169. margin: const EdgeInsets.symmetric(horizontal: 1),
  170. color: scheme.primary,
  171. );
  172. Widget _placeholder(ColorScheme scheme) => Container(
  173. width: 12,
  174. height: size * 1.05,
  175. margin: const EdgeInsets.symmetric(horizontal: 1),
  176. decoration: BoxDecoration(
  177. border: Border.all(color: scheme.outlineVariant, width: 1),
  178. borderRadius: BorderRadius.circular(2),
  179. ),
  180. );
  181. }
  182. /// 单个节点的视图。
  183. class _NodeView extends StatelessWidget {
  184. const _NodeView({
  185. required this.doc,
  186. required this.node,
  187. required this.parent,
  188. required this.index,
  189. required this.size,
  190. required this.onTapNode,
  191. required this.onLongPressNode,
  192. required this.onTapSlot,
  193. });
  194. final ExprDoc doc;
  195. final ExprNode node;
  196. /// 该节点所在槽的路径,以及它在槽里的下标。
  197. final SlotPath parent;
  198. final int index;
  199. final double size;
  200. final void Function(SlotPath parent, int index, bool before) onTapNode;
  201. final void Function(SlotPath parent, int index) onLongPressNode;
  202. final void Function(SlotPath path, SeqNode seq) onTapSlot;
  203. @override
  204. Widget build(BuildContext context) {
  205. final scheme = Theme.of(context).colorScheme;
  206. final body = switch (node) {
  207. LitNode l => _literal(l, scheme),
  208. FuncNode f => _function(context, f),
  209. FracNode f => _fraction(context, f),
  210. PowNode p => _power(context, p),
  211. GroupNode g => _group(context, g),
  212. BraceNode b => _brace(context, b),
  213. BigOpNode b => _bigOp(context, b),
  214. PostfixNode p => _row([
  215. _slot(context, p.operand, parent.push(index, 0)),
  216. _text(p.op, size),
  217. ]),
  218. };
  219. // 点节点的**左半边**把光标放到它前面,右半边放到它后面。
  220. //
  221. // 之前无论点哪都落到"后面",于是偏移 0(表达式最前面)那个位置永远够不着 ——
  222. // 用户只能把光标停在第一个字符之后,回不到行首。
  223. //
  224. // 宽度用 Builder 拿:Builder 自身不是 RenderObject,findRenderObject()
  225. // 会往下找到 GestureDetector 那个 box,尺寸正是节点的尺寸。
  226. return Builder(
  227. builder: (inner) => GestureDetector(
  228. behavior: HitTestBehavior.opaque,
  229. onLongPress: () => onLongPressNode(parent, index),
  230. onTapDown: (d) {
  231. final box = inner.findRenderObject() as RenderBox?;
  232. final before = d.localPosition.dx < (box?.size.width ?? 0) / 2;
  233. onTapNode(parent, index, before);
  234. },
  235. child: body,
  236. ),
  237. );
  238. }
  239. Widget _literal(LitNode l, ColorScheme scheme) {
  240. final isLetter = RegExp(r'^[A-Za-z]+$').hasMatch(l.text);
  241. return Text(
  242. l.text,
  243. style: TextStyle(
  244. fontSize: size,
  245. fontFamily: 'serif',
  246. fontStyle: isLetter ? FontStyle.italic : FontStyle.normal,
  247. color: scheme.onSurface,
  248. ),
  249. );
  250. }
  251. /// 常见函数用**数学记号**显示,而不是代码式的 `Name[...]`。
  252. ///
  253. /// 关键点:这里只改**怎么画**,不改槽本身 —— 参数槽还是原来那些,
  254. /// 所以照样能点进去编辑、光标照样能进。
  255. Widget _function(BuildContext context, FuncNode f) {
  256. switch (f.name) {
  257. case 'Sqrt':
  258. if (f.args.length == 1) return _radical(context, f);
  259. case 'Abs':
  260. if (f.args.length == 1) return _bars(context, f);
  261. case 'Integrate':
  262. if (f.args.length == 2) return _integral(context, f);
  263. case 'Sum':
  264. if (f.args.length == 2) return _bigOperator(context, f, '∑');
  265. case 'Product':
  266. if (f.args.length == 2) return _bigOperator(context, f, '∏');
  267. }
  268. return _plainFunction(context, f);
  269. }
  270. TextStyle _mathStyle(BuildContext context, double scale) => TextStyle(
  271. fontSize: size * scale,
  272. color: Theme.of(context).colorScheme.onSurface,
  273. );
  274. /// √ 盖住被开方数。
  275. ///
  276. /// 用画笔画成**一条连起来的折线**(下折 → 上挑 → 横线),而不是
  277. /// "√ 字符 + 一条上边框" —— 后者两边各按各的字形对齐,中间必然断开
  278. /// (用户实测反馈"根号是断开的")。
  279. Widget _radical(BuildContext context, FuncNode f) => _Radical(
  280. size: size,
  281. color: Theme.of(context).colorScheme.onSurface,
  282. child: _slot(context, f.args.first, parent.push(index, 0)),
  283. );
  284. Widget _bars(BuildContext context, FuncNode f) => _row([
  285. Text('|', style: _mathStyle(context, 1.2)),
  286. _slot(context, f.args.first, parent.push(index, 0)),
  287. Text('|', style: _mathStyle(context, 1.2)),
  288. ]);
  289. /// `Integrate[f, x]` 画成 `∫ f dx`。
  290. ///
  291. /// 参数顺序被重排了(数学写法就是 ∫ … d…),但**槽还是那两个槽**,
  292. /// 所以光标和点击命中都不受影响。
  293. Widget _integral(BuildContext context, FuncNode f) => _row([
  294. Text('∫', style: _mathStyle(context, 1.6)),
  295. _slot(context, f.args[0], parent.push(index, 0)),
  296. Text('d', style: _mathStyle(context, 0.9)),
  297. _slot(context, f.args[1], parent.push(index, 1)),
  298. ]);
  299. /// `Sum[f, {n,1,∞}]` 画成 `Σ f {n,1,∞}`(迭代器小一号)。
  300. Widget _bigOperator(BuildContext context, FuncNode f, String glyph) => _row([
  301. Text(glyph, style: _mathStyle(context, 1.6)),
  302. _slot(context, f.args[0], parent.push(index, 0)),
  303. Transform.translate(
  304. offset: Offset(0, size * 0.25),
  305. child: _slot(context, f.args[1], parent.push(index, 1), scale: 0.7),
  306. ),
  307. ]);
  308. Widget _plainFunction(BuildContext context, FuncNode f) {
  309. final scheme = Theme.of(context).colorScheme;
  310. return _row([
  311. Text(
  312. f.name,
  313. style: TextStyle(fontSize: size * 0.85, color: scheme.primary),
  314. ),
  315. Text('[', style: TextStyle(fontSize: size, color: scheme.onSurface)),
  316. for (var i = 0; i < f.args.length; i++) ...[
  317. if (i > 0)
  318. Text(', ', style: TextStyle(fontSize: size, color: scheme.onSurface)),
  319. _slot(context, f.args[i], parent.push(index, i)),
  320. ],
  321. Text(']', style: TextStyle(fontSize: size, color: scheme.onSurface)),
  322. ]);
  323. }
  324. Widget _fraction(BuildContext context, FracNode f) {
  325. final scheme = Theme.of(context).colorScheme;
  326. return Padding(
  327. padding: const EdgeInsets.symmetric(horizontal: 2),
  328. // IntrinsicWidth 让横线刚好横跨分子分母里较宽的那个。
  329. // 不能直接 width: double.infinity —— 这里是 Wrap 里的无界宽度,会报错。
  330. child: IntrinsicWidth(
  331. child: Column(
  332. mainAxisSize: MainAxisSize.min,
  333. children: [
  334. _slot(context, f.num, parent.push(index, 0)),
  335. Container(height: 1.4, color: scheme.onSurface),
  336. _slot(context, f.den, parent.push(index, 1)),
  337. ],
  338. ),
  339. ),
  340. );
  341. }
  342. Widget _power(BuildContext context, PowNode p) {
  343. return _row([
  344. _slot(context, p.base, parent.push(index, 0)),
  345. Transform.translate(
  346. offset: Offset(0, -size * 0.35),
  347. child: _slot(context, p.exp, parent.push(index, 1), scale: 0.7),
  348. ),
  349. ]);
  350. }
  351. Widget _group(BuildContext context, GroupNode g) {
  352. final scheme = Theme.of(context).colorScheme;
  353. final style = TextStyle(fontSize: size, color: scheme.onSurface);
  354. return _row([
  355. Text('(', style: style),
  356. _slot(context, g.inner, parent.push(index, 0)),
  357. Text(')', style: style),
  358. ]);
  359. }
  360. Widget _brace(BuildContext context, BraceNode b) {
  361. final style = TextStyle(
  362. fontSize: size,
  363. color: Theme.of(context).colorScheme.onSurface,
  364. );
  365. return _row([
  366. Text('{', style: style),
  367. _slot(context, b.inner, parent.push(index, 0)),
  368. Text('}', style: style),
  369. ]);
  370. }
  371. /// 大运算符:上下限画在**习惯位置**。
  372. ///
  373. /// ∫ 上限定在上方、下限定在下方,后面接被积函数和 dx
  374. /// ∑ / ∏ 同理,下限在下、上限在上
  375. /// lim 的条件写在 "lim" 正下方
  376. ///
  377. /// 上下限为空时不占位(不定积分就是"∫ f dx",没有上下限)。
  378. Widget _bigOp(BuildContext context, BigOpNode b) {
  379. final body = _slot(context, b.body, parent.push(index, 0));
  380. final variable = _slot(context, b.variable, parent.push(index, 1));
  381. final lower = _slot(context, b.lower, parent.push(index, 2), scale: 0.5);
  382. final upper = _slot(context, b.upper, parent.push(index, 3), scale: 0.5);
  383. if (b.kind == 'Limit') {
  384. // lim 下面写"x→0"
  385. final under = Row(
  386. mainAxisSize: MainAxisSize.min,
  387. children: [
  388. _slot(context, b.variable, parent.push(index, 1), scale: 0.6),
  389. Text('→', style: _mathStyle(context, 0.6)),
  390. lower,
  391. ],
  392. );
  393. return _row([
  394. Column(
  395. mainAxisSize: MainAxisSize.min,
  396. children: [
  397. Text('lim', style: _mathStyle(context, 0.95)),
  398. under,
  399. ],
  400. ),
  401. body,
  402. ]);
  403. }
  404. final glyph = switch (b.kind) {
  405. 'Integrate' => '∫',
  406. 'Sum' => '∑',
  407. 'Product' => '∏',
  408. _ => '∑',
  409. };
  410. final stack = Column(
  411. mainAxisSize: MainAxisSize.min,
  412. children: [
  413. // 上下限**始终渲染** —— 空的时候画成小占位框。
  414. // 不渲染的话不定积分的两个限槽就成了够不着的死结构,永远填不进去。
  415. upper,
  416. Text(glyph, style: _mathStyle(context, 1.7)),
  417. lower,
  418. ],
  419. );
  420. if (b.kind == 'Integrate') {
  421. return _row([
  422. stack,
  423. body,
  424. Text('d', style: _mathStyle(context, 0.9)),
  425. variable,
  426. ]);
  427. }
  428. return _row([stack, body]);
  429. }
  430. Widget _row(List<Widget> children) => Wrap(
  431. crossAxisAlignment: WrapCrossAlignment.center,
  432. children: children,
  433. );
  434. /// [scale] 是**真的把字号改小**,而不是 Transform 缩放。
  435. ///
  436. /// Transform 只改视觉、不改布局,占位仍是原尺寸 —— 结果就是"字看着小了
  437. /// 但离运算符老远"(用户实测反馈)。直接把 size 传下去,布局才会跟着缩。
  438. Widget _slot(BuildContext context, SeqNode seq, SlotPath path,
  439. {double scale = 1}) =>
  440. _SlotView(
  441. doc: doc,
  442. seq: seq,
  443. path: path,
  444. size: size * scale,
  445. onTapNode: onTapNode,
  446. onLongPressNode: onLongPressNode,
  447. onTapSlot: onTapSlot,
  448. );
  449. Widget _text(String t, double s) => Text(t, style: TextStyle(fontSize: s));
  450. }
  451. /// 根号:画笔画出的折线 + 上划线,被开方数挂在横线下面。
  452. class _Radical extends StatelessWidget {
  453. const _Radical({
  454. required this.size,
  455. required this.color,
  456. required this.child,
  457. });
  458. final double size;
  459. final Color color;
  460. final Widget child;
  461. @override
  462. Widget build(BuildContext context) {
  463. final arm = size * 0.42; // 左侧那一段"折"的宽度
  464. return CustomPaint(
  465. painter: _RadicalPainter(color, arm),
  466. child: Padding(
  467. padding: EdgeInsets.only(left: arm, top: size * 0.30),
  468. child: child,
  469. ),
  470. );
  471. }
  472. }
  473. class _RadicalPainter extends CustomPainter {
  474. _RadicalPainter(this.color, this.arm);
  475. final Color color;
  476. final double arm;
  477. @override
  478. void paint(Canvas canvas, Size s) {
  479. final paint = Paint()
  480. ..color = color
  481. ..strokeWidth = 1.4
  482. ..style = PaintingStyle.stroke
  483. ..strokeJoin = StrokeJoin.miter
  484. ..strokeCap = StrokeCap.butt;
  485. // 从左下起笔 → 折到底 → 挑到顶 → 横着盖住被开方数
  486. final path = Path()
  487. ..moveTo(0, s.height * 0.55)
  488. ..lineTo(arm * 0.4, s.height * 0.92)
  489. ..lineTo(arm, 0)
  490. ..lineTo(s.width, 0);
  491. canvas.drawPath(path, paint);
  492. }
  493. @override
  494. bool shouldRepaint(covariant _RadicalPainter old) =>
  495. old.color != color || old.arm != arm;
  496. }
  497. /// 选中时给节点盖一层高亮背景。
  498. class _SelectedOrNot extends StatelessWidget {
  499. const _SelectedOrNot({required this.highlighted, required this.child});
  500. final bool highlighted;
  501. final Widget child;
  502. @override
  503. Widget build(BuildContext context) {
  504. if (!highlighted) return child;
  505. return Container(
  506. decoration: BoxDecoration(
  507. color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.22),
  508. borderRadius: BorderRadius.circular(3),
  509. ),
  510. child: child,
  511. );
  512. }
  513. }