# `Alternera.Plugin.Editor`
[🔗](https://github.com/10e-ab/alternera-sdk/blob/v0.9.0/alternera_plugin_editor/lib/alternera/plugin/editor.ex#L1)

What a plugin's step editor builds on: the props the pipeline editor gives
it, the ways back to the pipeline editor (`notify_step_settings_changed/2`,
`request_step_input/3`), the step editor's own chrome (`section_toggle/1`)
and, delegated to `Alternera.UIKit`, the proxy's look (`icon/1`,
`callout/1`, `badge/1`, `copy_button/1`, `disclosure/1`).

A step editor is a LiveComponent the pipeline editor mounts once per step,
inside its own form. A plugin writes one like this, and its `editor/0`
returns the module:

    defmodule MyPlugin.Editor do
      use Phoenix.LiveComponent
      import Alternera.Plugin.Editor

      @impl true
      def render(assigns) do
        ~H"""
        <div id={@id}>
          <button type="button" id={@prefix <> "-add"} phx-click="add" phx-target={@myself}>
            <.icon name="hero-plus" class="h-3 w-3" /> Add
          </button>
        </div>
        """
      end

      @impl true
      def handle_event("add", _params, socket) do
        notify_step_settings_changed(socket.assigns, %{"added" => true})
        {:noreply, socket}
      end
    end

## Props

Every step editor gets all of these on every update, whichever plugin it
edits (`props/0` lists them). An editor reads what it needs and ignores the
rest. Several exist for one or two editors, named below.

The step:

  * `id`: the LiveComponent's id, `pipeline-step-editor-<node_key>`, with a
    prefix where the pipeline is drawn more than once on a page. Put it on
    the root element.
  * `prefix`: the step card's DOM id. Start every DOM id and input name in
    the editor with it, so that two steps never collide.
  * `node_key`: the step's key in the editor's tree. It is not the step id
    shown on the card, and it is what `notify_step_settings_changed/2` names
    the step by.
  * `plugin`: the plugin id, a string. It tells apart plugins that share an
    editor (Rewrite and Transform, Call and For each).
  * `section`: the section the step sits in, `"before"`, `"implementation"`,
    `"after"` or `"on_error"`. No editor reads it today: a directional
    plugin's side arrives in `settings` instead.
  * `settings`: the step's settings, a map, never nil. See "Settings".
  * `errors`: the messages the last save was refused with for this step, a
    list of strings, `[]` without any. The messages about its Id and
    Description, which the card shows, are left out.
  * `read_only`: a boolean. When true the pipeline editor ignores what an
    editor reports, so an editor refuses its events and logs them.
  * `starter`: the source last generated for the step, or nil. An editor
    with a starter asks before replacing a source unless it equals this one,
    as Script's does.
  * `input_as_recorded?`: whether the step's body is the one the exchange
    recorded: no enabled body step comes before it on its side. Only then
    do `json_paths` describe the step's input.
  * `steps_before`: the earlier steps whose outputs this step may read, in
    flow order, as `%{id, outputs}`: the step's id and its plugin's outputs
    as `%{name, label, keyed?, kind, keys}`, `keys` the keys its settings
    are known to give a keyed output (`Plugin.output_keys/1`, `[]` when
    none). A step without an id or without outputs is left out.
  * `step_id`: this step's own id, nil before it has one (Script lists its
    named values as `steps.<id>.outputs.<name>`).
  * `editing_in`: who else is in this step's settings, as `%{node, clients}`:
    the step's id in the editing session, nil before it has one, and the
    other clients, `[]` without any. Pass it to `section_toggle/1`'s
    `editing` and the host draws them on the Configuration line; for an
    editor without one the step card shows them above it.

