Skip to content

feat(core): inlineStyle, attributeStyleMap, computedStyleMap and getComputedStyle - #11674

Draft
edusperoni wants to merge 7 commits into
mainfrom
feat/web-style-api
Draft

edusperoni wants to merge 7 commits into
mainfrom
feat/web-style-api

Conversation

@edusperoni

Copy link
Copy Markdown
Contributor

PR Checklist

Stacked on #11673 (← #11672). Draft: the API shape is up for discussion.

Related: #11414

What is the current behavior?

The web splits a style in two: el.style holds the inline declarations as written, and getComputedStyle(el) gives the values that won the cascade. NativeScript has only view.style, which returns computed values (the cascade winner, converted to Color, lengths, numbers). There is no way to ask what was set locally, to read back a var()/calc() value as written, or to get the computed value as a css string.

What is the new behavior?

This adds the web-aligned APIs next to view.style, on top of the existing storage. Nothing existing changes: view.style reads and writes, view.style = '…' and the XML style attribute behave as before. view.style is meant to become inlineStyle in a future major.

"Local" stays one slot per property: everything written from code, view.X, XML attributes or inline strings.

Layers

strings typed
inline (local) view.inlineStyle view.attributeStyleMap
computed getComputedStyle(view) view.computedStyleMap() (= what view.style.X returns)

Map keys and getPropertyValue()/setProperty() names are css names (margin-top, --accent). Camel-case members (inlineStyle.marginTop) are derived from the css name.

view.inlineStyle (InlineStyleDeclaration)

  • One object per view, created lazily, read-only property. Assigning a string sets its cssText; assigning anything else throws.
  • Reads return the specified local value, or '' when the property has no local value:
    • var()/calc() values read the expression kept by fix(core): keep var() and calc() in local style values current #11673 ('calc(2 + var(--t))'), never the substitution. This includes an expression whose variable is undefined.
    • A var() shorthand reads its expression on the shorthand (inlineStyle.margin === 'var(--m)'). Its longhands read '', and the shorthand reads '' once a longhand is overwritten.
    • Plain values serialize the typed local value (view.color = 'red' reads 'rgb(255, 0, 0)').
    • A shorthand whose longhands are all local reads them composed ('4 6', box notation for four longhands). The result is checked by expanding it again; a shorthand that cannot be composed reads ''.
  • getPropertyValue, setProperty, removeProperty (returns the old value), getPropertyPriority (always ''), length, item(i), iteration. Custom properties (--x) work through the same methods.
  • Writes go through the existing local setters, so fix(core): keep var() and calc() in local style values current #11673's substitution and tracking apply. They fire change events and reach the native view like any view.style write.
  • cssText lists every local declaration (custom properties, then var() shorthands, then longhands).

cssText vs view.style = '…'

Assigning inlineStyle.cssText has full web semantics: it clears the whole local slot (values from code, view.X, XML attributes or a previous inline string), then applies the new declarations. A property the new text declares again is overwritten without passing through its default, so it fires no extra change.

view.style = '…' and the XML style attribute keep #11672's narrower behavior: they replace only what the previous inline string set. Changing that would make the outcome depend on the order XML attributes are applied in.

view.color = 'red';
view.style = 'opacity: 0.5'; // color stays red
view.inlineStyle.cssText = 'opacity: 0.5'; // color is cleared

view.attributeStyleMap (InlineStylePropertyMap)

The typed local values: get(name) returns the typed value or undefined, plus set(name, string | typed), has, delete, clear, size and iteration. A written object comes back as the same instance. An equal write to a non-inherited property may keep the previous instance. clear() is inlineStyle.cssText = ''. Assigning the property throws.

view.computedStyleMap() (ComputedStylePropertyMap)

The typed computed values, exactly what view.style.X returns today: get, has, size, iteration over every longhand. Live, read-only, one object per view.

getComputedStyle(view) (ComputedStyleDeclaration)

A named export from @nativescript/core (not on globalThis). It returns a live, read-only declaration, cached per view in a WeakMap. It supports camel-case reads, getPropertyValue(), length, item() and iteration, and returns canonical strings serialized from the typed computed value (colors as rgb()/rgba(), percentages as %). Writes throw, as the web's computed declaration does (setProperty, removeProperty, cssText, camel-case assignment). cssText reads '' like the web's.

