@applicaster/zapp-react-native-utils 16.0.0-alpha.8101951023 → 16.0.0-alpha.8114431136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/actionUtils/index.ts +3 -1
  2. package/actionsExecutor/actions/__tests__/navigateToScreen.test.ts +139 -5
  3. package/actionsExecutor/actions/__tests__/openBottomSheet.customContent.test.ts +24 -0
  4. package/actionsExecutor/actions/__tests__/openBottomSheet.inlineItems.test.ts +88 -0
  5. package/actionsExecutor/actions/navigateToScreen.ts +29 -45
  6. package/actionsExecutor/actions/openBottomSheet.ts +15 -5
  7. package/appUtils/playerManager/OverlayObserver/__tests__/getUpcomingQueue.test.ts +67 -0
  8. package/appUtils/playerManager/OverlayObserver/getUpcomingQueue.ts +15 -2
  9. package/appUtils/playerManager/__tests__/playerNative.test.ts +76 -0
  10. package/appUtils/playerManager/__tests__/playerNativeCommand.test.ts +62 -0
  11. package/appUtils/playerManager/__tests__/playerToolbox.test.ts +97 -0
  12. package/appUtils/playerManager/__tests__/usePlayerControllerSetup.test.tsx +62 -0
  13. package/appUtils/playerManager/const.ts +13 -0
  14. package/appUtils/playerManager/index.ts +7 -0
  15. package/appUtils/playerManager/player.ts +10 -0
  16. package/appUtils/playerManager/playerNative.ts +22 -0
  17. package/appUtils/playerManager/playerNativeCommand.ts +3 -6
  18. package/appUtils/playerManager/playerToolbox.ts +157 -0
  19. package/appUtils/playerManager/usePlayerControllerSetup.tsx +6 -0
  20. package/arrayUtils/__tests__/reorderByIds.test.ts +13 -0
  21. package/arrayUtils/index.ts +26 -43
  22. package/configurationUtils/__tests__/modalBlocksParser.test.ts +123 -0
  23. package/configurationUtils/modalBlocksParser.ts +38 -0
  24. package/focusManager/FocusManager.ts +26 -0
  25. package/focusManager/__tests__/FocusManager.test.ts +9 -0
  26. package/logger/__tests__/xrayToolbox.test.ts +69 -0
  27. package/logger/xrayToolbox.ts +67 -0
  28. package/manifestUtils/keys.js +0 -1
  29. package/manifestUtils/mobileAction/groups/__tests__/buildMobileActionButtonGroups.test.js +1 -1
  30. package/manifestUtils/mobileAction/groups/defaults.js +1 -1
  31. package/modalState/ModalOrchestrator.ts +1 -0
  32. package/modalState/__tests__/ModalOrchestrator.phase3.test.ts +16 -0
  33. package/modalState/types.ts +2 -0
  34. package/navigationUtils/xrayNavigator.ts +12 -0
  35. package/package.json +2 -2
  36. package/reactHooks/connection/index.tsx +8 -5
  37. package/reactHooks/feed/__tests__/useMarkPipesDataStale.test.tsx +243 -0
  38. package/reactHooks/feed/useMarkPipesDataStale.ts +68 -23
  39. package/riverComponetsMeasurementProvider/index.tsx +3 -1
  40. package/uiActionsRegistrator/__tests__/subscribe.test.ts +26 -0
  41. package/uiActionsRegistrator/registry.ts +16 -0
