Skip to content

Commit e736f9a

Browse files
committed
refactor(android): keep state for plain native objects in JS
Core stored JS properties on plain (non-extended) Java objects: listener back-references on native views, the cached default background drawable, default paddings, the SeekBar owner, a Frame's attach-listener owner, animator transition data, and activity callbacks/flags on embedded host activities. Runtimes where a plain object's JS wrapper can be dropped and rebuilt lose that state or pay to mirror it. Keep the state on the owning JS objects instead: View fields for listeners and the default background, per-owner listener instances for Slider, Frame and fragment animators, and an activity registry for activity callbacks. Expandos on extended objects (NativeScriptActivity, FragmentClass, TabHostImpl, listener implementations) are unchanged.
1 parent 8a6f0ca commit e736f9a

23 files changed

Lines changed: 284 additions & 246 deletions

‎packages/core/application/application.android.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { CoreTypes } from '../core-types';
22
import { profile } from '../profiling';
33
import type { View } from '../ui/core/view';
4-
import { AndroidActivityCallbacks, NavigationEntry } from '../ui/frame/frame-common';
4+
import { NavigationEntry } from '../ui/frame/frame-common';
55
import { isEmbedded } from '../ui/embedding';
6+
import { getActivityCallbacks, isNativeScriptActivity } from '../ui/frame/activity-callbacks-store';
67
import { SDK_VERSION } from '../utils/constants';
78
import { android as androidUtils, dataSerialize } from '../utils';
89
import { ApplicationCommon } from './application-common';
@@ -94,7 +95,7 @@ function initNativeScriptLifecycleCallbacks() {
9495
Application.android.setStartActivity(activity);
9596
}
9697

