Repository navigation
feat(core): inlineStyle, attributeStyleMap, computedStyleMap and getComputedStyle - #11674
edusperoni wants to merge 7 commits into
Conversation
…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.
|
View your CI Pipeline Execution ↗ for commit fe6bb82
💡 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 |
commit: |
NathanWalker
left a comment
There was a problem hiding this comment.
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 goneThe 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 everylength/item()/iteration call, sofor (i < cs.length) cs.item(i)is quadratic over ~90 longhands. Cache the array and invalidate it in the_onStylePropertyRegisteredlistener you already have. The same applies toinlineStyle.length+item(i)loops.CssStyleDeclarationPropertiesis 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 aconst x: Record<keyof CssStyleDeclarationProperties, true>. That checks both directions: the type at compile time, the registrations at runtime.- Device check:
test-ios/test-androidare green on this branch, which at least showsview-baseloading the new module (and its listener) on both runtimes is fine.
dfc41a6 to
110dfdf
Compare
PR Checklist
I have read the CLA and I hereby sign the CLA).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.styleholds the inline declarations as written, andgetComputedStyle(el)gives the values that won the cascade. NativeScript has onlyview.style, which returns computed values (the cascade winner, converted toColor, lengths, numbers). There is no way to ask what was set locally, to read back avar()/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.stylereads and writes,view.style = '…'and the XMLstyleattribute behave as before.view.styleis meant to becomeinlineStylein a future major."Local" stays one slot per property: everything written from code,
view.X, XML attributes or inline strings.Layers
view.inlineStyleview.attributeStyleMapgetComputedStyle(view)view.computedStyleMap()(= whatview.style.Xreturns)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)cssText; assigning anything else throws.''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.var()shorthand reads its expression on the shorthand (inlineStyle.margin === 'var(--m)'). Its longhands read'', and the shorthand reads''once a longhand is overwritten.view.color = 'red'reads'rgb(255, 0, 0)').'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.view.stylewrite.cssTextlists every local declaration (custom properties, thenvar()shorthands, then longhands).cssTextvsview.style = '…'Assigning
inlineStyle.cssTexthas 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 XMLstyleattribute 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.attributeStyleMap(InlineStylePropertyMap)The typed local values:
get(name)returns the typed value orundefined, plusset(name, string | typed),has,delete,clear,sizeand iteration. A written object comes back as the same instance. An equal write to a non-inherited property may keep the previous instance.clear()isinlineStyle.cssText = ''. Assigning the property throws.view.computedStyleMap()(ComputedStylePropertyMap)The typed computed values, exactly what
view.style.Xreturns 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 onglobalThis). It returns a live, read-only declaration, cached per view in aWeakMap. It supports camel-case reads,getPropertyValue(),length,item()and iteration, and returns canonical strings serialized from the typed computed value (colors asrgb()/rgba(), percentages as%). Writes throw, as the web's computed declaration does (setProperty,removeProperty,cssText, camel-case assignment).cssTextreads''like the web's.Serializers
CssProperty,InheritedCssPropertyandCssAnimationPropertytake avalueSerializer?: (value: U) => stringoption (also throughoverrideHandlers). The default is the newserializeCssValue: 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-shadowhas its own serializer, because its parsed form keeps the layers in reverse order.clip-pathserializesnullasnone.ShorthandPropertytakesvalueSerializer?: (longhands: string[]) => stringto compose its serialized longhands.transformhas one:translate(…) scale(…) rotate3d(…), ornone.css-value-serializer.spec.tsiterates 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.tskeeps 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/_getLocalValueonCssProperty(sourceKey === Local) andCssAnimationProperty(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. AcssTextassignment orclear()never touches them.applyInlineStyletakes an optional list of extra longhands to replace, which is howcssTextclears 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, rawvar()/calc()expressions, pending shorthand longhands, shorthand composition for every registered shorthand), writes reaching change events and a native setter,cssTextfull replace vsview.style = '…', custom properties, keyframe masking, internals survivingclear(),attributeStyleMapwith aColorinstance,computedStyleMap()cascade winners,getComputedStyleliveness 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 --noEmitis clean.view-basenow imports a module that registers a listener at load time, so this needs an iOS/Android smoke test.Open questions
view.stylenames:textAlign(textAlignment),horizontalAlign,verticalAlign,rotatex/rotatey, everya11y*(a11yEnabledforaccessible, ...).inlineStyle.textAlignment = …does nothing. That is web parity, but it matters ifview.stylebecomesinlineStyle: should the NativeScript names be aliases?getComputedStyleserializes the typed value, so'red'reads'rgb(255, 0, 0)'. Some forms also differ from the web: dip lengths are unitless, gradient angles are inrad,font-weight: boldstaysbold.inlineStyleserializes the typed local value, soview.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. Onlyvar()/calc()values keep their specified form, from fix(core): keep var() and calc() in local style values current #11673.getComputedStyleonglobalThis? It is only a named export now. A global would help web-oriented libraries, butdomtypings already declare a different globalgetComputedStyle.background-image: linear-gradient(to bottom, red 0%, blue 100%).LinearGradient.equalscompares color-stop offsets by reference, so parsed gradients with offsets never compare equal. The serialization itself is right. FixingLinearGradient.equalswould also stop such gradients from re-applying on every cascade pass, but that belongs in a separate PR.view.stylewrites do (the web ignores them). A throwingCssPropertywrite has already set its source to Local before converting, soinlineStylethen shows the previous value as a local declaration. That is pre-existing behavior of the setter.inlineStyle.setPropertyignores them (web),attributeStyleMap.setthrows aTypeError(web).inlineStyle.lengthalso countsvar()declarations whose substitution left no value.attributeStyleMap.get()on avar()longhand returns the substituted typed value.inlineStyleandattributeStyleMap, butview.style = '…'still replaces all inline variables (as it did).backgroundalways reads'': its longhands never all take part in one write. Abackgroundwrite stores the bare image path, sobackground-imagethen reads~/a.png, noturl(~/a.png).cssText, and acssTextassignment orclear()resets them. Examples: the final values ofview.animate()(localopacity,translate*,scale*,rotate*,background-color), and sugar setters likeLabel.textWrap→white-spaceor thestatusBarStylesetter. Is that the intended contract for a futureview.style=inlineStyle?ShorthandPropertyOptions.valueSerializer,serializeCssValue,serializeColor,CssStyleDeclarationProperties(augment it to type plugin properties).