@@ -0,0 +1,97 @@
1
+ const mockRegister = jest.fn();
2
+ let mockXray: Record<string, unknown> | null = {};
3
+
4
+ jest.mock("../../../logger", () => ({
5
+ getXray: () => mockXray,
6
+ }));
7
+
8
+ const loadToolbox = () => {
9
+ let module;
10
+
11
+ jest.isolateModules(() => {
12
+ module = require("../playerToolbox");
13
+ });
14
+
15
+ return module as typeof import("../playerToolbox");
16
+ };
17
+
18
+ const player = (overrides = {}) => ({
19
+ getSeekableDuration: () => 100,
20
+ getContentPosition: () => 40,
21
+ seekTo: jest.fn(),
22
+ ...overrides,
23
+ });
24
+
25
+ const manager = (active) =>
26
+ ({ getActivePlayer: () => active, isCasting: () => false }) as any;
27
+
28
+ const registeredTools = async (active) => {
29
+ mockRegister.mockResolvedValue(undefined);
30
+ mockXray = { registerReactToolbox: mockRegister };
31
+ await loadToolbox().registerPlayerToolbox(manager(active));
32
+
33
+ const { tools } = mockRegister.mock.calls[0][0];
34
+
35
+ return Object.fromEntries(tools.map((tool) => [tool.name, tool.handler]));
36
+ };
37
+
38
+ describe("playerToolbox", () => {
39
+ beforeEach(() => {
40
+ mockRegister.mockReset();
41
+ });
42
+
43
+ it("does nothing when X-Ray has no React toolbox API", async () => {
44
+ mockXray = {};
45
+
46
+ await expect(
47
+ loadToolbox().registerPlayerToolbox(manager(null))
48
+ ).resolves.toBe(false);
49
+ });
50
+
51
+ it("does nothing when getXray returns null", async () => {
52
+ mockXray = null;
53
+
54
+ await expect(
55
+ loadToolbox().registerPlayerToolbox(manager(null))
56
+ ).resolves.toBe(false);
57
+ });
58
+
59
+ it("swallows a failed registration", async () => {
60
+ mockRegister.mockRejectedValue(new Error("no native bridge"));
61
+ mockXray = { registerReactToolbox: mockRegister };
62
+
63
+ await expect(
64
+ loadToolbox().registerPlayerToolbox(manager(null))
65
+ ).resolves.toBe(false);
66
+ });
67
+
68
+ it("seeks to an absolute position, from the end when negative, clamped", async () => {
69
+ const active = player();
70
+ const tools = await registeredTools(active);
71
+
72
+ expect(tools.seek({ position: 30 })).toEqual({ position: 30 });
73
+ expect(tools.seek({ position: -10 })).toEqual({ position: 90 });
74
+ expect(tools.seek({ position: 500 })).toEqual({ position: 100 });
75
+ expect(tools.seek({ position: -500 })).toEqual({ position: 0 });
76
+ expect(active.seekTo.mock.calls).toEqual([[30], [90], [100], [0]]);
77
+ });
78
+
79
+ it("offsets from the current position and refuses zero", async () => {
80
+ const tools = await registeredTools(player());
81
+
82
+ expect(tools.offset({ seconds: 15 })).toEqual({ from: 40, position: 55 });
83
+ expect(tools.offset({ seconds: -60 })).toEqual({ from: 40, position: 0 });
84
+
85
+ expect(() => tools.offset({ seconds: 0 })).toThrow(
86
+ "Ignored zero relative seek"
87
+ );
88
+ });
89
+
90
+ it("refuses to seek a stream that is not seekable", async () => {
91
+ const tools = await registeredTools(
92
+ player({ getSeekableDuration: () => 0 })
93
+ );
94
+
95
+ expect(() => tools.seek({ position: 10 })).toThrow("Seek is not supported");
96
+ });
97
+ });
@@ -0,0 +1,62 @@
1
+ import { renderHook } from "@testing-library/react-native";
2
+
3
+ import { usePlayerControllerSetup } from "../usePlayerControllerSetup";
4
+ import { PlayerAnalyticsManager } from "../../../analyticsUtils/PlayerAnalyticsManager";
5
+
6
+ const calls: string[] = [];
7
+
8
+ jest.mock("../index", () => ({
9
+ playerManager: {
10
+ isPlayerRegistered: jest.fn(() => false),
11
+ registerPlayer: jest.fn(() => calls.push("registerPlayer")),
12
+ unregisterPlayer: jest.fn(),
13
+ },
14
+ }));
15
+
16
+ jest.mock("../../../analyticsUtils/PlayerAnalyticsManager", () => ({
17
+ PlayerAnalyticsManager: {
18
+ getInstance: jest.fn(() => calls.push("analyticsManager")),
19
+ },
20
+ }));
21
+
22
+ jest.mock("../../../reactHooks/useConfiguration", () => ({
23
+ useConfiguration: () => ({}),
24
+ }));
25
+
26
+ jest.mock("../../../playerUtils/useValidatePlayerConfig", () => ({
27
+ useValidatePlayerConfig: jest.fn(),
28
+ }));
29
+
30
+ jest.mock("../../../reactUtils", () => ({
31
+ isTV: () => false,
32
+ }));
33
+
34
+ jest.mock(
35
+ "@applicaster/zapp-react-native-ui-components/Helpers/Platform",
36
+ () => ({
37
+ isAppleTV: () => false,
38
+ })
39
+ );
40
+
41
+ class Controller {
42
+ destroy = jest.fn();
43
+ }
44
+
45
+ describe("usePlayerControllerSetup", () => {
46
+ it("creates the analytics manager before the player registers", () => {
47
+ renderHook(() =>
48
+ usePlayerControllerSetup({
49
+ props: { playerId: "player-1", entry: { id: "entry-1" } },
50
+ ControllerType: Controller,
51
+ ref: null,
52
+ manifest: {},
53
+ pluginId: "plugin",
54
+ })
55
+ );
56
+
57
+ // The manager attaches analytics to players as they register, so a player
58
+ // registered before it exists would send no player analytics events
59
+ expect(PlayerAnalyticsManager.getInstance).toHaveBeenCalled();
60
+ expect(calls).toEqual(["analyticsManager", "registerPlayer"]);
61
+ });
62
+ });
@@ -59,6 +59,19 @@ export enum SharedPlayerCallBacksKeys {
59
59
  // PIP
60
60
  OnPlayerDetached = "onPlayerDetached",
61
61
  OnPlayerAttached = "onPlayerAttached",
62
+
63
+ OnRemoteCommand = "onRemoteCommand",
64
+ }
65
+
66
+ // Ids native sends in onRemoteCommand (lock screen / Control Center / CarPlay buttons)
67
+ export enum RemoteCommand {
68
+ Play = "play",
69
+ Pause = "pause",
70
+ Stop = "stop",
71
+ NextTrack = "nextTrack",
72
+ PreviousTrack = "previousTrack",
73
+ SkipForward = "skipForward",
74
+ SkipBackward = "skipBackward",
62
75
  }
