From 9ded9bc62b6ec5f2b3db51fa0fe17c6b07ceb3d3 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Thu, 12 Nov 2026 17:14:39 +0100 Subject: [PATCH 01/24] Track and clear initial applied params on slotted child views --- .../lib/src/client/slotted_child_view.dart | 10 ++++- .../test/client/slotted_child_view_test.dart | 37 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index e4a0e41ed..d0973bd73 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -369,14 +369,16 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (element.id.isEmpty) { element.id = newId; appliedId = newId; + } else if (element.id == newId && (appliedId == null || appliedId == newId)) { + appliedId = newId; } } if (newParams.classes case final newClasses?) { appliedClasses ??= []; for (final c in newClasses) { - if (!element.classList.contains(c)) { - element.classList.add(c); + element.classList.add(c); + if (!appliedClasses.contains(c)) { appliedClasses.add(c); } } @@ -388,6 +390,8 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (element.style.getPropertyValue(e.key).isEmpty) { element.style.setProperty(e.key, e.value); appliedStyles[e.key] = e.value; + } else if (element.style.getPropertyValue(e.key) == e.value && !appliedStyles.containsKey(e.key)) { + appliedStyles[e.key] = e.value; } } } @@ -398,6 +402,8 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (!element.hasAttribute(e.key)) { element.setAttribute(e.key, e.value); appliedAttributes[e.key] = e.value; + } else if (element.getAttribute(e.key) == e.value && !appliedAttributes.containsKey(e.key)) { + appliedAttributes[e.key] = e.value; } } } diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 08421d160..7e23a7626 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -236,6 +236,43 @@ void main() { expect(clicks, 1); }); + testClient('removes applied params when toggled off even if initially present in html', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + id: hasParams ? 'applied-id' : null, + classes: hasParams ? 'applied' : null, + styles: hasParams ? const Styles(color: Colors.red) : null, + attributes: hasParams ? const {'data-applied': 'true'} : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'applied-id'); + expect(btn.className, 'original applied'); + expect(btn.style.color, 'red'); + expect(btn.getAttribute('data-applied'), 'true'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.hasAttribute('id'), isFalse); + expect(btn.className, 'original'); + expect(btn.hasAttribute('style'), isFalse); + expect(btn.hasAttribute('data-applied'), isFalse); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; From 0318557b63eacdfc7070dce39091519f4deb1d69 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Thu, 12 Nov 2026 17:15:14 +0100 Subject: [PATCH 02/24] Update CHANGELOG.md --- packages/jaspr/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/jaspr/CHANGELOG.md b/packages/jaspr/CHANGELOG.md index 836762c58..149a1a085 100644 --- a/packages/jaspr/CHANGELOG.md +++ b/packages/jaspr/CHANGELOG.md @@ -13,6 +13,7 @@ - Fixed hot-reload losing changes when a new build starts before the previous reload has finished. - Fixed `jaspr serve` blocking all following reloads when a connected browser stops responding (e.g. a phone with the screen turned off). - Fixed a fragment staying in the DOM after it is removed or replaced when its first or last child renders nothing, such as `Component.empty()`. +- Fixed applied classes and properties from `Component.apply` not being removed from server components on the client when toggled off. ## 0.24.0-beta.0 From 5e509f43dbd3d10cd77dc23344bc7398ea6f1468 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 12:17:10 +0100 Subject: [PATCH 03/24] fix: track applied params with data-j-apply and client boundary markers --- .../lib/src/client/component_anchors.dart | 56 +++++++- .../lib/src/client/slotted_child_view.dart | 88 ++++++++++-- packages/jaspr/lib/src/dom/type_checks.dart | 4 + .../jaspr/lib/src/foundation/binding.dart | 3 + .../jaspr/lib/src/framework/components.dart | 72 +++++++++- .../jaspr/lib/src/framework/framework.dart | 3 +- .../adapters/client_component_adapter.dart | 28 +++- .../jaspr/lib/src/server/server_binding.dart | 3 + .../jaspr/test/client/client_reload_test.dart | 8 +- .../hydration/hydration_browser_test.dart | 79 +++++++++-- .../test/client/slotted_child_view_test.dart | 66 ++++++++- packages/jaspr/test/server/client_test.dart | 126 +++++++++++++++++- 12 files changed, 495 insertions(+), 41 deletions(-) diff --git a/packages/jaspr/lib/src/client/component_anchors.dart b/packages/jaspr/lib/src/client/component_anchors.dart index 0426e1d12..1985c2d72 100644 --- a/packages/jaspr/lib/src/client/component_anchors.dart +++ b/packages/jaspr/lib/src/client/component_anchors.dart @@ -4,6 +4,7 @@ import 'dart:convert'; import 'package:universal_web/web.dart' as web; import '../../client.dart'; +import '../dom/styles/styles.dart'; import '../dom/validator.dart'; sealed class ComponentAnchor { @@ -16,12 +17,24 @@ sealed class ComponentAnchor { } class ClientComponentAnchor extends ComponentAnchor { - ClientComponentAnchor._(super.name, super.key, super.startNode, this.data); + ClientComponentAnchor._(super.name, super.key, super.startNode, this.data, this.apply); String? data; + String? apply; late FutureOr builder; final List serverAnchors = []; + List<_ApplyData> get _decodedApplyParams { + if (apply case final rawApply?) { + final unescaped = const DomValidator().unescapeMarkerText(rawApply); + final list = jsonDecode(unescaped) as List; + return [ + for (final item in list) _ApplyData.fromMap(item as Map), + ]; + } + return const []; + } + /// The decoded parameters for this client component. Map get _decodedParameters { if (data case final rawData?) { @@ -43,7 +56,19 @@ class ClientComponentAnchor extends ComponentAnchor { assert(builder is ClientBuilder, 'ClientComponentAnchor was not resolved before calling build()'); final clientParameters = ClientParams(_decodedParameters, serverAnchors); - final component = (builder as ClientBuilder)(clientParameters); + var component = (builder as ClientBuilder)(clientParameters); + + for (final apply in _decodedApplyParams) { + component = Component.apply( + target: apply.target, + id: apply.id, + classes: apply.classes, + styles: apply.styles != null ? Styles(raw: apply.styles) : null, + attributes: apply.attributes, + child: component, + ); + } + return Builder(key: _ClientAnchorKey(key), builder: (_) => component); } @@ -146,7 +171,9 @@ class ServerComponentElement extends BuildableElement { } } -final _clientStartRegex = RegExp('^${DomValidator.clientMarkerPrefixRegex}(\\S+)(?:\\s+#(\\S*))?(?:\\s+data=(.*))?\$'); +final _clientStartRegex = RegExp( + '^${DomValidator.clientMarkerPrefixRegex}(\\S+)(?:\\s+#(\\S*))?(?:\\s+data<([^>]*)>)?(?:\\s+apply<([^>]*)>)?\$', +); final _clientEndRegex = RegExp('^/${DomValidator.clientMarkerPrefixRegex}(\\S+)\$'); final _serverStartRegex = RegExp('^s${DomValidator.clientMarkerPrefixRegex}(\\d+)(?:\\s+#(\\S*))?\$'); @@ -183,6 +210,7 @@ List extractAnchors({List? nodes}) { final name = match.group(1)!; final key = match.group(2); final data = match.group(3); + final apply = match.group(4); final resolvedKey = key != null ? '@$name#$key' @@ -192,7 +220,7 @@ List extractAnchors({List? nodes}) { return '@$name-${anchors.length}-$count'; })(); - anchors.add(ClientComponentAnchor._(name, resolvedKey, currNode, data)); + anchors.add(ClientComponentAnchor._(name, resolvedKey, currNode, data, apply)); continue; } @@ -269,3 +297,23 @@ List extractAnchors({List? nodes}) { return clientAnchors; } + +class _ApplyData { + _ApplyData({required this.target, this.id, this.classes, this.styles, this.attributes}); + + final ApplyTarget target; + final String? id; + final String? classes; + final Map? styles; + final Map? attributes; + + factory _ApplyData.fromMap(Map map) { + return _ApplyData( + target: map['t'] != null ? ApplyTarget.fromMap(map['t'] as Map) : ApplyTarget.anyChild, + id: map['i'] as String?, + classes: map['c'] as String?, + styles: (map['s'] as Map?)?.cast(), + attributes: (map['a'] as Map?)?.cast(), + ); + } +} diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index d0973bd73..206b81502 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -1,6 +1,8 @@ /// @docImport 'client_app.dart'; library; +import 'dart:convert'; + import 'package:universal_web/web.dart' as web; import '../dom/type_checks.dart'; @@ -240,10 +242,17 @@ class _SlottedChildViewElement extends DomRenderObjectElement { return renderObject; } + bool _didHydrate = false; final Map _appliedParams = nodeMap(); @override void updateRenderObject(SlottedDomRenderObject renderObject) { + final inheritedDomParams = inheritedDomParamsFor(renderObject); + if ((component.nodes != null || (inheritedDomParams != null && inheritedDomParams.isNotEmpty)) && !_didHydrate) { + _didHydrate = true; + _hydrateInitialNodes(renderObject); + } + for (final element in _appliedParams.keys) { _resetElementParams(element); } @@ -285,6 +294,75 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } + void _hydrateInitialNodes(SlottedDomRenderObject renderObject) { + final slotRanges = { + for (final slot in component.slots) + if (slot is _RangeChildSlot) slot.start: slot.end, + }; + + web.Node? current = renderObject.firstChildNode; + while (current != null) { + if (slotRanges[current] case final endNode?) { + if (current == renderObject.lastChildNode) break; + current = endNode; + if (slotRanges.containsKey(current)) continue; + if (current == renderObject.lastChildNode) break; + current = current.nextSibling; + continue; + } + + if (current.isElement) { + _hydrateInitialAppliedParams(current as web.Element); + } + + if (current == renderObject.lastChildNode) break; + current = current.nextSibling; + } + } + + void _hydrateInitialAppliedParams(web.Element root) { + void process(web.HTMLElement element) { + if (element.hasAttribute('data-j-apply')) { + final raw = element.getAttribute('data-j-apply')!; + element.removeAttribute('data-j-apply'); + + try { + final data = jsonDecode(raw) as Map; + final appliedId = data['i'] as String?; + final appliedClasses = (data['c'] as List?)?.cast(); + final appliedStylesList = (data['s'] as List?)?.cast(); + final appliedAttributesList = (data['a'] as List?)?.cast(); + + Map? appliedStyles; + if (appliedStylesList != null) { + appliedStyles = {for (final s in appliedStylesList) s: element.style.getPropertyValue(s)}; + } + + Map? appliedAttributes; + if (appliedAttributesList != null) { + appliedAttributes = {for (final a in appliedAttributesList) a: element.getAttribute(a) ?? ''}; + } + + _appliedParams[element] = _AppliedParams( + target: ApplyTarget.anyChild, + id: appliedId, + classes: appliedClasses, + styles: appliedStyles, + attributes: appliedAttributes, + ); + } catch (_) {} + } + } + + if (root.isHtmlElement) { + process(root as web.HTMLElement); + } + final descendants = root.querySelectorAll('[data-j-apply]'); + for (int i = 0; i < descendants.length; i++) { + process(descendants.item(i) as web.HTMLElement); + } + } + List _findMatchingElements(web.Element root, ApplyTarget target) { final elements = []; @@ -369,16 +447,14 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (element.id.isEmpty) { element.id = newId; appliedId = newId; - } else if (element.id == newId && (appliedId == null || appliedId == newId)) { - appliedId = newId; } } if (newParams.classes case final newClasses?) { appliedClasses ??= []; for (final c in newClasses) { - element.classList.add(c); - if (!appliedClasses.contains(c)) { + if (!element.classList.contains(c)) { + element.classList.add(c); appliedClasses.add(c); } } @@ -390,8 +466,6 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (element.style.getPropertyValue(e.key).isEmpty) { element.style.setProperty(e.key, e.value); appliedStyles[e.key] = e.value; - } else if (element.style.getPropertyValue(e.key) == e.value && !appliedStyles.containsKey(e.key)) { - appliedStyles[e.key] = e.value; } } } @@ -402,8 +476,6 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (!element.hasAttribute(e.key)) { element.setAttribute(e.key, e.value); appliedAttributes[e.key] = e.value; - } else if (element.getAttribute(e.key) == e.value && !appliedAttributes.containsKey(e.key)) { - appliedAttributes[e.key] = e.value; } } } diff --git a/packages/jaspr/lib/src/dom/type_checks.dart b/packages/jaspr/lib/src/dom/type_checks.dart index 90ca5a051..6b52685cb 100644 --- a/packages/jaspr/lib/src/dom/type_checks.dart +++ b/packages/jaspr/lib/src/dom/type_checks.dart @@ -10,6 +10,7 @@ import 'package:universal_web/js_interop.dart'; // See also https://github.com/dart-lang/sdk/issues/60344 extension DomTypeTests on JSAny? { bool get isElement => this == null ? false : instanceof(_cachedElementConstructor); + bool get isHtmlElement => this == null ? false : instanceof(_cachedHtmlElementConstructor); bool get isHtmlInputElement => this == null ? false : instanceof(_cachedHtmlInputElementConstructor); bool get isHtmlAnchorElement => this == null ? false : instanceof(_cachedHtmlAnchorElementConstructor); bool get isHtmlSelectElement => this == null ? false : instanceof(_cachedHtmlSelectElementConstructor); @@ -21,6 +22,7 @@ extension DomTypeTests on JSAny? { } final _cachedElementConstructor = _elementConstructor; +final _cachedHtmlElementConstructor = _htmlElementConstructor; final _cachedHtmlInputElementConstructor = _htmlInputElementConstructor; final _cachedHtmlAnchorElementConstructor = _htmlAnchorElementConstructor; final _cachedHtmlSelectElementConstructor = _htmlSelectElementConstructor; @@ -32,6 +34,8 @@ final _cachedDocumentFragmentConstructor = _documentFragmentConstructor; @JS('Element') external JSFunction get _elementConstructor; +@JS('HTMLElement') +external JSFunction get _htmlElementConstructor; @JS('HTMLInputElement') external JSFunction get _htmlInputElementConstructor; @JS('HTMLAnchorElement') diff --git a/packages/jaspr/lib/src/foundation/binding.dart b/packages/jaspr/lib/src/foundation/binding.dart index 825fd6b62..58160c467 100644 --- a/packages/jaspr/lib/src/foundation/binding.dart +++ b/packages/jaspr/lib/src/foundation/binding.dart @@ -8,6 +8,9 @@ abstract class AppBinding with SchedulerBinding { /// Whether the current app is run on the client (in the browser) bool get isClient; + /// Whether this app has client components registered. + bool get hasClients => false; + /// The currently active url. /// /// On the server, this is the request url. diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index bbf0de139..a1666ed51 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -91,6 +91,11 @@ class DomElement extends DomRenderObjectElement { attributes = Map.of(attributes ?? {}); events = Map.of(events ?? {}); + final appliedClasses = []; + final appliedStyles = []; + final appliedAttributes = []; + String? appliedId; + for (final param in inheritedDomParams.reversed) { if (param.target.tag case final expectedTag? when expectedTag != component.tag) continue; if (param.target.id case final expectedId? when expectedId != id) continue; @@ -99,21 +104,35 @@ class DomElement extends DomRenderObjectElement { continue; } - id ??= param.id; + if (param.id case final paramId? when id == null) { + id = paramId; + appliedId = paramId; + } if (param.classes case final paramClasses?) { + for (final c in paramClasses) { + if (!classesSet.contains(c)) { + appliedClasses.add(c); + } + } classesSet.addAll(paramClasses); } if (param.styles case final stylesProps?) { for (final MapEntry(:key, :value) in stylesProps.entries) { - styles[key] ??= value; + if (!styles.containsKey(key)) { + styles[key] = value; + appliedStyles.add(key); + } } } if (param.attributes case final attributesMap?) { for (final MapEntry(:key, :value) in attributesMap.entries) { - attributes[key] ??= value; + if (!attributes.containsKey(key)) { + attributes[key] = value; + appliedAttributes.add(key); + } } } @@ -125,14 +144,30 @@ class DomElement extends DomRenderObjectElement { } classes = classesSet.join(' '); + + if (!binding.isClient && binding.hasClients) { + if (appliedId != null || + appliedClasses.isNotEmpty || + appliedStyles.isNotEmpty || + appliedAttributes.isNotEmpty) { + final diff = { + 'i': ?appliedId, + if (appliedClasses.isNotEmpty) 'c': appliedClasses, + if (appliedStyles.isNotEmpty) 's': appliedStyles, + if (appliedAttributes.isNotEmpty) 'a': appliedAttributes, + }; + attributes['data-j-apply'] = jsonEncode(diff); + } + } } renderObject.update(id, classes, styles, attributes, events); } } -class _ApplyDomComponent extends StatelessComponent implements DomComponent { - const _ApplyDomComponent({ +@internal +class ApplyDomComponent extends StatelessComponent implements DomComponent { + const ApplyDomComponent({ this.target = ApplyTarget.anyChild, this.id, this.classes, @@ -162,6 +197,14 @@ class _ApplyDomComponent extends StatelessComponent implements DomComponent { @override List? get children => null; + Map toMap() => { + if (target != ApplyTarget.anyChild) 't': target.toMap(), + if (id != null) 'i': id, + if (classes != null) 'c': classes, + if (styles?.properties case final s? when s.isNotEmpty) 's': s, + if (attributes != null && attributes!.isNotEmpty) 'a': attributes, + }; + @override Component build(BuildContext context) { return _InheritedDomComponent.merge( @@ -233,6 +276,25 @@ final class ApplyTarget { for (final c in classes) '.$c', ], ].join(); + + Map toMap() => { + if (!onlyChildren) 'd': true, + if (tag != null) 't': tag, + if (id != null) 'i': id, + if (classes != null && classes!.isNotEmpty) 'c': classes!.toList(), + }; + + factory ApplyTarget.fromMap(Map map) { + final onlyChildren = map['d'] != true; + final tag = map['t'] as String?; + final id = map['i'] as String?; + final classes = (map['c'] as List?)?.cast().toSet(); + if (onlyChildren) { + return ApplyTarget.childWith(tag: tag, id: id, classes: classes); + } else { + return ApplyTarget.descendantWith(tag: tag, id: id, classes: classes); + } + } } @protected diff --git a/packages/jaspr/lib/src/framework/framework.dart b/packages/jaspr/lib/src/framework/framework.dart index ce97983af..0211c091c 100644 --- a/packages/jaspr/lib/src/framework/framework.dart +++ b/packages/jaspr/lib/src/framework/framework.dart @@ -9,6 +9,7 @@ library; import 'dart:async'; import 'dart:collection'; +import 'dart:convert'; import 'package:meta/meta.dart'; import 'package:universal_web/web.dart' as web; @@ -159,7 +160,7 @@ abstract class Component { Map? events, required Component child, Key? key, - }) = _ApplyDomComponent; + }) = ApplyDomComponent; /// Creates a component which renders a list of child components without any wrapping element. /// diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index 071faf531..cffb928d0 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import '../../dom/validator.dart'; import '../../framework/framework.dart'; import '../components/client_component_registry.dart'; @@ -15,6 +17,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { bool _isClientBoundary = true; late String? data; + String? applyData; @override void prepareBoundary(ChildGroup group) { @@ -43,6 +46,29 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { } data = getData(); + + final applied = []; + var hasRenderElement = false; + element.visitAncestorElements((e) { + if (registry.serverElements.containsKey(e)) { + return false; + } + if (e is RenderObjectElement) { + hasRenderElement = true; + } + if (e.component case final ApplyDomComponent applyComp) { + if (!applyComp.target.onlyChildren || !hasRenderElement) { + applied.add(applyComp); + } + } + return true; + }); + + if (applied.isNotEmpty) { + applyData = const DomValidator().escapeMarkerText(jsonEncode(applied.map((a) => a.toMap()).toList())); + } else { + applyData = null; + } } @override @@ -52,7 +78,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { } final startMarker = MarkupRenderText( - '', + '', true, ); final endMarker = MarkupRenderText('', true); diff --git a/packages/jaspr/lib/src/server/server_binding.dart b/packages/jaspr/lib/src/server/server_binding.dart index 652bed5c1..8e4ce4981 100644 --- a/packages/jaspr/lib/src/server/server_binding.dart +++ b/packages/jaspr/lib/src/server/server_binding.dart @@ -29,6 +29,9 @@ class ServerAppBinding extends AppBinding with ComponentsBinding { @override bool get isClient => false; + @override + bool get hasClients => _options?.clients?.isNotEmpty ?? false; + @override String get basePath => request.basePath; diff --git a/packages/jaspr/test/client/client_reload_test.dart b/packages/jaspr/test/client/client_reload_test.dart index dc8eeb8e8..d53ae03ef 100644 --- a/packages/jaspr/test/client/client_reload_test.dart +++ b/packages/jaspr/test/client/client_reload_test.dart @@ -99,7 +99,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; web.document.body!.innerHTML = '
' - ' ' + ' ' ' ' '

Fallback

' ' ' @@ -126,7 +126,7 @@ void main() { final newBody = web.document.createElement('body') as web.HTMLBodyElement; newBody.innerHTML = '
' - ' ' + ' ' ' ' '

Fallback

' ' ' @@ -161,7 +161,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; web.document.body!.innerHTML = '
' - ' ' + ' ' ' ' '
' .toJS; @@ -186,7 +186,7 @@ void main() { final newBody = web.document.createElement('body') as web.HTMLBodyElement; newBody.innerHTML = '
' - ' ' + ' ' ' ' '
' .toJS; diff --git a/packages/jaspr/test/client/hydration/hydration_browser_test.dart b/packages/jaspr/test/client/hydration/hydration_browser_test.dart index edb2b99b0..bb0f2952a 100644 --- a/packages/jaspr/test/client/hydration/hydration_browser_test.dart +++ b/packages/jaspr/test/client/hydration/hydration_browser_test.dart @@ -85,14 +85,69 @@ void main() { expect(p2Element.textContent, equals('C')); }); + testClient('should mount Component.apply from marker during hydration', (tester) async { + final marker = DomValidator.clientMarkerPrefix; + window.document.body!.innerHTML = + '
' + ' ' + '

Content

' + ' ' + '
' + .toJS; + + final pElement = window.document.querySelector('body p')!; + expect(pElement.textContent, equals('Content')); + + Jaspr.initializeApp( + options: ClientOptions( + clients: { + 'app_apply': ClientLoader((_) => p([Component.text('Hydrated')])), + }, + ), + ); + + runApp(const ClientApp()); + await pumpEventQueue(); + + expect(pElement.textContent, equals('Hydrated')); + expect(pElement.id, equals('applied-id')); + expect(pElement.className, equals('applied-from-marker')); + }); + + testClient('should safely parse marker when data contains "apply=" string', (tester) async { + final marker = DomValidator.clientMarkerPrefix; + window.document.body!.innerHTML = + '
' + ' ' + '

Content

' + ' ' + '
' + .toJS; + + Jaspr.initializeApp( + options: ClientOptions( + clients: { + 'app_with_text': ClientLoader((params) => p([Component.text(params.get('msg'))])), + }, + ), + ); + + runApp(const ClientApp()); + await pumpEventQueue(); + + final pElement = window.document.querySelector('body p')!; + expect(pElement.textContent, equals('please apply=here')); + expect(pElement.className, equals('applied-cls')); + }); + testClient('should find and hydrate multiple markers with params', (tester) async { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' '

Hello

' ' ' - ' ' + ' ' '

Hello

' ' ' '
' @@ -130,7 +185,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' '

' ' ' ' Server Element' @@ -175,12 +230,12 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '

' - ' ' + ' ' '
' ' ' '

' ' Server Element' - ' ' + ' ' ' Fallback' ' ' '

' @@ -233,10 +288,10 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' '
' ' ' - ' ' + ' ' ' Fallback' ' ' ' ' @@ -284,7 +339,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' ' ' ' ' ' ' @@ -328,7 +383,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' ' ' '

Fallback

' ' ' @@ -362,7 +417,7 @@ void main() { final newBody = window.document.createElement('body') as HTMLBodyElement; newBody.innerHTML = '
' - ' ' + ' ' ' ' '

Fallback

' ' ' @@ -387,7 +442,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' '
' ' ' ' Server Element' @@ -427,7 +482,7 @@ void main() { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = '
' - ' ' + ' ' '
' ' ' ' First Element' diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 7e23a7626..d192fdcec 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -237,7 +237,7 @@ void main() { }); testClient('removes applied params when toggled off even if initially present in html', (tester) async { - window.document.body!.innerHTML = '
' + window.document.body!.innerHTML = '
' .toJS; var hasParams = true; late void Function(void Function() cb) setState; @@ -273,6 +273,70 @@ void main() { expect(btn.hasAttribute('data-applied'), isFalse); }); + testClient('preserves child-owned id and classes when client apply toggles off', (tester) async { + window.document.body!.innerHTML = + '
' + .toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + id: hasParams ? 'save' : null, + classes: hasParams ? 'active' : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'save'); + expect(btn.className, 'btn active'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.id, 'save'); + expect(btn.className, 'btn'); + }); + + testClient('preserves outer applied params when inner apply toggles off', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + classes: 'server-class', + child: .apply( + target: .descendantWith(tag: 'button'), + classes: hasParams ? 'client-class' : null, + child: SlottedChildView(slots: const []), + ), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.className, 'child-class client-class server-class'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.className, 'child-class server-class'); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index b51207c63..938ff6e4e 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -158,7 +158,7 @@ void main() { '\n' '\n' ' \n' - '
\n' + '
\n' '\n' '', ), @@ -213,7 +213,7 @@ void main() { '\n' ' \n' ' \n' - ' \n' + ' \n' '
Hello
\n' ' \n' ' \n' @@ -236,7 +236,7 @@ void main() { '\n' ' \n' ' \n' - ' \n' + ' \n' '
HelloHello
\n' ' \n' ' \n' @@ -260,7 +260,7 @@ void main() { '\n' ' \n' ' \n' - ' \n' + ' \n' '
\n' ' \n' ' \n' @@ -284,7 +284,7 @@ void main() { '\n' ' \n' ' \n' - ' \n' + ' \n' '
\n' ' \n' ' \n' @@ -293,5 +293,121 @@ void main() { ), ); }); + + testServer('encodes applied params above client component in marker', (tester) async { + tester.pumpComponent( + Component.apply( + classes: 'outer-class', + id: 'outer-id', + child: App1(), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + equals( + '\n' + '\n' + ' \n' + ' \n' + ' \n' + '
\n' + ' \n' + ' \n' + '\n' + '', + ), + ); + }); + + testServer('encodes applied params above client component wrapping server component', (tester) async { + tester.pumpComponent( + Component.apply( + classes: 'server-class', + child: AppWithServerComponent( + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + equals( + '\n' + '\n' + ' \n' + ' \n' + ' \n' + '
Hello
\n' + ' \n' + ' \n' + '\n' + '', + ), + ); + }); + testServer('does not encode direct child apply params when separated by a render element', (tester) async { + tester.pumpComponent( + Component.apply( + target: ApplyTarget.anyChild, + classes: 'parent-class', + child: div([ + App1(), + ]), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + equals( + '\n' + '\n' + ' \n' + ' \n' + '
\n' + ' \n' + '\n' + '', + ), + ); + }); + + testServer('encodes descendant apply params even when separated by a render element', (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(), + classes: 'descendant-class', + child: div([ + App1(), + ]), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + equals( + '\n' + '\n' + ' \n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + '\n' + '', + ), + ); + }); }); } From eb7000b2942564636719bb54dd5f7d464a7662a5 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 12:28:28 +0100 Subject: [PATCH 04/24] refactor: add data-j-apply in AppliedParamsAdapter when client boundary exists above --- packages/jaspr/lib/jaspr.dart | 2 +- .../jaspr/lib/src/foundation/binding.dart | 3 ++ .../jaspr/lib/src/framework/components.dart | 4 +- .../jaspr/lib/src/framework/framework.dart | 1 - .../adapters/applied_params_adapter.dart | 43 +++++++++++++++++++ .../components/client_component_registry.dart | 6 +++ .../jaspr/lib/src/server/server_binding.dart | 14 ++++++ packages/jaspr/test/server/client_test.dart | 41 ++++++++++++++++-- 8 files changed, 106 insertions(+), 8 deletions(-) create mode 100644 packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart diff --git a/packages/jaspr/lib/jaspr.dart b/packages/jaspr/lib/jaspr.dart index fd8a43fd1..a0afde45f 100644 --- a/packages/jaspr/lib/jaspr.dart +++ b/packages/jaspr/lib/jaspr.dart @@ -20,7 +20,7 @@ export 'src/foundation/scheduler.dart'; export 'src/foundation/sync.dart'; export 'src/foundation/synchronous_future.dart'; export 'src/framework/framework.dart' - hide GlobalComponentsBinding, DomRenderObjectElement, ApplyParams, DomParamsResolver; + hide GlobalComponentsBinding, DomRenderObjectElement, ApplyParams, DomParamsResolver, ApplyDomComponent; export 'src/stub/app_context_stub.dart' if (dart.library.js_interop) 'src/client/app_context.dart' if (dart.library.io) 'src/server/app_context.dart' diff --git a/packages/jaspr/lib/src/foundation/binding.dart b/packages/jaspr/lib/src/foundation/binding.dart index 58160c467..47a9d6298 100644 --- a/packages/jaspr/lib/src/foundation/binding.dart +++ b/packages/jaspr/lib/src/foundation/binding.dart @@ -27,4 +27,7 @@ abstract class AppBinding with SchedulerBinding { /// Report an error that occurred during the build process of [element]. void reportBuildError(Element element, Object error, StackTrace stackTrace); + + /// Called during server rendering when [element] has applied DOM parameters. + void trackAppliedParams(DomElement element, Map diff) {} } diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index a1666ed51..3132581a1 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -145,7 +145,7 @@ class DomElement extends DomRenderObjectElement { classes = classesSet.join(' '); - if (!binding.isClient && binding.hasClients) { + if (!binding.isClient) { if (appliedId != null || appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || @@ -156,7 +156,7 @@ class DomElement extends DomRenderObjectElement { if (appliedStyles.isNotEmpty) 's': appliedStyles, if (appliedAttributes.isNotEmpty) 'a': appliedAttributes, }; - attributes['data-j-apply'] = jsonEncode(diff); + binding.trackAppliedParams(this, diff); } } } diff --git a/packages/jaspr/lib/src/framework/framework.dart b/packages/jaspr/lib/src/framework/framework.dart index 0211c091c..87a99a4b6 100644 --- a/packages/jaspr/lib/src/framework/framework.dart +++ b/packages/jaspr/lib/src/framework/framework.dart @@ -9,7 +9,6 @@ library; import 'dart:async'; import 'dart:collection'; -import 'dart:convert'; import 'package:meta/meta.dart'; import 'package:universal_web/web.dart' as web; diff --git a/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart b/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart new file mode 100644 index 000000000..21502cec3 --- /dev/null +++ b/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart @@ -0,0 +1,43 @@ +import 'dart:convert'; + +import '../../framework/framework.dart'; +import '../components/client_component_registry.dart'; +import '../markup_render_object.dart'; +import '../server_binding.dart'; + +final class AppliedParamsAdapter extends RenderAdapter { + final Map> elements = {}; + + void add(DomElement element, Map diff) { + elements[element] = diff; + } + + @override + void apply(MarkupRenderObject root) { + final registry = binding.clientRegistry; + if (registry == null) return; + + for (final MapEntry(:key, :value) in elements.entries) { + if (_hasClientBoundaryAbove(key, registry)) { + final renderObject = key.renderObject as MarkupRenderElement; + (renderObject.attributes ??= {})['data-j-apply'] = jsonEncode(value); + } + } + } + + bool _hasClientBoundaryAbove(Element element, ClientComponentRegistryElement registry) { + if (registry.serverElements.containsKey(element) || registry.clientElements.containsKey(element)) { + return true; + } + + var hasBoundary = false; + element.visitAncestorElements((e) { + if (registry.serverElements.containsKey(e) || registry.clientElements.containsKey(e)) { + hasBoundary = true; + return false; + } + return true; + }); + return hasBoundary; + } +} diff --git a/packages/jaspr/lib/src/server/components/client_component_registry.dart b/packages/jaspr/lib/src/server/components/client_component_registry.dart index 7e10c57de..597cfef42 100644 --- a/packages/jaspr/lib/src/server/components/client_component_registry.dart +++ b/packages/jaspr/lib/src/server/components/client_component_registry.dart @@ -14,6 +14,12 @@ class ClientComponentRegistry extends ObserverComponent { class ClientComponentRegistryElement extends ObserverElement { ClientComponentRegistryElement(super.component); + @override + void mount(Element? parent, ElementSlot newSlot) { + super.mount(parent, newSlot); + (binding as ServerAppBinding).clientRegistry = this; + } + bool _didHandleClientScript = false; final Map clientElements = {}; diff --git a/packages/jaspr/lib/src/server/server_binding.dart b/packages/jaspr/lib/src/server/server_binding.dart index 8e4ce4981..5931678af 100644 --- a/packages/jaspr/lib/src/server/server_binding.dart +++ b/packages/jaspr/lib/src/server/server_binding.dart @@ -7,6 +7,7 @@ import 'dart:typed_data'; import 'package:meta/meta.dart'; import '../../jaspr.dart'; +import 'adapters/applied_params_adapter.dart'; import 'adapters/document_structure_helper.dart'; import 'adapters/global_styles_adapter.dart'; import 'async_build_owner.dart'; @@ -32,6 +33,19 @@ class ServerAppBinding extends AppBinding with ComponentsBinding { @override bool get hasClients => _options?.clients?.isNotEmpty ?? false; + ClientComponentRegistryElement? clientRegistry; + + AppliedParamsAdapter? _appliedParamsAdapter; + + @override + void trackAppliedParams(DomElement element, Map diff) { + if (hasClients) { + final adapter = _appliedParamsAdapter ??= AppliedParamsAdapter(); + addRenderAdapter(adapter); + adapter.add(element, diff); + } + } + @override String get basePath => request.basePath; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 938ff6e4e..a40ab30c3 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -369,9 +369,7 @@ void main() { '\n' '\n' ' \n' - ' \n' - '
\n' - ' \n' + '
\n' '\n' '', ), @@ -398,7 +396,7 @@ void main() { '\n' ' \n' ' \n' - '
\n' + '
\n' ' \n' '
\n' ' \n' @@ -409,5 +407,40 @@ void main() { ), ); }); + + testServer('does not add data-j-apply to server elements without client boundary above', (tester) async { + tester.pumpComponent( + div([ + Component.apply( + classes: 'pure-server-applied', + child: div([ + p([text('pure server')]), + ]), + ), + App1(), + ]), + ); + + final response = await tester.request('/'); + + expect( + response.body, + equals( + '\n' + '\n' + ' \n' + ' \n' + '
\n' + '

pure server

\n' + ' \n' + '
\n' + ' \n' + '
\n' + ' \n' + '\n' + '', + ), + ); + }); }); } From 57e6ad9c1e94c25a6e7f003b9e2041fed4e61e08 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 12:59:41 +0100 Subject: [PATCH 05/24] refactor: walk client boundary subtree to apply data-j-apply without AppBinding tracking --- .../jaspr/lib/src/foundation/binding.dart | 6 --- .../jaspr/lib/src/framework/components.dart | 6 ++- .../adapters/applied_params_adapter.dart | 43 ------------------- .../adapters/client_component_adapter.dart | 15 +++++++ .../components/client_component_registry.dart | 6 --- .../jaspr/lib/src/server/server_binding.dart | 17 -------- 6 files changed, 19 insertions(+), 74 deletions(-) delete mode 100644 packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart diff --git a/packages/jaspr/lib/src/foundation/binding.dart b/packages/jaspr/lib/src/foundation/binding.dart index 47a9d6298..825fd6b62 100644 --- a/packages/jaspr/lib/src/foundation/binding.dart +++ b/packages/jaspr/lib/src/foundation/binding.dart @@ -8,9 +8,6 @@ abstract class AppBinding with SchedulerBinding { /// Whether the current app is run on the client (in the browser) bool get isClient; - /// Whether this app has client components registered. - bool get hasClients => false; - /// The currently active url. /// /// On the server, this is the request url. @@ -27,7 +24,4 @@ abstract class AppBinding with SchedulerBinding { /// Report an error that occurred during the build process of [element]. void reportBuildError(Element element, Object error, StackTrace stackTrace); - - /// Called during server rendering when [element] has applied DOM parameters. - void trackAppliedParams(DomElement element, Map diff) {} } diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 3132581a1..7671ad2e5 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -49,6 +49,9 @@ class DomElement extends DomRenderObjectElement { @override DomComponent get component => super.component as DomComponent; + @internal + Map? appliedDiff; + @override List buildOwnChildren() { return component.children ?? const []; @@ -150,13 +153,12 @@ class DomElement extends DomRenderObjectElement { appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || appliedAttributes.isNotEmpty) { - final diff = { + appliedDiff = { 'i': ?appliedId, if (appliedClasses.isNotEmpty) 'c': appliedClasses, if (appliedStyles.isNotEmpty) 's': appliedStyles, if (appliedAttributes.isNotEmpty) 'a': appliedAttributes, }; - binding.trackAppliedParams(this, diff); } } } diff --git a/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart b/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart deleted file mode 100644 index 21502cec3..000000000 --- a/packages/jaspr/lib/src/server/adapters/applied_params_adapter.dart +++ /dev/null @@ -1,43 +0,0 @@ -import 'dart:convert'; - -import '../../framework/framework.dart'; -import '../components/client_component_registry.dart'; -import '../markup_render_object.dart'; -import '../server_binding.dart'; - -final class AppliedParamsAdapter extends RenderAdapter { - final Map> elements = {}; - - void add(DomElement element, Map diff) { - elements[element] = diff; - } - - @override - void apply(MarkupRenderObject root) { - final registry = binding.clientRegistry; - if (registry == null) return; - - for (final MapEntry(:key, :value) in elements.entries) { - if (_hasClientBoundaryAbove(key, registry)) { - final renderObject = key.renderObject as MarkupRenderElement; - (renderObject.attributes ??= {})['data-j-apply'] = jsonEncode(value); - } - } - } - - bool _hasClientBoundaryAbove(Element element, ClientComponentRegistryElement registry) { - if (registry.serverElements.containsKey(element) || registry.clientElements.containsKey(element)) { - return true; - } - - var hasBoundary = false; - element.visitAncestorElements((e) { - if (registry.serverElements.containsKey(e) || registry.clientElements.containsKey(e)) { - hasBoundary = true; - return false; - } - return true; - }); - return hasBoundary; - } -} diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index cffb928d0..4355e08d3 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -77,6 +77,8 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { return; } + _applyParamsToDescendants(element); + final startMarker = MarkupRenderText( '', true, @@ -87,6 +89,19 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { group.children.insertBefore(endMarker); } + void _applyParamsToDescendants(Element parent) { + parent.visitChildren((child) { + if (child is DomElement) { + if (child.appliedDiff case final diff?) { + if (child.renderObject case final MarkupRenderElement renderObject) { + (renderObject.attributes ??= {})['data-j-apply'] = jsonEncode(diff); + } + } + } + _applyParamsToDescendants(child); + }); + } + String? getData() { final data = target.dataFor( element.component, diff --git a/packages/jaspr/lib/src/server/components/client_component_registry.dart b/packages/jaspr/lib/src/server/components/client_component_registry.dart index 597cfef42..7e10c57de 100644 --- a/packages/jaspr/lib/src/server/components/client_component_registry.dart +++ b/packages/jaspr/lib/src/server/components/client_component_registry.dart @@ -14,12 +14,6 @@ class ClientComponentRegistry extends ObserverComponent { class ClientComponentRegistryElement extends ObserverElement { ClientComponentRegistryElement(super.component); - @override - void mount(Element? parent, ElementSlot newSlot) { - super.mount(parent, newSlot); - (binding as ServerAppBinding).clientRegistry = this; - } - bool _didHandleClientScript = false; final Map clientElements = {}; diff --git a/packages/jaspr/lib/src/server/server_binding.dart b/packages/jaspr/lib/src/server/server_binding.dart index 5931678af..652bed5c1 100644 --- a/packages/jaspr/lib/src/server/server_binding.dart +++ b/packages/jaspr/lib/src/server/server_binding.dart @@ -7,7 +7,6 @@ import 'dart:typed_data'; import 'package:meta/meta.dart'; import '../../jaspr.dart'; -import 'adapters/applied_params_adapter.dart'; import 'adapters/document_structure_helper.dart'; import 'adapters/global_styles_adapter.dart'; import 'async_build_owner.dart'; @@ -30,22 +29,6 @@ class ServerAppBinding extends AppBinding with ComponentsBinding { @override bool get isClient => false; - @override - bool get hasClients => _options?.clients?.isNotEmpty ?? false; - - ClientComponentRegistryElement? clientRegistry; - - AppliedParamsAdapter? _appliedParamsAdapter; - - @override - void trackAppliedParams(DomElement element, Map diff) { - if (hasClients) { - final adapter = _appliedParamsAdapter ??= AppliedParamsAdapter(); - addRenderAdapter(adapter); - adapter.add(element, diff); - } - } - @override String get basePath => request.basePath; From ae6dc03668f797ae307632976466c8c3e0e3b994 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 13:06:07 +0100 Subject: [PATCH 06/24] perf: stop descending at nested client boundaries when applying params --- .../lib/src/server/adapters/client_component_adapter.dart | 5 +++++ .../lib/src/server/components/client_component_registry.dart | 1 + 2 files changed, 6 insertions(+) diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index 4355e08d3..c9d635a08 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -45,6 +45,8 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { return; } + registry.clientBoundaries.add(element); + data = getData(); final applied = []; @@ -91,6 +93,9 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { void _applyParamsToDescendants(Element parent) { parent.visitChildren((child) { + if (registry.clientBoundaries.contains(child)) { + return; + } if (child is DomElement) { if (child.appliedDiff case final diff?) { if (child.renderObject case final MarkupRenderElement renderObject) { diff --git a/packages/jaspr/lib/src/server/components/client_component_registry.dart b/packages/jaspr/lib/src/server/components/client_component_registry.dart index 7e10c57de..11196c3ac 100644 --- a/packages/jaspr/lib/src/server/components/client_component_registry.dart +++ b/packages/jaspr/lib/src/server/components/client_component_registry.dart @@ -17,6 +17,7 @@ class ClientComponentRegistryElement extends ObserverElement { bool _didHandleClientScript = false; final Map clientElements = {}; + final Set clientBoundaries = {}; int serverElementNum = 1; final Map<(Element, Component), int> serverComponents = {}; From cbe6eb713dbdf4f97ece06d128e2a7ad72e2025b Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 13:09:31 +0100 Subject: [PATCH 07/24] test: remove obsolete apply= substring test now that <...> delimiters are used --- .../hydration/hydration_browser_test.dart | 26 ------------------- 1 file changed, 26 deletions(-) diff --git a/packages/jaspr/test/client/hydration/hydration_browser_test.dart b/packages/jaspr/test/client/hydration/hydration_browser_test.dart index 81fd1af7a..b8e6ae94c 100644 --- a/packages/jaspr/test/client/hydration/hydration_browser_test.dart +++ b/packages/jaspr/test/client/hydration/hydration_browser_test.dart @@ -114,32 +114,6 @@ void main() { expect(pElement.className, equals('applied-from-marker')); }); - testClient('should safely parse marker when data contains "apply=" string', (tester) async { - final marker = DomValidator.clientMarkerPrefix; - window.document.body!.innerHTML = - '
' - ' ' - '

Content

' - ' ' - '
' - .toJS; - - Jaspr.initializeApp( - options: ClientOptions( - clients: { - 'app_with_text': ClientLoader((params) => p([Component.text(params.get('msg'))])), - }, - ), - ); - - runApp(const ClientApp()); - await pumpEventQueue(); - - final pElement = window.document.querySelector('body p')!; - expect(pElement.textContent, equals('please apply=here')); - expect(pElement.className, equals('applied-cls')); - }); - testClient('should find and hydrate multiple markers with params', (tester) async { final marker = DomValidator.clientMarkerPrefix; window.document.body!.innerHTML = From 0ec58cba05ed20ed0a3f3c323f76439745374d96 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 13:31:09 +0100 Subject: [PATCH 08/24] Use compact key-prefix encoding for data-j-apply with delimiter escaping --- .../lib/src/client/slotted_child_view.dart | 31 +++++++++++---- .../jaspr/lib/src/framework/components.dart | 26 +++++++++---- .../adapters/client_component_adapter.dart | 2 +- .../test/client/slotted_child_view_test.dart | 38 +++++++++++++++++-- packages/jaspr/test/server/client_test.dart | 22 +++++++++-- 5 files changed, 97 insertions(+), 22 deletions(-) diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index 68c02ee85..b5cecc369 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -1,8 +1,6 @@ /// @docImport 'client_app.dart'; library; -import 'dart:convert'; - import 'package:universal_web/web.dart' as web; import '../dom/type_checks.dart'; @@ -316,11 +314,27 @@ class _SlottedChildViewElement extends DomRenderObjectElement { element.removeAttribute('data-j-apply'); try { - final data = jsonDecode(raw) as Map; - final appliedId = data['i'] as String?; - final appliedClasses = (data['c'] as List?)?.cast(); - final appliedStylesList = (data['s'] as List?)?.cast(); - final appliedAttributesList = (data['a'] as List?)?.cast(); + String? appliedId; + List? appliedClasses; + List? appliedStylesList; + List? appliedAttributesList; + + for (final section in raw.split(';')) { + final colonIndex = section.indexOf(':'); + if (colonIndex == -1) continue; + final key = section.substring(0, colonIndex); + final val = section.substring(colonIndex + 1); + switch (key) { + case 'i': + appliedId = _unescapeApplyValue(val); + case 'c': + appliedClasses = val.split(',').map(_unescapeApplyValue).toList(); + case 's': + appliedStylesList = val.split(',').map(_unescapeApplyValue).toList(); + case 'a': + appliedAttributesList = val.split(',').map(_unescapeApplyValue).toList(); + } + } Map? appliedStyles; if (appliedStylesList != null) { @@ -635,3 +649,6 @@ class ChildSlotRenderObject extends DomRenderObject removeChild(child); } } + +String _unescapeApplyValue(String val) => + val.contains('%') ? val.replaceAll('%2C', ',').replaceAll('%3B', ';').replaceAll('%25', '%') : val; diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 7671ad2e5..b2b0e5a4b 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -50,7 +50,7 @@ class DomElement extends DomRenderObjectElement { DomComponent get component => super.component as DomComponent; @internal - Map? appliedDiff; + String? appliedDiff; @override List buildOwnChildren() { @@ -153,12 +153,20 @@ class DomElement extends DomRenderObjectElement { appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || appliedAttributes.isNotEmpty) { - appliedDiff = { - 'i': ?appliedId, - if (appliedClasses.isNotEmpty) 'c': appliedClasses, - if (appliedStyles.isNotEmpty) 's': appliedStyles, - if (appliedAttributes.isNotEmpty) 'a': appliedAttributes, - }; + final parts = []; + if (appliedId != null) { + parts.add('i:${_escapeApplyValue(appliedId)}'); + } + if (appliedClasses.isNotEmpty) { + parts.add('c:${appliedClasses.map(_escapeApplyValue).join(',')}'); + } + if (appliedStyles.isNotEmpty) { + parts.add('s:${appliedStyles.map(_escapeApplyValue).join(',')}'); + } + if (appliedAttributes.isNotEmpty) { + parts.add('a:${appliedAttributes.map(_escapeApplyValue).join(',')}'); + } + appliedDiff = parts.join(';'); } } } @@ -499,3 +507,7 @@ class _FragmentElement extends MultiChildRenderObjectElement { @override void updateRenderObject(RenderFragment fragment) {} } + +String _escapeApplyValue(String val) => (val.contains(';') || val.contains(',') || val.contains('%')) + ? val.replaceAll('%', '%25').replaceAll(';', '%3B').replaceAll(',', '%2C') + : val; diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index c9d635a08..0ca3def08 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -99,7 +99,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { if (child is DomElement) { if (child.appliedDiff case final diff?) { if (child.renderObject case final MarkupRenderElement renderObject) { - (renderObject.attributes ??= {})['data-j-apply'] = jsonEncode(diff); + (renderObject.attributes ??= {})['data-j-apply'] = diff; } } } diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index a9479aa4d..687dc112e 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -237,7 +237,7 @@ void main() { }); testClient('removes applied params when toggled off even if initially present in html', (tester) async { - window.document.body!.innerHTML = '
' + window.document.body!.innerHTML = '
' .toJS; var hasParams = true; late void Function(void Function() cb) setState; @@ -275,8 +275,7 @@ void main() { testClient('preserves child-owned id and classes when client apply toggles off', (tester) async { window.document.body!.innerHTML = - '
' - .toJS; + '
'.toJS; var hasParams = true; late void Function(void Function() cb) setState; @@ -306,7 +305,7 @@ void main() { }); testClient('preserves outer applied params when inner apply toggles off', (tester) async { - window.document.body!.innerHTML = '
' + window.document.body!.innerHTML = '
' .toJS; var hasParams = true; late void Function(void Function() cb) setState; @@ -337,6 +336,37 @@ void main() { expect(btn.className, 'child-class server-class'); }); + testClient('correctly unescapes special characters in data-j-apply', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + id: hasParams ? 'btn;1,2%3' : null, + classes: hasParams ? 'c;1 c,2' : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'btn;1,2%3'); + expect(btn.className, 'c;1 c,2'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.hasAttribute('id'), isFalse); + expect(btn.className, ''); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 59d7e03fd..950be70ca 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -358,7 +358,7 @@ void main() { ' \n' ' \n' ' \n' - '
\n' + '
\n' ' \n' ' \n' '\n' @@ -387,7 +387,7 @@ void main() { ' \n' ' \n' ' \n' - '
Hello
\n' + '
Hello
\n' ' \n' ' \n' '\n' @@ -443,7 +443,7 @@ void main() { ' \n' '
\n' ' \n' - '
\n' + '
\n' ' \n' '
\n' ' \n' @@ -487,5 +487,21 @@ void main() { ), ); }); + testServer('escapes special characters in data-j-apply', (tester) async { + tester.pumpComponent( + Component.apply( + id: 'test;1,2%3', + classes: 'c;1 c,2', + child: App1(), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('data-j-apply="i:test%3B1%2C2%253;c:c%3B1,c%2C2"'), + ); + }); }); } From 5aa7b67a2cd21bd1c54fd7b1b9e4ba173754ed86 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 13:37:25 +0100 Subject: [PATCH 09/24] Only add data-j-apply to server component elements --- .../adapters/client_component_adapter.dart | 20 +----------------- .../adapters/server_component_adapter.dart | 21 ++++++++++++++++++- packages/jaspr/test/server/client_test.dart | 20 ++++++++++++------ 3 files changed, 35 insertions(+), 26 deletions(-) diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index 0ca3def08..a9c86343b 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -79,8 +79,6 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { return; } - _applyParamsToDescendants(element); - final startMarker = MarkupRenderText( '', true, @@ -91,22 +89,6 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { group.children.insertBefore(endMarker); } - void _applyParamsToDescendants(Element parent) { - parent.visitChildren((child) { - if (registry.clientBoundaries.contains(child)) { - return; - } - if (child is DomElement) { - if (child.appliedDiff case final diff?) { - if (child.renderObject case final MarkupRenderElement renderObject) { - (renderObject.attributes ??= {})['data-j-apply'] = diff; - } - } - } - _applyParamsToDescendants(child); - }); - } - String? getData() { final data = target.dataFor( element.component, @@ -149,7 +131,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { for (final element in elements) { registry.serverElements[element] = s; - binding.addRenderAdapter(ServerComponentAdapter(s, element)); + binding.addRenderAdapter(ServerComponentAdapter(registry, s, element)); } return 's${DomValidator.clientMarkerPrefix}$s'; diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index 4916da924..886b4eaf1 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -1,19 +1,38 @@ import '../../dom/validator.dart'; +import '../../framework/framework.dart'; +import '../components/client_component_registry.dart'; import '../markup_render_object.dart'; import 'element_boundary_adapter.dart'; final class ServerComponentAdapter extends ElementBoundaryAdapter { - ServerComponentAdapter(this.id, super.element) + ServerComponentAdapter(this.registry, this.id, super.element) : super(priority: ElementBoundaryAdapter.serverComponentBoundaryPriority); + final ClientComponentRegistryElement registry; final int id; @override void applyBoundary(ChildGroup group) { + _applyParamsToSubtree(element); + final startMarker = MarkupRenderText('', true); final endMarker = MarkupRenderText('', true); group.children.insertAfter(startMarker); group.children.insertBefore(endMarker); } + + void _applyParamsToSubtree(Element element) { + if (registry.clientBoundaries.contains(element)) { + return; + } + if (element is DomElement) { + if (element.appliedDiff case final diff?) { + if (element.renderObject case final MarkupRenderElement renderObject) { + (renderObject.attributes ??= {})['data-j-apply'] = diff; + } + } + } + element.visitChildren(_applyParamsToSubtree); + } } diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 950be70ca..7f4e5c9ea 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -358,7 +358,7 @@ void main() { ' \n' ' \n' ' \n' - '
\n' + '
\n' ' \n' ' \n' '\n' @@ -370,6 +370,7 @@ void main() { testServer('encodes applied params above client component wrapping server component', (tester) async { tester.pumpComponent( Component.apply( + target: const ApplyTarget.descendantWith(), classes: 'server-class', child: AppWithServerComponent( child: span(classes: 'child-class', [text('Hello')]), @@ -386,8 +387,12 @@ void main() { '\n' ' \n' ' \n' - ' \n' - '
Hello
\n' + ' \n' + '
\n' + ' \n' + ' Hello\n' + ' \n' + '
\n' ' \n' ' \n' '\n' @@ -443,7 +448,7 @@ void main() { ' \n' '
\n' ' \n' - '
\n' + '
\n' ' \n' '
\n' ' \n' @@ -487,12 +492,15 @@ void main() { ), ); }); - testServer('escapes special characters in data-j-apply', (tester) async { + testServer('escapes special characters in data-j-apply on server components', (tester) async { tester.pumpComponent( Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), id: 'test;1,2%3', classes: 'c;1 c,2', - child: App1(), + child: AppWithServerComponent( + child: span([text('Hello')]), + ), ), ); From e9212ea064cd2d42301a9e7e79755ab94a05d3e9 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 14:00:32 +0100 Subject: [PATCH 10/24] Ignore RenderFragment in client apply check and only emit data-j-apply for client-managed params --- .../jaspr/lib/src/framework/components.dart | 54 +-------- .../adapters/client_component_adapter.dart | 2 +- .../adapters/server_component_adapter.dart | 111 +++++++++++++++++- .../test/client/slotted_child_view_test.dart | 28 +++++ packages/jaspr/test/server/client_test.dart | 63 ++++++++++ 5 files changed, 207 insertions(+), 51 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 716371b91..e796faf48 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -49,9 +49,6 @@ class DomElement extends DomRenderObjectElement { @override DomComponent get component => super.component as DomComponent; - @internal - String? appliedDiff; - @override List buildOwnChildren() { return component.children ?? const []; @@ -94,11 +91,6 @@ class DomElement extends DomRenderObjectElement { attributes = Map.of(attributes ?? {}); events = Map.of(events ?? {}); - final appliedClasses = []; - final appliedStyles = []; - final appliedAttributes = []; - String? appliedId; - for (final param in inheritedDomParams.reversed) { if (param.target.tag case final expectedTag? when expectedTag != component.tag) continue; // DOM Element.id is empty when neither the id field nor the attributes map supplies an ID. @@ -110,33 +102,21 @@ class DomElement extends DomRenderObjectElement { if (param.id case final paramId? when id == null) { id = paramId; - appliedId = paramId; } if (param.classes case final paramClasses?) { - for (final c in paramClasses) { - if (!classesSet.contains(c)) { - appliedClasses.add(c); - } - } classesSet.addAll(paramClasses); } if (param.styles case final stylesProps?) { for (final MapEntry(:key, :value) in stylesProps.entries) { - if (!styles.containsKey(key)) { - styles[key] = value; - appliedStyles.add(key); - } + styles[key] ??= value; } } if (param.attributes case final attributesMap?) { for (final MapEntry(:key, :value) in attributesMap.entries) { - if (!attributes.containsKey(key)) { - attributes[key] = value; - appliedAttributes.add(key); - } + attributes[key] ??= value; } } @@ -148,28 +128,6 @@ class DomElement extends DomRenderObjectElement { } classes = classesSet.join(' '); - - if (!binding.isClient) { - if (appliedId != null || - appliedClasses.isNotEmpty || - appliedStyles.isNotEmpty || - appliedAttributes.isNotEmpty) { - final parts = []; - if (appliedId != null) { - parts.add('i:${_escapeApplyValue(appliedId)}'); - } - if (appliedClasses.isNotEmpty) { - parts.add('c:${appliedClasses.map(_escapeApplyValue).join(',')}'); - } - if (appliedStyles.isNotEmpty) { - parts.add('s:${appliedStyles.map(_escapeApplyValue).join(',')}'); - } - if (appliedAttributes.isNotEmpty) { - parts.add('a:${appliedAttributes.map(_escapeApplyValue).join(',')}'); - } - appliedDiff = parts.join(';'); - } - } } renderObject.update(id, classes, styles, attributes, events); @@ -227,6 +185,7 @@ class ApplyDomComponent extends StatelessComponent implements DomComponent { styles: styles?.properties, attributes: attributes, events: events, + source: context as Element, ), child: child, ); @@ -326,7 +285,6 @@ abstract class DomRenderObjectElement extends MultiChildRenderObjectElement { } @internal - @protected List? inheritedDomParamsFor(RenderObject target) { return inheritedDomResolver?.call(target); } @@ -361,6 +319,7 @@ class ApplyParams { this.styles, this.attributes, this.events, + this.source, }); final ApplyTarget target; @@ -369,6 +328,7 @@ class ApplyParams { final Map? styles; final Map? attributes; final Map? events; + final Element? source; } typedef DomParamsResolver = List Function(RenderObject target); @@ -491,7 +451,3 @@ class _FragmentElement extends MultiChildRenderObjectElement { @override void updateRenderObject(RenderFragment fragment) {} } - -String _escapeApplyValue(String val) => (val.contains(';') || val.contains(',') || val.contains('%')) - ? val.replaceAll('%', '%25').replaceAll(';', '%3B').replaceAll(',', '%2C') - : val; diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index a9c86343b..2878f1b9a 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -55,7 +55,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { if (registry.serverElements.containsKey(e)) { return false; } - if (e is RenderObjectElement) { + if (e is RenderObjectElement && e.renderObject is! RenderFragment) { hasRenderElement = true; } if (e.component case final ApplyDomComponent applyComp) { diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index 886b4eaf1..2a31e3fbd 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -27,7 +27,7 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { return; } if (element is DomElement) { - if (element.appliedDiff case final diff?) { + if (_computeAppliedDiff(element) case final diff?) { if (element.renderObject case final MarkupRenderElement renderObject) { (renderObject.attributes ??= {})['data-j-apply'] = diff; } @@ -35,4 +35,113 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { } element.visitChildren(_applyParamsToSubtree); } + + String? _computeAppliedDiff(DomElement domElement) { + final inheritedDomParams = domElement.inheritedDomParamsFor(domElement.renderObject); + if (inheritedDomParams == null || inheritedDomParams.isEmpty) return null; + + final component = domElement.component; + String? id = component.id; + final classesSet = { + if (component.classes case final c?) ...c.split(_htmlClassWhitespace).where((s) => s.isNotEmpty), + }; + final styles = Map.of(component.styles?.properties ?? {}); + final attributes = Map.of(component.attributes ?? {}); + + final appliedClasses = []; + final appliedStyles = []; + final appliedAttributes = []; + String? appliedId; + + for (final param in inheritedDomParams.reversed) { + if (param.target.tag case final expectedTag? when expectedTag != component.tag) continue; + // DOM Element.id is empty when neither the id field nor the attributes map supplies an ID. + final effectiveId = id ?? attributes['id'] ?? ''; + if (param.target.id case final expectedId? when expectedId != effectiveId) continue; + if (param.target.classes case final expectedClasses? when !expectedClasses.every(classesSet.contains)) { + continue; + } + + final isClient = _isClientManaged(param); + + if (param.id case final paramId? when id == null) { + id = paramId; + if (isClient) { + appliedId = paramId; + } + } + + if (param.classes case final paramClasses?) { + for (final c in paramClasses) { + if (!classesSet.contains(c)) { + if (isClient) { + appliedClasses.add(c); + } + } + } + classesSet.addAll(paramClasses); + } + + if (param.styles case final stylesProps?) { + for (final MapEntry(:key, :value) in stylesProps.entries) { + if (!styles.containsKey(key)) { + styles[key] = value; + if (isClient) { + appliedStyles.add(key); + } + } + } + } + + if (param.attributes case final attributesMap?) { + for (final MapEntry(:key, :value) in attributesMap.entries) { + if (!attributes.containsKey(key)) { + attributes[key] = value; + if (isClient) { + appliedAttributes.add(key); + } + } + } + } + } + + if (appliedId != null || appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || appliedAttributes.isNotEmpty) { + final parts = []; + if (appliedId != null) { + parts.add('i:${_escapeApplyValue(appliedId)}'); + } + if (appliedClasses.isNotEmpty) { + parts.add('c:${appliedClasses.map(_escapeApplyValue).join(',')}'); + } + if (appliedStyles.isNotEmpty) { + parts.add('s:${appliedStyles.map(_escapeApplyValue).join(',')}'); + } + if (appliedAttributes.isNotEmpty) { + parts.add('a:${appliedAttributes.map(_escapeApplyValue).join(',')}'); + } + return parts.join(';'); + } + return null; + } + + bool _isClientManaged(ApplyParams param) { + final source = param.source; + if (source == null) return false; + if (registry.serverElements.containsKey(source)) return false; + var isServer = false; + source.visitAncestorElements((ancestor) { + if (registry.serverElements.containsKey(ancestor)) { + isServer = true; + return false; + } + return true; + }); + return !isServer; + } } + +final _htmlClassWhitespace = RegExp(r'[\t\n\f\r ]+'); + +String _escapeApplyValue(String val) => (val.contains(';') || val.contains(',') || val.contains('%')) + ? val.replaceAll('%', '%25').replaceAll(';', '%3B').replaceAll(',', '%2C') + : val; diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 9b709de3f..eebfb34f8 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -486,6 +486,34 @@ void main() { expect(btn.className, ''); }); + testClient('preserves server-only applied params when client apply toggles off', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + classes: hasParams ? 'client-applied' : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.className, 'btn server-applied client-applied'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.className, 'btn server-applied'); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 7f4e5c9ea..f6c1536da 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -511,5 +511,68 @@ void main() { contains('data-j-apply="i:test%3B1%2C2%253;c:c%3B1,c%2C2"'), ); }); + testServer('encodes direct child apply params across fragments', (tester) async { + tester.pumpComponent( + Component.apply( + classes: 'fragment-applied', + child: Component.fragment([ + App1(), + ]), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains(''), + ); + }); + + testServer('does not add data-j-apply for server-only apply inside server component', (tester) async { + tester.pumpComponent( + AppWithServerComponent( + child: Component.apply( + classes: 'server-only', + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }); + + testServer('only includes client-managed params in data-j-apply when server component has its own apply', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'client-managed', + child: AppWithServerComponent( + child: Component.apply( + classes: 'server-only', + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + }); }); } From a0d32690c089f78cc72ea3dbc693f03c82827cad Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 14:20:25 +0100 Subject: [PATCH 11/24] Optimize client-managed apply check and support nested client component applies --- .../jaspr/lib/src/framework/components.dart | 5 ++++ .../adapters/server_component_adapter.dart | 15 ++++-------- packages/jaspr/test/server/client_test.dart | 23 +++++++++++++++++++ 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index e796faf48..6fe4d44b8 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -384,6 +384,11 @@ class _InheritedDomComponent extends InheritedComponent { } } +@internal +bool hasInheritedDomParams(Element element) { + return element._inheritedElements?.containsKey(_InheritedDomComponent) ?? false; +} + /// Represents a plain text node with no additional properties. /// /// Styling is done through the parent element(s) and their styles. diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index 2a31e3fbd..f87934901 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -13,7 +13,9 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { @override void applyBoundary(ChildGroup group) { - _applyParamsToSubtree(element); + if (hasInheritedDomParams(element)) { + _applyParamsToSubtree(element); + } final startMarker = MarkupRenderText('', true); final endMarker = MarkupRenderText('', true); @@ -127,16 +129,7 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { bool _isClientManaged(ApplyParams param) { final source = param.source; if (source == null) return false; - if (registry.serverElements.containsKey(source)) return false; - var isServer = false; - source.visitAncestorElements((ancestor) { - if (registry.serverElements.containsKey(ancestor)) { - isServer = true; - return false; - } - return true; - }); - return !isServer; + return source.depth < element.depth; } } diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index f6c1536da..36a90b922 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -574,5 +574,28 @@ void main() { contains('Hello'), ); }); + + testServer('emits data-j-apply for apply inside a client component nested in a server component', (tester) async { + tester.pumpComponent( + AppWithServerComponent( + child: div([ + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'inner-client-applied', + child: AppWithServerComponent( + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ]), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + }); }); } From df2fcab5dade4ae3da12a22346a27efe7efccdf6 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 14:25:59 +0100 Subject: [PATCH 12/24] Isolate client-managed apply bounds between parent and current server component --- .../adapters/server_component_adapter.dart | 19 ++++++++++- packages/jaspr/test/server/client_test.dart | 32 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index f87934901..9a6865e67 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -126,10 +126,27 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { return null; } + int? _minDepth; + + int _getMinDepth() { + if (_minDepth case final minDepth?) { + return minDepth; + } + Element? parentServer; + element.visitAncestorElements((ancestor) { + if (registry.serverElements.containsKey(ancestor)) { + parentServer = ancestor; + return false; + } + return true; + }); + return _minDepth = parentServer?.depth ?? 0; + } + bool _isClientManaged(ApplyParams param) { final source = param.source; if (source == null) return false; - return source.depth < element.depth; + return source.depth > _getMinDepth() && source.depth < element.depth; } } diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 36a90b922..07bcb2b7f 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -597,5 +597,37 @@ void main() { contains('Hello'), ); }); + + testServer( + 'handles nested alternating server-client boundaries by isolating outer applies from inner server components', + (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'outer-applied', + child: AppWithServerComponent( + child: div([ + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'inner-client-applied', + child: AppWithServerComponent( + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains( + 'Hello', + ), + ); + }, + ); }); } From 5ee7b4d89da5435a6b986efa5d1d55f4b59e699f Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:16:50 +0100 Subject: [PATCH 13/24] Simplify _isClientManaged to depth check and add test for client-defined applies --- .../adapters/server_component_adapter.dart | 19 +------ packages/jaspr/test/server/client_test.dart | 53 ++++++++++++++++++- 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index 9a6865e67..f87934901 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -126,27 +126,10 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { return null; } - int? _minDepth; - - int _getMinDepth() { - if (_minDepth case final minDepth?) { - return minDepth; - } - Element? parentServer; - element.visitAncestorElements((ancestor) { - if (registry.serverElements.containsKey(ancestor)) { - parentServer = ancestor; - return false; - } - return true; - }); - return _minDepth = parentServer?.depth ?? 0; - } - bool _isClientManaged(ApplyParams param) { final source = param.source; if (source == null) return false; - return source.depth > _getMinDepth() && source.depth < element.depth; + return source.depth < element.depth; } } diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 07bcb2b7f..2820cf850 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -124,6 +124,26 @@ class AppWithCustomModel extends StatelessComponent { } } +class AppWithApplyAndServerComponent extends StatelessComponent { + const AppWithApplyAndServerComponent({required this.child}); + + final Component child; + + @override + Component build(BuildContext context) { + return div( + attributes: {'data-app': 'with-apply-and-child'}, + [ + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'client-applied', + child: child, + ), + ], + ); + } +} + void main() { group('@client', () { setUpAll(() { @@ -139,6 +159,10 @@ void main() { 'app_with_server_component', params: (app) => {'child': app.child}, ), + AppWithApplyAndServerComponent: ClientTarget( + 'app_with_apply_and_server_component', + params: (app) => {'child': app.child}, + ), AppWithMultipleServerComponents: ClientTarget( 'app_with_multiple_server_components', params: (app) => {'child1': app.child1, 'child2': app.child2}, @@ -624,10 +648,37 @@ void main() { expect( response.body, contains( - 'Hello', + 'Hello', ), ); }, ); + + testServer('includes both outer and client-defined applies in data-j-apply while excluding server-only applies', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'outer-applied', + child: AppWithApplyAndServerComponent( + child: Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'server-only', + child: span(classes: 'child-class', [text('Hello')]), + ), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains( + 'Hello', + ), + ); + }); }); } From ba88b5ef9600bdda33f357dc3ad1c45b77fff103 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:34:32 +0100 Subject: [PATCH 14/24] Deduplicate apply matching and diff computation to DomElement and use extension getter for hasInheritedDomParams --- .../jaspr/lib/src/framework/components.dart | 109 ++++++++++++++++-- .../adapters/server_component_adapter.dart | 98 +--------------- 2 files changed, 103 insertions(+), 104 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 6fe4d44b8..141db5953 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -92,11 +92,8 @@ class DomElement extends DomRenderObjectElement { events = Map.of(events ?? {}); for (final param in inheritedDomParams.reversed) { - if (param.target.tag case final expectedTag? when expectedTag != component.tag) continue; - // DOM Element.id is empty when neither the id field nor the attributes map supplies an ID. - if (param.target.id case final expectedId? when expectedId != (id ?? attributes['id'] ?? '')) continue; - if (param.target.classes case final expectedClasses? - when !expectedClasses.every((c) => classesSet.contains(c))) { + final String effectiveId = id ?? attributes['id'] ?? ''; + if (!param.target.matches(tag: component.tag, id: effectiveId, classes: classesSet)) { continue; } @@ -132,8 +129,95 @@ class DomElement extends DomRenderObjectElement { renderObject.update(id, classes, styles, attributes, events); } + + @internal + String? computeAppliedDiff(bool Function(ApplyParams) isClientManaged) { + final inheritedDomParams = inheritedDomParamsFor(renderObject); + if (inheritedDomParams == null || inheritedDomParams.isEmpty) return null; + + String? id = component.id; + final classesSet = {...?_splitClasses(component.classes)}; + final styles = {...?component.styles?.properties}; + final attributes = {...?component.attributes}; + + final appliedClasses = []; + final appliedStyles = []; + final appliedAttributes = []; + String? appliedId; + + for (final param in inheritedDomParams.reversed) { + final String effectiveId = id ?? attributes['id'] ?? ''; + if (!param.target.matches(tag: component.tag, id: effectiveId, classes: classesSet)) { + continue; + } + + final isClient = isClientManaged(param); + + if (param.id case final paramId? when id == null) { + id = paramId; + if (isClient) { + appliedId = paramId; + } + } + + if (param.classes case final paramClasses?) { + for (final c in paramClasses) { + if (!classesSet.contains(c)) { + if (isClient) { + appliedClasses.add(c); + } + } + } + classesSet.addAll(paramClasses); + } + + if (param.styles case final stylesProps?) { + for (final MapEntry(:key, :value) in stylesProps.entries) { + if (!styles.containsKey(key)) { + styles[key] = value; + if (isClient) { + appliedStyles.add(key); + } + } + } + } + + if (param.attributes case final attributesMap?) { + for (final MapEntry(:key, :value) in attributesMap.entries) { + if (!attributes.containsKey(key)) { + attributes[key] = value; + if (isClient) { + appliedAttributes.add(key); + } + } + } + } + } + + if (appliedId != null || appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || appliedAttributes.isNotEmpty) { + final parts = []; + if (appliedId != null) { + parts.add('i:${_escapeApplyValue(appliedId)}'); + } + if (appliedClasses.isNotEmpty) { + parts.add('c:${appliedClasses.map(_escapeApplyValue).join(',')}'); + } + if (appliedStyles.isNotEmpty) { + parts.add('s:${appliedStyles.map(_escapeApplyValue).join(',')}'); + } + if (appliedAttributes.isNotEmpty) { + parts.add('a:${appliedAttributes.map(_escapeApplyValue).join(',')}'); + } + return parts.join(';'); + } + return null; + } } +String _escapeApplyValue(String val) => (val.contains(';') || val.contains(',') || val.contains('%')) + ? val.replaceAll('%', '%25').replaceAll(';', '%3B').replaceAll(',', '%2C') + : val; + @internal class ApplyDomComponent extends StatelessComponent implements DomComponent { const ApplyDomComponent({ @@ -230,6 +314,15 @@ final class ApplyTarget { /// The classes an element must all have to match, or `null` for any. final Set? classes; + + @internal + bool matches({required String tag, required String id, required Set classes}) { + if (this.tag case final expectedTag? when expectedTag != tag) return false; + if (this.id case final expectedId? when expectedId != id) return false; + if (this.classes case final expectedClasses? when !expectedClasses.every(classes.contains)) return false; + return true; + } + Map toMap() => { if (!onlyChildren) 'd': true, if (tag != null) 't': tag, @@ -384,9 +477,9 @@ class _InheritedDomComponent extends InheritedComponent { } } -@internal -bool hasInheritedDomParams(Element element) { - return element._inheritedElements?.containsKey(_InheritedDomComponent) ?? false; +extension DomParamsElement on Element { + @internal + bool get hasInheritedDomParams => _inheritedElements?.containsKey(_InheritedDomComponent) ?? false; } /// Represents a plain text node with no additional properties. diff --git a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart index f87934901..1dc1004b6 100644 --- a/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/server_component_adapter.dart @@ -13,7 +13,7 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { @override void applyBoundary(ChildGroup group) { - if (hasInheritedDomParams(element)) { + if (element.hasInheritedDomParams) { _applyParamsToSubtree(element); } @@ -29,7 +29,7 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { return; } if (element is DomElement) { - if (_computeAppliedDiff(element) case final diff?) { + if (element.computeAppliedDiff(_isClientManaged) case final diff?) { if (element.renderObject case final MarkupRenderElement renderObject) { (renderObject.attributes ??= {})['data-j-apply'] = diff; } @@ -38,103 +38,9 @@ final class ServerComponentAdapter extends ElementBoundaryAdapter { element.visitChildren(_applyParamsToSubtree); } - String? _computeAppliedDiff(DomElement domElement) { - final inheritedDomParams = domElement.inheritedDomParamsFor(domElement.renderObject); - if (inheritedDomParams == null || inheritedDomParams.isEmpty) return null; - - final component = domElement.component; - String? id = component.id; - final classesSet = { - if (component.classes case final c?) ...c.split(_htmlClassWhitespace).where((s) => s.isNotEmpty), - }; - final styles = Map.of(component.styles?.properties ?? {}); - final attributes = Map.of(component.attributes ?? {}); - - final appliedClasses = []; - final appliedStyles = []; - final appliedAttributes = []; - String? appliedId; - - for (final param in inheritedDomParams.reversed) { - if (param.target.tag case final expectedTag? when expectedTag != component.tag) continue; - // DOM Element.id is empty when neither the id field nor the attributes map supplies an ID. - final effectiveId = id ?? attributes['id'] ?? ''; - if (param.target.id case final expectedId? when expectedId != effectiveId) continue; - if (param.target.classes case final expectedClasses? when !expectedClasses.every(classesSet.contains)) { - continue; - } - - final isClient = _isClientManaged(param); - - if (param.id case final paramId? when id == null) { - id = paramId; - if (isClient) { - appliedId = paramId; - } - } - - if (param.classes case final paramClasses?) { - for (final c in paramClasses) { - if (!classesSet.contains(c)) { - if (isClient) { - appliedClasses.add(c); - } - } - } - classesSet.addAll(paramClasses); - } - - if (param.styles case final stylesProps?) { - for (final MapEntry(:key, :value) in stylesProps.entries) { - if (!styles.containsKey(key)) { - styles[key] = value; - if (isClient) { - appliedStyles.add(key); - } - } - } - } - - if (param.attributes case final attributesMap?) { - for (final MapEntry(:key, :value) in attributesMap.entries) { - if (!attributes.containsKey(key)) { - attributes[key] = value; - if (isClient) { - appliedAttributes.add(key); - } - } - } - } - } - - if (appliedId != null || appliedClasses.isNotEmpty || appliedStyles.isNotEmpty || appliedAttributes.isNotEmpty) { - final parts = []; - if (appliedId != null) { - parts.add('i:${_escapeApplyValue(appliedId)}'); - } - if (appliedClasses.isNotEmpty) { - parts.add('c:${appliedClasses.map(_escapeApplyValue).join(',')}'); - } - if (appliedStyles.isNotEmpty) { - parts.add('s:${appliedStyles.map(_escapeApplyValue).join(',')}'); - } - if (appliedAttributes.isNotEmpty) { - parts.add('a:${appliedAttributes.map(_escapeApplyValue).join(',')}'); - } - return parts.join(';'); - } - return null; - } - bool _isClientManaged(ApplyParams param) { final source = param.source; if (source == null) return false; return source.depth < element.depth; } } - -final _htmlClassWhitespace = RegExp(r'[\t\n\f\r ]+'); - -String _escapeApplyValue(String val) => (val.contains(';') || val.contains(',') || val.contains('%')) - ? val.replaceAll('%', '%25').replaceAll(';', '%3B').replaceAll(',', '%2C') - : val; From d464390af13fc022d08ec4cf2632720b8b31619e Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:38:28 +0100 Subject: [PATCH 15/24] Store applied params in updateRenderObject and reuse in computeAppliedDiff --- .../jaspr/lib/src/framework/components.dart | 110 +++++++++--------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 141db5953..8f3ebc959 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -43,12 +43,22 @@ List? _splitClasses(String? classes) { return classNames.isEmpty ? null : classNames; } +typedef _AppliedParam = ({ + ApplyParams param, + String? id, + List? classes, + List? styles, + List? attributes, +}); + class DomElement extends DomRenderObjectElement { DomElement(DomComponent super.component); @override DomComponent get component => super.component as DomComponent; + List<_AppliedParam>? _appliedParams; + @override List buildOwnChildren() { return component.children ?? const []; @@ -79,6 +89,7 @@ class DomElement extends DomRenderObjectElement { @override void updateRenderObject(RenderElement renderObject) { + _appliedParams = null; var id = component.id; var classes = component.classes; var styles = component.styles?.properties; @@ -87,9 +98,9 @@ class DomElement extends DomRenderObjectElement { if (inheritedDomParamsFor(renderObject) case final inheritedDomParams? when inheritedDomParams.isNotEmpty) { final classesSet = {...?_splitClasses(classes)}; - styles = Map.of(styles ?? {}); - attributes = Map.of(attributes ?? {}); - events = Map.of(events ?? {}); + styles = {...?styles}; + attributes = {...?attributes}; + events = {...?events}; for (final param in inheritedDomParams.reversed) { final String effectiveId = id ?? attributes['id'] ?? ''; @@ -97,23 +108,39 @@ class DomElement extends DomRenderObjectElement { continue; } + String? appliedId; + List? appliedClasses; + List? appliedStyles; + List? appliedAttributes; + if (param.id case final paramId? when id == null) { id = paramId; + appliedId = paramId; } if (param.classes case final paramClasses?) { - classesSet.addAll(paramClasses); + for (final c in paramClasses) { + if (classesSet.add(c)) { + (appliedClasses ??= []).add(c); + } + } } if (param.styles case final stylesProps?) { for (final MapEntry(:key, :value) in stylesProps.entries) { - styles[key] ??= value; + if (!styles.containsKey(key)) { + styles[key] = value; + (appliedStyles ??= []).add(key); + } } } if (param.attributes case final attributesMap?) { for (final MapEntry(:key, :value) in attributesMap.entries) { - attributes[key] ??= value; + if (!attributes.containsKey(key)) { + attributes[key] = value; + (appliedAttributes ??= []).add(key); + } } } @@ -122,6 +149,16 @@ class DomElement extends DomRenderObjectElement { events[key] ??= value; } } + + if (appliedId != null || appliedClasses != null || appliedStyles != null || appliedAttributes != null) { + (_appliedParams ??= []).add(( + param: param, + id: appliedId, + classes: appliedClasses, + styles: appliedStyles, + attributes: appliedAttributes, + )); + } } classes = classesSet.join(' '); @@ -132,65 +169,28 @@ class DomElement extends DomRenderObjectElement { @internal String? computeAppliedDiff(bool Function(ApplyParams) isClientManaged) { - final inheritedDomParams = inheritedDomParamsFor(renderObject); - if (inheritedDomParams == null || inheritedDomParams.isEmpty) return null; - - String? id = component.id; - final classesSet = {...?_splitClasses(component.classes)}; - final styles = {...?component.styles?.properties}; - final attributes = {...?component.attributes}; + final applied = _appliedParams; + if (applied == null || applied.isEmpty) return null; final appliedClasses = []; final appliedStyles = []; final appliedAttributes = []; String? appliedId; - for (final param in inheritedDomParams.reversed) { - final String effectiveId = id ?? attributes['id'] ?? ''; - if (!param.target.matches(tag: component.tag, id: effectiveId, classes: classesSet)) { - continue; - } - - final isClient = isClientManaged(param); + for (final entry in applied) { + if (!isClientManaged(entry.param)) continue; - if (param.id case final paramId? when id == null) { - id = paramId; - if (isClient) { - appliedId = paramId; - } + if (entry.id case final id?) { + appliedId = id; } - - if (param.classes case final paramClasses?) { - for (final c in paramClasses) { - if (!classesSet.contains(c)) { - if (isClient) { - appliedClasses.add(c); - } - } - } - classesSet.addAll(paramClasses); + if (entry.classes case final classes?) { + appliedClasses.addAll(classes); } - - if (param.styles case final stylesProps?) { - for (final MapEntry(:key, :value) in stylesProps.entries) { - if (!styles.containsKey(key)) { - styles[key] = value; - if (isClient) { - appliedStyles.add(key); - } - } - } + if (entry.styles case final styles?) { + appliedStyles.addAll(styles); } - - if (param.attributes case final attributesMap?) { - for (final MapEntry(:key, :value) in attributesMap.entries) { - if (!attributes.containsKey(key)) { - attributes[key] = value; - if (isClient) { - appliedAttributes.add(key); - } - } - } + if (entry.attributes case final attributes?) { + appliedAttributes.addAll(attributes); } } From 4928e5879831f2c98d703d7f21edb48366a14047 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:42:51 +0100 Subject: [PATCH 16/24] Restore Map.of in updateRenderObject --- packages/jaspr/lib/src/framework/components.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 8f3ebc959..fc0f5f0b6 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -98,9 +98,9 @@ class DomElement extends DomRenderObjectElement { if (inheritedDomParamsFor(renderObject) case final inheritedDomParams? when inheritedDomParams.isNotEmpty) { final classesSet = {...?_splitClasses(classes)}; - styles = {...?styles}; - attributes = {...?attributes}; - events = {...?events}; + styles = Map.of(styles ?? {}); + attributes = Map.of(attributes ?? {}); + events = Map.of(events ?? {}); for (final param in inheritedDomParams.reversed) { final String effectiveId = id ?? attributes['id'] ?? ''; From d55a89b5adf07a2dee007c305826179e4fe2a9ba Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:45:33 +0100 Subject: [PATCH 17/24] Hide DomParamsElement from public jaspr.dart export --- packages/jaspr/lib/jaspr.dart | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/jaspr/lib/jaspr.dart b/packages/jaspr/lib/jaspr.dart index a0afde45f..3d7613cdc 100644 --- a/packages/jaspr/lib/jaspr.dart +++ b/packages/jaspr/lib/jaspr.dart @@ -20,7 +20,13 @@ export 'src/foundation/scheduler.dart'; export 'src/foundation/sync.dart'; export 'src/foundation/synchronous_future.dart'; export 'src/framework/framework.dart' - hide GlobalComponentsBinding, DomRenderObjectElement, ApplyParams, DomParamsResolver, ApplyDomComponent; + hide + GlobalComponentsBinding, + DomRenderObjectElement, + ApplyParams, + DomParamsResolver, + ApplyDomComponent, + DomParamsElement; export 'src/stub/app_context_stub.dart' if (dart.library.js_interop) 'src/client/app_context.dart' if (dart.library.io) 'src/server/app_context.dart' From 3e1079fd80266f059872d62d262db9c05b58f917 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Fri, 13 Nov 2026 15:54:55 +0100 Subject: [PATCH 18/24] Address review comments: support SVG and range anchors in hydration, and fix boundary check for server-child root --- .../lib/src/client/slotted_child_view.dart | 82 ++++++++++--------- packages/jaspr/lib/src/dom/type_checks.dart | 4 + .../adapters/client_component_adapter.dart | 30 +++---- .../test/client/slotted_child_view_test.dart | 67 +++++++++++++++ packages/jaspr/test/server/client_test.dart | 18 ++++ 5 files changed, 150 insertions(+), 51 deletions(-) diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index 1b613109f..f9313d048 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -241,7 +241,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } bool _didHydrate = false; - final Map _appliedParams = nodeMap(); + final Map _appliedParams = nodeMap(); @override void updateRenderObject(SlottedDomRenderObject renderObject) { @@ -266,7 +266,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { final elements = _findMatchingElements(current as web.Element, param.target); for (final element in elements) { - _updateElementParams(element as web.HTMLElement, param); + _updateElementParams(element, param); } } } @@ -282,33 +282,26 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } void _hydrateInitialNodes(SlottedDomRenderObject renderObject) { - final slotRanges = { - for (final slot in component.slots) - if (slot is _RangeChildSlot) slot.start: slot.end, - }; + final slotRanges = nodeMap(); + for (final slot in component.slots) { + if (slot is _RangeChildSlot) slotRanges[slot.start] = slot.end; + } web.Node? current = renderObject.firstChildNode; while (current != null) { - if (slotRanges[current] case final endNode?) { - if (current == renderObject.lastChildNode) break; - current = endNode; - if (slotRanges.containsKey(current)) continue; - if (current == renderObject.lastChildNode) break; - current = current.nextSibling; - continue; - } - if (current.isElement) { _hydrateInitialAppliedParams(current as web.Element); } - if (current == renderObject.lastChildNode) break; - current = current.nextSibling; + if (current == renderObject.lastChildNode) { + break; + } + current = slotRanges[current] ?? current.nextSibling; } } void _hydrateInitialAppliedParams(web.Element root) { - void process(web.HTMLElement element) { + void process(web.Element element) { if (element.hasAttribute('data-j-apply')) { final raw = element.getAttribute('data-j-apply')!; element.removeAttribute('data-j-apply'); @@ -338,7 +331,10 @@ class _SlottedChildViewElement extends DomRenderObjectElement { Map? appliedStyles; if (appliedStylesList != null) { - appliedStyles = {for (final s in appliedStylesList) s: element.style.getPropertyValue(s)}; + final style = element.inlineStyle; + if (style != null) { + appliedStyles = {for (final s in appliedStylesList) s: style.getPropertyValue(s)}; + } } Map? appliedAttributes; @@ -357,12 +353,10 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } - if (root.isHtmlElement) { - process(root as web.HTMLElement); - } + process(root); final descendants = root.querySelectorAll('[data-j-apply]'); for (int i = 0; i < descendants.length; i++) { - process(descendants.item(i) as web.HTMLElement); + process(descendants.item(i) as web.Element); } } @@ -410,7 +404,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { /// Removes the params this view applied to [element], /// without leaving behind empty attributes that it didn't have before. - static void _resetElementParams(web.HTMLElement element, _AppliedParams params) { + static void _resetElementParams(web.Element element, _AppliedParams params) { if (params.id != null && element.id == params.id) { element.removeAttribute('id'); } @@ -425,14 +419,17 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } if (params.styles case final appliedStyles? when appliedStyles.isNotEmpty) { - for (final e in appliedStyles.entries) { - element.style.removeProperty(e.key); - } - if (element.style.length == 0) { - // Read the attribute first, so the browser syncs the pending style changes into it. - // Otherwise, it can sync them afterwards and add back an empty `style` attribute. - element.getAttribute('style'); - element.removeAttribute('style'); + final style = element.inlineStyle; + if (style != null) { + for (final e in appliedStyles.entries) { + style.removeProperty(e.key); + } + if (style.length == 0) { + // Read the attribute first, so the browser syncs the pending style changes into it. + // Otherwise, it can sync them afterwards and add back an empty `style` attribute. + element.getAttribute('style'); + element.removeAttribute('style'); + } } } @@ -449,7 +446,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } - void _updateElementParams(web.HTMLElement element, ApplyParams newParams) { + void _updateElementParams(web.Element element, ApplyParams newParams) { final params = _appliedParams[element]; String? appliedId = params?.id; @@ -477,10 +474,13 @@ class _SlottedChildViewElement extends DomRenderObjectElement { if (newParams.styles case final newStyles?) { appliedStyles ??= {}; - for (final e in newStyles.entries) { - if (element.style.getPropertyValue(e.key).isEmpty) { - element.style.setProperty(e.key, e.value); - appliedStyles[e.key] = e.value; + final style = element.inlineStyle; + if (style != null) { + for (final e in newStyles.entries) { + if (style.getPropertyValue(e.key).isEmpty) { + style.setProperty(e.key, e.value); + appliedStyles[e.key] = e.value; + } } } } @@ -521,6 +521,14 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } +extension on web.Element { + web.CSSStyleDeclaration? get inlineStyle { + if (isHtmlElement) return (this as web.HTMLElement).style; + if (isSvgElement) return (this as web.SVGElement).style; + return null; + } +} + class _AppliedParams extends ApplyParams { _AppliedParams({ required super.target, diff --git a/packages/jaspr/lib/src/dom/type_checks.dart b/packages/jaspr/lib/src/dom/type_checks.dart index 6b52685cb..56d417c90 100644 --- a/packages/jaspr/lib/src/dom/type_checks.dart +++ b/packages/jaspr/lib/src/dom/type_checks.dart @@ -19,6 +19,7 @@ extension DomTypeTests on JSAny? { bool get isText => this == null ? false : instanceof(_cachedTextConstructor); bool get isComment => this == null ? false : instanceof(_cachedCommentConstructor); bool get isDocumentFragment => this == null ? false : instanceof(_cachedDocumentFragmentConstructor); + bool get isSvgElement => this == null ? false : instanceof(_cachedSvgElementConstructor); } final _cachedElementConstructor = _elementConstructor; @@ -31,6 +32,7 @@ final _cachedHtmlOptionElementConstructor = _htmlOptionElementConstructor; final _cachedTextConstructor = _textConstructor; final _cachedCommentConstructor = _commentConstructor; final _cachedDocumentFragmentConstructor = _documentFragmentConstructor; +final _cachedSvgElementConstructor = _svgElementConstructor; @JS('Element') external JSFunction get _elementConstructor; @@ -52,3 +54,5 @@ external JSFunction get _textConstructor; external JSFunction get _commentConstructor; @JS('DocumentFragment') external JSFunction get _documentFragmentConstructor; +@JS('SVGElement') +external JSFunction get _svgElementConstructor; diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index 2878f1b9a..9f0d23ae8 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -50,21 +50,23 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { data = getData(); final applied = []; - var hasRenderElement = false; - element.visitAncestorElements((e) { - if (registry.serverElements.containsKey(e)) { - return false; - } - if (e is RenderObjectElement && e.renderObject is! RenderFragment) { - hasRenderElement = true; - } - if (e.component case final ApplyDomComponent applyComp) { - if (!applyComp.target.onlyChildren || !hasRenderElement) { - applied.add(applyComp); + if (!registry.serverElements.containsKey(element)) { + var hasRenderElement = false; + element.visitAncestorElements((e) { + if (registry.serverElements.containsKey(e)) { + return false; + } + if (e is RenderObjectElement && e.renderObject is! RenderFragment) { + hasRenderElement = true; } - } - return true; - }); + if (e.component case final ApplyDomComponent applyComp) { + if (!applyComp.target.onlyChildren || !hasRenderElement) { + applied.add(applyComp); + } + } + return true; + }); + } if (applied.isNotEmpty) { applyData = const DomValidator().escapeMarkerText(jsonEncode(applied.map((a) => a.toMap()).toList())); diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index eebfb34f8..7c383b8ec 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -514,6 +514,73 @@ void main() { expect(btn.className, 'btn server-applied'); }); + testClient('hydrates and cleans up data-j-apply on SVG root element', (tester) async { + window.document.body!.innerHTML = + ''.toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .childWith(tag: 'svg'), + classes: hasParams ? 'applied' : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final svg = window.document.querySelector('svg')!; + expect(svg.getAttribute('class'), 'icon applied'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(svg.getAttribute('class'), 'icon'); + }); + + testClient('hydrates and cleans up data-j-apply on range slot element anchors', (tester) async { + window.document.body!.innerHTML = + 'Start' + '' + 'End' + .toJS; + final spans = window.document.querySelectorAll('span'); + final start = spans.item(0)! as HTMLElement; + final end = spans.item(1)! as HTMLElement; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'span'), + classes: hasParams ? 'applied' : null, + child: SlottedChildView( + slots: [ + ChildSlot.between(start: start, end: end, child: button([])), + ], + ), + ); + }, + ), + ); + + expect(start.getAttribute('class'), 'anchor applied'); + expect(end.getAttribute('class'), 'end-anchor applied'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(start.getAttribute('class'), 'anchor'); + expect(end.getAttribute('class'), 'end-anchor'); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 2820cf850..a4dc02485 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -341,6 +341,24 @@ void main() { ); }); + testServer('does not serialize outer client applies onto client component directly nested as server component', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + classes: 'outer-apply', + child: AppWithServerComponent(child: App1()), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('
'), + ); + }); + testServer('renders server components inside custom model parameter', (tester) async { tester.pumpComponent(AppWithCustomModel(model: ModelWithComponent(span([text('Custom Model')])))); From e5d145e66484fe88a822a1e4af433937074b283c Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 10:01:42 +0100 Subject: [PATCH 19/24] Address review comments: account for dedicated fields in attribute diffs, reset hydration on reload, and collect server-child root apply --- .../lib/src/client/slotted_child_view.dart | 7 ++ .../jaspr/lib/src/framework/components.dart | 10 ++- .../adapters/client_component_adapter.dart | 7 +- .../test/client/slotted_child_view_test.dart | 40 ++++++++++ packages/jaspr/test/server/client_test.dart | 80 +++++++++++++++++++ 5 files changed, 139 insertions(+), 5 deletions(-) diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index f9313d048..66d6b4a5f 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -248,6 +248,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { final inheritedDomParams = inheritedDomParamsFor(renderObject); if ((component.nodes != null || (inheritedDomParams != null && inheritedDomParams.isNotEmpty)) && !_didHydrate) { _didHydrate = true; + _appliedParams.clear(); _hydrateInitialNodes(renderObject); } @@ -514,6 +515,12 @@ class _SlottedChildViewElement extends DomRenderObjectElement { ); } + @override + void onReload() { + _didHydrate = false; + super.onReload(); + } + @override void unmount() { _resetAppliedParams(); diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index fc0f5f0b6..6b012dc9f 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -97,7 +97,10 @@ class DomElement extends DomRenderObjectElement { var events = component.events; if (inheritedDomParamsFor(renderObject) case final inheritedDomParams? when inheritedDomParams.isNotEmpty) { - final classesSet = {...?_splitClasses(classes)}; + final classesSet = { + ...?_splitClasses(classes), + ...?_splitClasses(attributes?['class']), + }; styles = Map.of(styles ?? {}); attributes = Map.of(attributes ?? {}); events = Map.of(events ?? {}); @@ -113,7 +116,7 @@ class DomElement extends DomRenderObjectElement { List? appliedStyles; List? appliedAttributes; - if (param.id case final paramId? when id == null) { + if (param.id case final paramId? when id == null && !attributes.containsKey('id')) { id = paramId; appliedId = paramId; } @@ -138,6 +141,9 @@ class DomElement extends DomRenderObjectElement { if (param.attributes case final attributesMap?) { for (final MapEntry(:key, :value) in attributesMap.entries) { if (!attributes.containsKey(key)) { + if (key == 'id' && (id != null || appliedId != null)) continue; + if (key == 'class' && classesSet.isNotEmpty) continue; + if (key == 'style' && styles.isNotEmpty) continue; attributes[key] = value; (appliedAttributes ??= []).add(key); } diff --git a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart index 9f0d23ae8..87ce4ab95 100644 --- a/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart +++ b/packages/jaspr/lib/src/server/adapters/client_component_adapter.dart @@ -53,9 +53,7 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { if (!registry.serverElements.containsKey(element)) { var hasRenderElement = false; element.visitAncestorElements((e) { - if (registry.serverElements.containsKey(e)) { - return false; - } + final isServerElement = registry.serverElements.containsKey(e); if (e is RenderObjectElement && e.renderObject is! RenderFragment) { hasRenderElement = true; } @@ -64,6 +62,9 @@ final class ClientComponentAdapter extends ElementBoundaryAdapter { applied.add(applyComp); } } + if (isServerElement) { + return false; + } return true; }); } diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 7c383b8ec..6ce690de6 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -423,6 +423,46 @@ void main() { expect(btn.className, 'btn'); }); + testClient('re-hydrates data-j-apply on reload and cleans up when apply is disabled', (tester) async { + const html = + '
'; + window.document.body!.innerHTML = html.toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return .apply( + target: .descendantWith(tag: 'button'), + id: hasParams ? 'applied-id' : null, + classes: hasParams ? 'applied' : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + var btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'applied-id'); + expect(btn.className, 'original applied'); + + // Reload with fresh server DOM containing data-j-apply + await _reload(tester, html); + + btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'applied-id'); + expect(btn.className, 'original applied'); + + // Now toggle off the apply params + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.hasAttribute('id'), isFalse); + expect(btn.className, 'original'); + }); + testClient('preserves outer applied params when inner apply toggles off', (tester) async { window.document.body!.innerHTML = '
' .toJS; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index a4dc02485..e652caa9b 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -359,6 +359,40 @@ void main() { ); }); + testServer( + 'serializes server-child root apply wrapper onto nested client component while excluding outer applies', + ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + classes: 'outer-apply', + child: AppWithServerComponent( + child: Component.apply( + classes: 'server-only', + child: App1(), + ), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains(''), + ); + expect( + response.body, + isNot(contains('')), + ); + expect( + response.body, + isNot(contains('')), + ); + }, + ); + testServer('renders server components inside custom model parameter', (tester) async { tester.pumpComponent(AppWithCustomModel(model: ModelWithComponent(span([text('Custom Model')])))); @@ -593,6 +627,52 @@ void main() { ); }); + testServer('does not record applied id when child element owns an id in attributes map', (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + id: 'save', + child: AppWithServerComponent( + child: span(attributes: {'id': 'save'}, [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }); + + testServer('does not record applied class attribute when child element has dedicated classes', (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + attributes: const {'class': 'highlight'}, + child: AppWithServerComponent( + child: span(classes: 'label', [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }); + testServer('only includes client-managed params in data-j-apply when server component has its own apply', ( tester, ) async { From 1c26931e8abd0d7099b8fecfd813250c180de117 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 11:57:38 +0100 Subject: [PATCH 20/24] Address review comments: respect child slot boundaries during hydration and include inline styles in baseline --- .../lib/src/client/slotted_child_view.dart | 72 ++++++++++++++-- packages/jaspr/lib/src/client/utils.dart | 3 + .../jaspr/lib/src/framework/components.dart | 31 ++++++- .../test/client/slotted_child_view_test.dart | 82 +++++++++++++++++++ packages/jaspr/test/server/client_test.dart | 50 +++++++++++ 5 files changed, 228 insertions(+), 10 deletions(-) diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index 66d6b4a5f..08ae6d6b5 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -36,6 +36,9 @@ abstract class ChildSlot extends Component { /// Creates the render object that renders [child] into part of [parent]'s nodes. ChildSlotRenderObject createRenderObject(SlottedDomRenderObject parent); + /// Creates a filter function that checks whether a node is inside this slot's content. + bool Function(web.Node) createFilter(SlottedDomRenderObject parent); + /// Whether this slot renders into the same DOM nodes as [oldComponent]. /// /// A slot can't be updated with one that renders into different nodes, @@ -60,6 +63,23 @@ class _RangeChildSlot extends ChildSlot { return ChildSlotRenderObject.between(parent, start, end); } + @override + bool Function(web.Node) createFilter(SlottedDomRenderObject parent) { + final parentElement = start.parentElement; + if (parentElement == null) return (_) => false; + + return (web.Node element) { + if (!parentElement.contains(element)) return false; + if (start.contains(element) || end.contains(element)) return false; + + const following = web.Node.DOCUMENT_POSITION_FOLLOWING; + const containedBy = web.Node.DOCUMENT_POSITION_CONTAINED_BY; + final isAfterStart = (start.compareDocumentPosition(element) & (following | containedBy)) == following; + final isBeforeEnd = (end.compareDocumentPosition(element) & web.Node.DOCUMENT_POSITION_PRECEDING) != 0; + return isAfterStart && isBeforeEnd; + }; + } + @override bool canUpdate(ChildSlot oldComponent) { return oldComponent is _RangeChildSlot && oldComponent.start == start && oldComponent.end == end; @@ -75,15 +95,13 @@ class _QueryChildSlot extends ChildSlot { @override final Component child; - @override - ChildSlotRenderObject createRenderObject(SlottedDomRenderObject parent) { - web.Element? target; + web.Element? findTargetElement(SlottedDomRenderObject parent) { web.Node? current = parent.firstChildNode; while (current != null) { if (current.isElement) { - target = (current as web.Element).querySelector(query); + final target = (current as web.Element).querySelector(query); if (target != null) { - break; + return target; } } if (current == parent.lastChildNode) { @@ -91,10 +109,23 @@ class _QueryChildSlot extends ChildSlot { } current = current.nextSibling; } + return null; + } + + @override + ChildSlotRenderObject createRenderObject(SlottedDomRenderObject parent) { + final target = findTargetElement(parent); assert(target != null, 'No node found for query "$query" in ChildSlot.'); return ChildSlotRenderObject(target!, parent); } + @override + bool Function(web.Node) createFilter(SlottedDomRenderObject parent) { + final target = findTargetElement(parent); + if (target == null) return (_) => false; + return (web.Node element) => element != target && target.contains(element); + } + @override bool canUpdate(ChildSlot oldComponent) { return oldComponent is _QueryChildSlot && oldComponent.query == query; @@ -287,11 +318,12 @@ class _SlottedChildViewElement extends DomRenderObjectElement { for (final slot in component.slots) { if (slot is _RangeChildSlot) slotRanges[slot.start] = slot.end; } + final isInsideSlot = _createSlotFilter(renderObject); web.Node? current = renderObject.firstChildNode; while (current != null) { if (current.isElement) { - _hydrateInitialAppliedParams(current as web.Element); + _hydrateInitialAppliedParams(current as web.Element, isInsideSlot); } if (current == renderObject.lastChildNode) { @@ -301,7 +333,24 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } - void _hydrateInitialAppliedParams(web.Element root) { + bool Function(web.Node) _createSlotFilter(SlottedDomRenderObject renderObject) { + if (component.slots.isEmpty) { + return (_) => false; + } + + final filters = [ + for (final slot in component.slots) slot.createFilter(renderObject), + ]; + + return (web.Node element) { + for (final filter in filters) { + if (filter(element)) return true; + } + return false; + }; + } + + void _hydrateInitialAppliedParams(web.Element root, bool Function(web.Node) isInsideSlot) { void process(web.Element element) { if (element.hasAttribute('data-j-apply')) { final raw = element.getAttribute('data-j-apply')!; @@ -354,10 +403,15 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } } - process(root); + if (!isInsideSlot(root)) { + process(root); + } final descendants = root.querySelectorAll('[data-j-apply]'); for (int i = 0; i < descendants.length; i++) { - process(descendants.item(i) as web.Element); + final element = descendants.item(i) as web.Element; + if (!isInsideSlot(element)) { + process(element); + } } } diff --git a/packages/jaspr/lib/src/client/utils.dart b/packages/jaspr/lib/src/client/utils.dart index bd361b7d5..f07e2ab14 100644 --- a/packages/jaspr/lib/src/client/utils.dart +++ b/packages/jaspr/lib/src/client/utils.dart @@ -11,6 +11,9 @@ import 'package:universal_web/web.dart' as web; /// since separate Dart references to the same node aren't `identical` on Wasm. Map nodeMap() => LinkedHashMap(hashCode: _nodeHashCode); +/// Creates a set of DOM nodes with efficient lookups. +Set nodeSet() => LinkedHashSet(hashCode: _nodeHashCode); + /// A JS `WeakMap` from JS objects to numbers. /// /// Unlike an [Expando], it compares keys as JS objects. diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 6b012dc9f..9a2746c26 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -43,6 +43,25 @@ List? _splitClasses(String? classes) { return classNames.isEmpty ? null : classNames; } +/// Parses raw CSS inline style declarations into a map of property-value pairs. +/// +/// Returns `null` when [style] is `null` or contains no declarations. +Map? _parseInlineStyles(String? style) { + if (style == null || style.isEmpty) return null; + + final styles = {}; + for (final declaration in style.split(';')) { + final colon = declaration.indexOf(':'); + if (colon == -1) continue; + final property = declaration.substring(0, colon).trim().toLowerCase(); + final value = declaration.substring(colon + 1).trim(); + if (property.isNotEmpty && value.isNotEmpty) { + styles[property] = value; + } + } + return styles.isEmpty ? null : styles; +} + typedef _AppliedParam = ({ ApplyParams param, String? id, @@ -101,7 +120,11 @@ class DomElement extends DomRenderObjectElement { ...?_splitClasses(classes), ...?_splitClasses(attributes?['class']), }; - styles = Map.of(styles ?? {}); + final rawStyles = _parseInlineStyles(attributes?['style']); + styles = { + ...?rawStyles, + ...?styles, + }; attributes = Map.of(attributes ?? {}); events = Map.of(events ?? {}); @@ -168,6 +191,12 @@ class DomElement extends DomRenderObjectElement { } classes = classesSet.join(' '); + if (rawStyles != null) { + attributes.remove('style'); + } + if (styles.isEmpty) { + styles = null; + } } renderObject.update(id, classes, styles, attributes, events); diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 6ce690de6..4e313f4c8 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -621,6 +621,88 @@ void main() { expect(end.getAttribute('class'), 'end-anchor'); }); + testClient('leaves data-j-apply in nested range slot for inner view to hydrate', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + final mainElement = window.document.querySelector('main')!; + var hasInnerApply = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return Component.apply( + target: const ApplyTarget.descendantWith(tag: 'button'), + classes: 'outer-class', + child: SlottedChildView( + slots: [ + ChildSlot.between( + start: mainElement.firstChild!, + end: mainElement.lastChild!, + child: Component.apply( + target: const ApplyTarget.childWith(tag: 'button'), + id: hasInnerApply ? 'inner' : null, + child: SlottedChildView(slots: const []), + ), + ), + ], + ), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'inner'); + expect(btn.classList.contains('outer-class'), isTrue); + + setState(() => hasInnerApply = false); + await pumpEventQueue(); + + expect(btn.hasAttribute('id'), isFalse); + }); + + testClient('leaves data-j-apply in nested query slot for inner view to hydrate', (tester) async { + window.document.body!.innerHTML = '
' + .toJS; + var hasInnerApply = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return Component.apply( + target: const ApplyTarget.descendantWith(tag: 'button'), + classes: 'outer-class', + child: SlottedChildView( + slots: [ + ChildSlot.fromQuery( + '.slot-target', + child: Component.apply( + target: const ApplyTarget.childWith(tag: 'button'), + id: hasInnerApply ? 'inner' : null, + child: SlottedChildView(slots: const []), + ), + ), + ], + ), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.id, 'inner'); + expect(btn.classList.contains('outer-class'), isTrue); + + setState(() => hasInnerApply = false); + await pumpEventQueue(); + + expect(btn.hasAttribute('id'), isFalse); + }); + testClient('applies direct child params to root range slot', (tester) async { window.document.body!.innerHTML = ''.toJS; final start = window.document.body!.firstChild!; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index e652caa9b..25168fdab 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -673,6 +673,56 @@ void main() { ); }); + testServer('does not record applied style property when child element owns style in attributes map', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + styles: Styles(color: Colors.red), + child: AppWithServerComponent( + child: span(attributes: {'style': 'color: red'}, [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }); + + testServer('records only new applied style property when child element owns inline styles in attributes map', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + styles: Styles(color: Colors.red, margin: Margin.all(8.px)), + child: AppWithServerComponent( + child: span(attributes: {'style': 'color: red'}, [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('data-j-apply="s:margin"'), + ); + expect( + response.body, + isNot(contains('s:color')), + ); + }); + testServer('only includes client-managed params in data-j-apply when server component has its own apply', ( tester, ) async { From 73211a52fccbf73d9968aa6e6875da6df4c6fe7a Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 12:49:15 +0100 Subject: [PATCH 21/24] Do not apply wrapper styles to elements with raw style attributes --- .../jaspr/lib/src/framework/components.dart | 34 ++------ packages/jaspr/test/server/client_test.dart | 79 ++++++++++++++++++- 2 files changed, 82 insertions(+), 31 deletions(-) diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 9a2746c26..1e9c41067 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -43,25 +43,6 @@ List? _splitClasses(String? classes) { return classNames.isEmpty ? null : classNames; } -/// Parses raw CSS inline style declarations into a map of property-value pairs. -/// -/// Returns `null` when [style] is `null` or contains no declarations. -Map? _parseInlineStyles(String? style) { - if (style == null || style.isEmpty) return null; - - final styles = {}; - for (final declaration in style.split(';')) { - final colon = declaration.indexOf(':'); - if (colon == -1) continue; - final property = declaration.substring(0, colon).trim().toLowerCase(); - final value = declaration.substring(colon + 1).trim(); - if (property.isNotEmpty && value.isNotEmpty) { - styles[property] = value; - } - } - return styles.isEmpty ? null : styles; -} - typedef _AppliedParam = ({ ApplyParams param, String? id, @@ -120,11 +101,7 @@ class DomElement extends DomRenderObjectElement { ...?_splitClasses(classes), ...?_splitClasses(attributes?['class']), }; - final rawStyles = _parseInlineStyles(attributes?['style']); - styles = { - ...?rawStyles, - ...?styles, - }; + styles = Map.of(styles ?? {}); attributes = Map.of(attributes ?? {}); events = Map.of(events ?? {}); @@ -152,7 +129,11 @@ class DomElement extends DomRenderObjectElement { } } - if (param.styles case final stylesProps?) { + // Elements with raw inline styles in `attributes['style']` are not augmented + // with styles from apply wrappers. Mixing structured styles with raw inline + // declarations is not supported and would require complex CSS declaration parsing + // and risk corrupting raw declarations. + if (param.styles case final stylesProps? when !attributes.containsKey('style')) { for (final MapEntry(:key, :value) in stylesProps.entries) { if (!styles.containsKey(key)) { styles[key] = value; @@ -191,9 +172,6 @@ class DomElement extends DomRenderObjectElement { } classes = classesSet.join(' '); - if (rawStyles != null) { - attributes.remove('style'); - } if (styles.isEmpty) { styles = null; } diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index 25168fdab..dc0d31058 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -698,7 +698,7 @@ void main() { ); }); - testServer('records only new applied style property when child element owns inline styles in attributes map', ( + testServer('does not apply wrapper styles when child element owns inline styles in attributes map', ( tester, ) async { tester.pumpComponent( @@ -715,11 +715,84 @@ void main() { expect( response.body, - contains('data-j-apply="s:margin"'), + isNot(contains('data-j-apply')), ); expect( response.body, - isNot(contains('s:color')), + contains('style="color: red"'), + ); + }); + + testServer('preserves child inline styles with semicolons inside quotes and data URLs when applying classes', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'applied-class', + child: AppWithServerComponent( + child: span( + attributes: { + 'style': + 'font-family: "A;B"; background-image: url("data:image/svg+xml;utf8,;"); color: red', + }, + [text('Hello')], + ), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('class="applied-class"'), + ); + expect( + response.body, + contains('data-j-apply="c:applied-class"'), + ); + expect( + response.body, + contains('font-family: "A;B"'), + ); + expect( + response.body, + contains('background-image: url("data:image/svg+xml;utf8,<svg>;<circle/>")'), + ); + expect( + response.body, + contains('color: red'), + ); + }); + + testServer('preserves casing of CSS custom properties in child inline styles and ignores wrapper styles', ( + tester, + ) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + styles: Styles(raw: {'--brandColor': 'blue', '--otherColor': 'green'}), + child: AppWithServerComponent( + child: span( + attributes: { + 'style': '--brandColor: red; color: var(--brandColor)', + }, + [text('Hello')], + ), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), ); }); From 9a91b8d2f3b107017a200f2b3c11d309501e0676 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 16:44:12 +0100 Subject: [PATCH 22/24] Address review comments: simplify style merging, align raw class handling, and clean up ChildSlot filter --- docs/concepts/components.mdx | 10 +++ .../lib/src/client/slotted_child_view.dart | 18 ++--- .../jaspr/lib/src/framework/components.dart | 11 +-- .../jaspr/lib/src/framework/framework.dart | 17 ++++ .../test/client/slotted_child_view_test.dart | 53 ++++++++++++ packages/jaspr/test/server/client_test.dart | 81 +++++++++++++++++++ 6 files changed, 176 insertions(+), 14 deletions(-) diff --git a/docs/concepts/components.mdx b/docs/concepts/components.mdx index 86c408ace..691c6bd1e 100644 --- a/docs/concepts/components.mdx +++ b/docs/concepts/components.mdx @@ -260,6 +260,16 @@ The above component renders the following HTML:
``` +#### Precedence and Merging Rules + +When properties are applied, the following rules and special cases apply: + +- **Target Precedence**: Properties defined on the target element always take precedence over applied properties. Where multiple nested `Component.apply()` components target the same element, inner (closer) wrappers take precedence over outer ones. +- **Classes**: Applied class names are merged as a set of whitespace-separated tokens with the target's classes. If a target element specifies class names via `attributes: {'class': ...}`, classes from `Component.apply()` are **never applied** to that element to preserve raw attributes and prevent duplicate HTML attributes. +- **Styles**: Applied styles are merged on a per-property basis. Any style property already defined on the target element is preserved. If a target element specifies raw inline styles via `attributes: {'style': ...}`, styles from `Component.apply()` are **never applied** to that element to avoid corrupting raw style declarations or unsafe mixing of structured and raw styles. +- **ID & Attributes**: An `id` or other attributes defined on the target element (or in its `attributes` map) are never overwritten by applied values. +- **Events**: Event listeners on the target element take precedence; applied listeners are added as supplementary listeners if not already bound. + ## Formatting Whitespace When pre-rendering your components in **server** and **static** mode, Jaspr will output cleanly formatted html on a best-effort basis. This means it will add newlines and indentations to your html element, while trying to not affect the way the html is rendered. diff --git a/packages/jaspr/lib/src/client/slotted_child_view.dart b/packages/jaspr/lib/src/client/slotted_child_view.dart index 08ae6d6b5..fba0a2f68 100644 --- a/packages/jaspr/lib/src/client/slotted_child_view.dart +++ b/packages/jaspr/lib/src/client/slotted_child_view.dart @@ -36,9 +36,6 @@ abstract class ChildSlot extends Component { /// Creates the render object that renders [child] into part of [parent]'s nodes. ChildSlotRenderObject createRenderObject(SlottedDomRenderObject parent); - /// Creates a filter function that checks whether a node is inside this slot's content. - bool Function(web.Node) createFilter(SlottedDomRenderObject parent); - /// Whether this slot renders into the same DOM nodes as [oldComponent]. /// /// A slot can't be updated with one that renders into different nodes, @@ -63,8 +60,7 @@ class _RangeChildSlot extends ChildSlot { return ChildSlotRenderObject.between(parent, start, end); } - @override - bool Function(web.Node) createFilter(SlottedDomRenderObject parent) { + bool Function(web.Node) _createFilter() { final parentElement = start.parentElement; if (parentElement == null) return (_) => false; @@ -119,8 +115,7 @@ class _QueryChildSlot extends ChildSlot { return ChildSlotRenderObject(target!, parent); } - @override - bool Function(web.Node) createFilter(SlottedDomRenderObject parent) { + bool Function(web.Node) _createFilter(SlottedDomRenderObject parent) { final target = findTargetElement(parent); if (target == null) return (_) => false; return (web.Node element) => element != target && target.contains(element); @@ -279,7 +274,6 @@ class _SlottedChildViewElement extends DomRenderObjectElement { final inheritedDomParams = inheritedDomParamsFor(renderObject); if ((component.nodes != null || (inheritedDomParams != null && inheritedDomParams.isNotEmpty)) && !_didHydrate) { _didHydrate = true; - _appliedParams.clear(); _hydrateInitialNodes(renderObject); } @@ -339,7 +333,12 @@ class _SlottedChildViewElement extends DomRenderObjectElement { } final filters = [ - for (final slot in component.slots) slot.createFilter(renderObject), + for (final slot in component.slots) + switch (slot) { + _RangeChildSlot s => s._createFilter(), + _QueryChildSlot s => s._createFilter(renderObject), + _ => (_) => false, + }, ]; return (web.Node element) { @@ -571,6 +570,7 @@ class _SlottedChildViewElement extends DomRenderObjectElement { @override void onReload() { + _resetAppliedParams(); _didHydrate = false; super.onReload(); } diff --git a/packages/jaspr/lib/src/framework/components.dart b/packages/jaspr/lib/src/framework/components.dart index 1e9c41067..e9c8759d7 100644 --- a/packages/jaspr/lib/src/framework/components.dart +++ b/packages/jaspr/lib/src/framework/components.dart @@ -121,7 +121,7 @@ class DomElement extends DomRenderObjectElement { appliedId = paramId; } - if (param.classes case final paramClasses?) { + if (param.classes case final paramClasses? when !attributes.containsKey('class')) { for (final c in paramClasses) { if (classesSet.add(c)) { (appliedClasses ??= []).add(c); @@ -131,8 +131,7 @@ class DomElement extends DomRenderObjectElement { // Elements with raw inline styles in `attributes['style']` are not augmented // with styles from apply wrappers. Mixing structured styles with raw inline - // declarations is not supported and would require complex CSS declaration parsing - // and risk corrupting raw declarations. + // declarations is not supported. if (param.styles case final stylesProps? when !attributes.containsKey('style')) { for (final MapEntry(:key, :value) in stylesProps.entries) { if (!styles.containsKey(key)) { @@ -146,7 +145,7 @@ class DomElement extends DomRenderObjectElement { for (final MapEntry(:key, :value) in attributesMap.entries) { if (!attributes.containsKey(key)) { if (key == 'id' && (id != null || appliedId != null)) continue; - if (key == 'class' && classesSet.isNotEmpty) continue; + if (key == 'class' && (classesSet.isNotEmpty || classes != null)) continue; if (key == 'style' && styles.isNotEmpty) continue; attributes[key] = value; (appliedAttributes ??= []).add(key); @@ -171,7 +170,9 @@ class DomElement extends DomRenderObjectElement { } } - classes = classesSet.join(' '); + classes = attributes.containsKey('class') + ? component.classes + : (classesSet.isEmpty ? null : classesSet.join(' ')); if (styles.isEmpty) { styles = null; } diff --git a/packages/jaspr/lib/src/framework/framework.dart b/packages/jaspr/lib/src/framework/framework.dart index 87a99a4b6..e73738342 100644 --- a/packages/jaspr/lib/src/framework/framework.dart +++ b/packages/jaspr/lib/src/framework/framework.dart @@ -126,6 +126,23 @@ abstract class Component { /// On the client, this also applies to the server-rendered elements of a server component, /// such as a component passed to a @client component. /// + /// ### Precedence and Merging Rules + /// + /// - **Precedence**: Target-owned properties always take precedence over applied properties. + /// Inner [Component.apply] wrappers also take precedence over outer ones. + /// - **Classes**: Applied [classes] are merged as a set of whitespace-separated tokens with + /// the target's classes. If the target element specifies raw class names via `attributes: {'class': ...}`, + /// classes from [Component.apply] are **never applied** to that element to preserve raw attributes + /// and prevent duplicate HTML attributes. + /// - **Styles**: Applied [styles] are merged on a per-property basis. Any style property already + /// defined on the target element is preserved. If a target element specifies raw inline styles via + /// `attributes: {'style': ...}`, styles from [Component.apply] are **never applied** to that element + /// to avoid corrupting raw style declarations or unsafe mixing of structured and raw styles. + /// - **ID & Attributes**: An `id` or other attributes defined on the target element (or in its attributes map) + /// are never overwritten by applied values. + /// - **Events**: Event listeners on the target element take precedence; applied listeners are added as + /// supplementary listeners if not already bound. + /// /// Example: /// ```dart /// return Component.apply( diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index 4e313f4c8..a6479973a 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -423,6 +423,59 @@ void main() { expect(btn.className, 'btn'); }); + // To be revisited: slotted child hydration with raw inline styles. + testClient( + 'does not apply wrapper styles during hydration when element has raw inline styles in html', + (tester) async { + window.document.body!.innerHTML = '
'.toJS; + + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'button'), + styles: const Styles(backgroundColor: Colors.yellow, color: Colors.red), + child: SlottedChildView(slots: const []), + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.style.color, 'blue'); + expect(btn.style.backgroundColor, ''); + }, + skip: true, + ); + + // To be revisited: CSS shorthand and longhand property overlap. + testClient( + 'preserves child shorthand styles when wrapper applies overlapping longhand style', + (tester) async { + window.document.body!.innerHTML = '
'.toJS; + var hasParams = true; + late void Function(void Function() cb) setState; + + tester.pumpComponent( + StatefulBuilder( + builder: (context, set) { + setState = set; + return Component.apply( + target: const ApplyTarget.descendantWith(tag: 'button'), + styles: hasParams ? Styles(margin: Margin.only(left: 8.px)) : null, + child: SlottedChildView(slots: const []), + ); + }, + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.style.marginLeft, '4px'); + + setState(() => hasParams = false); + await pumpEventQueue(); + + expect(btn.style.marginLeft, '4px'); + }, + skip: true, + ); + testClient('re-hydrates data-j-apply on reload and cleans up when apply is disabled', (tester) async { const html = '
'; diff --git a/packages/jaspr/test/server/client_test.dart b/packages/jaspr/test/server/client_test.dart index dc0d31058..13b578e21 100644 --- a/packages/jaspr/test/server/client_test.dart +++ b/packages/jaspr/test/server/client_test.dart @@ -723,6 +723,87 @@ void main() { ); }); + testServer('does not emit duplicate class attributes when child has class in attributes map', (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + classes: 'highlight', + child: AppWithServerComponent( + child: span(attributes: {'class': 'label'}, [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + final spanMatch = RegExp(r']*>').firstMatch(response.body)!.group(0)!; + expect('class='.allMatches(spanMatch).length, equals(1)); + }); + + // To be revisited: CSS shorthand and longhand property overlap. + testServer( + 'does not apply wrapper longhand style when child defines shorthand style', + (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + styles: Styles(margin: Margin.only(left: 8.px)), + child: AppWithServerComponent( + child: span(styles: Styles(margin: Margin.all(4.px)), [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }, + skip: true, + ); + + // To be revisited: CSS shorthand and longhand property overlap. + testServer( + 'does not apply wrapper shorthand style when child defines longhand style', + (tester) async { + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'span'), + styles: Styles(margin: Margin.all(8.px)), + child: AppWithServerComponent( + child: span(styles: Styles(margin: Margin.only(left: 4.px)), [text('Hello')]), + ), + ), + ); + + final response = await tester.request('/'); + + expect( + response.body, + contains('Hello'), + ); + expect( + response.body, + isNot(contains('data-j-apply')), + ); + }, + skip: true, + ); + testServer('preserves child inline styles with semicolons inside quotes and data URLs when applying classes', ( tester, ) async { From 5ee41f0b48dffecc7e37b4e8314445c35c43f60b Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 18:15:56 +0100 Subject: [PATCH 23/24] Add skipped hydration test for raw class attributes --- .../test/client/slotted_child_view_test.dart | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/jaspr/test/client/slotted_child_view_test.dart b/packages/jaspr/test/client/slotted_child_view_test.dart index a6479973a..d273a8e97 100644 --- a/packages/jaspr/test/client/slotted_child_view_test.dart +++ b/packages/jaspr/test/client/slotted_child_view_test.dart @@ -444,6 +444,26 @@ void main() { skip: true, ); + // To be revisited: slotted child hydration with raw class attribute. + testClient( + 'does not apply wrapper classes during hydration when element has raw class in attributes', + (tester) async { + window.document.body!.innerHTML = '
'.toJS; + + tester.pumpComponent( + Component.apply( + target: const ApplyTarget.descendantWith(tag: 'button'), + classes: 'highlight', + child: SlottedChildView(slots: const []), + ), + ); + + final btn = window.document.querySelector('button')! as HTMLElement; + expect(btn.className, 'label'); + }, + skip: true, + ); + // To be revisited: CSS shorthand and longhand property overlap. testClient( 'preserves child shorthand styles when wrapper applies overlapping longhand style', From d5f957530776665f615ca4bc2b50dbf89ee1ec96 Mon Sep 17 00:00:00 2001 From: Kilian Schulte Date: Wed, 18 Nov 2026 18:18:29 +0100 Subject: [PATCH 24/24] Update CHANGELOG with Component.apply behavior changes --- packages/jaspr/CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/jaspr/CHANGELOG.md b/packages/jaspr/CHANGELOG.md index 3c3128577..2559f890e 100644 --- a/packages/jaspr/CHANGELOG.md +++ b/packages/jaspr/CHANGELOG.md @@ -4,7 +4,12 @@ ### Fixes -- Fixed applied classes and properties from `Component.apply` not being removed from server components on the client when toggled off. +- Fixed `Component.apply` not applying to server-rendered components inside `@client` components on the client, and fixed applied properties not being removed from slotted child elements when toggled off. + - Applied properties and classes are now tracked and cleanly removed on toggle-off without clearing the child element's own properties. + - Target-defined properties always take precedence over applied properties, with structured styles merging on a per-property basis. + - Raw `class` and `style` attributes defined in an element's `attributes` map are preserved verbatim without wrapper styles or classes applied, preventing duplicate HTML attributes. + - Child elements with an `id` or attributes in their `attributes` map are never overwritten by applied values. + - Slotted child views reset applied parameters and event listeners on reload before re-hydration. - Fixed a server built with `dart build cli` on Linux with Dart 3.14 or later not finding its `web` directory and failing with "Could not resolve project directory containing pubspec.yaml" when no `pubspec.yaml` is above it. Since Dart 3.14 such a bundle keeps the snapshot in `lib/libdartaot.so`, which `Platform.script` points at. - Fixed `jaspr serve` with Flutter embedding or plugins failing on Flutter 3.50, which moved the precompiled DDC SDK to `kernel/ddc/canary` and `kernel/ddc/stable`. - Fixed `jaspr build` and `jaspr serve` stopping a build daemon that another Jaspr process in the same directory started, which left that process serving empty 503 responses.