// The state of the UI and its rules. `step` is pure: it gives the next model and the
// effects. `update` makes a Rabbita command of each effect.

///|
/// The path of a new project.
#derive(Eq, Debug)
pub(all) enum AddState {
  /// The user types it.
  Typing
  /// The server refused it, or the folder dialog did not open. The text is for the user.
  Refused(String)
  /// The folder dialog of the system is open. Only a desktop window has one.
  Browsing
  /// The server has it and did not answer.
  Sending
}

///|
pub extend AddState with Eq::{equal, not_equal}

///|
pub extend AddState with @debug.Debug::{to_repr}

///|
/// The dialog that is open. Two dialogs are never open at the same time.
#derive(Eq, Debug)
pub(all) enum Dialog {
  NoDialog
  /// The field for the path of a new project. `path` is the text of the user, and
  /// only the server knows its rules.
  AddDialog(path~ : String, state~ : AddState)
  /// The question before Mission Control stops.
  ConfirmStop
  /// The command palette, with the text of the user and the selected action. `step`
  /// keeps the selection in the results. Without a result it is `None`.
  Palette(query~ : String, selected~ : ActionId?)
}

///|
pub extend Dialog with Eq::{equal, not_equal}

///|
pub extend Dialog with @debug.Debug::{to_repr}

///|
/// The dialog that adds a project, with an empty field.
pub fn Dialog::add() -> Dialog {
  AddDialog(path="", state=Typing)
}

///|
/// An element of the page that shows a dialog.
#derive(Eq, Debug)
pub(all) enum DialogElement {
  AddElement
  StopElement
  PaletteElement
}

///|
pub extend DialogElement with Eq::{equal, not_equal}

///|
pub extend DialogElement with @debug.Debug::{to_repr}

///|
/// The ID of the element.
fn DialogElement::id(self : DialogElement) -> String {
  match self {
    AddElement => "add-project-dialog"
    StopElement => "stop-dialog"
    PaletteElement => "palette"
  }
}

///|
/// The ID of the field for the path in the dialog that adds a project.
let add_path_id : String = "add-path"

///|
/// The ID of the title of the main area. Each state of the view has one.
let main_title_id : String = "main-title"

///|
/// The element that shows the dialog.
fn Dialog::element(self : Dialog) -> DialogElement? {
  match self {
    NoDialog => None
    AddDialog(..) => Some(AddElement)
    ConfirmStop => Some(StopElement)
    Palette(..) => Some(PaletteElement)
  }
}

///|
/// The state of the primary sidebar, which is at the left of a wide window.
#derive(Eq, Debug)
pub(all) enum PrimarySidebar {
  Shown
  Hidden
}

///|
pub extend PrimarySidebar with Eq::{equal, not_equal}

///|
pub extend PrimarySidebar with @debug.Debug::{to_repr}

///|
/// The state from the text that the browser kept. Each text that the UI does not write
/// gives `Shown`, also the empty one of a browser that kept nothing.
fn PrimarySidebar::of_stored(text : String) -> PrimarySidebar {
  match text {
    "hidden" => Hidden
    _ => Shown
  }
}

///|
/// The text that the browser keeps.
fn PrimarySidebar::stored(self : PrimarySidebar) -> String {
  match self {
    Shown => "shown"
    Hidden => "hidden"
  }
}

///|
fn PrimarySidebar::other(self : PrimarySidebar) -> PrimarySidebar {
  match self {
    Shown => Hidden
    Hidden => Shown
  }
}

///|
/// The ID of the control that the user sees in this state. It gives the other state.
fn PrimarySidebar::control_id(self : PrimarySidebar) -> String {
  match self {
    Shown => "hide-primary-sidebar"
    Hidden => "show-primary-sidebar"
  }
}

///|
/// The key of the state in the storage of the browser.
let primary_sidebar_key : String = "mission-control-primary-sidebar"

