import type ManagedObject from 'sap/ui/base/ManagedObject'; import type ElementOverlay from 'sap/ui/dt/ElementOverlay'; import FlexUtils from 'sap/ui/fl/Utils'; import type FlexCommand from 'sap/ui/rta/command/FlexCommand'; import type { Manifest } from 'sap/ui/rta/RuntimeAuthoring'; import RuntimeAuthoring from 'sap/ui/rta/RuntimeAuthoring'; import IsReuseComponentApi from 'sap/ui/rta/util/isReuseComponent'; import { getControlById } from '../utils/core'; import { getChangeDefinition, getFlexChangeList } from '../utils/changes.js'; import { isLowerThanMinimalUi5Version, Ui5VersionInfo } from '../utils/version.js'; export interface Deferred { promise: Promise; resolve: (value: T | PromiseLike) => void; reject: (reason?: unknown) => void; } export interface FragmentChange { content: { fragmentPath: string; }; } export type ReuseComponentChecker = (controlId: string) => boolean; let reuseComponentChecker: ReuseComponentChecker | undefined; /** * Resets the reuse component checker. */ export function resetReuseComponentChecker(): void { reuseComponentChecker = undefined; } /** * Defers the resolution of the promise, stores resolve/reject functions so that they can be accessed at a later stage. * * @description A Deferred object contains an unresolved promise along with the functions to resolve or reject that promise. * * @returns {Deferred} Deferred object */ export function createDeferred(): Deferred { let resolve: Deferred['resolve'] | null = null; let reject: Deferred['reject'] | null = null; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); if (resolve === null || reject === null) { throw new Error('Failed to initialize resolve and reject functions.'); } return { promise, resolve, reject }; } /** * Checks for the existence of a change associated with a specific fragment name in the RTA command stack. * * @param {RuntimeAuthoring} rta - The RuntimeAuthoring instance to check for existing changes. * @param {string} commandName - The name of the fragment to check for existing changes. * @param {string} propertyPath - The path to the property as string separated by dot in the change definition to check. * @param {string} propertyValue - The value to match against the specified property. * @returns {Promise} A promise that resolves to `true` if a matching change is found, otherwise `false`. */ export function checkForExistingChange( rta: RuntimeAuthoring, commandName: string, propertyPath: string, propertyValue: string ): boolean { const allCommands = rta.getCommandStack().getCommands(); return allCommands.some((command: FlexCommand) => { if (typeof command.getCommands === 'function') { const subCommand = command.getCommands().find((c: FlexCommand) => c?.getProperty('name') === commandName); return subCommand && matchesChangeProperty(subCommand, propertyPath, propertyValue); } else { return matchesChangeProperty(command, propertyPath, propertyValue); } }); } /** * Retrieves the value of a nested property from an object based on a dot-separated path. * * @param obj - The object from which to retrieve the nested property. * @param path - A dot-separated string representing the path to the desired property. * For example, "a.b.c" will attempt to access `obj.a.b.c`. * @returns The value of the nested property if it exists, or `undefined` if any part of the path is invalid. */ export function getNestedProperty(obj: object, path: string): unknown { return path.split('.').reduce((acc: unknown, key) => { return (acc as Record)?.[key]; }, obj); } /** * Checks if a specific property in the command's change matches the given value. * * @param {FlexCommand} command - The command object containing the prepared change to be examined. * @param {string} propertyPath - The path to the property in the change definition to check. * @param {string} propertyValue - The value to match against the specified property. * @returns {boolean} Returns true if the command's change contains the specified property with the matching value; otherwise, returns false. */ export function matchesChangeProperty(command: FlexCommand, propertyPath: string, propertyValue: string): boolean { return getFlexChangeList(command).some((change) => { const changeDefinition = getChangeDefinition(change); const nestedProperty = getNestedProperty(changeDefinition, propertyPath); return typeof nestedProperty === 'string' ? nestedProperty.includes(propertyValue) : false; }); } /** * Collects the `content.viewId` values of all pending `codeExt` changes in the RTA command stack for a * given controller. A base page controller extension has no `viewId` (yields `undefined`), while an * instance-specific extension yields the ID of the view it is bound to. * * @param {RuntimeAuthoring} rta - The RuntimeAuthoring instance to inspect. * @param {string} controllerName - The controller name to match against `selector.controllerName`. * @returns {(string | undefined)[]} The `content.viewId` of each matching pending codeExt change. */ export function getPendingCodeExtViewIds(rta: RuntimeAuthoring, controllerName: string): (string | undefined)[] { const allCommands = rta.getCommandStack().getCommands(); const viewIds: (string | undefined)[] = []; const collectFromCommand = (command: FlexCommand): void => { getFlexChangeList(command).forEach((change) => { const changeDefinition = getChangeDefinition(change); if (getNestedProperty(changeDefinition, 'changeType') !== 'codeExt') { return; } if (getNestedProperty(changeDefinition, 'selector.controllerName') !== controllerName) { return; } const viewId = getNestedProperty(changeDefinition, 'content.viewId'); viewIds.push(typeof viewId === 'string' ? viewId : undefined); }); }; allCommands.forEach((command: FlexCommand) => { if (typeof command.getCommands === 'function') { command.getCommands().forEach((subCommand: FlexCommand) => { if (subCommand?.getProperty('name') === 'codeExt') { collectFromCommand(subCommand); } }); } else { collectFromCommand(command); } }); return viewIds; } interface ControllerInfo { controllerName: string; viewId: string; } interface ViewLike { getId(): string; getControllerModuleName?(): string | undefined; getController?(): { getMetadata(): { getName(): string } } | undefined; getParent?(): ManagedObject | null; } /** * Resolves the controller name of a view, preferring the typed controller module name and falling * back to the controller instance's metadata name. Returns an empty string when the view owns no * controller. * * @param view The view for which to resolve the controller name. * @returns The controller name (`module:...` or class name), or an empty string when none is resolvable. */ function resolveControllerName(view: ViewLike): string { const moduleName = view?.getControllerModuleName?.(); return moduleName ? `module:${moduleName}` : view?.getController?.()?.getMetadata?.().getName() ?? ''; } /** * Gets controller name and view ID for the given UI5 control. * * @param control UI5 control. * @returns The controller name and view ID. */ export function getControllerInfoForControl(control: ManagedObject): ControllerInfo { let view = FlexUtils.getViewForControl(control) as ViewLike; let controllerName = resolveControllerName(view); while (!controllerName) { const parent = view?.getParent?.(); if (!parent) { break; } const parentView = FlexUtils.getViewForControl(parent) as ViewLike; if (!parentView || parentView === view) { break; } view = parentView; controllerName = resolveControllerName(view); } // viewId is intentionally the controller-bearing view's ID (which may be an ancestor of the // original view). The change file binds controllerName and viewId as a pair — returning the // innermost view's ID when it has no controller would create an inconsistent pair that the // server could never match. return { controllerName, viewId: view.getId() }; } /** * Gets controller name and view ID for the given overlay control. * * @param overlayControl The overlay control. * @returns The controller name and view ID. */ export function getControllerInfo(overlayControl: ElementOverlay): ControllerInfo { const control = overlayControl.getElement(); return getControllerInfoForControl(control); } /** * Gets the reuse component checker function. * * @param ui5VersionInfo UI5 version information. * @returns The reuse component checker function. */ export async function getReuseComponentChecker(ui5VersionInfo: Ui5VersionInfo): Promise { if (reuseComponentChecker) { return reuseComponentChecker; } let reuseComponentApi: typeof IsReuseComponentApi; if (!isLowerThanMinimalUi5Version(ui5VersionInfo, { major: 1, minor: 134 })) { reuseComponentApi = (await import('sap/ui/rta/util/isReuseComponent')).default; } reuseComponentChecker = function isReuseComponent(controlId: string): boolean { const ui5Control = getControlById(controlId); if (!ui5Control) { return false; } const component = FlexUtils.getComponentForControl(ui5Control); if (reuseComponentApi) { return reuseComponentApi(component); } if (!component) { return false; } const appComponent = FlexUtils.getAppComponentForControl(component); if (!appComponent) { return false; } const manifest = component.getManifest() as Manifest; const appManifest = appComponent.getManifest() as Manifest; const componentName = manifest?.['sap.app']?.id; // Look for component name in component usages of app component manifest const componentUsages = appManifest?.['sap.ui5']?.componentUsages; return Object.values(componentUsages || {}).some((componentUsage) => { return componentUsage.name === componentName; }); }; return reuseComponentChecker; }