カーソルキーでアイディアを自動追加 – 開発日記(5)

キーボード操作の機能改善 2023/03/20

カーソル右を押したときに隣のレーンに移動し、かつ不足するアイディアを自動で追加するようにした。

ただ、やや挙動がおかしい。laneKeysにうまく値が入らないようだ。

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'indent_line_painter.dart';
import 'dart:math';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(child: LaneManager()),
      ),
    );
  }
}

class LaneManager extends StatefulWidget {
  @override
  State<LaneManager> createState() => _LaneManagerState();
}

class _LaneManagerState extends State<LaneManager> {
  List<GlobalKey<_LaneState>> laneKeys = [];
  double _scale = 1.0;

  List<Lane> lanes = [
    Lane(key: GlobalKey<_LaneState>(), ideas: [Idea(key: GlobalKey<_IdeaState>(), index: 0)])
  ];


  @override
  void initState() {
    super.initState();
    lanes.forEach((lane) {
      if (lane.key != null && lane.key is GlobalKey<_LaneState>) {
        laneKeys.add(lane.key as GlobalKey<_LaneState>);
      }
    });
  }

  void addLane() {
    setState(() {
      lanes.add(Lane(key: GlobalKey<_LaneState>(), ideas: [Idea(key: GlobalKey<_IdeaState>(), index: 0)]));
    });
  }

  void removeLane() {
    setState(() {
      if (lanes.length > 1) {
        lanes.removeLast();
      }
    });
  }

  void focusNextLane(int targetLane, int targetIdeaIndex) {
    if (targetLane < 0 || targetIdeaIndex < 0) return;
    if (targetLane == lanes.length) {
      addLane();
    }
    if (targetLane < lanes.length) {
      while (lanes[targetLane].ideas.length <= targetIdeaIndex) {
        _LaneState targetLaneState = laneKeys[targetLane].currentState!;
        targetLaneState.addNewIdea(targetLaneState.widget.ideas.length);
      }
      lanes[targetLane].ideas[targetIdeaIndex].key.currentState?._textFocusNode.requestFocus();
    }
  }

  void scaleUp() {
    setState(() {
      _scale += 0.1;
    });
  }

  void scaleDown() {
    setState(() {
      _scale = max(_scale - 0.1, 0.1);
    });
  }

