calculator_page.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_math_fork/flutter_math.dart';
  5. import 'package:provider/provider.dart';
  6. import 'curve_plot.dart';
  7. import 'expr_editor.dart';
  8. import 'expr_node.dart';
  9. import 'expr_parse.dart';
  10. import 'symja.dart';
  11. import 'symja_functions.dart';
  12. /// 科学计算器(默认主界面)。
  13. ///
  14. /// 输入用**结构化节点树**(见 lib/expr_node.dart),不是字符串:
  15. /// 按键把节点插进当前光标槽,分数竖排、指数上标、多参数函数各有自己的槽。
  16. /// 纯文本输入留给控制台。
  17. class CalculatorPage extends StatefulWidget {
  18. const CalculatorPage({super.key});
  19. @override
  20. State<CalculatorPage> createState() => _CalculatorPageState();
  21. }
  22. class _CalculatorPageState extends State<CalculatorPage> {
  23. final _doc = ExprDoc();
  24. SymjaResult? _preview;
  25. SymjaResult? _committed;
  26. String? _error;
  27. Timer? _debounce;
  28. int _seq = 0;
  29. /// 用户点了"光标已经在的地方"—— 显示粘贴入口。
  30. bool _pastePrompt = false;
  31. @override
  32. void dispose() {
  33. _debounce?.cancel();
  34. super.dispose();
  35. }
  36. // ------------------------------------------------------------------ 求值
  37. /// 编辑器每次变化都走这里:清掉上次的提交态,防抖后重算预览。
  38. void _onDocChanged() {
  39. setState(() {
  40. _committed = null;
  41. _error = null;
  42. _pastePrompt = false; // 动过内容/光标就收起操作栏
  43. });
  44. _debounce?.cancel();
  45. _debounce = Timer(const Duration(milliseconds: 500), _runPreview);
  46. }
  47. String get _source => _doc.toSymja();
  48. void _snack(String msg) {
  49. if (!mounted) return;
  50. ScaffoldMessenger.of(context)
  51. ..hideCurrentSnackBar()
  52. ..showSnackBar(SnackBar(content: Text(msg)));
  53. }
  54. Future<void> _copy(String text, String what) async {
  55. await Clipboard.setData(ClipboardData(text: text));
  56. _snack('已复制$what:$text');
  57. }
  58. /// 从剪贴板读一段 Symja 表达式,解析成节点树后整体替换。
  59. ///
  60. /// 解析器只认一个明确的子集,**认不出来就报错**,不会猜着解析 ——
  61. /// 猜错了你会看到算错的结果,那比报错糟糕得多。
  62. Future<void> _paste() async {
  63. final data = await Clipboard.getData(Clipboard.kTextPlain);
  64. final text = (data?.text ?? '').trim();
  65. if (text.isEmpty) {
  66. _snack('剪贴板里没有文本');
  67. return;
  68. }
  69. try {
  70. final parsed = parseSymjaExpr(text);
  71. setState(() {
  72. _pastePrompt = false;
  73. if (_doc.selection != null) _doc.deleteSelection(); // 有选区就替换掉
  74. _doc.insertNodesAtCursor(parsed.children); // 否则插到光标处
  75. _preview = null;
  76. _committed = null;
  77. _error = null;
  78. });
  79. _onDocChanged();
  80. _snack('已粘贴到光标处:${_doc.toSymja()}');
  81. } on ExprParseException catch (e) {
  82. _snack('这段表达式没法转成按钮式输入 —— $e');
  83. }
  84. }
  85. // ------------------------------------------------------------------ 选区操作
  86. /// 操作栏上的图标按钮。压扁一点,别把这条栏撑高。
  87. Widget _barButton(IconData icon, String tip, VoidCallback onTap) => IconButton(
  88. tooltip: tip,
  89. icon: Icon(icon, size: 20),
  90. visualDensity: VisualDensity.compact,
  91. padding: const EdgeInsets.symmetric(horizontal: 6),
  92. constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
  93. onPressed: onTap,
  94. );
  95. Future<void> _copySelection() async {
  96. final t = _doc.selectionText;
  97. if (t.isEmpty) return;
  98. await _copy(t, '选中内容');
  99. setState(() => _doc.clearSelection());
  100. }
  101. Future<void> _cutSelection() async {
  102. final t = _doc.selectionText;
  103. if (t.isEmpty) return;
  104. await Clipboard.setData(ClipboardData(text: t));
  105. setState(() {
  106. _doc.deleteSelection();
  107. _pastePrompt = false;
  108. });
  109. _onDocChanged();
  110. _snack('已剪切:$t');
  111. }
  112. void _dismissBar() {
  113. setState(() {
  114. _pastePrompt = false;
  115. _doc.clearSelection();
  116. });
  117. }
  118. /// 选中部分内容后自动出现的操作栏;或点了光标处时的粘贴入口。
  119. Widget? _contextBar() {
  120. final sel = _doc.selection;
  121. final hasSel = sel != null && !sel.isEmpty;
  122. if (!hasSel && !_pastePrompt) return null;
  123. final scheme = Theme.of(context).colorScheme;
  124. return Material(
  125. color: scheme.surfaceContainerHighest,
  126. child: Padding(
  127. padding: const EdgeInsets.only(left: 12, right: 4),
  128. child: Row(
  129. children: [
  130. Expanded(
  131. child: Text(
  132. hasSel ? '已选中 ${_doc.selectionText}' : '粘贴到光标处',
  133. maxLines: 1,
  134. overflow: TextOverflow.ellipsis,
  135. style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
  136. ),
  137. ),
  138. // 用图标而不是文字按钮 —— 文字太占地方,一条栏塞不下几个
  139. if (hasSel) ...[
  140. _barButton(Icons.copy, '复制', _copySelection),
  141. _barButton(Icons.cut, '剪切', _cutSelection),
  142. ] else
  143. _barButton(Icons.paste, '粘贴', _paste),
  144. _barButton(Icons.close, '取消选择', _dismissBar),
  145. ],
  146. ),
  147. ),
  148. );
  149. }
  150. Future<void> _runPreview() async {
  151. final expr = _source;
  152. if (expr.isEmpty || expr == 'Null') {
  153. if (mounted) setState(() => _preview = null);
  154. return;
  155. }
  156. final session = context.read<SymjaSession>();
  157. final id = ++_seq;
  158. final r = await session.preview(expr);
  159. if (!mounted || id != _seq) return; // 已有更新的预览在路上
  160. setState(() => _preview = r);
  161. }
  162. Future<void> _commit() async {
  163. final expr = _source;
  164. if (expr.isEmpty || expr == 'Null') return;
  165. _debounce?.cancel();
  166. final session = context.read<SymjaSession>();
  167. final id = ++_seq; // 让在途的预览作废
  168. try {
  169. final r = await session.evaluate(expr);
  170. if (!mounted || id != _seq) return;
  171. setState(() {
  172. _committed = r;
  173. _preview = null;
  174. _error = null;
  175. });
  176. } on SymjaException catch (e) {
  177. if (!mounted || id != _seq) return;
  178. setState(() {
  179. _error = '$e';
  180. _committed = null;
  181. _preview = null;
  182. });
  183. }
  184. await session.refreshVariables();
  185. }
  186. Future<void> _plotCurrent() async {
  187. final expr = _source;
  188. if (expr.isEmpty || expr == 'Null') return;
  189. final session = context.read<SymjaSession>();
  190. final messenger = ScaffoldMessenger.of(context);
  191. try {
  192. final s = await session.sample(expr, from: -6.3, to: 6.3, count: 240);
  193. if (!mounted) return;
  194. await showDialog<void>(
  195. context: context,
  196. builder: (_) => AlertDialog(
  197. title: Text('$expr (${s.ys.length} 点,${s.elapsedMs} ms)'),
  198. content: SizedBox(
  199. width: 360,
  200. height: 420,
  201. child: CurvePlot(series: [
  202. CurveSeries(
  203. label: expr,
  204. color: const Color(0xFF3F51B5),
  205. points: [
  206. for (var i = 0; i < s.ys.length; i++)
  207. Offset(s.xAt(i), s.ys[i]),
  208. ],
  209. ),
  210. ]),
  211. ),
  212. actions: [
  213. TextButton(
  214. onPressed: () => Navigator.pop(context),
  215. child: const Text('关闭'),
  216. ),
  217. ],
  218. ),
  219. );
  220. } on SymjaException catch (e) {
  221. messenger.showSnackBar(SnackBar(content: Text('$e')));
  222. }
  223. }
  224. // ------------------------------------------------------------------ 按键
  225. void _press(_Key k) {
  226. switch (k.act) {
  227. case _Act.char:
  228. if (k.mergeDigit) {
  229. // 数字键并入左边那个数字字面量,`42` 才是一个数而不是两个节点
  230. _doc.insertChar(k.payload);
  231. } else {
  232. _doc.insert(LitNode(k.payload, display: k.display));
  233. }
  234. case _Act.fn:
  235. _doc.makeFunction(k.payload);
  236. case _Act.fnPrefixed:
  237. // 像 D 这种,第一个参数留空给用户填,其余预置好
  238. _doc.makeFunction(k.payload, prefill: k.prefill);
  239. case _Act.bigOp:
  240. // ∫ / Σ / lim:上下限单独成槽,才画得到习惯位置
  241. final p = k.prefill;
  242. _doc.makeBigOp(
  243. k.payload,
  244. variable: p.isNotEmpty ? p[0] : 'x',
  245. lower: p.length > 1 ? p[1] : '',
  246. upper: p.length > 2 ? p[2] : '',
  247. );
  248. case _Act.sqrt:
  249. _doc.makeFunction('Sqrt');
  250. case _Act.group:
  251. _doc.makeGroup();
  252. case _Act.power:
  253. _doc.makePower();
  254. case _Act.brace:
  255. _doc.makeBrace();
  256. case _Act.newRow:
  257. _doc.addMatrixRow();
  258. case _Act.frac:
  259. _doc.makeFraction();
  260. case _Act.postfix:
  261. // 阶乘是后缀:把光标左边那个节点收进来当操作数
  262. final operand = _doc.takeLeft();
  263. _doc.insert(PostfixNode(
  264. operand: SeqNode(operand == null ? null : [operand]),
  265. ));
  266. case _Act.comma:
  267. _doc.nextArgument();
  268. case _Act.back:
  269. _doc.backspace();
  270. case _Act.clear:
  271. _doc.clear();
  272. case _Act.commit:
  273. _commit();
  274. return; // 提交不改文档,不用刷新
  275. }
  276. _onDocChanged();
  277. }
  278. Future<void> _showPalette() async {
  279. final picked = await showModalBottomSheet<({String value, bool isFn})>(
  280. context: context,
  281. isScrollControlled: true,
  282. showDragHandle: true,
  283. builder: (_) => const _FunctionPalette(),
  284. );
  285. if (picked == null) return;
  286. if (picked.isFn) {
  287. _doc.makeFunction(picked.value);
  288. } else {
  289. _doc.insert(LitNode(picked.value));
  290. }
  291. _onDocChanged();
  292. }
  293. // ------------------------------------------------------------------ UI
  294. @override
  295. Widget build(BuildContext context) {
  296. final session = context.watch<SymjaSession>();
  297. final bar = _contextBar();
  298. return Scaffold(
  299. appBar: AppBar(
  300. // 不显示标题、顶栏压扁 —— 省下来的竖向空间给键盘
  301. toolbarHeight: 44,
  302. actions: [
  303. // 精确 / 近似 切换。默认精确:`1/3` 就是 `1/3`,这是符号计算的意义所在。
  304. TextButton(
  305. onPressed: () {
  306. session.approximate = !session.approximate;
  307. _onDocChanged(); // 立刻按新模式重算预览
  308. },
  309. child: Text(
  310. session.approximate ? '≈ 近似' : '精确',
  311. style: TextStyle(
  312. fontFamily: 'monospace',
  313. fontSize: 13,
  314. color: Theme.of(context).colorScheme.primary,
  315. ),
  316. ),
  317. ),
  318. IconButton(
  319. tooltip: '画图(x ∈ [-6.3, 6.3])',
  320. icon: const Icon(Icons.show_chart),
  321. onPressed: _plotCurrent,
  322. ),
  323. IconButton(
  324. tooltip: '函数面板',
  325. icon: const Icon(Icons.functions),
  326. onPressed: _showPalette,
  327. ),
  328. ],
  329. ),
  330. body: SafeArea(
  331. child: Column(
  332. children: [
  333. _display(context),
  334. ?bar,
  335. const Divider(height: 1),
  336. Expanded(child: _keypad(context)),
  337. ],
  338. ),
  339. ),
  340. );
  341. }
  342. Widget _display(BuildContext context) {
  343. final scheme = Theme.of(context).colorScheme;
  344. final shown = _committed ?? _preview;
  345. return Container(
  346. width: double.infinity,
  347. constraints: const BoxConstraints(minHeight: 132),
  348. padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
  349. color: scheme.surfaceContainerLow,
  350. child: Column(
  351. crossAxisAlignment: CrossAxisAlignment.end,
  352. children: [
  353. // 固定高度 + 超高时纵向滚动。
  354. // 不固定的话,表达式一变高(分式、Σ 带上下限)编辑区就撑大,
  355. // 下面的键盘整体往下跳,手指刚瞄好的键就换位置了。
  356. SizedBox(
  357. height: 104,
  358. child: SingleChildScrollView(
  359. scrollDirection: Axis.vertical,
  360. reverse: true, // 内容超高时把底部(光标那侧)留在视野里
  361. child: ExprEditor(
  362. doc: _doc,
  363. onChanged: _onDocChanged,
  364. onCaretTapped: () => setState(() => _pastePrompt = true),
  365. ),
  366. ),
  367. ),
  368. const SizedBox(height: 6),
  369. // 常显。它就是真正送进引擎的那串文本(也是"复制表达式"复制走的内容),
  370. // 空槽会写成 Null、隐含括号也会露出来。
  371. Text(
  372. _source,
  373. textAlign: TextAlign.right,
  374. maxLines: 2,
  375. overflow: TextOverflow.ellipsis,
  376. style: TextStyle(
  377. fontFamily: 'monospace',
  378. fontSize: 11,
  379. color: scheme.outline,
  380. ),
  381. ),
  382. const SizedBox(height: 6),
  383. SizedBox(
  384. height: 52,
  385. width: double.infinity,
  386. child: GestureDetector(
  387. key: const ValueKey('calc-result'),
  388. // 点结果 = 复制结果
  389. onTap: shown == null ? null : () => _copy(shown.text, '结果'),
  390. behavior: HitTestBehavior.opaque,
  391. child: FittedBox(
  392. fit: BoxFit.scaleDown,
  393. alignment: Alignment.centerRight,
  394. child: _resultView(context, shown),
  395. ),
  396. ),
  397. ),
  398. ],
  399. ),
  400. );
  401. }
  402. Widget _resultView(BuildContext context, SymjaResult? shown) {
  403. final scheme = Theme.of(context).colorScheme;
  404. if (_error != null) {
  405. return SelectableText(
  406. _error!,
  407. style: TextStyle(
  408. fontFamily: 'monospace',
  409. fontSize: 13,
  410. color: scheme.error,
  411. ),
  412. );
  413. }
  414. if (shown == null) return const SizedBox.shrink();
  415. // 用 Text 而不是 SelectableText:点结果是"复制",选中文字反而挡住点击
  416. final plain = Text(
  417. shown.text,
  418. style: const TextStyle(fontFamily: 'monospace', fontSize: 22),
  419. );
  420. final tex = shown.tex;
  421. final body = tex == null
  422. ? plain
  423. : Math.tex(
  424. tex,
  425. mathStyle: MathStyle.display,
  426. textStyle: TextStyle(fontSize: 26, color: scheme.onSurface),
  427. onErrorFallback: (_) => plain,
  428. );
  429. return Row(
  430. mainAxisSize: MainAxisSize.min,
  431. children: [
  432. if (_committed != null) ...[
  433. Icon(Icons.check_circle, size: 16, color: scheme.primary),
  434. const SizedBox(width: 6),
  435. Text('${_committed!.elapsedMs} ms',
  436. style: TextStyle(fontSize: 11, color: scheme.outline)),
  437. const SizedBox(width: 10),
  438. ],
  439. body,
  440. ],
  441. );
  442. }
  443. Widget _keypad(BuildContext context) {
  444. return LayoutBuilder(
  445. builder: (context, box) {
  446. final rows = <List<_Key>>[
  447. // 1 大运算符
  448. [
  449. _Key('∫', _Act.bigOp, payload: 'Integrate', prefill: ['x']),
  450. _Key('Σ', _Act.bigOp,
  451. payload: 'Sum', prefill: ['n', '1', 'Infinity']),
  452. _Key('d/dx', _Act.fnPrefixed, payload: 'D', prefill: ['', 'x']),
  453. _Key('lim', _Act.bigOp, payload: 'Limit', prefill: ['x', '0']),
  454. _Key('solve', _Act.fnPrefixed, payload: 'Solve', prefill: ['', 'x']),
  455. ],
  456. // 2 常用函数
  457. [
  458. _Key('sin', _Act.fn, payload: 'Sin'),
  459. _Key('cos', _Act.fn, payload: 'Cos'),
  460. _Key('tan', _Act.fn, payload: 'Tan'),
  461. _Key('ln', _Act.fn, payload: 'Log'),
  462. _Key('√', _Act.sqrt),
  463. ],
  464. // 3 变量
  465. [
  466. _Key('x', _Act.char, payload: 'x'),
  467. _Key('a', _Act.char, payload: 'a'),
  468. _Key('b', _Act.char, payload: 'b'),
  469. _Key('t', _Act.char, payload: 't'),
  470. _Key('n', _Act.char, payload: 'n'),
  471. ],
  472. // 4 运算符:解方程、赋值、代入、定义函数全靠它们。
  473. // 都是"运算符"不是"函数",所以放键盘上而不是函数面板里。
  474. [
  475. _Key('=', _Act.char, payload: '=', tint: true),
  476. _Key('==', _Act.char, payload: '==', tint: true),
  477. _Key('/.', _Act.char, payload: '/.', tint: true),
  478. _Key('->', _Act.char, payload: '->', tint: true),
  479. _Key('_', _Act.char, payload: '_', tint: true),
  480. ],
  481. // 5 数字与括号
  482. [
  483. _Key('7', _Act.char, payload: '7', mergeDigit: true),
  484. _Key('8', _Act.char, payload: '8', mergeDigit: true),
  485. _Key('9', _Act.char, payload: '9', mergeDigit: true),
  486. _Key('(', _Act.group),
  487. _Key('/', _Act.frac),
  488. ],
  489. [
  490. _Key('4', _Act.char, payload: '4', mergeDigit: true),
  491. _Key('5', _Act.char, payload: '5', mergeDigit: true),
  492. _Key('6', _Act.char, payload: '6', mergeDigit: true),
  493. _Key('×', _Act.char, payload: '*'),
  494. _Key('!', _Act.postfix),
  495. ],
  496. [
  497. _Key('1', _Act.char, payload: '1', mergeDigit: true),
  498. _Key('2', _Act.char, payload: '2', mergeDigit: true),
  499. _Key('3', _Act.char, payload: '3', mergeDigit: true),
  500. _Key('+', _Act.char, payload: '+'),
  501. _Key('−', _Act.char, payload: '-'),
  502. ],
  503. // 7 花括号:矩阵用
  504. [
  505. _Key('0', _Act.char, payload: '0', mergeDigit: true),
  506. _Key('.', _Act.char, payload: '.', mergeDigit: true),
  507. _Key('^', _Act.power),
  508. _Key('{', _Act.brace),
  509. _Key('},{', _Act.newRow, tint: true),
  510. ],
  511. [
  512. _Key('⌫', _Act.back, tint: true),
  513. _Key('CLR', _Act.clear, tint: true),
  514. _Key(',', _Act.comma),
  515. _Key('ANS', _Act.char, payload: '%', tint: true, display: 'ANS'),
  516. // 键盘负责"敲字符",✓ 负责"执行"。两者都叫 = 会撞车。
  517. _Key('✓', _Act.commit, primary: true),
  518. ],
  519. ];
  520. // 7 行 + 6 个间隙,再扣掉 Padding 上下各 6 ——
  521. // box.maxHeight 是 padding **之前**的高度,漏掉会溢出。
  522. final h = (box.maxHeight - 12 - 8 * 6) / 9;
  523. return Padding(
  524. padding: const EdgeInsets.all(6),
  525. child: Column(
  526. children: [
  527. for (var r = 0; r < rows.length; r++) ...[
  528. if (r > 0) const SizedBox(height: 6),
  529. SizedBox(
  530. height: h,
  531. child: Row(
  532. children: [
  533. for (var c = 0; c < rows[r].length; c++) ...[
  534. if (c > 0) const SizedBox(width: 6),
  535. Expanded(child: _keyButton(rows[r][c])),
  536. ],
  537. ],
  538. ),
  539. ),
  540. ],
  541. ],
  542. ),
  543. );
  544. },
  545. );
  546. }
  547. Widget _keyButton(_Key k) {
  548. final scheme = Theme.of(context).colorScheme;
  549. final bg = k.primary
  550. ? scheme.primary
  551. : k.tint
  552. ? scheme.surfaceContainerHighest
  553. : scheme.surfaceContainerLow;
  554. final fg = k.primary ? scheme.onPrimary : scheme.onSurface;
  555. return Material(
  556. // 加 key 是为了让测试能精确定位按键 —— 编辑器里渲染出的字面量(比如 'x')
  557. // 和键盘上同名的按键都符合 find.text,会撞车。
  558. key: ValueKey('key-${k.label}'),
  559. color: bg,
  560. borderRadius: BorderRadius.circular(10),
  561. child: InkWell(
  562. borderRadius: BorderRadius.circular(10),
  563. onTap: () => _press(k),
  564. child: Center(
  565. child: Text(
  566. k.label,
  567. style: TextStyle(
  568. color: fg,
  569. fontSize: k.label.length > 2 ? 13 : 17,
  570. fontFamily: k.label.length > 2 ? null : 'monospace',
  571. ),
  572. ),
  573. ),
  574. ),
  575. );
  576. }
  577. }
  578. enum _Act {
  579. char,
  580. fn,
  581. fnPrefixed,
  582. bigOp,
  583. brace,
  584. newRow,
  585. sqrt,
  586. group,
  587. power,
  588. frac,
  589. postfix,
  590. comma,
  591. back,
  592. clear,
  593. commit,
  594. }
  595. @immutable
  596. class _Key {
  597. final String label;
  598. final _Act act;
  599. final String payload;
  600. /// fnPrefixed 用:第一个参数留空给用户填,其余的预置。
  601. final List<String> prefill;
  602. /// 数字键:并入左边那个数字字面量,而不是各建一个节点。
  603. final bool mergeDigit;
  604. /// 编辑框里显示的名字(和真正送出去的 payload 不同时用)。
  605. final String? display;
  606. final bool tint;
  607. final bool primary;
  608. const _Key(
  609. this.label,
  610. this.act, {
  611. this.payload = '',
  612. this.prefill = const [],
  613. this.mergeDigit = false,
  614. this.display,
  615. this.tint = false,
  616. this.primary = false,
  617. });
  618. }
  619. /// 函数面板:检索 Symja 的两百多个函数名,选中后插入一个函数节点。
  620. class _FunctionPalette extends StatefulWidget {
  621. const _FunctionPalette();
  622. @override
  623. State<_FunctionPalette> createState() => _FunctionPaletteState();
  624. }
  625. class _FunctionPaletteState extends State<_FunctionPalette> {
  626. final _search = TextEditingController();
  627. String _q = '';
  628. @override
  629. void dispose() {
  630. _search.dispose();
  631. super.dispose();
  632. }
  633. @override
  634. Widget build(BuildContext context) {
  635. final q = _q.trim().toLowerCase();
  636. final fns = kSymjaFunctions
  637. .where((f) => q.isEmpty || f.toLowerCase().contains(q))
  638. .toList(growable: false);
  639. return DraggableScrollableSheet(
  640. expand: false,
  641. initialChildSize: 0.75,
  642. maxChildSize: 0.95,
  643. builder: (context, scroll) => Column(
  644. children: [
  645. Padding(
  646. padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
  647. child: TextField(
  648. controller: _search,
  649. autofocus: true,
  650. decoration: InputDecoration(
  651. isDense: true,
  652. hintText: '函数名(共 ${kSymjaFunctions.length} 个)',
  653. prefixIcon: const Icon(Icons.search),
  654. border: const OutlineInputBorder(),
  655. ),
  656. onChanged: (v) => setState(() => _q = v),
  657. ),
  658. ),
  659. // 常量做成可点的 —— 它们从键盘上挪走了,得有个地方能按。
  660. Padding(
  661. padding: const EdgeInsets.symmetric(horizontal: 16),
  662. child: Wrap(
  663. spacing: 8,
  664. runSpacing: 4,
  665. crossAxisAlignment: WrapCrossAlignment.center,
  666. children: [
  667. Text('常量', style: Theme.of(context).textTheme.bodySmall),
  668. for (final c in kSymjaConstants)
  669. ActionChip(
  670. label: Text(
  671. c,
  672. style: const TextStyle(
  673. fontFamily: 'monospace', fontSize: 12),
  674. ),
  675. visualDensity: VisualDensity.compact,
  676. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  677. onPressed: () =>
  678. Navigator.pop(context, (value: c, isFn: false)),
  679. ),
  680. ],
  681. ),
  682. ),
  683. const Divider(height: 16),
  684. Expanded(
  685. child: fns.isEmpty
  686. ? const Center(child: Text('没有匹配的函数'))
  687. : ListView.builder(
  688. controller: scroll,
  689. itemCount: fns.length,
  690. itemBuilder: (_, i) => ListTile(
  691. dense: true,
  692. title: Text(
  693. fns[i],
  694. style: const TextStyle(fontFamily: 'monospace'),
  695. ),
  696. // 一句中文说明,挂名字后面
  697. subtitle: Text(
  698. kSymjaFunctionHelp[fns[i]] ?? '',
  699. style: const TextStyle(fontSize: 12),
  700. ),
  701. onTap: () => Navigator.pop(
  702. context, (value: fns[i], isFn: true)),
  703. ),
  704. ),
  705. ),
  706. ],
  707. ),
  708. );
  709. }
  710. }