editNotebook function
Perform a notebook edit operation.
Implementation
Future<({bool success, String message, int cellCount})> editNotebook({
required String notebookPath,
required NotebookCommand command,
int? cellIndex,
String? content,
String? cellType,
int? targetIndex,
}) async {
final file = File(notebookPath);
if (!await file.exists()) {
return (
success: false,
message: 'Notebook not found: $notebookPath',
cellCount: 0,
);
}
final jsonStr = await file.readAsString();
final notebook = Notebook.fromJson(jsonDecode(jsonStr));
switch (command) {
case NotebookCommand.addCell:
final cell = NotebookCell(
cellType: cellType ?? 'code',
source: content != null
? content.split('\n').map((l) => '$l\n').toList()
: [''],
);
final idx = cellIndex ?? notebook.cells.length;
if (idx < 0 || idx > notebook.cells.length) {
return (
success: false,
message: 'Invalid index: $idx',
cellCount: notebook.cells.length,
);
}
notebook.cells.insert(idx, cell);
break;
case NotebookCommand.editCell:
if (cellIndex == null ||
cellIndex < 0 ||
cellIndex >= notebook.cells.length) {
return (
success: false,
message: 'Invalid cell index: $cellIndex',
cellCount: notebook.cells.length,
);
}
if (content != null) {
notebook.cells[cellIndex].source = content
.split('\n')
.map((l) => '$l\n')
.toList();
}
if (cellType != null) {
notebook.cells[cellIndex].cellType = cellType;
}
break;
case NotebookCommand.deleteCell:
if (cellIndex == null ||
cellIndex < 0 ||
cellIndex >= notebook.cells.length) {
return (
success: false,
message: 'Invalid cell index: $cellIndex',
cellCount: notebook.cells.length,
);
}
notebook.cells.removeAt(cellIndex);
break;
case NotebookCommand.moveCell:
if (cellIndex == null ||
targetIndex == null ||
cellIndex < 0 ||
cellIndex >= notebook.cells.length ||
targetIndex < 0 ||
targetIndex >= notebook.cells.length) {
return (
success: false,
message: 'Invalid indices: $cellIndex → $targetIndex',
cellCount: notebook.cells.length,
);
}
final cell = notebook.cells.removeAt(cellIndex);
notebook.cells.insert(targetIndex, cell);
break;
}
await file.writeAsString(notebook.toJsonString());
return (
success: true,
message: '${command.name} succeeded.',
cellCount: notebook.cells.length,
);
}