  @override
  Widget build(BuildContext context) {
    return LaneManagerInheritedWidget(
      laneManagerState: this,
      child: Column(
        children: [
          Align(
            alignment: Alignment.topCenter,
            child: Container(
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: addLane,
                    child: Text("レーン追加"),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: removeLane,
                    child: Text("レーン削除"),
                  ),
                  SizedBox(width: 30),
                  ElevatedButton(
                    onPressed: scaleUp,
                    child: Text("拡大"),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: scaleDown,
                    child: Text("縮小"),
                  ),
                ],
              ),
            ),
          ),
          const Divider(),
          Expanded(
            child: Transform.scale(
              scale: _scale,
              alignment: Alignment.topLeft,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: lanes.length,
                itemBuilder: (context, index) {
                  return Container(
                    width: MediaQuery.of(context).size.width * 0.4,
                    child: lanes[index],
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class LaneManagerInheritedWidget extends InheritedWidget {
  final _LaneManagerState laneManagerState;

  LaneManagerInheritedWidget({required this.laneManagerState, required Widget child})
      : super(child: child);

  @override
  bool updateShouldNotify(LaneManagerInheritedWidget oldWidget) => true;

  static _LaneManagerState of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<LaneManagerInheritedWidget>()!
        .laneManagerState;
  }
}

class Lane extends StatefulWidget {
  final List<Idea> ideas;
  Lane({required GlobalKey<_LaneState> key, required this.ideas});

  @override
  _LaneState createState() => _LaneState();
}

class _LaneState extends State<Lane> {
  List<Idea> get ideas => widget.ideas;

  void addNewIdea(int currentIndex) {
    setState(() {
      int currentIndentLevel =
          ideas[currentIndex].key.currentState?.indentLevel ?? 0;
      ideas.insert(
        currentIndex + 1,
        Idea(
          key: GlobalKey<_IdeaState>(),
          index: currentIndex + 1,
          textFieldHeight: 48.0,
          initialIndentLevel: currentIndentLevel,
        ),
      );
      for (int i = currentIndex + 2; i < ideas.length; i++) {
        ideas[i].index = i;
      }
    });
  }

  void moveIdea(int currentIndex, int direction) {
    if (currentIndex + direction >= 0 &&
        currentIndex + direction < ideas.length) {
      setState(() {
        Idea temp = ideas[currentIndex];
        ideas[currentIndex] = ideas[currentIndex + direction];
        ideas[currentIndex + direction] = temp;
        ideas[currentIndex].key.currentState?.updateIndex(currentIndex);
        ideas[currentIndex + direction]
            .key
            .currentState
            ?.updateIndex(currentIndex + direction);
      });
    }
  }

  void deleteIdea(int currentIndex) {
    if (ideas.length > 1) {
      setState(() {
        ideas.removeAt(currentIndex);
        for (int i = currentIndex; i < ideas.length; i++) {
          ideas[i].index = i;
        }
        if (currentIndex > 0) {
          ideas[currentIndex - 1]
              .key
              .currentState
              ?._textFocusNode
              .requestFocus();
        } else {
          ideas[currentIndex].key.currentState?._textFocusNode.requestFocus();
        }
      });
    }
  }

  void focusAdjacentIdea(int currentIndex, int direction) {
    if (currentIndex + direction >= 0 &&
        currentIndex + direction < ideas.length) {
      ideas[currentIndex + direction]
          .key
          .currentState
          ?._textFocusNode
          .requestFocus();
    }
  }

  void redrawIdeas() {
    setState(() {});
  }

  void redrawAffectedIdeas(int startIndex, int endIndex) {
    if (startIndex < 0 || endIndex >= ideas.length) return;
    setState(() {
      for (int i = startIndex; i <= endIndex; i++) {
        ideas[i].key.currentState?.updateIndentLevel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return LaneInheritedWidget(
      laneState: this,
      child: ListView.builder(
        itemCount: ideas.length,
        itemBuilder: (context, index) {
          return ideas[index];
        },
      ),
    );
  }
}

class LaneInheritedWidget extends InheritedWidget {
  final _LaneState laneState;

  LaneInheritedWidget({required this.laneState, required Widget child})
      : super(child: child);

  @override
  bool updateShouldNotify(LaneInheritedWidget oldWidget) => true;

  static _LaneState of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<LaneInheritedWidget>()!
        .laneState;
  }
}

class Idea extends StatefulWidget {
  int index;
  final GlobalKey<_IdeaState> key;
  final double indentWidth; //インデントの下げ幅
  final double boxSpacing; //他のエディタとの間隔
  final double textFieldHeight; //テキスト欄の高さ
  final int initialIndentLevel;

  Idea({
    required this.key,
    required this.index,
    this.indentWidth = 40.0,
    this.boxSpacing = 8.0,
    this.textFieldHeight = 48.0, //デフォルトは48
    this.initialIndentLevel = 0,
  }) : super(key: ValueKey('Idea ${index}'));

  @override
  _IdeaState createState() => _IdeaState();
}

class _IdeaState extends State<Idea> {
  TextEditingController _textController = TextEditingController();
  int indentLevel = 0;
  FocusNode _textFocusNode = FocusNode();

  void updateIndex(int newIndex) {
    setState(() {
      widget.index = newIndex;
    });
  }

  void updateIndentLevel() {
    setState(() {
      indentLevel = widget.key.currentState?.indentLevel ?? indentLevel;
    });
  }

  // インデントの線を描画する
  void _indentLinePaint(Canvas canvas, Size size) {
    indentLinePaint(canvas, size, context, widget.index, indentLevel, widget.textFieldHeight, widget.boxSpacing, widget.indentWidth);
  }

  @override
  void initState() {
    super.initState();
    indentLevel = widget.initialIndentLevel;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_textFocusNode);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Focus(
        onKey: (FocusNode node, RawKeyEvent event) {
          if (event.runtimeType == RawKeyDownEvent) {
            if (event.logicalKey == LogicalKeyboardKey.capsLock) {
              // CapsLockキーを無視する条件を追加
              return KeyEventResult.ignored;
            } else if (event.isControlPressed) {
              //コントロールキー
              bool needRepaint = false;
              if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
                LaneInheritedWidget.of(context).moveIdea(widget.index, -1);
                needRepaint = true;
              } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
                LaneInheritedWidget.of(context).moveIdea(widget.index, 1);
                needRepaint = true;
              }

              if (needRepaint) {
                findAndRepaintAffectedIdeas(context, widget.index, indentLevel, widget.index, widget.index + 1 /*Ctrlキーの場合、1つ下からチェックが必要*/);
              }
            } else if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
              LaneInheritedWidget.of(context)
                  .focusAdjacentIdea(widget.index, -1);
            } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
              if (widget.index == LaneInheritedWidget.of(context).ideas.length - 1) {
                LaneInheritedWidget.of(context).addNewIdea(widget.index);
              } else {
                LaneInheritedWidget.of(context).focusAdjacentIdea(widget.index, 1);
              }
            } else if (event.logicalKey == LogicalKeyboardKey.arrowRight &&
                _textController.selection.baseOffset == _textController.text.length) {
              int laneIndex = LaneManagerInheritedWidget.of(context).lanes.indexOf(LaneInheritedWidget.of(context).widget);
              LaneManagerInheritedWidget.of(context).focusNextLane(laneIndex+1, widget.index);
            } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft &&
                _textController.selection.baseOffset == 0) {
              int laneIndex = LaneManagerInheritedWidget.of(context).lanes.indexOf(LaneInheritedWidget.of(context).widget);
              LaneManagerInheritedWidget.of(context).focusNextLane(laneIndex-1, widget.index);
            } else if (event.logicalKey == LogicalKeyboardKey.tab) {
              //TABキー
              if (event.isShiftPressed) {
                setState(() {
                  indentLevel = max(0, indentLevel - 1);
                });
              } else {
                setState(() {
                  indentLevel += 1;
                });
              }

              findAndRepaintAffectedIdeas(context, widget.index, indentLevel, widget.index, widget.index);

              return KeyEventResult.handled; //デフォルトのタブの挙動を無効化して、フォーカスの移動を防ぐ
            } else if ((event.logicalKey == LogicalKeyboardKey.delete ||
                    event.logicalKey == LogicalKeyboardKey.backspace) &&
                _textController.text.isEmpty) {
              LaneInheritedWidget.of(context).deleteIdea(widget.index);
            }
          }
          return KeyEventResult.ignored;
        },
        child: RawKeyboardListener(
          focusNode: FocusNode(),
          child: Container(
            margin: EdgeInsets.symmetric(
                horizontal: 16, vertical: widget.boxSpacing),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(
                    width: 26,
                    child: DecoratedBox(
                        decoration: BoxDecoration(color: Colors.red))),
                Expanded(
                  flex: 4,
                  child: Row(children: [
                    CustomPaint(
                      painter: _CustomPainter(_indentLinePaint),
                      child: Container(width: widget.indentWidth * indentLevel),
                    ),
                    Expanded(
                      child: Container(
                        height: widget.textFieldHeight,
                        child: TextField(
                          controller: _textController,
                          focusNode: _textFocusNode,
                          maxLines: 1,
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          keyboardType: TextInputType.multiline,
                          textInputAction: TextInputAction.done,
                          onSubmitted: (value) {
                            _textFocusNode.unfocus();
                            LaneInheritedWidget.of(context)
                                .addNewIdea(widget.index);
                          },
                        ),
                      ),
                    ),
                  ]),
                ),
              ],
            ),
          ),
        ));
  }
}