Serializers

  • CssProperty, InheritedCssProperty and CssAnimationProperty take a valueSerializer?: (value: U) => string option (also through overrideHandlers). The default is the new serializeCssValue: strings as is, numbers, booleans, Color → rgb()/rgba() (alpha rounded so it parses back to the same byte), lengths (dip unitless, px, %), LinearGradient, shadows, strokes, font-variation-settings, lists.
  • box-shadow has its own serializer, because its parsed form keeps the layers in reverse order. clip-path serializes null as none.
  • ShorthandProperty takes valueSerializer?: (longhands: string[]) => string to compose its serialized longhands. transform has one: translate(…) scale(…) rotate3d(…), or none.
  • css-value-serializer.spec.ts iterates every registered longhand with representative values. It fails when a property has no sample. For each sample it checks that the serialization, written back to a view, gives an equal value: the property's own comparer suppresses the change event, with Color-aware deep equality for comparer-less data such as shadows.

Internals

  • properties/index.ts keeps a registry of style properties by css name, with a listener the declarations use to define the camel-case accessors as properties register (including plugin properties registered later).
  • _isLocalValueSet/_getLocalValue on CssProperty (sourceKey === Local) and CssAnimationProperty (its local slot, so a keyframe does not hide a local value). A kept expression whose substitution left no value still counts as declared.
  • _-prefixed internals (_fontInternal, _backgroundInternal, _paddingInternal, _fontScaleInternal) are excluded everywhere. A cssText assignment or clear() never touches them.
  • applyInlineStyle takes an optional list of extra longhands to replace, which is how cssText clears the whole slot in the same pass.

Tests

  • ui/styling/css-value-serializer.spec.ts: round-trip over every registered longhand (330+ cases), color alpha bytes 0–255, percentage float noise.
  • ui/styling/style-declaration.spec.ts: reads ('' for css-only values, raw var()/calc() expressions, pending shorthand longhands, shorthand composition for every registered shorthand), writes reaching change events and a native setter, cssText full replace vs view.style = '…', custom properties, keyframe masking, internals surviving clear(), attributeStyleMap with a Color instance, computedStyleMap() cascade winners, getComputedStyle liveness and canonical strings, read-only properties throwing.
  • npx vitest run --root packages/core: 64 files, 1139 passed, 1 skipped. npx tsc -p packages/core/tsconfig.lib.json --noEmit is clean.
  • Not run on a device yet. view-base now imports a module that registers a listener at load time, so this needs an iOS/Android smoke test.

Open questions

  1. Camel-case names come from css names. 16 differ from the view.style names: textAlign (textAlignment), horizontalAlign, verticalAlign, rotatex/rotatey, every a11y* (a11yEnabled for accessible, ...). inlineStyle.textAlignment = … does nothing. That is web parity, but it matters if view.style becomes inlineStyle: should the NativeScript names be aliases?
  2. Canonical vs as-written computed strings. getComputedStyle serializes the typed value, so 'red' reads 'rgb(255, 0, 0)'. Some forms also differ from the web: dip lengths are unitless, gradient angles are in rad, font-weight: bold stays bold.
  3. Specified string for plain local values. inlineStyle serializes the typed local value, so view.color = 'red' reads 'rgb(255, 0, 0)' where the web returns 'red'. Keeping the specified string for every local string write would need a map per view. Measured in V8: about 230 bytes per view for one entry and about 330 for three, before the retained strings. Every local write would also pay a map write or delete, and most views carry XML attribute values. So this PR serializes. Only var()/calc() values keep their specified form, from fix(core): keep var() and calc() in local style values current #11673.
  4. getComputedStyle on globalThis? It is only a named export now. A global would help web-oriented libraries, but dom typings already declare a different global getComputedStyle.
  5. Round-trip allow-list. One sample: background-image: linear-gradient(to bottom, red 0%, blue 100%). LinearGradient.equals compares color-stop offsets by reference, so parsed gradients with offsets never compare equal. The serialization itself is right. Fixing LinearGradient.equals would also stop such gradients from re-applying on every cascade pass, but that belongs in a separate PR.
  6. Invalid writes throw, as view.style writes do (the web ignores them). A throwing CssProperty write has already set its source to Local before converting, so inlineStyle then shows the previous value as a local declaration. That is pre-existing behavior of the setter.
  7. Unknown names: inlineStyle.setProperty ignores them (web), attributeStyleMap.set throws a TypeError (web).
  8. Map vs declaration contents. The maps count typed local values only, while inlineStyle.length also counts var() declarations whose substitution left no value. attributeStyleMap.get() on a var() longhand returns the substituted typed value.
  9. Custom properties are supported in inlineStyle and attributeStyleMap, but view.style = '…' still replaces all inline variables (as it did).
  10. Shorthand reads. background always reads '': its longhands never all take part in one write. A background write stores the bare image path, so background-image then reads ~/a.png, not url(~/a.png).
  11. Framework writes count as local. In the one-slot model, values the framework writes locally show up in cssText, and a cssText assignment or clear() resets them. Examples: the final values of view.animate() (local opacity, translate*, scale*, rotate*, background-color), and sugar setters like Label.textWrap → white-space or the statusBarStyle setter. Is that the intended contract for a future view.style = inlineStyle?
  12. New public surface beyond the brief: ShorthandPropertyOptions.valueSerializer, serializeCssValue, serializeColor, CssStyleDeclarationProperties (augment it to type plugin properties).