97-
if (!this.nativescriptActivity && 'isNativeScriptActivity' in activity) {
98+
if (!this.nativescriptActivity && isNativeScriptActivity(activity)) {
9899
this.nativescriptActivity = activity;
99100
}
100101

@@ -206,7 +207,7 @@ function initNativeScriptLifecycleCallbacks() {
206207

207208
// `onActivityCreated` registers a window for every activity in the process, so the
208209
// window's role cannot tell a NativeScript activity from a third-party one.
209-
if ('isNativeScriptActivity' in activity) {
210+
if (isNativeScriptActivity(activity)) {
210211
Application.android._setWindowActive(nativeWindow, false, activity);
211212
}
212213

@@ -794,7 +795,7 @@ export class AndroidApplication extends ApplicationCommon implements IAndroidApp
794795
.filter((window) => window.state === 'attached' && !window._surfaceGone)
795796
.map((window) => (window as AndroidNativeWindow).activity);
796797
// startActivity/foregroundActivity can be third-party (SDK) activities, which must never be relaunched as a window.
797-
const startActivity = [this.startActivity, this.foregroundActivity, ...windowActivities].find((activity) => activity && 'isNativeScriptActivity' in activity && !activity.isFinishing() && !activity.isDestroyed());
798+
const startActivity = [this.startActivity, this.foregroundActivity, ...windowActivities].find((activity) => isNativeScriptActivity(activity) && !activity.isFinishing() && !activity.isDestroyed());
798799

799800
if (startActivity) {
800801
intent.setClass(context, startActivity.getClass());
@@ -833,7 +834,7 @@ export class AndroidApplication extends ApplicationCommon implements IAndroidApp
833834
if (!activity) {
834835
return undefined;
835836
}
836-
const callbacks: AndroidActivityCallbacks = activity['_callbacks'];
837+
const callbacks = getActivityCallbacks(activity);
837838

838839
setRootView(callbacks ? callbacks.getRootView() : undefined);
839840
return getRootView();
@@ -848,7 +849,7 @@ export class AndroidApplication extends ApplicationCommon implements IAndroidApp
848849
}
849850

850851
// this.mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
851-
const callbacks: AndroidActivityCallbacks = activity['_callbacks'];
852+
const callbacks = getActivityCallbacks(activity);
852853
if (!callbacks) {
853854
throw new Error('Cannot find android activity callbacks.');
854855
}

‎packages/core/application/open-window.android.spec.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,20 @@ vi.hoisted(() => {
66

77
import { AndroidApplication } from './application.android';
88
import type { AndroidNativeWindow } from '../native-window/native-window.android';
9+
import { _registerActivityCallbacks } from '../ui/frame/activity-callbacks-store';
910

1011
function activity(name: string, nativeScript = true) {
11-
return {
12-
...(nativeScript ? { isNativeScriptActivity: true } : {}),
12+
const result = {
1313
getClass: () => name,
1414
isFinishing: () => false,
1515
isDestroyed: () => false,
1616
isInMultiWindowMode: () => false,
1717
startActivity: vi.fn(),
1818
} as unknown as androidx.appcompat.app.AppCompatActivity;
19+
if (nativeScript) {
20+
_registerActivityCallbacks(result, {} as any);
21+
}
22+
return result;
1923
}
2024

2125
describe('Android openWindow activity selection', () => {

‎packages/core/native-window/native-window.android.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import type { View } from '../ui/core/view';
22
import { CoreTypes } from '../core-types';
33
import { SDK_VERSION } from '../utils/constants';
4-
import type { AndroidActivityCallbacks } from '../ui/frame/frame-common';
5-
import { CALLBACKS } from '../ui/frame/frame-constants';
4+
import { getActivityCallbacks } from '../ui/frame/activity-callbacks-store';
65
import { NativeWindow } from './native-window-common';
76
import type { WindowRole } from './window-base';
87

@@ -104,7 +103,7 @@ export class AndroidNativeWindow extends NativeWindow {
104103
throw new Error('NativeWindow: Activity is no longer available.');
105104
}
106105

107-
const callbacks: AndroidActivityCallbacks = (activity as any)[CALLBACKS];
106+
const callbacks = getActivityCallbacks(activity);
108107
if (!callbacks) {
109108
throw new Error('NativeWindow: Cannot find activity callbacks.');
110109
}

‎packages/core/ui/action-bar/index.android.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ export class NavigationButton extends ActionItem {}
145145

146146
export class ActionBar extends ActionBarBase {
147147
private _android: AndroidActionBarSettings;
148+
private _menuItemClickListener: androidx.appcompat.widget.Toolbar.OnMenuItemClickListener & { owner: WeakRef<ActionBar> };
148149
public nativeViewProtected: androidx.appcompat.widget.Toolbar;
149150

150151
constructor() {
@@ -176,12 +177,13 @@ export class ActionBar extends ActionBarBase {
176177
initializeMenuItemClickListener();
177178
const menuItemClickListener = new MenuItemClickListener(this);
178179
nativeView.setOnMenuItemClickListener(menuItemClickListener);
179-
(<any>nativeView).menuItemClickListener = menuItemClickListener;
180+
this._menuItemClickListener = <ActionBar['_menuItemClickListener']>menuItemClickListener;
180181
}
181182

182183
public disposeNativeView() {
183-
if ((<any>this.nativeViewProtected)?.menuItemClickListener) {
184-
(<any>this.nativeViewProtected).menuItemClickListener.owner = null;
184+
if (this._menuItemClickListener) {
185+
this._menuItemClickListener.owner = null;
186+
this._menuItemClickListener = null;
185187
}
186188
super.disposeNativeView();
187189
}

‎packages/core/ui/button/index.android.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ export class Button extends ButtonBase {
6363
nativeViewProtected: android.widget.Button;
6464

6565
private _stateListAnimator: any;
66+
private _clickListener: android.view.View.OnClickListener & { owner: WeakRef<Button> };
6667

6768
@profile
6869
public createNativeView() {
@@ -81,12 +82,13 @@ export class Button extends ButtonBase {
8182
initializeClickListener();
8283
const clickListener = new ClickListener(this);
8384
nativeView.setOnClickListener(clickListener);
84-
(<any>nativeView).clickListener = clickListener;
85+
this._clickListener = <Button['_clickListener']>clickListener;
8586
}
8687

8788
public disposeNativeView() {
88-
if ((<any>this.nativeViewProtected)?.clickListener) {
89-
(<any>this.nativeViewProtected).clickListener.owner = null;
89+
if (this._clickListener) {
90+
this._clickListener.owner = null;
91+
this._clickListener = null;
9092
}
9193
super.disposeNativeView();
9294
}

‎packages/core/ui/core/view-base/index.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1227,15 +1227,11 @@ export abstract class ViewBase extends Observable {
12271227
this._isPaddingRelative = nativeView.isPaddingRelative();
12281228
}
12291229

1230+
// Plugins whose native view is not an android.view.View pre-seed defaultPaddings.
12301231
let result: any /* android.graphics.Rect */ = DEFAULT_VIEW_PADDINGS.get(className) || (<any>nativeView).defaultPaddings;
12311232
if (result === undefined) {
1232-
DEFAULT_VIEW_PADDINGS.set(className, org.nativescript.widgets.ViewHelper.getPadding(nativeView));
1233-
(<any>nativeView).defaultPaddings = DEFAULT_VIEW_PADDINGS.get(className);
1234-
result = DEFAULT_VIEW_PADDINGS.get(className);
1235-
}
1236-
1237-
if (!nativeView.defaultPaddings) {
1238-
nativeView.defaultPaddings = DEFAULT_VIEW_PADDINGS.get(className);
1233+
result = org.nativescript.widgets.ViewHelper.getPadding(nativeView);
1234+
DEFAULT_VIEW_PADDINGS.set(className, result);
12391235
}
12401236

12411237
this._setDefaultPaddings(result);

‎packages/core/ui/core/view/index.android.ts‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import { AccessibilityLiveRegion, AccessibilityRole, AndroidAccessibilityEvent,
2525
import * as Utils from '../../../utils';
2626
import { SDK_VERSION } from '../../../utils/constants';
2727
import { BoxShadow } from '../../styling/box-shadow';
28-
import { NativeScriptAndroidView } from '../../utils';
2928

3029
export * from './view-common';
3130
// helpers (these are okay re-exported here)
@@ -618,9 +617,16 @@ export class View extends ViewCommon {
618617
private layoutChangeListener: android.view.View.OnLayoutChangeListener;
619618
private _rootManager: androidx.fragment.app.FragmentManager;
620619
private insetListenerIsSet: boolean;
620+
// undefined means not captured yet; null is a captured "no background".
621+
private _cachedDrawable: android.graphics.drawable.Drawable | null;
622+
private _cachedDrawableNativeView: android.view.View;
621623

622624
nativeViewProtected: android.view.View;
623625

626+
private _getCachedDrawable(nativeView: android.view.View): android.graphics.drawable.Drawable | null | undefined {
627+
return this._cachedDrawableNativeView === nativeView ? this._cachedDrawable : undefined;
628+
}
629+
624630
// TODO: Implement unobserve that detach the touchListener.
625631
_observe(type: GestureTypes, callback: (args: GestureEventData) => void, thisArg?: any): void {
626632
super._observe(type, callback, thisArg);
@@ -889,6 +895,8 @@ export class View extends ViewCommon {
889895
if (this.insetListenerIsSet) {
890896
this.clearInsetListener();
891897
}
898+
this._cachedDrawable = undefined;
899+
this._cachedDrawableNativeView = undefined;
892900
super.disposeNativeView();
893901
}
894902

@@ -1650,14 +1658,15 @@ export class View extends ViewCommon {
16501658
}
16511659

16521660
public _applyBackground(background: Background, isBorderDrawable: boolean, onlyColor: boolean, backgroundDrawable: android.graphics.drawable.Drawable) {
1653-
const nativeView = <NativeScriptAndroidView>this.nativeViewProtected;
1661+
const nativeView = this.nativeViewProtected;
1662+
const cachedDrawable = this._getCachedDrawable(nativeView);
16541663

16551664
if (onlyColor) {
16561665
const backgroundColor = background.color.android;
16571666

16581667
if (isBorderDrawable) {
16591668
// We need to duplicate the drawable or we lose the "default" cached drawable
1660-
backgroundDrawable = nativeView._cachedDrawable != null ? AndroidHelper.getCopyOrDrawable(nativeView._cachedDrawable, nativeView.getResources()) : null;
1669+
backgroundDrawable = cachedDrawable != null ? AndroidHelper.getCopyOrDrawable(cachedDrawable, nativeView.getResources()) : null;
16611670
nativeView.setBackground(backgroundDrawable);
16621671
}
16631672

@@ -1684,7 +1693,7 @@ export class View extends ViewCommon {
16841693

16851694
if (background.isEmpty()) {
16861695
// Reset background to default if not already set
1687-
const defaultDrawable = nativeView._cachedDrawable ?? null;
1696+
const defaultDrawable = cachedDrawable ?? null;
16881697
if (backgroundDrawable !== defaultDrawable) {
16891698
nativeView.setBackground(defaultDrawable);
16901699
}
@@ -1736,7 +1745,7 @@ export class View extends ViewCommon {
17361745
}
17371746

17381747
protected onBackgroundOrBorderPropertyChanged() {
1739-
const nativeView = <NativeScriptAndroidView>this.nativeViewProtected;
1748+
const nativeView = this.nativeViewProtected;
17401749
if (!nativeView) {
17411750
return;
17421751
}
@@ -1745,15 +1754,15 @@ export class View extends ViewCommon {
17451754
const drawable = nativeView.getBackground();
17461755
const isBorderDrawable = drawable instanceof org.nativescript.widgets.BorderDrawable;
17471756

1748-
// Use undefined as not set. getBackground will never return undefined only Drawable or null;
1749-
if (nativeView._cachedDrawable === undefined) {
1750-
nativeView._cachedDrawable = drawable;
1757+
if (this._cachedDrawableNativeView !== nativeView) {
1758+
this._cachedDrawableNativeView = nativeView;
1759+
this._cachedDrawable = drawable;
17511760
}
17521761

17531762
if (background.clearFlags & BackgroundClearFlags.CLEAR_BOX_SHADOW) {
17541763
// Clear background if we're clearing the box shadow
17551764
if (drawable instanceof org.nativescript.widgets.BoxShadowDrawable) {
1756-
nativeView.setBackground(nativeView._cachedDrawable ?? null);
1765+
nativeView.setBackground(this._cachedDrawable ?? null);
17571766
}
17581767
}
17591768

‎packages/core/ui/core/view/view-helper/index.android.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ export const IOSHelper = 0;
77

88
const androidxGraphics = androidx.core.graphics;
99

10+
// Colors applied through a color filter cannot be read back from the drawable.
11+
const drawableFilterColors = new WeakMap<android.graphics.drawable.Drawable, number>();
12+
1013
export class AndroidHelper {
1114
static getDrawableColor(drawable: android.graphics.drawable.Drawable): Color {
1215
if (!drawable) {
@@ -20,8 +23,7 @@ export class AndroidHelper {
2023
} else if (drawable instanceof android.graphics.drawable.ColorDrawable) {
2124
color = drawable.getColor();
2225
} else {
23-
// This is a way to retrieve drawable color when set using color filter
24-
color = (drawable as any)._backgroundColor;
26+
color = drawableFilterColors.get(drawable);
2527
}
2628

2729
return new Color(color);
@@ -33,9 +35,7 @@ export class AndroidHelper {
3335
drawable.setColor(color);
3436
} else {
3537
drawable.setColorFilter(androidxGraphics.BlendModeColorFilterCompat.createBlendModeColorFilterCompat(color, blendMode ?? androidxGraphics.BlendModeCompat.SRC_IN));
36-
37-
// This is a way to retrieve drawable color when set using color filter
38-
(drawable as any)._backgroundColor = color;
38+
drawableFilterColors.set(drawable, color);
3939
}
4040
}
4141

@@ -45,9 +45,7 @@ export class AndroidHelper {
4545
drawable.setColor(-1);
4646
} else {
4747
drawable.clearColorFilter();
48-
49-
// This is a way to retrieve drawable color when set using color filter
50-
delete (drawable as any)._backgroundColor;
48+
drawableFilterColors.delete(drawable);
5149
}
5250
}
5351

‎packages/core/ui/date-picker/index.android.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ function initializeDateChangedListener(): void {
5959
export class DatePicker extends DatePickerBase {
6060
nativeViewProtected: android.widget.DatePicker;
6161
timePicker: TimePicker;
62+
private _dateChangedListener: android.widget.DatePicker.OnDateChangedListener & { owner: DatePicker };
6263

6364
public createNativeView() {
6465
const picker = new android.widget.DatePicker(this._context);
@@ -73,7 +74,7 @@ export class DatePicker extends DatePickerBase {
7374
const nativeView = this.nativeViewProtected;
7475
const listener = new DateChangedListener(this);
7576
nativeView.init(this.year, this.month - 1, this.day, listener);
76-
(<any>nativeView).listener = listener;
77+
this._dateChangedListener = <DatePicker['_dateChangedListener']>listener;
7778
if (this.showTime) {
7879
this.timePicker = new TimePicker();
7980
this.timePicker.width = this.width;
@@ -89,8 +90,9 @@ export class DatePicker extends DatePickerBase {
8990
if (this.timePicker) {
9091
this.timePicker.disposeNativeView();
9192
}
92-
if ((<any>this.nativeViewProtected)?.listener) {
93-
(<any>this.nativeViewProtected).listener.owner = null;
93+
if (this._dateChangedListener) {
94+
this._dateChangedListener.owner = null;
95+
this._dateChangedListener = null;
9496
}
9597
super.disposeNativeView();
9698
}

‎packages/core/ui/editable-text-base/index.android.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
8888
private _dirtyTextAccumulator: string;
8989
private _keyListenerCache: android.text.method.KeyListener;
9090
private _inputType: number;
91+
private _editTextListeners: EditTextListeners & { owner: WeakRef<EditableTextBase> };
9192

9293
public _changeFromCode: boolean;
9394

@@ -110,18 +111,18 @@ export abstract class EditableTextBase extends EditableTextBaseCommon {
110111
editText.addTextChangedListener(listeners);
111112
editText.setOnFocusChangeListener(listeners);
112113
editText.setOnEditorActionListener(listeners);
113-
(<any>editText).listener = listeners;
114+
this._editTextListeners = <EditableTextBase['_editTextListeners']>listeners;
114115
this._inputType = editText.getInputType();
115116
}
116117

117118
public disposeNativeView(): void {
118119
const editText = this.nativeTextViewProtected;
119120

120-
editText.removeTextChangedListener((<any>editText).listener);
121+
editText.removeTextChangedListener(this._editTextListeners);
121122
editText.setOnFocusChangeListener(null);
122123
editText.setOnEditorActionListener(null);
123-
(<any>editText).listener.owner = null;
124-
(<any>editText).listener = null;
124+
this._editTextListeners.owner = null;
125+
this._editTextListeners = null;
125126
this._keyListenerCache = null;
126127
this._dirtyTextAccumulator = undefined;
127128
this._inputType = 0;

0 commit comments

Comments
 (0)