///|
/// The size of the window. A small one has no space for the primary sidebar, and shows
/// the same content in a sheet.
#derive(Eq, Debug)
pub(all) enum WindowSize {
  Wide
  Small
}

///|
pub extend WindowSize with Eq::{equal, not_equal}

///|
pub extend WindowSize with @debug.Debug::{to_repr}

///|
/// The state of one view.
#derive(Eq, Debug)
pub struct Model {
  connection : ConnectionState
  surface : @app.Surface
  /// The instance whose server gave the page.
  instance : @app.InstanceName
  /// What the server tells about itself, after the first connection.
  info : @app.AppInfo?
  /// The list of the server, or `None` before the first one. It stays while the
  /// connection is lost.
  projects : ReadOnlyArray[@app.Project]?
  /// The project in the address of the page. The list can be without it: see
  /// `Model::open_project`.
  open : @app.ProjectId?
  dialog : Dialog
  /// The choice of the user for a wide window. It stays while the window is small.
  primary_sidebar : PrimarySidebar
  window : WindowSize
  /// A failure that has no other place, as text for the user.
  notice : String?
}

///|
pub extend Model with Eq::{equal, not_equal}

///|
pub extend Model with @debug.Debug::{to_repr}

///|
/// The state of a view before its first connection.
pub fn Model::Model(
  surface~ : @app.Surface,
  instance~ : @app.InstanceName,
  primary_sidebar~ : PrimarySidebar,
  window~ : WindowSize,
) -> Model {
  {
    connection: Connecting,
    surface,
    instance,
    info: None,
    projects: None,
    open: None,
    dialog: NoDialog,
    primary_sidebar,
    window,
    notice: None,
  }
}

///|
/// The details of a project, or `None` when the list does not have it.
fn Model::find(self : Model, id : @app.ProjectId) -> @app.Project? {
  self.projects.bind(projects => {
    projects.iter().find_first(project => project.id == id)
  })
}

///|
/// The open project, or `None` when no project is open or the list does not have it.
pub fn Model::open_project(self : Model) -> @app.Project? {
  self.open.bind(id => self.find(id))
}

///|
/// The name of the instance, if it is not `stable`.
pub fn Model::other_instance(self : Model) -> String? {
  guard self.instance != @app.InstanceName::of_channel(Stable) else { None }
  Some(self.instance.to_string())
}

///|
/// The view ended: it does not connect again, and its state does not change.
pub fn Model::is_over(self : Model) -> Bool {
  self.connection is (Restarted | Stopped)
}

///|
/// The part of an address before the ID of a project.
let project_hash : String = "#/projects/"

///|
/// The project in the fragment of an address, such as `#/projects/3`. Each other text
/// gives `None`, because a user can type an address.
pub fn project_of_hash(hash : String) -> @app.ProjectId? {
  guard hash.strip_prefix(project_hash) is Some(number) else { None }
  let id = @app.ProjectId::ProjectId(@string.parse_int(number)) catch {
    _ => return None
  }
  // `+3` and `03` are also numbers, but a project has one address.
  guard hash_of_project(Some(id)) == hash else { None }
  Some(id)
}

///|
/// The fragment of the address of a project, or of no project.
pub fn hash_of_project(project : @app.ProjectId?) -> String {
  match project {
    Some(id) => "\{project_hash}\{id.to_int()}"
    None => "#/"
  }
}

