Skip to content

fix: change the page's Dialogs layer by list operations, never re-send open dialogs - #141

Merged
AdamMusa merged 2 commits into
mainfrom
audit/dialogs-list-diff
Nov 21, 2026
Merged

AdamMusa merged 2 commits into
mainfrom
audit/dialogs-list-diff

Conversation

@AdamMusa

Copy link
Copy Markdown
Owner

Fixes #138

What changed

All library changes are in packages/ruflet_core/lib/ruflet_ui/ruflet/page.rb. Nothing changes in the engine or the template: both already apply list add, remove and move ops (models/control.dart, applyPatch). Those ops have been in the template's vendored engine since its first commit.

Once the client has mounted the Dialogs layer, changes to it go out as list ops on _dialogs.controls. Before, every change re-sent the whole list.

  • Page#push_dialogs_update! diffs against the list Ruby last published to the client (@published_dialogs). It sends, in one patch:

    • [2, 1, i] for each dialog that left the list;
    • [1, 1, i, map] for each dialog that joined it;
    • [3, 1, from, 1, to] when the order changed.

    A dialog that stays in the list is never re-sent. Its own changes (a new title, open: true when it is shown again) go out as its own patch. If it has no published state to diff against, its props are sent in full on the same control.

  • A bare page.update (send_changed_control_patches, now split into send_dirty_control_patches) sends the same list ops when the container's list changed. It used to re-send the whole list there. The rest of that method works as before: same dirty detection, same covered-descendant rule, same order.

  • Closing dialogs stay until the client reports them closed. A dialog that left the page's list while it is closing stays in the client's list until the client reports it closed: update_control open: false or dismiss, noted by note_dialog_closed_on_client. Removing it in the same frame as its open: false would cut the close short and leave its route on screen. This covers:

    • hot reload (Server#reload_app! closes the open dialogs, then the reloaded block shows an overlay);
    • close on a slot dialog, which also clears the slot.

    A dialog the client reported closed is removed at the next Dialogs change. If it is shown again, it is removed and added as a new control, as the whole-list send did. A report goes stale when the app opens that dialog again (forget_reopened_dialog_closes!).

  • The baseline is reset whenever the whole container reaches a client:

    • the register_client reply (register_page_patch);
    • a view patch that mounts the container;
    • a whole-list patch.

    prepare_for_reconnect! forgets it. When the client's list is unknown, the whole list is sent, as before, so index ops never go stale. If a send raises, the list is treated as unknown.

show_dialog, open, close, show_snack_bar, show_bottom_sheet, the dialog=/snack_bar=/bottom_sheet= slot setters, the events and Server#reload_app! are unchanged.

How verified

Client side, on the real engine. gen_wire.rb records the exact messages Ruby sends in 8 scenarios, once from main and once from this branch. A widget test then replays them with Control.applyPatch, as RufletBackend does. All messages of one Ruby step are applied before the next frame, the worst case. A user dismiss is the system back button. Counts are visible copies, expected value after each step.

The test ran on:

  • engine codex/engine-initialization 00d1df3c;
  • the vendored engine of template main 8b08569, which every published gem fetches.

Results are identical on both, for Material and Cupertino:

Scenario main this branch
W1 snack bar over open dialog A, then close(a) A: 1, 2, 1 (stuck) 1, 1, 0
S1 dialog B over modal A, close B, then A A: 1, 2, 2, 1 1, 1, 1, 0
S2 close(a); open(snack) in one handler A: 1, 1 1, 0
P1 bare page.update after the user dismissed B over A A: 1, 2, 2, 3 1, 1, 1, 1
R1 hot reload with an open modal; the reloaded block shows a snack bar D: 1, 1 (modal stuck) 1, 0
F1 Flet-style slot dialog (dialog.open = true; page.update) reopened, then a snack bar A: 0, 1, 0, 1, 2 0, 1, 0, 1, 1
SL slot dialog closed while a snack bar is shown in one handler, then dialog B A: 1, 1, 1 1, 0, 0
RS the same dialog shown, dismissed, shown, closed, shown 1, 0, 1, 0, 1 1, 0, 1, 0, 1

Both runs pass (32 tests each; the test asserts this branch's counts). The replay test, the wire recorder and the output are in the first comment below.

New Ruby tests. They fail with the fix reverted and pass with it.

  • packages/ruflet_core/test/dialogs_layer_test.rb (13 tests). With main's page.rb: 13 runs, 12 failures. The passing one is the re-show guard (RS above), which main also gets right. Most tests count what a user sees through test/support/dialogs_client.rb. That file models the engine's applyPatch instance semantics and the open/_open route lifecycle: present, pop, a late dismiss report, and a route stranded when its control leaves the list before a frame rebuilds it. It reproduces the client counts above. The tests cover:
    • W1, S1, S2, P1, F1, SL and RS;
    • the exact add and remove ops;
    • re-showing while closing (a patch, not a resend);
    • a changed title of an open dialog going out with the next Dialogs update and then counted as published;
    • reconnect and the register reply as the new baseline;
    • a seeded random walk (12 seeds × 250 turns) of handlers, double calls in one handler, user dismissals and late dismiss reports. It checks that nothing is ever stranded or shown twice, that the client's list holds each page dialog exactly once, and that after settling the client shows exactly the dialogs the page has open. The walk exercises adds, removes, moves, retained closing dialogs, full re-sends and stale reports. On main it fails on the first seed.
  • packages/ruflet_server/test/reload_app_dialogs_test.rb (2 tests, real Server#reload_app!). On main, the reload whose block shows a snack bar fails: the modal stays stuck. The reload whose block shows nothing passes on both. That case was already correct: a plain reload does not touch _dialogs.
  • Updated the tests that pinned the whole-list wire to the new shape. Their intent is unchanged.
    • about_dialog, alert_dialog and bottom_sheet compatibility tests: a dismiss now sends one list remove.
    • page_compatibility_test: the first dialog goes out as an add op.
    • date_picker_dialog_presentation_test: its helper reads the controls the latest Dialogs patch adds.

Existing suites. Each test file ran in its own process, as CI does, and all passed:

Package Files Runs
ruflet_core 211 2421
ruflet_server 18 229
ruflet_rails 19 306
ruflet 27 892

Other checks.

  • H1 goldens (cd packages/ruflet && ruby test/compat/compat.rb --jobs 4): 358 checked, exit 0, no golden changed. The register reply and the Rails endpoint's first render still carry the whole container.
  • Explorer tests (url_test, app_test, standalone_apps_test) on ruflet_explorer main, with RUBYLIB pointing at this branch: all pass.
  • Embedded VM: page.rb compiles with the VM's mrbc (host_vm build). The methods the new code uses (downto, insert, delete_at, reject!, filter_map, each_with_index with return) behave the same under its mruby. I did not rebuild the VM artifacts. As with any ruflet_core change, --self builds pick this up only once the embedded VM is rebuilt. Until then they keep today's wire.

Behavior changes

These are bug fixes for duplicated and stuck overlays (D6). Nothing changes in how apps are written or run. The register reply, first renders and every non-Dialogs patch are byte-identical (H1 goldens).

  1. Once the client has mounted the page's Dialogs layer, changes to it are sent as list ops on _dialogs.controls. Before, one replace op carried the whole list. An overlay already on the client is not sent again, so it is no longer duplicated and stays closable. This is the fix for W1, S1, S2, P1, F1 and SL.
  2. A dismissed overlay leaves the client's list with a list remove. The first time this happens:
    • a dismiss that still tracks the dialog sends [2, 1, i] instead of the remaining list;
    • a bare page.update after a client-side dismiss sends a remove instead of re-sending the other dialogs.
  3. A closing dialog stays until the client reports it closed. This applies when the dialog left the page's list in the same pass that sent its open: false: hot reload teardown, or close of a slot dialog. Ruby removes it at the next Dialogs change. This is the fix for the modal left on screen by a reload (R1) and by SL.
  4. Changes to a dialog that is already on the client go out as that dialog's own patches when another overlay is shown. Before, the dialog was re-sent whole (and duplicated).
  5. show_dialog on a page that has never been sent now sends only the view patch, which already carries the dialog. The second whole-list patch that recreated the dialog is gone.

Follow-ups (not in this PR)

  • Engine hardening, already proposed in the audit: keyed overlay widgets, or keeping the instance on a same-id replace.
  • _overlay is still re-sent as a whole list on change (push_overlay_update!).

…d open dialogs

Every change to _dialogs.controls was sent as one replace op carrying
the whole list. The engine builds a new Control for every map in a
replaced list, while the route an open dialog presented belongs to the
old instance (control_route.dart; _open in the template). So a second
overlay over an open dialog presented a second copy of it, the first
copy stayed on screen, and Ruby's open: false (addressed by id, now the
new instance) could no longer close it. A bare page.update after the
user dismissed one of two stacked dialogs re-sent the other the same
way, and close + show in one handler, or a hot reload whose block shows
an overlay, removed a closing dialog in the frame of its open: false and
left its route (a modal) on screen.

- Page keeps the list it last published to the client and sends add,
  remove and move list ops on _dialogs.controls (push_dialogs_update!
  and a bare update whose container list changed). A dialog that stays
  is never re-sent; its own changes go out as its own patches, sent in
  full when it has no published state.
- A dialog that left the list while closing stays on the client until
  the client reports it closed (update_control open: false or dismiss);
  a reported dialog is removed, and added again as a new control when it
  is shown again, as before.
- The record is reset whenever the whole container reaches a client
  (register reply, a view patch that mounts it) and forgotten on
  prepare_for_reconnect!, so index ops never go stale; unknown means
  the whole list is sent, as before.

show_dialog, open, close, the slot setters and reload_app! are
unchanged. The engine and the live template already apply list ops.

Fixes #138
@AdamMusa

Copy link
Copy Markdown
Owner Author

Client-side evidence for this PR (see "How verified").

gen_wire.rb records what Ruby sends for each scenario. Run it with RUFLET_ROOT=<checkout>: once on main, written to f17fx_wire_main.json, and once on this branch, written to f17fx_wire_fixed.json. f17fx_replay_test.dart replays both recordings with Control.applyPatch. Copy it and the two JSON files into packages/ruflet/test/widgets/ and run flutter test (Flutter 3.41.2).

The output below is from engine codex/engine-initialization 00d1df3c. The vendored engine of template main 8b08569 gave byte-identical F17FX lines. Both runs: +32: All tests passed!.

Output (counts are seen/expected after each step)
F17FX PageDesign.material main | W1 snack bar over an open dialog, then close(A) | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Saved=1/1 ; ruby: Dialog A=1/0
F17FX PageDesign.material main | S1 dialog B over modal A, close B then A | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Dialog B=1/1 ; ruby: Dialog A=2/1 Dialog B=0/0 ; ruby: Dialog A=1/0 Dialog B=0/0
F17FX PageDesign.material main | S2 close(A) and open(snack) in one handler | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=1/0 Saved=1/1
F17FX PageDesign.material main | P1 bare page.update after the user dismissed dialog B over A | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Dialog B=1/1 ; dismiss(Dialog B): Dialog A=2/1 Dialog B=0/0 ; ruby: Dialog A=3/1 Dialog B=0/0
F17FX PageDesign.material main | RS the same dialog shown, dismissed and shown again | AS EXPECTED | ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 ; ruby: Dialog A=1/1
F17FX PageDesign.material main | F1 Flet-style slot dialog reopened on the same control, then a snack bar | WRONG | ruby: Dialog A=0/0 ; ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Saved=1/1
F17FX PageDesign.material main | SL slot dialog closed while a snack bar is shown in one handler, then dialog B | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=1/0 Saved=1/1 ; ruby: Dialog A=1/0 Dialog B=1/1
F17FX PageDesign.material main | R1 hot reload with an open modal, reloaded block shows a snack bar | WRONG | ruby: Modal D=1/1 ; ruby: Modal D=1/0 Reloaded=1/1
F17FX PageDesign.material fixed | W1 snack bar over an open dialog, then close(A) | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Saved=1/1 ; ruby: Dialog A=0/0
F17FX PageDesign.material fixed | S1 dialog B over modal A, close B then A | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Dialog B=1/1 ; ruby: Dialog A=1/1 Dialog B=0/0 ; ruby: Dialog A=0/0 Dialog B=0/0
F17FX PageDesign.material fixed | S2 close(A) and open(snack) in one handler | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 Saved=1/1
F17FX PageDesign.material fixed | P1 bare page.update after the user dismissed dialog B over A | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Dialog B=1/1 ; dismiss(Dialog B): Dialog A=1/1 Dialog B=0/0 ; ruby: Dialog A=1/1 Dialog B=0/0
F17FX PageDesign.material fixed | RS the same dialog shown, dismissed and shown again | AS EXPECTED | ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 ; ruby: Dialog A=1/1
F17FX PageDesign.material fixed | F1 Flet-style slot dialog reopened on the same control, then a snack bar | AS EXPECTED | ruby: Dialog A=0/0 ; ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Saved=1/1
F17FX PageDesign.material fixed | SL slot dialog closed while a snack bar is shown in one handler, then dialog B | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 Saved=1/1 ; ruby: Dialog A=0/0 Dialog B=1/1
F17FX PageDesign.material fixed | R1 hot reload with an open modal, reloaded block shows a snack bar | AS EXPECTED | ruby: Modal D=1/1 ; ruby: Modal D=0/0 Reloaded=1/1
F17FX PageDesign.cupertino main | W1 snack bar over an open dialog, then close(A) | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Saved=1/1 ; ruby: Dialog A=1/0
F17FX PageDesign.cupertino main | S1 dialog B over modal A, close B then A | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Dialog B=1/1 ; ruby: Dialog A=2/1 Dialog B=0/0 ; ruby: Dialog A=1/0 Dialog B=0/0
F17FX PageDesign.cupertino main | S2 close(A) and open(snack) in one handler | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=1/0 Saved=1/1
F17FX PageDesign.cupertino main | P1 bare page.update after the user dismissed dialog B over A | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Dialog B=1/1 ; dismiss(Dialog B): Dialog A=2/1 Dialog B=0/0 ; ruby: Dialog A=3/1 Dialog B=0/0
F17FX PageDesign.cupertino main | RS the same dialog shown, dismissed and shown again | AS EXPECTED | ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 ; ruby: Dialog A=1/1
F17FX PageDesign.cupertino main | F1 Flet-style slot dialog reopened on the same control, then a snack bar | WRONG | ruby: Dialog A=0/0 ; ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=2/1 Saved=1/1
F17FX PageDesign.cupertino main | SL slot dialog closed while a snack bar is shown in one handler, then dialog B | WRONG | ruby: Dialog A=1/1 ; ruby: Dialog A=1/0 Saved=1/1 ; ruby: Dialog A=1/0 Dialog B=1/1
F17FX PageDesign.cupertino main | R1 hot reload with an open modal, reloaded block shows a snack bar | WRONG | ruby: Modal D=1/1 ; ruby: Modal D=1/0 Reloaded=1/1
F17FX PageDesign.cupertino fixed | W1 snack bar over an open dialog, then close(A) | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Saved=1/1 ; ruby: Dialog A=0/0
F17FX PageDesign.cupertino fixed | S1 dialog B over modal A, close B then A | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Dialog B=1/1 ; ruby: Dialog A=1/1 Dialog B=0/0 ; ruby: Dialog A=0/0 Dialog B=0/0
F17FX PageDesign.cupertino fixed | S2 close(A) and open(snack) in one handler | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 Saved=1/1
F17FX PageDesign.cupertino fixed | P1 bare page.update after the user dismissed dialog B over A | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Dialog B=1/1 ; dismiss(Dialog B): Dialog A=1/1 Dialog B=0/0 ; ruby: Dialog A=1/1 Dialog B=0/0
F17FX PageDesign.cupertino fixed | RS the same dialog shown, dismissed and shown again | AS EXPECTED | ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 ; ruby: Dialog A=1/1
F17FX PageDesign.cupertino fixed | F1 Flet-style slot dialog reopened on the same control, then a snack bar | AS EXPECTED | ruby: Dialog A=0/0 ; ruby: Dialog A=1/1 ; dismiss(Dialog A): Dialog A=0/0 ; ruby: Dialog A=1/1 ; ruby: Dialog A=1/1 Saved=1/1
F17FX PageDesign.cupertino fixed | SL slot dialog closed while a snack bar is shown in one handler, then dialog B | AS EXPECTED | ruby: Dialog A=1/1 ; ruby: Dialog A=0/0 Saved=1/1 ; ruby: Dialog A=0/0 Dialog B=1/1
F17FX PageDesign.cupertino fixed | R1 hot reload with an open modal, reloaded block shows a snack bar | AS EXPECTED | ruby: Modal D=1/1 ; ruby: Modal D=0/0 Reloaded=1/1
f17fx_replay_test.dart
// F17 fixer: replays the exact messages Ruby sends (gen_wire.rb output:
// f17fx_wire_main.json = ruflet main, f17fx_wire_fixed.json = the fix) on the
// real client, applying them with Control.applyPatch as RufletBackend does.
// Every message of one Ruby step is applied before the next frame (the worst
// case). A user dismiss is the system back button (pops the top route).
// Asserts the dialog counts for the fixed wire; prints all counts.
import 'dart:convert';
import 'dart:io';

import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:ruflet/ruflet.dart';
import 'package:ruflet/src/models/page_design.dart';
import 'package:ruflet/src/widgets/page_context.dart';
import 'package:ruflet/src/widgets/platform_app.dart';

class _Backend extends RufletBackend {
  final events = <String>[];
  _Backend(PageDesign design)
      : super(
            pageUri: Uri.parse('inprocess://f17fx'),
            assetsDir: '',
            extensions: [],
            multiView: false) {
    isLoading = false;
    platform = design == PageDesign.cupertino
        ? TargetPlatform.iOS
        : TargetPlatform.android;
  }
  @override
  void updateControl(int id, Map<String, dynamic> props,
          {bool dart = true, bool python = true, bool notify = false}) =>
      super.updateControl(id, props, dart: dart, python: false, notify: notify);
  @override
  void triggerControlEventById(int controlId, String eventName,
          [dynamic eventData]) =>
      events.add('$controlId.$eventName');
}

Future<_Backend> _pump(WidgetTester tester, PageDesign design) async {
  final backend = _Backend(design);
  // What Ruby's first view patch mounts (ids as gen_wire.rb's pages get them).
  backend.page.update({
    'views': [
      {
        '_c': 'View',
        '_i': 20,
        'route': '/',
        'controls': [
          {'_c': 'Text', '_i': 100, 'value': 'body'}
        ],
      }
    ],
    '_overlay': {'_c': 'Overlay', '_i': 101, 'controls': []},
    '_services': {'_c': 'ServiceRegistry', '_i': 102, '_services': []},
    '_dialogs': {'_c': 'Dialogs', '_i': 103, 'controls': []},
  }, shouldNotify: false);
  await tester.pumpWidget(ChangeNotifierProvider<RufletBackend>.value(
    value: backend,
    child: PlatformApp(
      design: design,
      config: PlatformAppConfig(
        title: 'f17fx',
        showSemanticsDebugger: false,
        themeMode: RufletThemeMode.light,
        routerDelegate: null,
        routeInformationParser: null,
        routeInformationProvider: null,
        localizationsDelegates: const [],
        supportedLocales: const [Locale('en')],
        locale: const Locale('en'),
        home: PageContext(
          widgetsDesign: design,
          themeMode: RufletThemeMode.light,
          brightness: Brightness.light,
          child: ListenableBuilder(
            listenable: backend.page,
            builder: (_, __) =>
                ControlWidget(control: backend.page.children('views').first),
          ),
        ),
      ),
    ),
  ));
  await tester.pumpAndSettle();
  return backend;
}

void _apply(_Backend b, Map<String, dynamic> message) {
  final id = message['id'] as int;
  final target = id == 1 ? b.page : b.controlsIndex.get(id);
  if (target == null) {
    // ignore: avoid_print
    print('F17FX   (no control $id on the client; message dropped)');
    return;
  }
  target.applyPatch(message['patch'] as List<dynamic>, b);
}

const _dialogTitles = {'Dialog A', 'Dialog B', 'Modal D'};

Map<String, dynamic> _load(String wire) => jsonDecode(
        File('test/widgets/f17fx_wire_$wire.json').readAsStringSync())
    as Map<String, dynamic>;

void main() {
  for (final design in [PageDesign.material, PageDesign.cupertino]) {
    for (final wire in ['main', 'fixed']) {
      final scenarios = _load(wire);
      for (final entry in scenarios.entries) {
        testWidgets('$design $wire ${entry.key}', (tester) async {
          final b = await _pump(tester, design);
          final seen = <String>[];
          var matches = true;
          for (final step in (entry.value as List).cast<Map<String, dynamic>>()) {
            if (step['kind'] == 'ruby') {
              for (final m in (step['messages'] as List)) {
                _apply(b, (m as Map).cast<String, dynamic>());
              }
            } else {
              await tester.binding.handlePopRoute();
            }
            await tester.pumpAndSettle();
            final expect = step['expect'] as Map<String, dynamic>?;
            if (expect == null) continue;
            final counts = <String>[];
            expect.forEach((title, n) {
              final count = find.text(title).evaluate().length;
              counts.add('$title=$count/$n');
              if (_dialogTitles.contains(title) && count != n) matches = false;
            });
            seen.add('${step['kind'] == 'ruby' ? 'ruby' : 'dismiss(${step['title']})'}: ${counts.join(' ')}');
          }
          // ignore: avoid_print
          print('F17FX $design $wire | ${entry.key} | '
              '${matches ? "AS EXPECTED" : "WRONG"} | ${seen.join(' ; ')} '
              '| exc=${tester.takeException()}');
          if (wire == 'fixed') expect(matches, isTrue, reason: seen.join(' ; '));
        });
      }
    }
  }
}
gen_wire.rb
# F17 fixer: records the exact messages Ruby sends for the overlay scenarios,
# for replay on the real Flutter client (f17fx_replay_test.dart).
# usage: RUFLET_ROOT=<checkout> ruby gen_wire.rb <out.json>
root = ENV.fetch("RUFLET_ROOT")
$LOAD_PATH.unshift(File.join(root, "packages/ruflet_core/lib"))
$LOAD_PATH.unshift(File.join(root, "packages/ruflet_server/lib"))
require "ruflet"
require "ruflet_server"
require "json"

# Scenario recorder. Ruby steps record what the page sends. A user dismiss
# step is performed by the Dart test (tap on the barrier); the recorder then
# delivers the reports the client sends after a pop (open:false + dismiss)
# and records whatever Ruby answers with.
class Recorder
  attr_reader :steps, :page

  def initialize
    @sent = []
    @page = Ruflet::Page.new(session_id: "s1", client_details: { "route" => "/" },
                             sender: ->(_a, payload) { @sent << payload })
    @page.add(Ruflet.text("body"))
    @sent.clear
    @steps = []
  end

  def ruby(expect, &block)
    block.call(@page)
    @steps << { "kind" => "ruby", "messages" => take, "expect" => expect }
  end

  # The client popped `control` (a Ruby close or a user dismiss): it reports it.
  def report(control)
    @page.apply_client_update(control.wire_id, { "open" => false })
    @page.dispatch_event(target: control.wire_id, name: "dismiss", data: nil)
    msgs = take
    @steps << { "kind" => "ruby", "messages" => msgs, "expect" => nil } unless msgs.empty?
  end

  def user_dismiss(title, control, expect)
    @steps << { "kind" => "user_dismiss", "title" => title, "expect" => expect }
    report(control)
  end

  def take
    out = JSON.parse(JSON.generate(@sent))
    @sent.clear
    out
  end
end

def dialog(title, **props) = Ruflet.alert_dialog(title: Ruflet.text(title), **props)
def snack(text) = Ruflet.snack_bar(content: Ruflet.text(text))

scenarios = {}

r = Recorder.new
a = dialog("Dialog A")
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.ruby("Dialog A" => 1, "Saved" => 1) { |pg| pg.show_snack_bar(snack("Saved")) }
r.ruby("Dialog A" => 0) { |pg| pg.close(a) }
r.report(a)
scenarios["W1 snack bar over an open dialog, then close(A)"] = r.steps

r = Recorder.new
a = dialog("Dialog A", modal: true)
b = dialog("Dialog B")
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.ruby("Dialog A" => 1, "Dialog B" => 1) { |pg| pg.show_dialog(b) }
r.ruby("Dialog A" => 1, "Dialog B" => 0) { |pg| pg.close(b) }
r.report(b)
r.ruby("Dialog A" => 0, "Dialog B" => 0) { |pg| pg.close(a) }
r.report(a)
scenarios["S1 dialog B over modal A, close B then A"] = r.steps

r = Recorder.new
a = dialog("Dialog A")
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.ruby("Dialog A" => 0, "Saved" => 1) { |pg| pg.close(a); pg.open(snack("Saved")) }
r.report(a)
scenarios["S2 close(A) and open(snack) in one handler"] = r.steps

r = Recorder.new
a = dialog("Dialog A")
b = dialog("Dialog B")
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.ruby("Dialog A" => 1, "Dialog B" => 1) { |pg| pg.show_dialog(b) }
r.user_dismiss("Dialog B", b, "Dialog A" => 1, "Dialog B" => 0)
r.ruby("Dialog A" => 1, "Dialog B" => 0) { |pg| pg.update }
scenarios["P1 bare page.update after the user dismissed dialog B over A"] = r.steps

r = Recorder.new
a = dialog("Dialog A")
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.user_dismiss("Dialog A", a, "Dialog A" => 0)
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
r.ruby("Dialog A" => 0) { |pg| pg.close(a) }
r.report(a)
r.ruby("Dialog A" => 1) { |pg| pg.show_dialog(a) }
scenarios["RS the same dialog shown, dismissed and shown again"] = r.steps

r = Recorder.new
a = dialog("Dialog A")
r.ruby("Dialog A" => 0) { |pg| pg.dialog = a }
r.ruby("Dialog A" => 1) { |pg| a.props["open"] = true; pg.update }
r.user_dismiss("Dialog A", a, "Dialog A" => 0)
r.ruby("Dialog A" => 1) { |pg| a.props["open"] = true; pg.update }
r.ruby("Dialog A" => 1, "Saved" => 1) { |pg| pg.show_snack_bar(snack("Saved")) }
scenarios["F1 Flet-style slot dialog reopened on the same control, then a snack bar"] = r.steps

r = Recorder.new
a = dialog("Dialog A", open: true)
r.ruby("Dialog A" => 1) { |pg| pg.dialog = a }
r.ruby("Dialog A" => 0, "Saved" => 1) { |pg| pg.close(a); pg.show_snack_bar(snack("Saved")) }
r.report(a)
r.ruby("Dialog A" => 0, "Dialog B" => 1) { |pg| pg.show_dialog(dialog("Dialog B")) }
scenarios["SL slot dialog closed while a snack bar is shown in one handler, then dialog B"] = r.steps

# Server#reload_app! on a page with an open modal; the reloaded block shows a snack bar.
r = Recorder.new
reloaded = false
server = Ruflet::Server.new(port: 0) do |pg|
  pg.add(Ruflet.text("body"))
  pg.show_snack_bar(snack("Reloaded")) if reloaded
end
ws = Object.new
def ws.closed? = false
server.instance_variable_get(:@sessions)["k"] = r.page
server.instance_variable_get(:@connections)["k"] = ws
d = dialog("Modal D", modal: true)
r.ruby("Modal D" => 1) { |pg| pg.show_dialog(d) }
reloaded = true
r.ruby("Modal D" => 0, "Reloaded" => 1) { |_pg| server.reload_app! }
r.report(d)
scenarios["R1 hot reload with an open modal, reloaded block shows a snack bar"] = r.steps

File.write(ARGV.fetch(0), JSON.pretty_generate(scenarios))
puts "wrote #{scenarios.size} scenarios to #{ARGV[0]}"

@AdamMusa
AdamMusa merged commit 51db9a6 into main Nov 21, 2026
12 checks passed
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.

Dialogs layer is re-sent as a whole list: a second overlay duplicates an open dialog that then cannot close; close+show and hot reload strand a modal

1 participant