class _CustomPainter extends CustomPainter {
  final void Function(Canvas, Size) _paint;

  _CustomPainter(this._paint);

  @override
  void paint(Canvas canvas, Size size) {
    _paint(canvas, size);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

indent_line_painter.dart

import 'package:flutter/material.dart';
import 'main.dart';

void indentLinePaint(Canvas canvas,Size size,BuildContext context, int index, int _indentLevel, double textFieldHeight, double boxSpacing, double indentWidth) {
  // インデントの線を描画する
  final paint = Paint()
    ..color = Colors.grey
    ..strokeWidth = 1;
  var leftX = indentWidth / 2;

  // 一行上のIdeaの_indentLevelを取得する
  int upperIndentLevel = 0;
  int upperIndex = index - 1;

  //描画:Canvasの起点は左側センター
  if (_indentLevel > 0 && index > 0 /*一番上の時はツリーを描画しない*/) {
    //一番上の親が居ない場合の特別対応:自分の上のどこかに、indentLevelが小さい親がいるかチェック
    bool cancelFlg = false; //描画しない特別な場合用
    var i = index - 1;
    while (i >= 0) {
      if ((LaneInheritedWidget.of(context)
          .ideas[i]
          .key
          .currentState
          ?.indentLevel ??
          0) <
          _indentLevel) {
        break;
      }
      i--;
    }
    if (i == -1) cancelFlg = true;

    if (!cancelFlg) {
      //縦の線:左側の基準
      leftX = leftX + (indentWidth * (_indentLevel - 1));

      //縦の線:自分の領域内で上に引く
      double startY =
          0 - (textFieldHeight / 2) - (boxSpacing * 2);

      //縦の線:自分の領域外でどのくらい上まで引くかを計算
      upperIndentLevel = LaneInheritedWidget.of(context)
          .ideas[upperIndex]
          .key
          .currentState
          ?.indentLevel ??
          0;
      if (_indentLevel <= upperIndentLevel) {
        while (_indentLevel < upperIndentLevel && upperIndex >= 0) {
          startY -= (textFieldHeight + boxSpacing * 2);
          upperIndex--;
          upperIndentLevel = LaneInheritedWidget.of(context)
              .ideas[upperIndex]
              .key
              .currentState
              ?.indentLevel ??
              0;
        }
        if (_indentLevel <= upperIndentLevel) {
          startY -= textFieldHeight / 2;
        }
      }

      //縦の線
      canvas.drawLine(Offset(leftX, 0), Offset(leftX, startY), paint);

      //横の線
      canvas.drawLine(Offset(leftX, size.height),
          Offset(indentWidth * _indentLevel, size.height), paint);
    }
  }
}

void findAndRepaintAffectedIdeas(BuildContext context, int myIndex, int myIndentLevel, int startIndex, int endIndex){
  // Find the start index
  for (int i = myIndex - 1; i >= 0; i--) {
    if (LaneInheritedWidget.of(context)
        .ideas[i]
        .key
        .currentState
        ?.indentLevel ==
        myIndentLevel - 1) {
      startIndex = i;
      break;
    }
  }
  // Find the end index
  for (int i = myIndex + 1;
  i < LaneInheritedWidget.of(context).ideas.length;
  i++) {
    if ((LaneInheritedWidget.of(context)
        .ideas[i]
        .key
        .currentState
        ?.indentLevel ??
        0) >=
        myIndentLevel) {
      endIndex = i;
      break;
    }
  }
  LaneInheritedWidget.of(context).redrawAffectedIdeas(startIndex, endIndex);
}

※本記事は、過去の記録(メモ)をもとに、他の方が読んで分かるように加筆・補足して掲載しています

テキストベースの思考整理ツール「アイディア・レーン」最新版はこちら

コメント

タイトルとURLをコピーしました