Repository navigation
fix: change the page's Dialogs layer by list operations, never re-send open dialogs - #141
Merged
Merged
Conversation
…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
Owner
Author
|
Client-side evidence for this PR (see "How verified").
The output below is from engine Output (counts are seen/expected after each step)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]}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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: truewhen 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 intosend_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: falseordismiss, noted bynote_dialog_closed_on_client. Removing it in the same frame as itsopen: falsewould cut the close short and leave its route on screen. This covers:Server#reload_app!closes the open dialogs, then the reloaded block shows an overlay);closeon 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:
register_clientreply (register_page_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, thedialog=/snack_bar=/bottom_sheet=slot setters, the events andServer#reload_app!are unchanged.How verified
Client side, on the real engine.
gen_wire.rbrecords the exact messages Ruby sends in 8 scenarios, once from main and once from this branch. A widget test then replays them withControl.applyPatch, asRufletBackenddoes. 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:
codex/engine-initialization00d1df3c;Results are identical on both, for Material and Cupertino:
close(a)close(a); open(snack)in one handlerpage.updateafter the user dismissed B over Adialog.open = true; page.update) reopened, then a snack barclosed while a snack bar is shown in one handler, then dialog BBoth 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'spage.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 throughtest/support/dialogs_client.rb. That file models the engine'sapplyPatchinstance semantics and theopen/_openroute 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:packages/ruflet_server/test/reload_app_dialogs_test.rb(2 tests, realServer#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.about_dialog,alert_dialogandbottom_sheetcompatibility 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:
ruflet_coreruflet_serverruflet_railsrufletOther checks.
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.url_test,app_test,standalone_apps_test) on ruflet_explorermain, withRUBYLIBpointing at this branch: all pass.page.rbcompiles with the VM'smrbc(host_vm build). The methods the new code uses (downto,insert,delete_at,reject!,filter_map,each_with_indexwithreturn) behave the same under itsmruby. I did not rebuild the VM artifacts. As with anyruflet_corechange,--selfbuilds 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).
_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.dismissthat still tracks the dialog sends[2, 1, i]instead of the remaining list;page.updateafter a client-side dismiss sends a remove instead of re-sending the other dialogs.open: false: hot reload teardown, orcloseof 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.show_dialogon 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)
_overlayis still re-sent as a whole list on change (push_overlay_update!).