Skip to content

feat(craft): add the media context - #32

Open
innkuika wants to merge 1 commit into
craft/engine-a2uifrom
craft/engine-media
Open

innkuika wants to merge 1 commit into
craft/engine-a2uifrom
craft/engine-media

Conversation

@innkuika

@innkuika innkuika commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the media context, so a template can adapt to the surface it renders on: switch media.width { "compact": ..., default: ... }. Stacked on #31. Same three parts as the other engine PRs: a blueprint, conformance cases and the code.

  • Blueprint: craft/blueprints/features/craft_media_context.blueprint.md.
  • Properties: templates see classes, never pixels.
    • width: compact below 600, medium below 840, expanded below 1200, large below 1600, extraLarge above (Material 3 window size classes);
    • height: compact below 480, medium below 900, expanded above;
    • orientation, platform and reducedMotion.
  • Evaluation: media.<parts> evaluates in the evaluator and the runtime. Without a context, or for unknown parts, it is absent, so a switch falls to its default. The new standard function atLeast(a, b) compares classes. A media change re-expands the template and keeps its state.
  • Flutter: CraftView derives the context from the space the view is given (LayoutBuilder), from the window (MediaQuery), or leaves it to the host. A resize across a class re-renders in the same frame with one expansion; a resize within a class does nothing. Other listeners on the runtime are notified after the frame.
  • Tests: 29 conformance cases in craft/conformance/craft/craft_media_context.yaml, plus unit and widget tests.
  • Theme references (theme.<parts>) stay undefined; design tokens come with the building blocks.

media_context.dart and atLeast started in yjbanov/a2ui_craft at aece53f, hence the co-author. An independent review checked the blueprint against the tests and the code, including mutations.

Pre-launch Checklist

One time:

For this PR:

  • I updated/added relevant documentation.
  • My code changes (if any) have tests.
  • License checks pass (python3 ./scripts/fix_licenses.py --check).
  • Format checks pass (./scripts/fix_format.sh --check).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the media_context feature across the Craft engine and its Flutter adapter. It introduces the MediaContext class, which quantizes surface dimensions into logical size classes, orientation, platform, and reduced-motion preferences. It adds the standard function atLeast for comparing size classes, integrates media references into the evaluator and runtime, and updates CraftView in Flutter to automatically resolve and update the media context from layout constraints or window queries. Comprehensive unit, widget, and conformance tests have been added to validate the implementation. I have no feedback to provide.

@ditman ditman left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Clean, well-specified media context layer — the quantized size-class model (classes rather than pixels), single-frame resize expansion with deferred listener notification, and 29 conformance cases are very solid.

A few items to tighten before (or cleanly alongside) landing:

  1. Post-stack barrel tightening reminder (lib/a2ui_craft.dart): Per our agreement on #23, please include src/media_context.dart when switching lib/a2ui_craft.dart to explicit show lists (export 'src/media_context.dart'; exposes internal engine plumbing readMedia and mediaFunctions alongside the public model, and #39 still leaves it as a wildcard).
  2. Avoid unconditional MediaQuery.sizeOf(context) in MediaSource.layout (craft_view.dart): Reading MediaQuery.sizeOf(context) unconditionally inside LayoutBuilder subscribes CraftView to window resizes even when its own layout constraints are bounded and unchanged, and throws if there is no MediaQuery ancestor. Only query MediaQuery for unbounded axes (or use maybeSizeOf).
  3. Guard _notifyingMedia in the post-frame callback (craft_view.dart): If widget.runtime is swapped or the view is disposed before the post-frame callback runs, setting _notifyingMedia = true around oldRuntime.refresh() can mask notifications from the new runtime.

(Also noted that MediaSource.layout intrinsic-size handling is already addressed in draft #39 via SpaceBuilder, so I left that out of this review.)

export 'src/evaluator.dart';
export 'src/expansion.dart';
export 'src/functions.dart';
export 'src/media_context.dart';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder for the post-stack barrel-tightening pass agreed in #23: please include src/media_context.dart when switching lib/a2ui_craft.dart to explicit show lists so internal plumbing stays private:

export 'src/media_context.dart'
    show HostPlatform, HeightClass, MediaContext, SurfaceOrientation, WidthClass;

Right now export 'src/media_context.dart'; also exposes internal engine plumbing (readMedia and mediaFunctions) on package:a2ui_craft/a2ui_craft.dart (and draft #39 still leaves this line as a wildcard export).

Comment on lines +279 to +295
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size window = MediaQuery.sizeOf(context);
_setMedia(
context,
Size(
constraints.hasBoundedWidth
? constraints.maxWidth
: window.width,
constraints.hasBoundedHeight
? constraints.maxHeight
: window.height,
),
);
return _renderRoot();
},
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling MediaQuery.sizeOf(context) unconditionally inside LayoutBuilder has two downsides when both constraints.hasBoundedWidth and constraints.hasBoundedHeight are true:

  1. It subscribes CraftView to every window-size change (e.g., soft keyboard or unrelated split-pane resize) even when its own bounded layout constraints did not change.
  2. It throws if CraftView is hosted in a subtree without a MediaQuery ancestor (unlike MediaQuery.maybeDisableAnimationsOf(context) in _setMedia, which handles absence gracefully).

Only calling MediaQuery.sizeOf(context) when !constraints.hasBoundedWidth || !constraints.hasBoundedHeight avoids both issues when constraints are bounded:

final Size? window =
    constraints.hasBoundedWidth && constraints.hasBoundedHeight
    ? null
    : MediaQuery.sizeOf(context);
_setMedia(
  context,
  Size(
    constraints.hasBoundedWidth ? constraints.maxWidth : window!.width,
    constraints.hasBoundedHeight ? constraints.maxHeight : window!.height,
  ),
);

(Note: when #39 replaces LayoutBuilder with SpaceBuilder, MediaQuery.maybeSizeOf(context) is still worth considering if missing-MediaQuery safety is desired.)

Drop-in regression test for craft/packages/a2ui_craft_flutter/test/craft_view_test.dart:

  testWidgets('bounded layout CraftView renders without a MediaQuery ancestor', (
    WidgetTester tester,
  ) async {
    final _Harness h = _Harness('''
      import core;
      widget root = Text(text: media.width);
    ''');
    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: Align(
          alignment: Alignment.topLeft,
          child: SizedBox(
            width: 400,
            height: 300,
            child: CraftView(
              runtime: h.runtime,
              libraries: <LibraryName, PrimitiveWidgetLibrary>{
                coreLibrary: _testWidgets,
              },
            ),
          ),
        ),
      ),
    );
    expect(tester.takeException(), isNull);
    expect(find.text('compact'), findsOneWidget);
  });

Comment on lines +193 to +201
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
_mediaNotificationScheduled = false;
_notifyingMedia = true;
try {
runtime.refresh();
} finally {
_notifyingMedia = false;
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 If CraftView is updated with a different widget.runtime (or disposed) before this post-frame callback runs, runtime.refresh() still executes with _notifyingMedia = true. If a listener on the old runtime mutates the new widget.runtime, _changed() on the new runtime would be swallowed.

Checking final bool same = mounted && identical(runtime, widget.runtime); and only setting _notifyingMedia = same (while still notifying runtime.refresh()) avoids masking notifications across a runtime swap.

Drop-in regression test for craft/packages/a2ui_craft_flutter/test/media_test.dart:

  testWidgets('swapping runtime before media post-frame does not mask changes', (
    WidgetTester tester,
  ) async {
    _largeSurface(tester);
    final _Harness h1 = _Harness('''
      import core;
      widget root = Text(text: media.width);
    ''');
    final _Harness h2 = _Harness('''
      import core;
      widget root = Text(text: data.v);
    ''');
    h2.runtime.data = <String, Object?>{'v': 'initial'};
    h1.runtime.addListener(() {
      h2.runtime.data = <String, Object?>{'v': 'updated'};
    });

    CraftRuntime current = h1.runtime;
    late StateSetter setHostState;
    SchedulerBinding.instance.addPostFrameCallback((Duration _) {
      setHostState(() => current = h2.runtime);
      tester.binding.buildOwner!.buildScope(tester.binding.rootElement!);
    });

    await tester.pumpWidget(
      StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          setHostState = setState;
          return _sized(
            CraftView(
              runtime: current,
              libraries: <LibraryName, PrimitiveWidgetLibrary>{
                coreLibrary: _widgets,
              },
              media: MediaSource.window,
            ),
            width: 400,
            height: 600,
            window: const Size(400, 600),
          );
        },
      ),
    );
    await tester.pump();
    expect(find.text('updated'), findsOneWidget);
  });

@innkuika
innkuika force-pushed the craft/engine-media branch 3 times, most recently from ff4c36c to a510a81 Compare December 3, 2026 19:00
Adds the craft_media_context feature: what a host tells templates about
the surface they render on, as classes rather than pixels, so that one
template adapts to a phone, a tablet or a desktop with `switch
media.width { ... }` or `atLeast(a: media.width, b: "expanded")`.

- craft/blueprints/features/craft_media_context.blueprint.md: the
  properties (width class compact/medium/expanded/large/extraLarge,
  height class compact/medium/expanded, orientation, optional platform,
  reducedMotion) and their media map; the size classes of a size in
  logical pixels (width breakpoints 600/840/1200/1600 as Material 3's
  window size classes, height 480/900 as Android's; landscape when wider
  than tall; negative or NaN refused); media references read the media
  map, absent for anything else and without a media context, in the
  evaluator and the runtime; the standard function atLeast, absent for
  names that are no size class; the runtime's media context, which
  notifies only when it changes (or, when the host asks, not at all, for
  it to notify later) and keeps state, arguments and data.
- craft/conformance/craft/craft_media_context.yaml: 29 cases (media maps
  of sizes, values through the evaluator, runtime scenarios with media
  changes and notifications), run by
  test/conformance/media_context_test.dart; its runtime scenarios use
  the expand_template action of test/conformance/runtime_engine.dart.
- packages/a2ui_craft: lib/src/media_context.dart (MediaContext,
  WidthClass, HeightClass, SurfaceOrientation, HostPlatform, readMedia,
  mediaFunctions); Evaluator.evaluate, TemplateRegistry.evaluate and
  CraftRuntime take a media context; TemplateRegistry adds atLeast to the
  function tables.
- packages/a2ui_craft_flutter: CraftView.media (MediaSource.layout by
  default, window, host) sets the runtime's media context from the view's
  layout constraints or the MediaQuery size, with the platform and the
  reduced-motion preference, before it expands, so a resize across a
  class renders in the same frame, and notifies the runtime's other
  listeners after that frame (CraftRuntime.setMedia(notify: false) and
  refresh), so a listening host never rebuilds during a build; widget
  tests.
- functions, runtime and craft_template_registry blueprints, the module
  table and the codebase blueprints updated for media references and
  atLeast.
- Conformance: the media_map, media_sizes and evaluate_media actions,
  expand_template's media context, and the F-CRAFT-MEDIA-01 to 05 feature
  IDs.

Based on the Craft prototype's media_context.dart and the atLeast
function. Changed from it: the media context belongs to the runtime and
is observable through the evaluator and expansions; atLeast is absent for
unknown names instead of reading them as compact; the form factor,
capabilities and their flags, the rendering engine and the text scale are
left out; the Flutter adapter measures the space itself.

Co-authored-by: Yegor <yegor.jbanov@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants