closeInstance method

void closeInstance({
  1. required String instanceId,
})

Visually, this is when the "x" icon of the instance's button on the FileTabBar is pressed

  1. The instance will be removed from workspace data.
  2. The instance will be unset as the active one.
  3. A new instance will be chosen, if possible, to be the active one.

Implementation

void closeInstance({
  required String instanceId,
}) {
  final String? paneId = api.workspace.workspaceConfigs.panesData.entries
      .where((entry) => entry.value.instances.contains(instanceId))
      .firstOrNull
      ?.key;
  if (paneId == null) {
    throw Exception('$instanceId is not in an existing pane');
  } else {
    int removeIndex = 0;
    // loop through each instanceId in the pane to determine the index of the instance to be removed
    // so that it can be used later on to set the next active instance
    for (int i = 0;
        i <
            api.workspace.workspaceConfigs.panesData[paneId]!.instances
                .length;
        i++) {
      if (api.workspace.workspaceConfigs.panesData[paneId]!.instances[i] ==
          instanceId) {
        removeIndex = i;
        break;
      }
    }
    api.window.unsetActiveInstance(instanceId: instanceId);
    api.workspace.workspaceConfigs.panesData[paneId]!.instances
        .removeAt(removeIndex);
    if (removeIndex != 0) {
      api.window.setActiveInstance(
        paneId: paneId,
        instanceId: api.workspace.workspaceConfigs.panesData[paneId]!
            .instances[removeIndex - 1],
      );
    }
  }
  AffogatoEvents.editorInstanceClosedEventsController.add(
    EditorInstanceClosedEvent(
      instanceId: instanceId,
      paneId: paneId,
    ),
  );
}