Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 2 additions & 12 deletions packages/flow/openadapt_flow/form_tx/codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from decimal import Decimal, InvalidOperation
from typing import Any, Sequence

from openadapt_flow.form_tx.presets import load_words
from openadapt_flow.form_tx.types import (
FieldCodecSpec,
FormCodecKind,
Expand Down Expand Up @@ -295,18 +296,7 @@ def resolve_unique_option(
intended_value: Any,
options: Sequence[ObservedOption],
spec: FieldCodecSpec,
placeholder_values: Sequence[str] = (
"",
"-- Select --",
"Select...",
"Choose...",
"Select one",
"-- Select one --",
"Choose one",
"Please choose",
"Choose",
"-- Choose one --",
),
placeholder_values: Sequence[str] = load_words("placeholders"),
) -> ObservedOption:
"""Resolve exactly one ``ObservedOption`` matching ``intended_value`` or fail closed.

Expand Down
83 changes: 83 additions & 0 deletions packages/flow/openadapt_flow/form_tx/presets/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""Domain presets for ``form_tx`` pack induction, kept as data.

A domain preset is a canonical domain schema (the fields a kind of form asks for,
with label synonyms) used by ``induce_form_pack`` and the ``--domain`` flag.
It is vocabulary for one kind of form, so it lives here as JSON
(``openadapt.form-domain-preset/v1``), not in the engine's code. The
``build_*_domain_schema`` functions in ``pack_compiler`` load these files and
return the same objects they used to build.

A word list (``openadapt.form-word-list/v1``, ``presets/words/*.json``) holds
the words one rule looks for, such as the entity kinds that name the person a
form is about. The module constants that used to hold them load these files.
"""

from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema

__all__ = [
"PRESET_SCHEMA",
"WORD_LIST_SCHEMA",
"load_domain_schema",
"load_words",
"preset_names",
]

PRESET_SCHEMA = "openadapt.form-domain-preset/v1"
WORD_LIST_SCHEMA = "openadapt.form-word-list/v1"
_DIR = Path(__file__).resolve().parent
_WORDS = _DIR / "words"


def preset_names() -> tuple[str, ...]:
"""The names of the presets shipped with this package."""

return tuple(sorted(p.stem for p in _DIR.glob("*.json")))


@lru_cache(maxsize=None)
def _raw(name: str) -> dict[str, Any]:
if name not in preset_names():
raise ValueError(f"unknown form_tx domain preset {name!r}")
data = json.loads((_DIR / f"{name}.json").read_text(encoding="utf-8"))
if not isinstance(data, dict) or data.get("schema") != PRESET_SCHEMA:
raise ValueError(f"preset {name!r} is not {PRESET_SCHEMA}")
preset = data.get("preset")
if not isinstance(preset, dict):
raise ValueError(f"preset {name!r} has no preset object")
return preset


def load_domain_schema(name: str) -> "CanonicalDomainSchema":
"""The canonical domain schema stored as preset ``name``."""

from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema

return CanonicalDomainSchema.model_validate(_raw(name))


@lru_cache(maxsize=None)
def load_words(name: str) -> tuple[str, ...]:
"""The words of word list ``name`` (``presets/words/<name>.json``), in order."""

names = {p.stem for p in _WORDS.glob("*.json")}
if name not in names:
raise ValueError(f"unknown form_tx word list {name!r}")
data = json.loads((_WORDS / f"{name}.json").read_text(encoding="utf-8"))
words = data.get("words") if isinstance(data, dict) else None
if (
not isinstance(data, dict)
or data.get("schema") != WORD_LIST_SCHEMA
or data.get("name") != name
or not isinstance(words, list)
or not all(isinstance(w, str) for w in words)
):
raise ValueError(f"word list {name!r} is not {WORD_LIST_SCHEMA}")
return tuple(words)
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"schema": "openadapt.form-word-list/v1",
"name": "placeholders",
"about": "Option texts that mean nothing is chosen yet. A control or summary showing one of these holds no value. A binding may list its own.",
"words": [
"",
"-- Select --",
"Select...",
"Choose...",
"Select one",
"-- Select one --",
"Choose one",
"Please choose",
"Choose",
"-- Choose one --"
]
}
40 changes: 22 additions & 18 deletions packages/flow/openadapt_flow/form_tx/reconciler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
PopupContractError,
SurfaceSettleTimeoutError,
)
from openadapt_flow.form_tx.presets import load_words
from openadapt_flow.form_tx.receipt import issue_form_tx_receipt
from openadapt_flow.form_tx.surface import (
AmbiguousAnchorError,
Expand Down Expand Up @@ -92,18 +93,17 @@
"self",
}
)
_DEFAULT_PLACEHOLDERS: tuple[str, ...] = (
"",
"-- Select --",
"Select...",
"Choose...",
"Select one",
"-- Select one --",
"Choose one",
"Please choose",
"Choose",
"-- Choose one --",
)
#: Option texts that mean nothing is chosen (data:
#: ``presets/words/placeholders.json``).
_DEFAULT_PLACEHOLDERS: tuple[str, ...] = load_words("placeholders")


def _pack_placeholders(pack: FormPack) -> tuple[str, ...]:
"""The placeholder texts for a control no binding names: the pack's own
list when it sets one, else the default."""
if pack.placeholder_values is not None:
return pack.placeholder_values
return _DEFAULT_PLACEHOLDERS


class ReconcilerSession:
Expand Down Expand Up @@ -1904,7 +1904,7 @@ def _scan_unbound_controls(
and not c.is_secret
and c.tag.casefold() == "input"
and c.input_type.casefold() in _FREE_TEXT_INPUT_TYPES
and _is_control_empty(c)
and _is_control_empty(c, _pack_placeholders(session.pack))
]
for ctrl in [*_editable_fields(snapshot), *readonly_text]:
if ctrl.modal_container:
Expand All @@ -1921,7 +1921,7 @@ def _scan_unbound_controls(
):
continue
label = collapse_whitespace(_field_label(ctrl)) or ctrl.dom_selector
empty = _is_control_empty(ctrl)
empty = _is_control_empty(ctrl, _pack_placeholders(session.pack))
shown = ""
if not empty:
shown = ctrl.current_value
Expand Down Expand Up @@ -2317,7 +2317,9 @@ def _run_popup_subroutine_steps(
return [halt]

if not _is_return_value_empty_or_zero(
return_before.current_value, subroutine.return_codec
return_before.current_value,
subroutine.return_codec,
_pack_placeholders(session.pack),
):
existing_fact = session.effective_facts.get(subroutine.return_output_key)
if existing_fact is not None and values_equivalent(
Expand Down Expand Up @@ -2583,7 +2585,9 @@ def _popup_snapshot(surface: FormSurfaceBackend) -> FormSnapshot:
facts=session.effective_facts,
)
if return_after is None or not _is_valid_non_zero_return_value(
return_after.current_value, subroutine.return_codec
return_after.current_value,
subroutine.return_codec,
_pack_placeholders(session.pack),
):
sig = f"popup_return|{subroutine.subroutine_id}"
halt_id = _deterministic_halt_id(
Expand Down Expand Up @@ -4189,7 +4193,7 @@ def _append_record(resolved_val: Any) -> HumanResolutionRecord:
placeholders = (
binding.placeholder_values
if binding is not None
else _DEFAULT_PLACEHOLDERS
else _pack_placeholders(session.pack)
)
act_halt = self._actuate_control(
active_surface,
Expand Down Expand Up @@ -4454,7 +4458,7 @@ def _append_record(resolved_val: Any) -> HumanResolutionRecord:
placeholders = (
binding.placeholder_values
if binding is not None
else _DEFAULT_PLACEHOLDERS
else _pack_placeholders(session.pack)
)
if live_ctrl is None or _is_control_empty(live_ctrl, placeholders):
refusal_msg = (
Expand Down
32 changes: 19 additions & 13 deletions packages/flow/openadapt_flow/form_tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

from openadapt_flow.form_tx.presets import load_words

FORM_DOSSIER_SCHEMA: Literal["openadapt.form-dossier/v1"] = "openadapt.form-dossier/v1"
UI_PROFILE_SCHEMA: Literal["openadapt.ui-profile/v1"] = "openadapt.ui-profile/v1"
FORM_PACK_SCHEMA: Literal["openadapt.form-pack/v1"] = "openadapt.form-pack/v1"
Expand Down Expand Up @@ -330,18 +332,7 @@ class FieldBindingSpec(BaseModel):
prefill_policy: PrefillPolicy = PrefillPolicy.HALT_ON_CONFLICT
triggers_re_render: bool = False
required_in_pack: bool = False
placeholder_values: tuple[str, ...] = (
"",
"-- Select --",
"Select...",
"Choose...",
"Select one",
"-- Select one --",
"Choose one",
"Please choose",
"Choose",
"-- Choose one --",
)
placeholder_values: tuple[str, ...] = load_words("placeholders")
# Type-ahead comboboxes: type only this many leading characters of the
# formatted value before reading suggestions. None types the whole value.
typeahead_query_chars: Optional[int] = Field(default=None, ge=1, le=200)
Expand Down Expand Up @@ -524,9 +515,24 @@ class FormPack(BaseModel):
# otherwise named on the receipt as not covered; one listed here keeps
# the run from verified_done instead.
required_intake_keys: tuple[str, ...] = ()
# Override of the engine's default placeholder texts
# (``form_tx/presets/words/placeholders.json``) for controls no binding
# names; a binding sets its own with ``placeholder_values``. None keeps
# the default.
placeholder_values: Optional[tuple[str, ...]] = None

def digest(self) -> str:
return canonical_sha256(self)
# An override left unset is not hashed, so a pack written before the
# field existed keeps its digest.
data = self.model_dump(mode="json")
for name in _UNHASHED_WHEN_UNSET:
if data.get(name) is None:
data.pop(name, None)
return canonical_sha256(data)


#: FormPack fields left out of the digest while they are None.
_UNHASHED_WHEN_UNSET = ("placeholder_values",)


class ObservedOption(BaseModel):
Expand Down
Loading
Loading