///|
/// What happens to a view.
pub(all) enum Msg {
  ConnectionChanged(ConnectionState)
  /// The view cannot try to connect. The text is for the user.
  ConnectionFailed(String)
  InfoRead(@app.AppInfo)
  /// The server gave its list, as a reply or as an event.
  ProjectsListed(ReadOnlyArray[@app.Project])
  /// A program asks the views of one kind to show a project.
  ProjectShown(@app.ShownProject)
  /// The server stops.
  AppStopping
  /// The address of the page changed, also because the view changed it.
  HashChanged(@app.ProjectId?)
  /// The window has a new size, which can be of the same kind.
  WindowResized(WindowSize)
  /// The user selects an action, with a control on the screen, in the palette or with
  /// its shortcut.
  ActionChosen(Action)
  /// The user presses a shortcut of the palette, or its control.
  PaletteOpened
  /// The user changed the text in the palette.
  PaletteTyped(String)
  /// The user selects the next result or the one before it.
  PaletteMoved(Direction)
  /// The user moved the pointer over an action of the palette.
  PalettePointed(ActionId)
  /// The user presses Enter in the palette. `seen` has the actions of the page at that
  /// moment.
  PaletteEntered(seen~ : ReadOnlyArray[Action])
  /// The user cancels the dialog that is open.
  CloseDialog
  /// The browser closed the element, because the user pressed Escape or because the
  /// view closed it. The browser tells it late: another dialog can be open.
  DialogClosed(DialogElement)
  /// The user changed the text of the path.
  PathTyped(String)
  /// The user asks for the folder dialog of the system.
  BrowseChosen
  /// The folder dialog of the system closed.
  FolderChosen(@app.ChosenFolder)
  /// The folder dialog of the system did not open.
  BrowseFailed(@proton_client.ClientFailure)
  /// The user sends the path to the server.
  AddSubmitted
  /// The server has the project of this path.
  ProjectAdded(path~ : String, @app.Project)
  /// The server did not add this path.
  AddFailed(path~ : String, @proton_client.ClientFailure)
  ProjectRemoved(@app.ProjectId)
  RemoveFailed(@app.ProjectId, @proton_client.ClientFailure)
  /// The user confirms in the dialog `ConfirmStop`.
  StopConfirmed
  /// A call or an event failed, and the user did not wait for it.
  CallFailed(@proton_client.ClientFailure)
  /// The user closes the notice.
  NoticeDismissed
}

///|
/// A call of the server.
#derive(Eq, Debug)
priv enum ServerCall {
  ReadInfo
  ReadProjects
  Add(String)
  /// Records that the user opens the project.
  RecordOpen(@app.ProjectId)
  Remove(@app.ProjectId)
  Stop
}

///|
/// What a step asks of the server and of the page.
// Only the tests compare effects and write them as text.
#warnings("-unused_value")
#derive(Eq, Debug)
priv enum Effect {
  Call(ServerCall)
  /// Opens the folder dialog of the system, with the desktop app and not the server.
  ChooseFolder
  ShowDialog(DialogElement)
  HideDialog(DialogElement)
  /// Scrolls the list of the palette, so that the user sees the action.
  ShowEntry(ActionId)
  /// Sets the address. The browser can go back to the old one.
  PushHash(@app.ProjectId?)
  /// Sets the address. The browser cannot go back to the old one.
  ReplaceHash(@app.ProjectId?)
  /// Puts the focus in the field for the path of a new project.
  FocusPath
  /// Puts the focus in the title of the main area, if the control that had it is gone.
  KeepFocus
  /// Puts the focus in the control that the user sees in this state of the primary
  /// sidebar, if the control that had it is gone.
  FocusPrimarySidebarControl(PrimarySidebar)
  /// Keeps the state for the next page of the same browser.
  StorePrimarySidebar(PrimarySidebar)
  /// Ends the connection for good. It does not know why the server went away.
  EndConnection
}

