Repository navigation
RFC: A modular NativeScript core #67
Replies: 3 comments 2 replies
|
This is tremendous effort @ammarahm-ed and like the direction all around. I'll give some deeper thought to the unresolved questions before commenting further. |
|
Great work overall! I really like the direction on a native view tree and a unified Taffy layout. That's exactly where core should be heading. I do have some concerns about the overall direction, though. This feels too fragmented. Many of these pieces don't split cleanly. The proposal also builds on some of core's existing events that are flawed today. WinterTC APIs should be globals, not imports. I'd argue strongly against anything like The design doesn't take the platform into account, and the platform is what NativeScript gives you. The proposed View, style and layout are one system. Each of them could be implemented fully in C++ with JS hooks. But making them independently replaceable means they can no longer be optimized together. If layout can be swapped out, it can't flatten the view hierarchy. If style can be swapped out, views and layout can't cooperate on cascading. Every internal API between them also becomes a public contract, so any internal change becomes a breaking change. And it fragments the ecosystem: "Which NativeScript are you using?" "Which CSS engine?" "What's the best NativeScript CSS engine in 2030?" It locks in the problem we already have. Today almost every part of core has been replaced by someone, somewhere: through plugins, patch-package or monkey patching. Fixing anything means working carefully around private APIs that people use publicly. Making that the architecture leaves us with five libraries, each with its own quirks, and core relegated to a default that the official advice says to replace. We're designing the seams before the thing. This is an RFC for a full remake of core, yet most of the discussion is about how to split it into packages so people can replace them. I think that's backwards. The projects that pulled off rewrites like this built the thing they wanted first and opened it up afterwards. TypeScript 7 shipped the native compiler before its API story was complete. oxlint shipped a fast linter and added JS plugin support later. Rspack shipped a fast core and grew webpack compatibility over time. None of them started by defining replaceable boundaries. Let's build the core we actually want first: ergonomic, familiar APIs and a great end-user experience, with responsibilities separated internally. Once that exists and the right boundaries have proven themselves, we can decide which ones deserve to become public extension points. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Summary
This RFC proposes rebuilding
@nativescript/coreas a set of packages whose boundaries the build enforces. The packages are released together and shipped as one product:@nativescript/coreremains the package apps install and the API they use, and it re-exports the packages.fsandfetchas separate packages, named after the web or Node API they provide.ios/,android/,macos/) that implements the package'sinterface.ts, so new platforms such as macOS, Windows and Linux add folders and change no shared code.globalThis, and platform capabilities beyond the standards, such as synchronous file access, are exposed on top.@nativescript/corekept as the one package an app installs and the one place apps and plugins import from. It re-exports every public API from a single entry, with no deep imports.All package names are working names under the
@nativescript/scope.Basic example
A minimal UI app with the default package:
Motivation
The numbers below come from a survey of
@nativescript/core9.1.4.Everything is reachable from everything.
exportsfield, andindex.tsimports./globalson its first line.globalsimportsapplication, which imports the XMLBuilder, which reaches the whole UI.http-requestimportsImageSource, which reaches fonts, the property system,ViewBaseandPage.utilson Android imports the frame stack.*-common.tsfiles exist partly to break import cycles.The result is that importing one function loads most of the package, and a headless app cannot exist.
The property system carries the cascade. About 281 properties are registered. Each one creates four to seven symbols, and the main property file is 1,781 lines. CSS values, inheritance and defaults are resolved inside JavaScript property setters.
A view is heavy before it shows anything.
ViewBase,ViewCommonand the platformViewtotal about 5,300 lines and declare roughly 120 to 140 instance fields.CSS does most of its work on the device.
!importantis stripped.Layout is implemented twice. iOS layouts are about 3,000 lines of TypeScript. Android layouts are about 5,200 lines of Java. They must be kept in agreement by hand.
XML ships to everyone. Most apps today use Angular, Vue, Solid, Svelte or React, but the XML builder, bindings and module registry are in every bundle.
APIs follow no standard.
Observable,Http,File,Folder,ApplicationSettingsandConnectivityare NativeScript inventions with their own names and semantics.Goals
Non-goals
fsandpath.Observable,ObservableArray,bindingContextand binding expressions are part of compat.@nativescript/coreis the supported API, and the interfaces between the packages are internal.Detailed design
Design rules
sideEffects: false. Standard globals are in place before the app entry runs; importing a package never installs one.exportsmap lists its root entry, and everything an app or a plugin may need is exported there. Deep imports do not resolve.@nativescript/coreis the one package that re-exports others, and it contains re-exports and nothing else.interface.ts, and one folder per platform implements it.Package map
A headless app links only
foundationand the capabilities it imports. Platform folders live inside each package, and a build includes the folder for one target.foundationEventTarget, device info, main-thread dispatch,Coloras a packed value. Target: under 3,000 lines.fs,path,fetch,storage,network,image-bitmapurl,streams,encoding,crypto,websocket,timerswinter-tcglobalThisbefore the app entry.viewViewElement, the@propdecorator, the node tree, the frame flush, theViewPlatforminterface.styleStyleEngineinterface, the style property registry, the change buffer format.css-nativecss-jsheadlesstarget.css-compilerlayoutwidgetswindowopenWindow, window events, and each window's environment for media queries.navigation,gestures,animation,aria,dialogs,listcorecompatThe default package:
@nativescript/core@nativescript/corekeeps its name and its role: the one package an app installs, and the one place apps and plugins import from. From its next major version it depends on the packages in this RFC at pinned versions and re-exports their public API from a single entry. It contains no code of its own.@nativescript/corefoundation:app, lifecycle events, device information, main-thread dispatch,Color, and the native helpers plugins rely on (current activity and application context on Android, key window and root view controller on iOS)fs,path,storage,network,image-bitmap, and the platform extensions to the standard APIs.fetch,URL, streams, encoding,crypto,WebSocketand timers are globalscreateUI, every widget and layout inwidgets,window(setWindowContentResolver,openWindow),navigation,list,gestures,animation,aria,dialogsViewElement,prop,Changed,MeasureSpec,Size,StyleChanges, style property registration, the base class for custom layouts, the widget base classes, and the platform interfacescss-js,css-compiler,devtoolsandcompatexportsmap lists the root. Anything an app or a plugin needs is exported there. When a plugin needs something that is missing, the fix is to export it.sideEffects: false, so the bundler keeps only what the app uses. A headless app that importsappandreadFileships no UI.createUI(window)takes the window it renders into. It uses the native CSS engine; there is no engine to choose.@nativescript/corepins a set of package versions that were tested together.@nativescript/coreis the supported API. The interfaces between packages are internal and change with releases.globalThiswhen the app entry runs: provided by the runtime where it implements it, and installed by the build where it does not.Web standards and naming
EventTarget,Event,CustomEvent,AbortSignalObservable,EventDataclick,pointerdown,keydown)tap, touch-only gesturesview.animate({...})roleandaria-*accessibilityLabeland relatedfetch, Streams,WebSocket, with handshake headers where the platform allows themHttp,http-requestlocalStorage)ApplicationSettingsfssubset in synchronous and promise forms, with WHATWG file-system handles beside itFile,Folder,knownFoldersglobalsNames are chosen in this order:
fs,path), implemented as a stated subset.View).Standards are the floor, not the ceiling. A standard API is never narrowed to what a browser allows when the platform can do more. File operations are synchronous on every platform, so
fshas synchronous functions beside the promise ones, as Node does. Browsers do not allow custom headers on a WebSocket handshake, but native platforms do, soWebSocketaccepts them, in the options shape that server runtimes already use. An extension follows an existing runtime's shape when one exists.Conformance is tested, not claimed: the relevant Web Platform Tests directories run against the
headlesstarget in CI.Foundation
foundationis the only package every app needs.appis anEventTargetfor process events:suspendwhen every window has gone to the background,resumewhen the first returns,exit,lowMemoryand uncaught errors. Creating UI is not a process event; see Windows and app lifecycle.AppPlatforminterface: lifecycle source, main-thread dispatch, device information.EventTarget,EventandCustomEventin TypeScript, following the DOM dispatch algorithm, with the step that finds a target's parent as an internal hook. A target outside the view tree has no parent, soappbehaves like Node'sEventTarget. A runtime's built-inEventTargetcannot be used: its parent lookup is not reachable from JavaScript, andeventPhase,currentTargetand the effect ofstopPropagation()are internal state of a built-inEvent. Foundation's classes are the ones onglobalThis.View system
A widget is an ordinary class. A shared base class declares what the widget is. A class in the platform folder says how it is realised.
ViewElementextendsEventTargetand holds tree links, attributes, the style handle andnative. Nothing else is added to it.ViewElementanswers withparentNode, which gives capture and bubble through the view tree. The parent lookup is an internal hook betweenfoundationandview.@propis a TC39 decorator on anaccessorfield. When the value changes it sets a bit in a dirty mask and schedules the flush.commit(changed)replaces[property.setNative]. It runs once per flush with the set of changed properties.connectedCallback()anddisconnectedCallback().createNativeView()anddisposeNativeView()keep their NativeScript names.class MyLabel extends Labelis supported, as isinstanceof.Where the native view attaches.
new Label()creates no native view. When the element is appended to a mounted tree,createNativeView()runs and its result becomesthis.native,commitruns with every property already set, the platform inserts the native view into its parent, andconnectedCallback()fires. Removal runs the reverse.Renderer API. Renderers get a DOM subset:
appendChild,insertBefore,removeChild,parentNode,firstChild,nextSibling,children,id,className,classList,setAttribute,style.setProperty,getComputedStyle,addEventListener,dispatchEvent,querySelector,matches. There is nodocument, no text nodes and noinnerHTML.One flush per frame.
Setting ten properties on a view costs one
commitcall.flushSync()forces the flush when code needs the result immediately.Windows and app lifecycle
A process and a window have separate lifecycles. A process can start with no window: a background fetch, a notification, an Android service. It can also have several windows: iPad and desktop windows, Android multi-window. The platform decides when a window exists, on a user action, through state restoration, or when the app calls
openWindow. When a window needs content, it asks the app for it.scene:willConnectToSession:options:, once per sceneInfo.plistActivity.onCreate, withsavedInstanceStateafter process deathNSWindow, or an instance of a SwiftUIWindowGroupopenWindow(id:)AppRegistry.registerComponent(name, factory)Application.setWindowContentResolver(request => …), withlaunchas the fallback for the first windowcreateUI(window)gives the window its own tree and its own environment for media queries, safe areas and appearance.dataand the platform's restoration state.appfiressuspendandresumefor the process as a whole.launchbelongs to compat. Compat bridges it to the content of the first window, as 9.x does.Two shapes are proposed for the content API.
Option A: a resolver, as 9.x has today. One function is called for every window that needs content.
Option B: named roots, as React Native's
AppRegistryand SwiftUI's scene ids work.Info.plistscene configurations, Android activities and SwiftUI scene ids. A scene declared natively can ask for its content by name.data.Option A is recommended. See Unresolved questions.
Platforms
A platform is a set of folders that implement a fixed set of interfaces. Every package has the same shape: an
interface.tsat the top that declares what a platform must provide, shared files beside it, and one folder per platform. A platform folder can hold as many files as the implementation needs.Resolution rule. One rule for app code, plugins and every package. For an import of
./backendfrom a file at the top of a package, in a build formacos, the bundler tries, in order:macos/backend.ts(the platform folder at the top of the package)backend.macos.ts(a suffixed file beside the importing file)backend.ts(a shared default, if the package has one)widgets, the sharedlabel/index.tsimports./label, which resolves toios/label/label.ts.linuxlooks forlinux/folders and.linux.tsfiles.headlesstarget as the reference.Backends are primitives. A platform does not implement the public API of a capability. It implements a small backend, and the public API is shared TypeScript on top.
The view interface.
What a platform gets for what it implements.
foundationfs,fetchfsAPI,fetch, XHR, FormData,localStoragethrough a file-backed defaultview,window, one containerA platform the packages do not ship. A community platform cannot add files to a published package. The proposal is one more resolver step: the app's config names a platform package, and when a package has no file for the target, the resolver looks there for the same path under the package's name (
@community/nativescript-linux/fs/backend.ts). See Unresolved questions.What a new platform has to bring. A way for JavaScript to reach the toolkit (a NativeScript runtime for that OS, or a native backend behind a C ABI), the
foundationandviewfiles, widget files added incrementally, and a passing conformance run. Untilcss-nativeis built for the target,css-jsworks unchanged.Style engine contract
viewtalks to styling only through theStyleEngineinterface instyle. The interface is internal. It keeps the view layer and the engine apart so that theheadlesstarget and the tests can runcss-js, and so that a new platform can run beforecss-nativeis built for it. Apps do not choose an engine.The interface covers sheets (
addSheet,removeSheet), nodes (createNode,destroyNode,insert,remove), selector inputs (setId,setClasses,setState,setAttr), inline style (setInline), environment (setEnv) andflush(changes), which fills a buffer with the computed values that changed. Nothing else in the system knows which engine is in use.CSS engine
css-compilerturns CSS text into a binary.nscsssheet: a header, interned atoms, selector programs, rules, fixed-size declarations, lookup indexes, keyframes and media queries, and strings. It uses offsets, not pointers, so the file can be memory-mapped read-only and used in place.css-nativeis C++20 in a restricted style (no exceptions, no RTTI) behind a C ABI. It memory-maps the sheet and parses nothing.!important, CSS variables, transitions and@font-faceare supported.css-jsimplements the same interface over the same bytes. It is the reference for tests in Node and the engine of theheadlesstarget, and it runs on a new platform untilcss-nativeis built for it. It is not offered to apps as an alternative.Native node tree
The CSS engine resolves style into a C++ node table. The layout properties that changed are written from it to Taffy through a C ABI, so style and layout run back to back in native code. It mirrors the tree structure and holds selector inputs, computed style and layout results. A node is a
u32handle with a generation counter.Commands go down in one buffer per flush. Changes come back in one buffer. A full C++ view layer (the React Native Fabric model) was considered and rejected: see Alternatives.
Property registry and code generation
Style properties are declared once, in a table in
style. A generator produces the C++ computed-style struct, the compiler's dispatch, thecss-jstables and the TypeScript types from that table. Value types and platform appliers are written by hand.Custom properties have three levels:
--accent). No code generation.@property --ripple-coloror the table. Generated at app build time, stored sparsely.engine.registerProperty. They use a dynamic id range. The compat layer uses this forCssProperty.Layout
Layout uses Taffy, an existing Rust layout library that implements CSS flexbox, CSS grid and block layout. It is shipped in the
layoutpackage and used on every platform. NativeScript's existing layouts stay as TypeScript classes that translate their properties into Taffy styles.Why Taffy
measure()plugs in.Existing layouts are a translation layer in TypeScript
Each layout class turns its own properties, and the layout properties of its children, into Taffy styles. No layout algorithm is written in TypeScript.
StackLayoutorientationtoflex-direction, no wrappingWrapLayoutflex-wrap: wrap;itemWidthanditemHeightto the children's sizeFlexboxLayoutGridLayoutrowsandcolumnsto grid templates:*tofr,autotoauto, numbers to lengths;row,coland spans to grid placementAbsoluteLayoutposition: absolute, withleftandtopas insetsDockLayouthorizontalAlignmentandverticalAlignmenttojustify-selfandalign-self,visibility: collapsetodisplay: nonedisplay: flex,display: gridordisplay: blockwith the standard properties.How a layout pass runs
measure().measure(), or whose layout is a custom layout in TypeScript, is flagged when it mounts. If the fast pass reaches such a node, it reports that a slow pass is needed.@CriticalNativemethods. These pass primitives only and skip the usual JNI transition. They cannot call into JavaScript, which is why the pass is split in two. The slow pass uses ordinary native methods.Float32Array, and the platform'ssetFrameis called only for nodes whose frame changed.Leaf measurement
sizeThatFits:on the view. On Android the view is measured on the Java side, inside the fast pass.measure()wins when it is defined. It is used for that element in place of the native measurement, and it can callthis.measureNative(w, h). The check is made once, at mount.View flattening
Every node in the tree has a Taffy node. Only the nodes that need one have a native view. A container that exists only to arrange its children is laid out and then skipped: its children are attached to the nearest ancestor that has a native view, at frames offset by the container's position.
display: blockkeeps the native view. A node withdisplay: blockgets a native view even when it has no background or anything else that would require one.nativecreates the native view and re-parents the children in the same flush.nativeViewto exist.What is taken from Mason
Mason is used as a source, not as a dependency. It contains more than core needs, including HTML-shaped elements.
layoutpackage's native codeThis table is based on Mason's README. Which files can be used as they are is still to be established from its source.
Proving it matches
Parity with the current layouts is checked with golden-frame tests generated from the existing Android and iOS implementations, and with the per-layout device suites in
apps/automated. A WebAssembly build of the same Rust code serves theheadlesstarget.Build
__DEV__is the only compile-time define.css-compilerand is emitted as an.nscssasset.require.contextmodule registration exists only in the compat XML entry.A minimal UI app with the default package:
Drawbacks
css-jsexists for tests, theheadlesstarget and new platforms, and it must agree withcss-native. One conformance suite runs against both.WebSocket, may dispatch the runtime's ownEventobjects, which failinstanceofchecks against foundation's classes. Which runtimes do this is part of unresolved question 8.GridLayoutstar and auto sizing,DockLayoutand rounding.headlesstarget first and macOS early is how mobile assumptions are found before the interfaces are frozen.Alternatives
stylo,selectors,cssparserand the html5ever crates. The engine would follow that cadence to obtain selector matching and a small property table.calc(), container queries and nesting. Apps use a small subset. Binary size and startup have not been measured.Stylo would bring a Rust-only toolchain and full-time maintenance of CSS semantics. Those are maintenance benefits, while the costs above are paid on every launch. The engine is therefore purpose-built around its constraints (a mapped file, the node table, restricted C++), and its behaviour is defined by this RFC's
StyleEnginecontract and conformance suite.Adoption strategy
Compat layer
@nativescript/compat(a working name) carries the 9.x API. Existing apps and plugins change no source: the build resolves their@nativescript/coreimports to it, as described under Existing plugins. New apps do not install it.Compat is a superset of the new core. It re-exports everything
@nativescript/coreexports and replaces the classes that have a legacy surface with subclasses of the new ones, so legacy and new code share one copy of every object and their views mix in one tree. It targets iOS and Android only.Observable,EventData,propertyChangeEventTargetProperty,CssProperty,[setNative]@propaccessors and the style registryView,ViewBase, lifecycle hooksViewElementand its lifecycle methodsview.style.*,addCss(string)StyleEngineand the on-device compilerApplication, globals, polyfillsfoundation,window,winter-tcBuilder, XML, bindings,moduleNamenew Property({...})defines a dirty-tracking accessor. The compatcommitcallsview[prop.setNative](value)for each changed property, so plugin code keeps working..ios.tsand.android.tsfiles, which the resolver rule also covers. Compat's widgets extend the new platform classes, so a plugin that subclassesLabelfrom@nativescript/coregets the native class underneath.launchandApplication.run. Compat bridges them to the content of the first window, and keepsApplication.setWindowContentResolverandApplication.openWindowas they are in 9.x.isIOS,isAndroid,__IOS__,__ANDROID__,view.iosandview.androidstay in compat. The new packages have none of these.tapmaps toclick,Httptofetch,FileandFoldertofs,ApplicationSettingstolocalStorage,Connectivitytonavigator.onLine..xmlview files.Behaviour that changes even under compat.
legacySpecificity!importantis honouredloadedloadedExisting plugins
An existing plugin is published against the 9.x API and is not rebuilt. It keeps working because its
@nativescript/coreimports resolve to compat, whose classes extend the new ones. A legacy plugin's view is therefore a realViewElement, and it can be used in a legacy app or in an app written against the new API.How a plugin gets compat
@nativescript/coreversion range includes the new major gets the new core. Every other package gets@nativescript/compat, including the 9.x deep paths such as@nativescript/core/ui/core/view. A published plugin needs no new release.ns migratewritescompat: truetonativescript.config.ts, and the app's own source then resolves to compat as well.app, the same tree and the same style engine.A view plugin
This is the shape of most view plugins today. Nothing in it changes.
The plugin's class sits on top of compat's
View, which sits onViewElement. Each step of the new frame flush arrives at compat'sView, and compat calls the method the plugin already has.extends ViewViewextendsViewElement. The plugin's view is a node in the new tree, styled by the new CSS engine and placed by the new layout.new Property(...),register()valueConverterruns in the setter andvalueChangedfires on change.[prop.setNative],[prop.getDefault]commitcallssetNativefor each changed property, once per frame.getDefaultis called once before the firstsetNative.CssProperty,InheritedCssProperty,ShorthandPropertycommitStyle, which calls the plugin'ssetNative.createNativeView,initNativeView,disposeNativeViewnativeViewProtected,nativeView,ios,androidnative.onLoaded,onUnloaded,loadedandunloadedeventsconnectedCallbackanddisconnectedCallback.onMeasure,setMeasuredDimension,layout.makeMeasureSpeconMeasure, compat definesmeasure(), which calls it and returns the measured size. Other classes are measured natively.onLayout,layoutNativeViewrequestLayout()notify,on,off, gesture eventsEventTargetunderneath.tapandclickare the same event.registerElement('Gauge', ...)in a flavoriOS view plugins
onMeasureis sized by a directsizeThatFits:call from the layout library, where today the measure pass runs in JavaScript.onMeasureoronLayoutkeep those methods and run on the JS measure path.View.measureChildandView.layoutChildkeep working. Compat implements those helpers by asking the layout library to solve the child's subtree.viewControlleris attached by compat's navigation and window code.NSObjectsubclasses and direct UIKit calls do not go through core.Android view plugins
this._contextis supplied by compat from the foreground activity thatfoundationtracks.Application.android.foregroundActivityandUtils.android.getApplicationContext()read the same source.ViewGroupthat measures and positions its children itself: a card, a pull-to-refresh, a drawer. The layout library treats such a view as one box. Inside it, Android asks the child for its size, and the child's native container answers by having the layout library solve its subtree under the constraints Android gave it. Theorg.nativescript.widgetslayout params fromui-mobile-basestay available for plugins that set them directly..aarfiles and Java or Kotlin sources are handled by the CLI and the runtime.Plugins without views
A plugin that uses
Application,Utils,File,Http,ApplicationSettingsorObservablegets compat's versions, which are adapters overfoundation,fs,fetch,storageandEventTarget. A plugin that only calls native APIs is unaffected.What can break
_setupUIView.prototypeor another core prototypePhase 5 of the migration plan runs the demo apps of a set of popular plugins unchanged. That run is the acceptance test for this section.
Moving a plugin to the new API
A plugin moves when its author chooses to. It declares the new major of
@nativescript/corein its version range and imports everything from the package root.class Gauge extends Viewclass Gauge extends ViewElement<GaugeView>new Property,register,[setNative]@prop() accessor value = 0and onecommit(changed)methodnew CssPropertycommitStyleindex.ios.ts,index.android.tsios/andandroid/folders, or the same suffixed filesonLoaded,onUnloadedconnectedCallback,disconnectedCallbackonMeasuremeasure()when the plugin computes its own sizeMigration plan
exportsmap, cut the three worst import edgesfoundationand the capability packagesfoundationalonecss-js, run under the existing view systemcss-nativeagainst the same test suiteheadlesstarget first, then iOS and Android; assemble the new@nativescript/coreentry as a prerelease@nativescript/compatand the build rule that routes legacy code to it; runapps/automatedand popular plugins unchanged; release the next major of@nativescript/corePhases 2 and 3 can start alongside phase 1.
Unresolved questions
@nativescript/coreversion range, plus one app-level flag. The alternative is a single app-wide switch, which is simpler but gives a new app with one old plugin the legacy API everywhere. The name@nativescript/compatis a working name.@nativescript/corere-exports. It currently re-exports every widget plus navigation, gestures, animation and dialogs. Candidates to leave out are the heavier or rarer ones, such as web-view, pickers andlist.fsandpathare a subset, with synchronous and promise forms. Streams andfs.watchneed a decision.tsconfigper target that setsrootDirsto the package root plus that target's folder, andmoduleSuffixesfor suffixed files. This needs confirming in a prototype.foundationis a placeholder.@nativescript/coreentry relies on the build reporting a missing platform implementation only when the app uses it. The alternative is a second entry for UI, so that a headless app never reaches widget files. The mechanism for the first needs a prototype.display: blockkeeps a native view on a node that would otherwise be flattened, which also makes every block-layout container a native view. A separate property would keep layout mode and flattening independent.@CriticalNativemethods are called from Java with primitives only. How a measurement that Taffy requests in the middle of a pass reaches an Android view under that constraint needs a prototype.AppRegistryand SwiftUI's scene ids. Option A is recommended.All reactions