63
76
 
64
77
  export enum PlayerRole {
@@ -11,6 +11,7 @@ import {
11
11
  import { setUserLanguagePreference } from "./userLanguagePreference";
12
12
  import { PlayerRole } from "./const";
13
13
  import { RNPlayerManager } from "./nativePlayerManager";
14
+ import { registerPlayerToolbox } from "./playerToolbox";
14
15
 
15
16
  const { log_error, log_debug, log_warning } = createLogger({
16
17
  category: "General",
@@ -54,6 +55,7 @@ export class PlayerManager {
54
55
  public static getInstance() {
55
56
  if (!PlayerManager.instance) {
56
57
  PlayerManager.instance = new PlayerManager();
58
+ registerPlayerToolbox(PlayerManager.instance);
57
59
  }
58
60
 
59
61
  return PlayerManager.instance;
@@ -395,6 +397,11 @@ export class PlayerManager {
395
397
  return this.manager.removeHandler(event, handler);
396
398
  }
397
399
 
400
+ /** Whether anything handles `event` now, e.g. a mounted PlayerContainer for "toggleFullscreen". */
401
+ public hasHandler(event: string) {
402
+ return this.manager.handlers[event]?.length > 0;
403
+ }
404
+
398
405
  // TODO: should not be
399
406
  public invokeHandler(event, ...args) {
400
407
  return this.manager.invokeHandler(event, ...args);
@@ -746,6 +746,13 @@ export class Player {
746
746
  });
747
747
  };
748
748
 
749
+ onRemoteCommand = (event: QuickBrickPlayer.RemoteCommandEvent) => {
750
+ this.invokeListenersUpdate({
751
+ callbackName: SharedPlayerCallBacksKeys.OnRemoteCommand,
752
+ event,
753
+ });
754
+ };
755
+
749
756
  getTracksState = (): QuickBrickPlayer.TracksState =>
750
757
  this.playerState.trackState;
751
758
 
@@ -823,6 +830,8 @@ export class Player {
823
830
  // PIP
824
831
  onPlayerDetached: this.onPlayerDetached,
825
832
  onPlayerAttached: this.onPlayerAttached,
833
+
834
+ onRemoteCommand: this.onRemoteCommand,
826
835
  });
827
836
 
828
837
  play = () => {};
@@ -832,6 +841,7 @@ export class Player {
832
841
  setPlaybackRate = (_rate) => {};
833
842
  startSleepTimer = (_timestamp) => {};
834
843
  cancelSleepTimer = () => {};
844
+ command = (_command: string, _userInfo?: Record<string, any>) => {};
835
845
 
836
846
  getPluginConfiguration = () => null;
837
847
  appStateChange = (_appState, _previousAppState) => {};
@@ -6,6 +6,7 @@ import { findNodeHandle } from "react-native";
6
6
  import { PlayerRole } from "./const";
7
7
  import { toBooleanWithDefaultFalse } from "../../booleanUtils";
8
8
  import { RNPlayerManager } from "./nativePlayerManager";
9
+ import { isApplePlatform } from "../../reactUtils";
9
10
 
10
11
  const logger = createLogger({
11
12
  category: "PlayerNativeController",
@@ -27,6 +28,7 @@ interface PlayerMethods {
27
28
  appStateChange?: (appState: string, previousAppState: string) => void;
28
29
  closeNativePlayer?: () => void;
29
30
  togglePlayPause?: () => void;
31
+ command?: (command: string, userInfo?: Record<string, any>) => void;
30
32
  }
31
33
 
32
34
  type PlayerComponent = ReactComponent<PlayerRefProps> & PlayerMethods;
@@ -52,6 +54,7 @@ const PlayerModuleFuncNames = {
52
54
  startSleepTimer: "startSleepTimer",
53
55
  cancelSleepTimer: "cancelSleepTimer",
54
56
  getSleepTimerEnd: "getSleepTimerEnd",
57
+ command: "command",
55
58
  };
56
59
 
57
60
  export class PlayerNative extends Player {
@@ -206,6 +209,25 @@ export class PlayerNative extends Player {
206
209
  }
207
210
  };
208
211
 
212
+ command = (command: string, userInfo?: Record<string, any>) => {
213
+ if (isApplePlatform()) {
214
+ const module = this.getPlayerModule();
215
+ module?.command?.(command, this.playerId, userInfo);
216
+
217
+ return true;
218
+ }
219
+
220
+ if (
221
+ !this.invokeNativeFunction(
222
+ PlayerModuleFuncNames.command,
223
+ command,
224
+ userInfo
225
+ )
226
+ ) {
227
+ this.currentPlayerComponent()?.command?.(command, userInfo);
228
+ }
229
+ };
230
+
209
231
  disableBufferAnimation = (): boolean => false;
210
232
 
211
233
  selectTrack = (
@@ -1,14 +1,11 @@
1
1
  import { isApplePlatform } from "../../reactUtils";
2
2
  import { NativeModules } from "react-native";
3
3
 
4
- const NativePlayerModule = isApplePlatform()
5
- ? NativeModules.PlayerModule
6
- : NativeModules.QuickBrickDefaultPlayerModule;
7
-
8
4
  const PlayerNativeCommandTypes = {
9
5
  pause: "pause",
10
6
  clearPlayerData: "clearPlayerData",
11
7
  removeViewByNativeId: "removeViewByNativeId",
8
+ setPlayerControls: "setPlayerControls",
12
9
  };
13
10
 
14
11
  const PlayerNativeSendCommand = (
@@ -16,8 +13,8 @@ const PlayerNativeSendCommand = (
16
13
  playerId: string,
17
14
  userInfo?: Record<string, any>
18
15
  ) => {
19
- if (playerId && command) {
20
- NativePlayerModule?.command?.(command, playerId, userInfo);
16
+ if (isApplePlatform() && playerId && command) {
17
+ NativeModules.PlayerModule?.command?.(command, playerId, userInfo);
21
18
  }
22
19
  };
23
20
 
@@ -0,0 +1,157 @@
1
+ import { registerXrayToolbox, XrayToolSpec } from "../../logger/xrayToolbox";
2
+ import type { PlayerManager } from "./index";
3
+
4
+ /**
5
+ * X-Ray `player.*` toolbox: lets an agent read and drive the active player without screenshots.
6
+ * Registered by the PlayerManager singleton itself, so it exists wherever players do. Skipped
7
+ * when the installed X-Ray plugin has no React toolbox API.
8
+ *
9
+ * How the player is shown (video modal mode, mini player) is navigation state: see `nav.*`.
10
+ */
11
+
12
+ const toNumber = (value: unknown) =>
13
+ typeof value === "number" && Number.isFinite(value) ? value : null;
14
+
15
+ const clamp = (value: number, max: number) => Math.min(Math.max(value, 0), max);
16
+
17
+ /** The range a seek can reach: the DVR window on live, the content on VOD. */
18
+ const requireSeekable = (player: {
19
+ getSeekableDuration: () => number | undefined;
20
+ }) => {
21
+ const seekable = toNumber(player.getSeekableDuration());
22
+
23
+ if (!seekable) throw new Error("Seek is not supported");
24
+
25
+ return seekable;
26
+ };
27
+
28
+ const tools = (manager: PlayerManager): XrayToolSpec[] => {
29
+ const requirePlayer = () => {
30
+ const player = manager.getActivePlayer();
31
+
32
+ if (!player) throw new Error("No active player");
33
+
34
+ return player;
35
+ };
36
+
37
+ return [
38
+ {
39
+ name: "state",
40
+ description:
41
+ "The active player: entry, position and duration in seconds, playing/buffering/ad/live/muted, " +
42
+ "role (Primary, Cell, Chromecast) and casting. active: false when nothing plays.",
43
+ handler: () => {
44
+ const player = manager.getActivePlayer();
45
+
46
+ if (!player) return { active: false, casting: manager.isCasting() };
47
+
48
+ const entry = player.getEntry();
49
+
50
+ return {
51
+ active: true,
52
+ playerId: player.playerId,
53
+ entry: entry ? { id: entry.id, title: entry.title } : null,
54
+ position: toNumber(player.getPosition()),
55
+ duration: toNumber(player.getDuration()),
56
+ // isPlaying() only means "not paused", which is also true before the stream starts.
57
+ playing: !!player.isReadyToPlay() && player.isPlaying(),
58
+ buffering: !!player.isBuffering(),
59
+ readyToPlay: !!player.isReadyToPlay(),
60
+ ad: player.isAd(),
61
+ live: !!player.isLive(),
62
+ muted: !!player.getIsMuted(),
63
+ role: player.playerRole,
64
+ casting: manager.isCasting(),
65
+ };
66
+ },
67
+ },
68
+ {
69
+ name: "play",
70
+ description: "Resume the active player.",
71
+ handler: () => {
72
+ requirePlayer().play();
73
+
74
+ return "OK";
75
+ },
76
+ },
77
+ {
78
+ name: "pause",
79
+ description: "Pause the active player.",
80
+ handler: () => {
81
+ requirePlayer().pause();
82
+
83
+ return "OK";
84
+ },
85
+ },
86
+ {
87
+ name: "seek",
88
+ description:
89
+ "Seek to an absolute position, as the player's console command does: seconds from the start, " +
90
+ "or from the end when negative. Clamped to the seekable range. Where it lands can differ: " +
91
+ "server-side ads snap back to the break before the target; read player.state afterwards.",
92
+ parameters: [
93
+ {
94
+ name: "position",
95
+ type: "number",
96
+ description:
97
+ "Seconds from the start; negative values count back from the end.",
98
+ },
99
+ ],
100
+ handler: ({ position }) => {
101
+ const player = requirePlayer();
102
+ const seconds = toNumber(position);
103
+
104
+ if (seconds === null) {
105
+ throw new Error("'position' must be a number of seconds");
106
+ }
107
+
108
+ const seekable = requireSeekable(player);
109
+
110
+ const target =
111
+ seconds >= 0
112
+ ? Math.min(seconds, seekable)
113
+ : clamp(seekable + seconds, seekable);
114
+
115
+ player.seekTo(target);
116
+
117
+ return { position: target };
118
+ },
119
+ },
120
+ {
121
+ name: "offset",
122
+ description:
123
+ "Seek relative to the current position, as the player's console command does: positive " +
124
+ "forward, negative back. Clamped to the seekable range.",
125
+ parameters: [
126
+ {
127
+ name: "seconds",
128
+ type: "number",
129
+ description: "Seconds to move: positive forward, negative back.",
130
+ },
131
+ ],
132
+ handler: ({ seconds }) => {
133
+ const player = requirePlayer();
134
+ const delta = toNumber(seconds);
135
+
136
+ if (delta === null) throw new Error("'seconds' must be a number");
137
+
138
+ if (delta === 0) throw new Error("Ignored zero relative seek");
139
+
140
+ const seekable = requireSeekable(player);
141
+ const from = toNumber(player.getContentPosition()) ?? 0;
142
+ const target = clamp(from + delta, seekable);
143
+
144
+ player.seekTo(target);
145
+
146
+ return { from, position: target };
147
+ },
148
+ },
149
+ ];
150
+ };
151
+
152
+ export const registerPlayerToolbox = (manager: PlayerManager) =>
153
+ registerXrayToolbox({
154
+ name: "player",
155
+ description: "Inspect and control the active player.",
156
+ tools: tools(manager),
157
+ });
@@ -8,6 +8,7 @@ import { isAppleTV } from "@applicaster/zapp-react-native-ui-components/Helpers/
8
8
  import { TVSeekController } from "../../reactHooks/player/TVSeekControlller/TVSeekController";
9
9
  import { KeyInputHandler } from "../keyInputHandler/KeyInputHandler";
10
10
  import { isTV } from "../../reactUtils";
11
+ import { PlayerAnalyticsManager } from "../../analyticsUtils/PlayerAnalyticsManager";
11
12
 
12
13
  // TODO: Rename to ControllerType
13
14
  export const usePlayerControllerSetup = ({
@@ -68,6 +69,11 @@ export const usePlayerControllerSetup = ({
68
69
  return;
69
70
  }
70
71
 
72
+ // The analytics manager attaches its listener when a player registers, so it
73
+ // must exist first; on web the Player wrapper that also creates it renders
74
+ // only after the lazily loaded engine chunk, i.e. after registration.
75
+ PlayerAnalyticsManager.getInstance();
76
+
71
77
  playerManager.registerPlayer({
72
78
  id: playerId,
73
79
  playerController,
@@ -47,4 +47,17 @@ describe("reorderByIds", () => {
47
47
 
48
48
  expect(result.map((i) => i.key)).toEqual(["c", "b", "a"]);
49
49
  });
50
+
51
+ it("reorders duplicate items when using unique slot identifiers via getId", () => {
52
+ const duplicateItems = [
53
+ { id: "x", slot: "s1", name: "First X" },
54
+ { id: "y", slot: "s2", name: "Y" },
55
+ { id: "x", slot: "s3", name: "Second X" },
56
+ ];
57
+
58
+ const result = reorderByIds(duplicateItems, ["s3", "s1"], (i) => i.slot);
59
+
60
+ expect(result).toHaveLength(3);
61
+ expect(result.map((i) => i.name)).toEqual(["Second X", "Y", "First X"]);
62
+ });
50
63
  });
@@ -167,7 +167,7 @@ export const anyTruthy = (xs: boolean[]) => xs.some(Boolean);
167
167
  export function reorderByIds<T>(
168
168
  items: T[],
169
169
  orderedIds: string[],
170
- getId: (item: T) => string | string[] = (item: any) => item?.id
170
+ getId: (item: T) => string = (item: any) => item?.id
171
171
  ): T[] {
172
172
  if (!items || items.length === 0) return [];
173
173
  if (!orderedIds || orderedIds.length === 0) return [...items];
@@ -175,14 +175,16 @@ export function reorderByIds<T>(
175
175
  const itemMap = new Map<string, T>();
176
176
 
177
177
  items.forEach((item) => {
178
- const rawId = getId(item);
179
- const keys = Array.isArray(rawId) ? rawId : [rawId];
180
-
181
- keys.forEach((key) => {
182
- if (key !== undefined && key !== null && key !== "") {
183
- itemMap.set(String(key), item);
184
- }
185
- });
178
+ const id = getId(item);
179
+
180
+ if (
181
+ id !== undefined &&
182
+ id !== null &&
183
+ id !== "" &&
184
+ !itemMap.has(String(id))
185
+ ) {
186
+ itemMap.set(String(id), item);
187
+ }
186
188
  });
187
189
 
188
190
  const reorderedSubset: T[] = [];
@@ -192,48 +194,29 @@ export function reorderByIds<T>(
192
194
  const strId = String(id);
193
195
  const item = itemMap.get(strId);
194
196
 
195
- if (item && !reorderedSubset.includes(item)) {
197
+ if (item && !orderedIdsSet.has(strId)) {
196
198
  reorderedSubset.push(item);
197
- const rawId = getId(item);
198
- const keys = Array.isArray(rawId) ? rawId : [rawId];
199
-
200
- keys.forEach((k) => {
201
- if (k !== undefined && k !== null && k !== "") {
202
- orderedIdsSet.add(String(k));
203
- }
204
- });
199
+ orderedIdsSet.add(strId);
205
200
  }
206
201
  });
207
202
 
208
203
  if (reorderedSubset.length === 0) return [...items];
209
204
 
210
205
  let subsetIdx = 0;
211
- const result: T[] = [];
212
-
213
- items.forEach((item) => {
214
- const rawId = getId(item);
215
- const keys = Array.isArray(rawId) ? rawId : [rawId];
216
-
217
- const isMatched = keys.some(
218
- (k) =>
219
- k !== undefined &&
220
- k !== null &&
221
- k !== "" &&
222
- orderedIdsSet.has(String(k))
223
- );
224
206
 
225
- if (isMatched) {
226
- if (subsetIdx < reorderedSubset.length) {
227
- result.push(reorderedSubset[subsetIdx++]);
228
- }
229
- } else {
230
- result.push(item);
207
+ return items.map((item) => {
208
+ const id = getId(item);
209
+
210
+ if (
211
+ id !== undefined &&
212
+ id !== null &&
213
+ id !== "" &&
214
+ orderedIdsSet.has(String(id)) &&
215
+ subsetIdx < reorderedSubset.length
216
+ ) {
217
+ return reorderedSubset[subsetIdx++];
231
218
  }
232
- });
233
-
234
- while (subsetIdx < reorderedSubset.length) {
235
- result.push(reorderedSubset[subsetIdx++]);
236
- }
237
219
 
238
- return result;
220
+ return item;
221
+ });
239
222
  }