…tyle

Assigning an inline style string merged into the previous inline
declarations. Like the web's cssText, a new string now replaces them:
properties the previous string set and the new one omits are unset and
fall back to the stylesheet value (or the default/inherited value).
Table-driven over margin, padding, gap, transform, background,
border-color, border-width, border-radius, font, flex-flow, flex and
android-content-inset: dropping the shorthand unsets every longhand,
falls back to the stylesheet longhands, and changing its value moves each
longhand at most once. Also covers shorthand/longhand order within one
string, narrowing a shorthand to one of its longhands, a shorthand that
expands to fewer longhands, and unexpanded shorthand values.
A local string value holding var() or calc() is now substituted before it
is converted, so style.marginTop = 'calc(2 + var(--t))', view.marginTop =
'var(--t)' and style.margin = 'var(--m)' no longer throw. The specified
expression is kept on the style together with the css variables its
substitution read. On every cascade pass the kept expressions whose
variables changed are substituted again, and a value is written only when
its substitution changed.

Any other local write to the property, including a reset or a shorthand
write that omits the longhand, releases the kept expression, so a later
code write wins over later cascade passes.
Add a valueSerializer option to CssProperty, InheritedCssProperty and
CssAnimationProperty, with serializeCssValue as the default: colors as
rgb()/rgba(), lengths, percentages, gradients, shadows, strokes and lists.
box-shadow and clip-path get their own serializers.

Keep a registry of style properties by css name, and local-value
accessors that also see the local slot of animated properties.
…omputedStyle

view.inlineStyle reads and writes the local values as css strings: the
specified expression for var()/calc() values, the serialized typed value
otherwise, and '' when there is none. Assigning its cssText replaces every
local value of the view.

view.attributeStyleMap and view.computedStyleMap() expose the typed local
and computed values by css name. getComputedStyle(view) returns a live,
read-only declaration of canonical computed strings.

ShorthandProperty takes a valueSerializer to compose its longhands;
transform has one.
@nx-cloud

nx-cloud Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit fe6bb82

Command Status Duration Result
nx test apps-automated -c=android ✅ Succeeded 2m 49s View ↗
nx run-many --target=test --configuration=ci --... ✅ Succeeded <1s View ↗

💡 With Ultracache enabled, Nx Cloud learns each task's file inputs in CI and uses them on later runs. Turn on Ultracache in workspace settings ↗ · Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-11-28 02:10:23 UTC

@pkg-pr-new

pkg-pr-new Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@nativescript/core@11674
npm i https://pkg.pr.new/@nativescript/vite@11674
npm i https://pkg.pr.new/@nativescript/webpack@11674

commit: fe6bb82

@NathanWalker NathanWalker left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Really nice work. The layering (inline / computed × string / typed) is the right model, and keeping view.style unchanged while adding the web shapes next to it is the right way to stage this. I pulled it locally: the vitest suite (1139 passed) and tsc are clean. Below is one bug I hit, then my take on the open questions.

Bug: cssText doesn't round-trip transforms

cssText writes longhands under their css names. scaleX, scaleY, translateX and translateY have camel-case css names, and those never parse from a css string. That is already true for stylesheets and for view.style = '…': .x { translateX: 10 } and view.style = 'translateX: 10' both do nothing today. Because this PR emits those names, cssText = cssText loses them:

view.inlineStyle.cssText = 'transform: translate(10, 20) rotate(45deg)';
view.inlineStyle.cssText;
// 'rotate: 45; rotatex: 0; rotatey: 0; scaleX: 1; scaleY: 1; translateX: 10; translateY: 20;'
view.inlineStyle.cssText = view.inlineStyle.cssText;
view.inlineStyle.cssText;
// 'rotate: 45; rotatex: 0; rotatey: 0;'  ← translate is gone

The simplest fix is for cssText to emit a composed shorthand whenever all of its longhands are local, as the web does. You already have composeShorthand and the transform serializer, so this produces transform: translate(10, 20) rotate3d(0, 0, 45) here, and margin: 4 6 instead of four longhands. Fall back to longhands when composition returns ''. Could you also add a transform case to the existing "round-trips through its own serialization" test? (Making the camel-case names parse is a separate, pre-existing issue.)

Open questions

1. Camel-case names. I'd add the NativeScript names as aliases (textAlignment, horizontalAlignment, rotateX, accessible, …): non-enumerable accessors that are left out of iteration and cssText. Right now inlineStyle.textAlignment = 'center' quietly creates an own property on the declaration and does nothing. Once view.style becomes inlineStyle, every existing view.style.textAlignment = … breaks with no error. Also worth considering: Object.preventExtensions(this) in the constructors. Prototype accessors, including ones added later by plugins, keep working, and a typo'd or unknown member then throws a TypeError in module (strict) code instead of being swallowed.

2. Canonical computed strings. Fine in principle. The gradient angle is the one that reads badly: linear-gradient(1.5707963267948966rad, …). Could it serialize as rounded deg, e.g. 90deg?

3. Serialize plain local values instead of keeping the specified string. Agree. The per-view map costs too much for what it buys.

4. getComputedStyle on globalThis. Keep it as a named export only. A global that conflicts with the dom typings will cause more confusion than it saves.

5. LinearGradient.equals. Agree it belongs in a separate PR.

6. Invalid writes throw. For inlineStyle.setProperty, I'd follow the web: ignore the write (and maybe Trace it). Libraries often call setProperty speculatively, and a throw there is a crash, not a warning. That depends on the pre-existing "source is set to Local before converting" problem being fixed first, otherwise a swallowed error leaves the declaration in a bad state. That fix seems worth its own small PR.

7, 9, 10. All fine as described.

8. Map contents. One more inconsistency: attributeStyleMap.get('margin') returns the string '4 6', while get('margin-top') returns the typed 4. Either document that shorthands come back as strings, or return undefined for shorthands, as the typed-values framing suggests.

11. Framework writes count as local. I think this is the real decision to settle before this leaves draft. Concrete case: label.textWrap = true; label.inlineStyle.cssText = 'opacity: 0.5' resets white-space, so textWrap reads back false. XML attributes (<Label color="red">) also get wiped by cssText, while on the web presentational attributes never live in el.style. I can live with the one-slot model if it's the documented contract, but then the cssText setter docs (and the future view.style migration notes) should say plainly that it resets XML attributes, sugar setters and animate() end values.

12. New public surface. I'd keep serializeCssValue/serializeColor internal (_-prefixed or not re-exported from ui/index) until someone needs them. Once exported, the canonical output format is hard to change, and question 2 suggests it may still change. ShorthandPropertyOptions.valueSerializer and CssStyleDeclarationProperties make sense to expose for plugin authors.

Design question: Typed OM names

attributeStyleMap and computedStyleMap() take the CSS Typed OM names, but they return NativeScript values (Color, { value, unit }, numbers) rather than CSSStyleValues. A web library that feature-detects el.attributeStyleMap will find it and then get objects it doesn't understand. getComputedStyle and inlineStyle are drop-in for string-based code, but these two aren't. Should the typed maps get NativeScript names, or stay out of this PR? computedStyleMap() is effectively view.style today. Happy either way, but I'd like that to be a deliberate choice.

Smaller things

  • computedLonghands() rebuilds the list from the registry on every length/item()/iteration call, so for (i < cs.length) cs.item(i) is quadratic over ~90 longhands. Cache the array and invalidate it in the _onStylePropertyRegistered listener you already have. The same applies to inlineStyle.length + item(i) loops.
  • CssStyleDeclarationProperties is a hand-kept list of about 115 names that will drift from the registrations. The serializer spec already walks every registered property, so it could assert each camel name is a key of a const x: Record<keyof CssStyleDeclarationProperties, true>. That checks both directions: the type at compile time, the registrations at runtime.
  • Device check: test-ios/test-android are green on this branch, which at least shows view-base loading the new module (and its listener) on both runtimes is fine.

@NathanWalker
NathanWalker force-pushed the fix/local-style-css-expressions branch from dfc41a6 to 110dfdf Compare November 27, 2026 22:30
Base automatically changed from fix/local-style-css-expressions to main November 27, 2026 22:33

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants