Skip to content

Commit e815cd1

Browse files
committed
feat: in-place component HMR under Vite
Support Angular's web-style HMR (ɵɵreplaceMetadata) on device instead of rebooting the app for template and stylesheet edits. - Bootstrap right away when the app has already launched (a dev server's boot UI owns launchEvent), and wire the HMR dispose hooks for import.meta.hot as well as webpackHot. - Tag each emulated component's CSS separately and implement componentReplaced(), so a replaced component's styles are dropped and re-applied from the new metadata. - Load external runtime styles (getExternalStyles), which dev servers emit for style HMR, resolved against the new NATIVESCRIPT_STYLE_BASE_URL token (defaults to __NS_DEV_ORIGIN__ set by @nativescript/vite). - Reload those stylesheets on Vite's css-update (vite:beforeUpdate via @nativescript/vite's device HMR registry), as Vite's client swaps a <link> on the web.
1 parent 8144504 commit e815cd1

3 files changed

Lines changed: 144 additions & 5 deletions

File tree

‎packages/angular/src/lib/application.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
457457
if (oldAddEventListener) {
458458
global.NativeScriptGlobals.events.addEventListener = oldAddEventListener;
459459
}
460-
if (import.meta['webpackHot']) {
460+
if (import.meta['webpackHot'] || import.meta['hot']) {
461461
// handle HMR Application.run
462462
global['__dispose_app_ng_platform__'] = () => {
463463
disposePlatform('hotreload');
@@ -490,7 +490,9 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
490490
return;
491491
}
492492

493-
if (options.embedded) {
493+
// A host that already launched the app (e.g. a dev server's boot UI) will not
494+
// fire launchEvent again, so bootstrap now instead of waiting for it.
495+
if (options.embedded || Application.hasLaunched()) {
494496
bootstrapRoot('applaunch');
495497
} else {
496498
Application.run();

‎packages/angular/src/lib/nativescript-renderer.ts‎

Lines changed: 130 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
inject,
33
Injectable,
44
Injector,
5+
OnDestroy,
56
Renderer2,
67
RendererFactory2,
78
RendererStyleFlags2,
@@ -11,7 +12,9 @@ import {
1112
} from '@angular/core';
1213
import {
1314
addTaggedAdditionalCSS,
15+
removeTaggedAdditionalCSS,
1416
Application,
17+
Http,
1518
ContentView,
1619
getViewById,
1720
Observable,
@@ -24,6 +27,7 @@ import {
2427
APP_ROOT_VIEW,
2528
ENABLE_REUSABE_VIEWS,
2629
NATIVESCRIPT_ROOT_MODULE_ID,
30+
NATIVESCRIPT_STYLE_BASE_URL,
2731
PREVENT_CHANGE_EVENTS_DURING_CD,
2832
PREVENT_SPECIFIC_EVENTS_DURING_CD,
2933
WRAP_CD_IN_TRANSACTION,
@@ -114,7 +118,13 @@ function modifiesDom() {
114118
};
115119
}
116120

117-
export class NativeScriptRendererFactory implements RendererFactory2 {
121+
interface DevHmrEvents {
122+
on?(event: string, cb: (payload: any) => void): void;
123+
off?(event: string, cb: (payload: any) => void): void;
124+
}
125+
126+
@Injectable()
127+
export class NativeScriptRendererFactory implements RendererFactory2, OnDestroy {
118128
private componentRenderers = new Map<string, Renderer2>();
119129
private defaultRenderer: Renderer2;
120130
// backwards compatibility with RadListView
@@ -128,13 +138,30 @@ export class NativeScriptRendererFactory implements RendererFactory2 {
128138
private injector = inject(Injector);
129139
private cdDepth = 0;
130140
private viewUtil = new ViewUtil(this.namespaceFilters, this.reuseViews);
141+
// `@nativescript/vite`'s device HMR client exposes this during dev only; it
142+
// delivers Vite's client events (`vite:beforeUpdate`, ...).
143+
private devHmr = (globalThis as { __NS_HOT_REGISTRY__?: DevHmrEvents }).__NS_HOT_REGISTRY__ ?? null;
131144

132145
constructor() {
133146
if (typeof this.reuseViews !== 'boolean') {
134147
this.reuseViews = false; // default to false
135148
}
136149
this.defaultRenderer = new NativeScriptRenderer(this.rootView);
150+
this.devHmr?.on?.('vite:beforeUpdate', this.onViteBeforeUpdate);
137151
}
152+
153+
// There is no `<link>` element on device: emulated renderers own the
154+
// stylesheets they loaded at runtime, so they reload them on `css-update`.
155+
private onViteBeforeUpdate = (payload: { updates?: { type: string; path: string; timestamp?: number }[] }) => {
156+
for (const update of payload?.updates ?? []) {
157+
if (update.type !== 'css-update') continue;
158+
this.componentRenderers.forEach((renderer) => {
159+
if (renderer instanceof EmulatedRenderer) {
160+
renderer.externalStyleChanged(update.path, update.timestamp);
161+
}
162+
});
163+
}
164+
};
138165
createRenderer(hostElement: any, type: RendererType2): Renderer2 {
139166
if (NativeScriptDebug.enabled) {
140167
NativeScriptDebug.rendererLog(
@@ -177,6 +204,29 @@ export class NativeScriptRendererFactory implements RendererFactory2 {
177204
this.componentRenderers.set(type.id, renderer);
178205
return renderer;
179206
}
207+
208+
/**
209+
* Called by Angular's HMR (`ɵɵreplaceMetadata`) before a component is
210+
* re-created with new metadata: drop its cached renderer and its styles so
211+
* the next `createRenderer` applies the replacement styles.
212+
*/
213+
componentReplaced(componentId: string): void {
214+
const renderer = this.componentRenderers.get(componentId);
215+
if (renderer instanceof EmulatedRenderer) {
216+
renderer.removeStyles();
217+
}
218+
this.componentRenderers.delete(componentId);
219+
}
220+
221+
ngOnDestroy(): void {
222+
this.devHmr?.off?.('vite:beforeUpdate', this.onViteBeforeUpdate);
223+
this.componentRenderers.forEach((renderer) => {
224+
if (renderer instanceof EmulatedRenderer) {
225+
renderer.removeStyles();
226+
}
227+
});
228+
this.componentRenderers.clear();
229+
}
180230
begin() {
181231
if (__APPLE__ && this.wrapCdInTransaction) {
182232
if (this.cdDepth > 0) {
@@ -503,14 +553,91 @@ export class EmulatedRenderer extends NativeScriptRenderer {
503553
private contentAttr: string;
504554
private hostAttr: string;
505555
private rootModuleId = inject(NATIVESCRIPT_ROOT_MODULE_ID);
556+
private styleBaseUrl = inject(NATIVESCRIPT_STYLE_BASE_URL);
557+
// Per-component tag so a single component's styles can be replaced (HMR)
558+
// without dropping every other component's CSS.
559+
private styleTag: string;
560+
private stylesRemoved = false;
561+
private componentId: string;
562+
private inlineStyles: (string | any[])[];
563+
private externalStyleUrls: string[];
564+
private externalStyles: string[] = [];
506565

507-
constructor(component: RendererType2, rootView: View) {
566+
constructor(
567+
private component: RendererType2,
568+
rootView: View,
569+
) {
508570
super(rootView);
509571

510572
const componentId = component.id.replace(ATTR_SANITIZER, '_');
573+
this.componentId = componentId;
511574
this.contentAttr = replaceNgAttribute(CONTENT_ATTR, componentId);
512575
this.hostAttr = replaceNgAttribute(HOST_ATTR, componentId);
576+
this.styleTag = `${this.rootModuleId}:${componentId}`;
577+
this.inlineStyles = component.styles;
578+
this.externalStyleUrls = Array.from(component.getExternalStyles?.(componentId) ?? []);
513579
this.addStyles(component.styles, componentId);
580+
this.loadExternalStyles();
581+
}
582+
583+
removeStyles(): void {
584+
this.stylesRemoved = true;
585+
removeTaggedAdditionalCSS(this.styleTag);
586+
}
587+
588+
/**
589+
* Reloads the external stylesheets served at `path`. `timestamp` busts any
590+
* cache between the app and the dev server, as Vite's client does when it
591+
* swaps a `<link>`. Returns whether this component loads that stylesheet.
592+
*/
593+
externalStyleChanged(path: string, timestamp?: number): boolean {
594+
if (this.stylesRemoved || !this.styleBaseUrl) return false;
595+
// Component style URLs may be relative to the base while the update path is root-relative.
596+
const pathname = new URL(path, this.styleBaseUrl).pathname;
597+
if (!this.externalStyleUrls.some((url) => new URL(url, this.styleBaseUrl).pathname === pathname)) {
598+
return false;
599+
}
600+
this.loadExternalStyles(timestamp);
601+
return true;
602+
}
603+
604+
// External runtime styles (dev servers emit these for style HMR) are URLs the
605+
// server already scoped to the component; they arrive after the views exist,
606+
// so the root view is restyled once they are applied.
607+
private loadExternalStyles(timestamp?: number): void {
608+
const urls = this.externalStyleUrls;
609+
if (!urls.length) return;
610+
if (!this.styleBaseUrl) {
611+
NativeScriptDebug.rendererError(
612+
`External styles for ${this.component.id} need NATIVESCRIPT_STYLE_BASE_URL to resolve: ${urls.join(', ')}`,
613+
);
614+
return;
615+
}
616+
// `Accept: text/css` is what a browser `<link>` sends; dev servers otherwise
617+
// answer a `.css` URL with a JS module (Vite's CSS-as-module wrapper).
618+
const fetchCss = (url: string) => {
619+
const target = new URL(url, this.styleBaseUrl);
620+
if (timestamp) target.searchParams.set('t', String(timestamp));
621+
return Http.request({ url: target.href, method: 'GET', headers: { Accept: 'text/css' } }).then((response) => {
622+
if (response.statusCode >= 400) throw new Error(`HTTP ${response.statusCode} for ${url}`);
623+
return response.content.toString();
624+
});
625+
};
626+
Promise.all(urls.map(fetchCss))
627+
.then((sheets) => {
628+
if (this.stylesRemoved) return;
629+
const reload = this.externalStyles.length > 0;
630+
this.externalStyles = sheets.map((css) => stripCssVarNamespace(css));
631+
if (reload) {
632+
removeTaggedAdditionalCSS(this.styleTag);
633+
this.addStyles(this.inlineStyles, this.componentId);
634+
}
635+
this.externalStyles.forEach((css) => addScopedStyleToCss(css, this.styleTag));
636+
Application.getRootView()?._onCssStateChange();
637+
})
638+
.catch((err) =>
639+
NativeScriptDebug.rendererError(`Failed to load external styles for ${this.component.id}: ${err}`),
640+
);
514641
}
515642

516643
applyToHost(view: NgView) {
@@ -538,6 +665,6 @@ export class EmulatedRenderer extends NativeScriptRenderer {
538665
styles
539666
.map((s) => s.toString())
540667
.map((s) => stripCssVarNamespace(replaceNgAttribute(s, componentId)))
541-
.forEach((s) => addScopedStyleToCss(s, this.rootModuleId));
668+
.forEach((s) => addScopedStyleToCss(s, this.styleTag));
542669
}
543670
}

‎packages/angular/src/lib/tokens.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,16 @@ export const WRAP_CD_IN_TRANSACTION = new InjectionToken<boolean>('NativeScriptW
1313
providedIn: 'root',
1414
factory: () => false,
1515
});
16+
/**
17+
* Base URL that Angular's external runtime styles (relative `.css` URLs, emitted by
18+
* dev servers for component style HMR) are resolved against — the role
19+
* `document.baseURI` plays on the web. Defaults to `globalThis.__NS_DEV_ORIGIN__`,
20+
* which a dev server session sets; `null` when no dev server is involved.
21+
*/
22+
export const NATIVESCRIPT_STYLE_BASE_URL = new InjectionToken<string | null>('NativeScriptStyleBaseUrl', {
23+
providedIn: 'root',
24+
factory: () => (globalThis as { __NS_DEV_ORIGIN__?: string }).__NS_DEV_ORIGIN__ ?? null,
25+
});
1626

1727
export type PageFactory = (options: PageFactoryOptions) => Page;
1828
export interface PageFactoryOptions {

0 commit comments

Comments
 (0)