import { auto , IController } from 'angular' ; import React from 'react' ; import { render } from 'react-dom' ; import angular , { ICompileService } from 'angular' ; import { DocViewRenderProps , AngularScope , AngularDirective } from './doc_views_types' ; import { DocViewerError } from '../components/doc_viewer/doc_viewer_render_error' ; /**
 * Compiles and injects the give angular template into the given dom node
 * returns a function to cleanup the injected angular element
 */ export async function injectAngularElement ( domNode , template , scopeProps , Controller , getInjector ) { const $injector = await getInjector ( ) ; const rootScope = $injector . get ( '$rootScope' ) ; const $compile = $injector . get ( '$compile' ) ; const newScope = Object . assign ( rootScope . $new ( ) , scopeProps ) ; if ( typeof Controller === 'function' ) { ( newScope as any ) . $ctrl = $injector . instantiate ( Controller , { $scope : newScope , } ) ; } const $target = angular . element ( domNode ) ; const $element = angular . element ( template ) ; newScope . $apply ( ( ) => { const linkFn = $compile ( $element ) ; $target . empty ( ) . append ( $element ) ; linkFn ( newScope ) ; } ) ; return ( ) => { newScope . $destroy ( ) ; } ; } /**
 * Converts a given legacy angular directive to a render function
 * for usage in a react component. Note that the rendering is async
 */ export function convertDirectiveToRenderFn ( directive , getInjector ) { return ( domNode , props ) => { let rejected = false ; const cleanupFnPromise = injectAngularElement ( domNode , directive . template , props , directive . controller , getInjector ) ; cleanupFnPromise . catch ( ( e ) => { rejected = true ; render ( < DocViewerError error = { e } / > , domNode ) ; } ) ; return ( ) => { if ( ! rejected ) { cleanupFnPromise . then ( ( cleanup ) => cleanup ( ) ) ; } } ; } ; }