The preview exchange, the exchange the pipeline editor previews against:

  * `exchange_id`: its id, or nil without one. The Call editor passes it on
    in its link to the called pipeline.
  * `step_input?`: whether there is one, that is `exchange_id` is not nil;
    in the flow, whether the step's plugin has a starter and the step is being
    edited. Script's editor offers "Generate from step input" only then.
  * `json_paths`: the JSON paths of its bodies, as `%{request: [path],
    response: [path]}`, both empty without an exchange, for suggestions.
    Paths, never values.
  * `name_hints`: names to suggest, a map from `:request_headers`,
    `:response_headers` and `:query` to `[{name, masked_value}]`, and from
    `:path` (the parameters of the pipeline's path template), `:context`
    (its declared context names), `:input` (its declared parameters) and
    `:vars` (the variables its steps write) to `[{name, nil}]`. For a step
    inside a Try's catch or On error, where `${error.<field>}` is set,
    `:error` holds the error's fields the same way. A template field
    passes the editor's assigns to `Editor.TemplateSuggestions.for_step/2`
    for the `${…}` references it suggests.
  * `played_header_names`: the response header names of this step's own
    played call or saved output, a list of strings, `[]` without one. The
    Request editor suggests them for a To row. Names, never values.

The pipeline and the tenant:

  * `tenant_id`: the tenant's id.
  * `pipeline_id`: this pipeline's id, nil for a pipeline not saved yet.
  * `pipelines`: the tenant's other pipelines, `[]` until the page's socket
    connects, as `%{id, name, private?, inputs, parameters}`:
    `inputs` the names each reads, `parameters` its declaration. The Call
    editor's targets.
  * `calls_back`: a `MapSet` of the ids of those that call this pipeline
    back, directly or through others. A Call step naming one closes a cycle.
  * `granted_proxy_users`: the tenant's active proxy users granted to
    pipelines, records with at least `id` and `display_name`, read once when
    the pipeline editor mounts. The Request editor's picker.
  * `cache_ids`: the ids of the pipeline's caches, as they are or will be on
    save, a list of strings. The Store editor's Invalidate picker.
  * `store_names`: the tenant's store names, a sorted list of strings, `[]`
    until they are read: the stores the instance holds and those
    configured. The Store and Response cache editors suggest them.
  * `current_user_id`: the signed-in user's id, nil where none is known:
    who uploaded a file into a step (`Plugin.Provisional.Files`). Never a
    permission: the application checks that itself.
  * `api_definitions`: the tenant's API definitions, `%{id, name,
    namespace, base_path, operations, versions, active_version, href,
    open_key}` (`operations` as `"GET /orders/{id}"`, `namespace` the one
    its schemas are referred to under, `versions` its releases highest
    first, `active_version` its Active version or nil, `href` the page that lists it and `open_key` its Workbench
    tab, nil without the Workbench), sorted by name, `[]` until they are
    read; only for a plugin that names a definition or has a JSON
    Schema setting. The Validate API and Serve API editors' picker and
    the Validate JSON editor's schema versions
    (`Plugin.Editor.DefinitionVersion`).
  * `shared_names`: the names steps of this step's plugin share state
    under across the tenant's pipelines
    (`c:Alternera.Plugin.Provisional.Analysis.shared_names/1`, and a
    Throttle or Circuit breaker container's name for the plugin of its
    kind), as `%{name, used_in}`, `used_in` the names of the pipelines
    that give it (this one as `"this pipeline"`), sorted by name; `[]`
    for a plugin that shares nothing by name. The Throttle and Circuit
    breaker editors suggest them, so a step joins a gate by its exact
    name.
  * `configured`: by setting key, the Configuration steps that may set
    this step's settings before it runs ("Settings by match"), each
    `%{value, from, certain?}` (`t:Alternera.Plugin.Editor.ByMatch.source/0`):
    the value it sets, where it is in words, and whether it runs on every
    request the step runs on; `%{}` when none does. `ByMatch` names the
    effective value from it in a From Configuration choice and its hover.
  * `pair`: for a step that opens the rest of the exchange in Before, or
    its Close in After, the pair it belongs to: a map with at least `role`
    (`:opener` or `:close`), `id` (the opener's id), `kind` (the opener's
    plugin id, nil when it is gone) and `on_refusal` (the opener's,
    `"fail"` or `"skip_to_after"`); nil for any other step. The Close
    editor's text.

The way back:

  * `notify`: the pipeline editor's `@myself`, for `send_update/2`.

## JS hooks and CSS

An editor in a package has no `assets/` directory in the proxy. Its
JavaScript is a colocated hook, written inside the HEEx next to the
element it serves and named with a leading dot, which the LiveView
compiler scopes to the module:

    <details id={@prefix <> "-panel"} phx-hook=".PasteFocus">
      <script :type={Phoenix.LiveView.ColocatedHook} name=".PasteFocus">
        export default {
          mounted() { ... }
        };
      </script>
      ...
    </details>

The compiler writes the hook under
`_build/<env>/phoenix-colocated/<app>/`, and the proxy's
`mix alternera.plugin_assets` imports every package application's hooks
into its bundle and adds the package's `lib` to the Tailwind `@source`
list, so a class used only in a package is generated. The proxy runs the
task before each asset build, and its two generated files are git-ignored;
a package adds nothing else. The proxy's own rule against `<script>` in
HEEx does not reach into a package: colocated is how a package ships JS.

A patch writes an element as the server rendered it, so client-side
state the server never renders (a `<details>` the user opened) is gone
after the next re-render, and the pipeline editor re-renders often: a
focus alone reports the editing presence, a keystroke the change. A hook
that owns such state keeps it across patches (`beforeUpdate`/`updated`),
as Map's Paste rows panel does.

## Settings

`settings` has string keys, as stored: a stored step goes through a
normalisation that turns its settings' keys to strings at every level. It is
`%{}` for a step with none. A directional plugin's settings carry a
`"direction"` no stored step has: `"request"`, `"answer"` or `"response"`, by
the section the step sits in. An editor sends it back like any other key,
and the pipeline editor drops it again.

# `badge`

A badge or pill; see `Alternera.UIKit.badge/1`.

# `badge_colors`

The colours `badge/1` takes.

# `callout`

The status box; see `Alternera.UIKit.callout/1`.

# `callout_accent`

The title colour of a callout kind; see `Alternera.UIKit.callout_accent/1`.

# `copy_button`

A copy-to-clipboard icon button; see `Alternera.UIKit.copy_button/1`.

# `disclosure`

A collapsible group of fields; see `Alternera.UIKit.disclosure/1`.

# `editor_find`

A find box: every case-insensitive match is marked, Enter and Shift+Enter
step through them, Escape or the × clears the box. It runs on the proxy's
`EditorFind` hook, client-side only; nothing is sent to the server.

`mode` is what `target_id` names:

  * `"editor"` - the textarea of a code editor (the `LuaEditor` hook with
    `data-find="true"`); Ctrl/Cmd+F in the editor comes to the box with
    the selected text
  * `"text"` - an element whose rendered text is searched, such as a body's
    `<pre>`; matches are painted with the CSS Custom Highlight API, so the
    element's markup is never touched and found again when it changes
  * `"textarea"` - a plain textarea (a body field, editable or not), which
    the page's highlights cannot reach inside: they are painted on a
    `find_mirror/1` laid over it, which the template puts beside the
    textarea in a `relative` wrapper

Ignored by patches, so a re-render cannot clear what is being typed; it
may stand inside a form, since its typing is kept from the form's change
event.

    <.editor_find id={@prefix <> "-source-find"} target_id={@prefix <> "-source"} />

## Attributes

* `id` (`:string`) (required)
* `target_id` (`:string`) (required) - The editor's textarea, or the text's element.
* `mode` (`:string`) - Defaults to `"editor"`. Must be one of `"editor"`, `"text"`, or `"textarea"`.
* `placeholder` (`:string`) - Defaults to `"Find in text"`.
* `class` (`:string`) - Defaults to `nil`.
* `input_class` (`:string`) - The input's width. Defaults to `"w-52"`.

# `find_mirror`

The layer a find box in `mode="textarea"` paints its matches on: laid
over the textarea `for` names, its text kept in step with the textarea's
(`text_find.js`), transparent but for the marks, and blind to the pointer.
It goes beside the textarea, inside a wrapper with `relative`:

    <div class="relative">
      <textarea id="body" ...></textarea>
      <.find_mirror for="body" />
    </div>

## Attributes

* `for` (`:string`) (required) - The textarea's id.

# `icon`

A Heroicon; see `Alternera.UIKit.icon/1`.

# `notify_step_settings_changed`

```elixir
@spec notify_step_settings_changed(map(), map()) :: :ok
```

Reports a step's new settings to the pipeline editor. `assigns` are the step
editor's own: `notify` names the pipeline editor and `node_key` the step.
Send string keys, as the settings are stored.

# `props`

```elixir
@spec props() :: [atom()]
```

The assigns every step editor gets, in the order the pipeline editor passes them.

# `put_number`

```elixir
@spec put_number(map(), String.t(), String.t()) :: map()
```

`settings` with a number field as typed into an input: an integer when
the text is one, else the text as typed, so the save refuses it by name
instead of the editor dropping it; left out when blank.

    put_number(%{}, "ttl", " 60")  #=> %{"ttl" => 60}
    put_number(%{}, "ttl", "6O")  #=> %{"ttl" => "6O"}
    put_number(%{"ttl" => 60}, "ttl", "")  #=> %{}

# `put_text`

```elixir
@spec put_text(map(), String.t(), String.t()) :: map()
```

`settings` with a text field as typed into an input: trimmed, and left
out when blank, so a cleared field falls back to the setting's default.

    put_text(%{}, "name", "  erp ")  #=> %{"name" => "erp"}
    put_text(%{"name" => "erp"}, "name", " ")  #=> %{}

# `request_step_input`

```elixir
@spec request_step_input(map(), atom(), :step_input | :request | :response) :: :ok
```

Asks the pipeline editor for the starter of a step, for a plugin that has
one (`Alternera.Plugin.Provisional.Editing`): `mode` is passed on to its
`starter/3`, and `source` names the body it is built from, `:step_input` for
the body the step gets, `:request` or `:response` for the exchange's body as
recorded.

The pipeline editor puts the starter in the step's settings, which come back
as a new `settings`. Without a body to build from it sends the step editor
(`myself`, which a LiveComponent's `assigns` hold) a `generate_note` saying
why, and it clears the note when one is built: an editor keeps
`generate_note` as an assign and shows it.

# `section_toggle`

The toggle of a step editor's Configuration section, open at first: a
chevron, and the inner block as its text. It flips `data-collapsed` on the
section (`<id>`, which carries `group/code`) and `aria-expanded` on itself
(`<id>-toggle`) on the client, so the state survives the re-render every edit
brings. Hide the section's content (`<id>-content`) with
`group-data-[collapsed]/code:hidden`:

    <div id={@prefix <> "-code"} class="group/code">
      <.section_toggle id={@prefix <> "-code"}>Configuration</.section_toggle>
      <div id={@prefix <> "-code-content"} class="group-data-[collapsed]/code:hidden">
        ...fields...
      </div>
    </div>

The toggle's `data-fold-kind="configuration"` is what a section's ⋮ menu folds
it by, for a plugin that says it draws one
(`c:Alternera.Plugin.Provisional.Editing.configuration_toggle?/0`).

`editing` takes the `editing_in` the editor was given: the others in the
step's settings then show on the toggle's line, open or closed, drawn by the
host's component (`config :alternera_plugin_editor, :presence, Module`,
whose `settings_chips/1` takes `id` and `editing`); without a host, as in a
plugin's own tests, nothing is drawn. The `heading` slot renders after the
toggle on its line too, for anything else. With either, the line carries
`data-settings-heading`, which tells the step card not to show the others
itself.

## Attributes

* `id` (`:string`) (required)
* `aria_label` (`:string`) - Defaults to `nil`.
* `class` (`:string`) - Defaults to `nil`.
* `editing` (`:map`) - Defaults to `nil`.
## Slots

* `heading`
* `inner_block`

# `shared_name_suggestions`

```elixir
@spec shared_name_suggestions([%{name: String.t(), used_in: [String.t()]}] | nil) ::
  [map()] | nil
```

The `shared_names` prop as a `SuggestInput`'s entries: each name, with the
pipelines that use it on the line under it (the first three, then how
many more). nil without any, so the input renders plain.

    shared_name_suggestions([%{name: "erp", used_in: ["this pipeline", "Orders"]}])
    #=> [%{value: "erp", description: "Used in this pipeline, Orders"}]

---

*Consult [api-reference.md](api-reference.md) for complete listing*