///|
/// Sends the call, and gives its answer as a message.
fn ServerCall::start(
  self : ServerCall,
  client : @proton_client.Client,
  send : (Msg) -> Unit,
) -> Unit {
  let failed = error => send(CallFailed(error))
  // The view never takes a call back, so it does not need the function that does.
  let _ = match self {
    ReadInfo =>
      client.invoke_with_callbacks(
        @app.app_info,
        @proton_contract.EmptyRequest::{ },
        info => send(InfoRead(info)),
        failed,
      )
    ReadProjects =>
      client.invoke_with_callbacks(
        @app.list_projects,
        @proton_contract.EmptyRequest::{ },
        projects => send(ProjectsListed(ReadOnlyArray::from_array(projects))),
        failed,
      )
    Add(path) =>
      client.invoke_with_callbacks(
        @app.add_project,
        { path, },
        added => send(ProjectAdded(path~, added.project)),
        error => send(AddFailed(path~, error)),
      )
    RecordOpen(id) =>
      client.invoke_with_callbacks(
        @app.open_project,
        id,
        // The event `projects_changed` has the new details.
        _ => (),
        failed,
      )
    Remove(id) =>
      client.invoke_with_callbacks(
        @app.remove_project,
        id,
        _ => send(ProjectRemoved(id)),
        error => send(RemoveFailed(id, error)),
      )
    Stop =>
      client.invoke_with_callbacks(
        @app.stop_app,
        @proton_contract.EmptyRequest::{ },
        _ => send(AppStopping),
        failed,
      )
  }
}

///|
/// Asks the desktop app for a folder, and gives its answer as a message.
fn ask_folder(
  desktop_app : @proton_client.Client,
  send : (Msg) -> Unit,
) -> Unit {
  // The view never takes the call back, because the user closes the folder dialog.
  let _ = desktop_app.invoke_with_callbacks(
    @app.choose_folder,
    @proton_contract.EmptyRequest::{ },
    chosen => send(FolderChosen(chosen)),
    error => send(BrowseFailed(error)),
  )
}

///|
/// The text of a failure for the user. The server writes the text of a refusal.
fn failure_text(failure : @proton_client.ClientFailure) -> String {
  match failure {
    RemoteFailure(message~, ..) => message
    TransportFailure(message~) => "No answer from Mission Control: \{message}"
    InvalidContract(message~)
    | ResponseDecode(message~)
    | EventDecode(message~) =>
      "Mission Control sent data that this page does not know: \{message}"
    BridgeUnavailable | RequestCancelled as other => other.message()
  }
}

///|
/// Opens a project and sets the address of the page.
fn Model::show(
  self : Model,
  id : @app.ProjectId,
  record~ : Bool,
) -> (Model, Array[Effect]) {
  guard self.open != Some(id) else { (self, []) }
  let next = { ..self, open: Some(id), }
  let effects : Array[Effect] = [PushHash(Some(id))]
  if record {
    effects.append(self.record_open(id))
  }
  if self.loses_control(next) {
    effects.push(KeepFocus)
  }
  (next, effects)
}

///|
/// Records the open of a project, if the server can do it now.
fn Model::record_open(self : Model, id : @app.ProjectId) -> Array[Effect] {
  if self.connection is Connected && self.find(id) is Some(_) {
    [Call(RecordOpen(id))]
  } else {
    []
  }
}

///|
/// The model with this dialog, if no other dialog is open.
fn Model::open_dialog(self : Model, dialog : Dialog) -> (Model, Array[Effect]) {
  guard self.dialog is NoDialog && dialog.element() is Some(element) else {
    (self, [])
  }
  ({ ..self, dialog, }, [ShowDialog(element)])
}

///|
/// The model with no notice. The button that closes the notice can have the focus.
fn Model::dismiss_notice(self : Model) -> (Model, Array[Effect]) {
  guard self.notice is Some(_) else { (self, []) }
  ({ ..self, notice: None, }, [KeepFocus])
}

///|
/// The model with no dialog. The browser gives the focus back to the control that had
/// it before the dialog, but that control can be gone.
fn Model::close_dialog(self : Model) -> (Model, Array[Effect]) {
  match self.dialog.element() {
    Some(element) =>
      ({ ..self, dialog: NoDialog, }, [HideDialog(element), KeepFocus])
    None => (self, [])
  }
}

///|
/// The model of a view that ended.
fn Model::end(
  self : Model,
  connection : ConnectionState,
) -> (Model, Array[Effect]) {
  let (model, effects) = self.close_dialog()
  // The controls of the page go away, also without a dialog.
  let effects = if effects.is_empty() { [KeepFocus] } else { effects }
  ({ ..model, connection, notice: None, }, effects)
}

///|
/// The change of the list or of the open project removes a control from the page, or
/// moves it. Both take the focus from the control. An open project and an empty list
/// have a button in the main area, and each project has its own one.
fn Model::loses_control(self : Model, next : Model) -> Bool {
  guard self.projects is Some(projects) else { false }
  let rows = next.projects.unwrap_or([])
  if self.open_project() is Some(project) &&
    !(next.open_project() is Some(other) && other.id == project.id) {
    true
  } else if projects.is_empty() {
    !rows.is_empty()
  } else {
    // New projects after the old ones move no row.
    projects.length() > rows.length() ||
    !projects.iter().zip(rows.iter()).all(pair => pair.0.id == pair.1.id)
  }
}

///|
/// The model that shows a failure. The status bar shows a lost connection, so a
/// failure that comes from the loss has no text.
fn Model::show_failure(
  self : Model,
  failure : @proton_client.ClientFailure,
) -> Model {
  guard self.connection is Connected else { self }
  { ..self, notice: Some(failure_text(failure)), }
}

///|
/// Does an action that is enabled, with no open dialog.
fn Model::do_action(self : Model, action : Action) -> (Model, Array[Effect]) {
  match action {
    OpenProject(project) => self.show(project.id, record=true)
    AddProject => self.open_dialog(Dialog::add())
    RemoveProject(project) => {
      let (model, effects) = self.dismiss_notice()
      (model, [Call(Remove(project.id)), ..effects])
    }
    SetPrimarySidebar(state) => {
      guard state != self.primary_sidebar else { (self, []) }
      (
        { ..self, primary_sidebar: state, },
        [StorePrimarySidebar(state), FocusPrimarySidebarControl(state)],
      )
    }
    StopApp => self.open_dialog(ConfirmStop)
  }
}

///|
/// Does an action that the user selected with a control or in the palette.
fn Model::choose(self : Model, action : Action) -> (Model, Array[Effect]) {
  guard action.enabled(self) else { (self, []) }
  match self.dialog {
    NoDialog => self.do_action(action)
    Palette(..) => {
      // The palette closes first, so it gives the focus back before a dialog takes it.
      // The title gets the focus last, only if the action has no better place for it.
      let closed = { ..self, dialog: NoDialog, }
      let (next, effects) = closed.do_action(action)
      (next, [HideDialog(PaletteElement), ..effects, KeepFocus])
    }
    // These dialogs are over each control.
    AddDialog(..) | ConfirmStop => (self, [])
  }
}

///|
/// The model after a message, and what the step asks of the server and the page.
fn step(model : Model, msg : Msg) -> (Model, Array[Effect]) {
  guard !model.is_over() else { (model, []) }
  let (next, effects) = step_alone(model, msg)
  let (next, show) = next.keep_selection(before=model)
  (next, [..effects, ..show])
}

///|
/// The step without its result for the selection in the palette.
fn step_alone(model : Model, msg : Msg) -> (Model, Array[Effect]) {
  match msg {
    ConnectionChanged(Connected) =>
      (
        { ..model, connection: Connected, },
        [Call(ReadInfo), Call(ReadProjects)],
      )
    ConnectionChanged(Restarted | Stopped as state) => model.end(state)
    ConnectionChanged(Connecting | Reconnecting as connection) =>
      ({ ..model, connection, }, [])
    ConnectionFailed(text) => ({ ..model, notice: Some(text), }, [])
    AppStopping => {
      let (model, effects) = model.end(Stopped)
      (model, [EndConnection, ..effects])
    }
    InfoRead(info) => ({ ..model, info: Some(info), }, [])
    ProjectsListed(projects) => {
      let next = { ..model, projects: Some(projects), }
      (next, if model.loses_control(next) { [KeepFocus] } else { [] })
    }
    ProjectShown({ project, surface, }) =>
      if surface == model.surface {
        // The program that asks for it also records it.
        model.show(project, record=false)
      } else {
        (model, [])
      }
    HashChanged(open) => {
      guard open != model.open else { (model, []) }
      let next = { ..model, open, }
      let effects = match open {
        Some(id) => model.record_open(id)
        None => []
      }
      if model.loses_control(next) {
        effects.push(KeepFocus)
      }
      (next, effects)
    }
    WindowResized(window) => ({ ..model, window, }, [])
    ActionChosen(action) => model.choose(action)
    PaletteOpened => model.open_palette()
    PaletteTyped(query) => model.search(query)
    PaletteMoved(direction) => model.move_selection(direction)
    PalettePointed(id) => model.point_at(id)
    PaletteEntered(seen~) => model.run_selection(seen)
    CloseDialog => model.close_dialog()
    DialogClosed(element) =>
      if model.dialog.element() == Some(element) {
        model.close_dialog()
      } else {
        (model, [])
      }
    PathTyped(path) =>
      match model.dialog {
        AddDialog(state=Typing | Refused(_), ..) =>
          ({ ..model, dialog: AddDialog(path~, state=Typing), }, [])
        _ => (model, [])
      }
    BrowseChosen =>
      match model.dialog {
        AddDialog(path~, state=Typing | Refused(_)) if model.surface is Desktop =>
          (
            { ..model, dialog: AddDialog(path~, state=Browsing), },
            [ChooseFolder],
          )
        _ => (model, [])
      }
    FolderChosen({ path: chosen, }) =>
      match model.dialog {
        AddDialog(path~, state=Browsing) => {
          let path = chosen.unwrap_or(path)
          ({ ..model, dialog: AddDialog(path~, state=Typing), }, [FocusPath])
        }
        // The user closed the dialog before the answer.
        _ => (model, [])
      }
    BrowseFailed(failure) =>
      match model.dialog {
        AddDialog(path~, state=Browsing) => {
          let state = Refused(failure_text(failure))
          ({ ..model, dialog: AddDialog(path~, state~), }, [FocusPath])
        }
        _ => (model, [])
      }
    AddSubmitted =>
      match model.dialog {
        AddDialog(path~, state=Typing | Refused(_)) if AddProject.enabled(model) &&
          !path.trim().is_empty() =>
          (
            { ..model, dialog: AddDialog(path~, state=Sending), },
            [Call(Add(path))],
          )
        _ => (model, [])
      }
    ProjectAdded(path~, project) =>
      if model.waits_for(path) {
        let (closed, hide) = { ..model, notice: None, }.close_dialog()
        let (shown, show) = closed
          .with_project(project)
          .show(project.id, record=true)
        (shown, [..hide, ..show])
      } else {
        // The user closed the dialog. The event `projects_changed` has the project.
        (model, [])
      }
    AddFailed(path~, failure) =>
      if model.waits_for(path) {
        let state = Refused(failure_text(failure))
        ({ ..model, dialog: AddDialog(path~, state~), }, [FocusPath])
      } else {
        (model, [])
      }
    ProjectRemoved(id) => {
      let projects = model.projects.map(projects => {
        projects.filter(project => project.id != id)
      })
      if model.open == Some(id) {
        ({ ..model, projects, open: None, }, [ReplaceHash(None), KeepFocus])
      } else {
        ({ ..model, projects, }, [KeepFocus])
      }
    }
    RemoveFailed(id, failure) =>
      // Without the project, another call or another view removed it.
      if model.find(id) is Some(_) {
        (model.show_failure(failure), [])
      } else {
        (model, [])
      }
    StopConfirmed =>
      if model.dialog is ConfirmStop && StopApp.enabled(model) {
        let (model, effects) = model.close_dialog()
        ({ ..model, notice: None, }, [..effects, Call(Stop)])
      } else {
        (model, [])
      }
    CallFailed(failure) => (model.show_failure(failure), [])
    NoticeDismissed => model.dismiss_notice()
  }
}

///|
/// The dialog waits for the answer of the server for this path.
fn Model::waits_for(self : Model, path : String) -> Bool {
  self.dialog is AddDialog(path=sent, state=Sending) && sent == path
}

///|
/// The model with these details of a project. A new project is the last one, as in the
/// list of the server.
fn Model::with_project(self : Model, project : @app.Project) -> Model {
  let projects = self.projects.unwrap_or([])
  let projects = if self.find(project.id) is Some(_) {
    projects.map(other => if other.id == project.id { project } else { other })
  } else {
    ReadOnlyArray::from_array([..projects, project])
  }
  { ..self, projects: Some(projects), }
}

///|
/// The command that does an effect.
fn Effect::command(
  self : Effect,
  emit : @cmd.Emit[Msg],
  connection : Connection,
) -> @cmd.Cmd {
  match self {
    Call(call) =>
      @cmd.custom_cmd(scheduler => {
        call.start(connection.client, msg => scheduler.add(emit(msg)))
      })
    ChooseFolder =>
      @cmd.custom_cmd(scheduler => {
        ask_folder(@proton_client.desktop, msg => scheduler.add(emit(msg)))
      })
    ShowDialog(element) => @dialog.show(element.id())
    HideDialog(element) => @dialog.close(element.id())
    ShowEntry(id) =>
      @cmd.custom_cmd(_ => show_element(id.element()), kind=@cmd.after_render)
    PushHash(project) => @nav.push_url(hash_of_project(project))
    ReplaceHash(project) => @nav.replace_url(hash_of_project(project))
    FocusPath =>
      @cmd.custom_cmd(_ => focus_element(add_path_id), kind=@cmd.after_render)
    KeepFocus => keep_focus(main_title_id)
    FocusPrimarySidebarControl(state) => keep_focus(state.control_id())
    StorePrimarySidebar(state) =>
      @cmd.custom_cmd(_ => store_text(primary_sidebar_key, state.stored()))
    EndConnection => @cmd.custom_cmd(_ => (connection.stopped)())
  }
}

///|
extern "js" fn focus_element(id : String) -> Unit =
  #| (id) => { document.getElementById(id)?.focus(); }

///|
/// Scrolls the list around the element, and only if a part of it is not visible.
extern "js" fn show_element(id : String) -> Unit =
  #| (id) => { document.getElementById(id)?.scrollIntoView({ block: "nearest" }); }

///|
/// The text that the browser kept for this key, or an empty text. A browser that blocks
/// the storage throws.
extern "js" fn stored_text(key : String) -> String =
  #| (key) => {
  #|   try { return localStorage.getItem(key) ?? ""; }
  #|   catch { return ""; }
  #| }

///|
/// Keeps the text for the next page. With a browser that keeps nothing, the next page
/// starts without it.
extern "js" fn store_text(key : String, text : String) -> Unit =
  #| (key, text) => { try { localStorage.setItem(key, text); } catch {} }

///|
/// Puts the focus in the element with this ID, if no control has it after the next
/// change of the page.
fn keep_focus(id : String) -> @cmd.Cmd {
  @cmd.custom_cmd(_ => keep_focus_in(id), kind=@cmd.after_render)
}

///|
/// A control of a sheet that closes still has the focus, but it is inert.
extern "js" fn keep_focus_in(id : String) -> Unit =
  #| (id) => {
  #|   const at = document.activeElement;
  #|   if (!at || at === document.body || at.closest("[inert]")) {
  #|     document.getElementById(id)?.focus({ preventScroll: true });
  #|   }
  #| }

///|
/// The model after a message, and the command that does the rest, with the connection
/// to the server.
pub fn update(
  model : Model,
  msg : Msg,
  emit : @cmd.Emit[Msg],
  connection : Connection,
) -> (Model, @cmd.Cmd) {
  let (next, effects) = step(model, msg)
  (next, @cmd.batch(effects.map(effect => effect.command(emit, connection))))
}