import { ISuperdesk , IExtension , IRestApiResponse } from 'superdesk-api' ; import { getAnnotationInputWithKnowledgeBase } from './AnnotationInputWithKnowledgeBase' ; import { getAnnotationsLibraryPage } from './annotations-library-page' ; import { getFields } from './GetFields' ; import { IKnowledgeBaseItem } from './interfaces' ; const RESOURCE = 'concept_items' ; function getAnnotationsInKnowledgeBase ( superdesk , annotationText ) { const { dataApi } = superdesk ; const { nameField } = getFields ( superdesk ) ; const { generateFilterForServer } = superdesk . forms ; return dataApi . query < IKnowledgeBaseItem > ( RESOURCE , 1 , { field : 'name' , direction : 'ascending' } , { name : generateFilterForServer ( nameField . type , annotationText ) } ) ; } function annotationExistsInKnowledgeBase ( superdesk , annotationText , definitionHtml ? ) { return getAnnotationsInKnowledgeBase ( superdesk , annotationText ) . then ( ( res ) => { if ( definitionHtml == null ) { return res . _items . length > 0 ; } const matches = res . _items . filter ( ( item ) => item . definition_html === definitionHtml ) ; return matches . length > 0 ; } ) ; } function annotationFromLibraryTabSelectedByDefault ( superdesk , annotationText , mode ) { const { assertNever } = superdesk . helpers ; if ( mode === 'edit' ) { return Promise . resolve ( false ) ; } else if ( mode === 'create' ) { return annotationExistsInKnowledgeBase ( superdesk , annotationText ) ; } else { return assertNever ( mode ) ; } } function onAnnotationCreate ( superdesk , language , annotationText , definitionHtml ) { annotationExistsInKnowledgeBase ( superdesk , annotationText , definitionHtml ) . then ( ( exists ) => { if ( ! exists ) { superdesk . dataApi . create ( RESOURCE , { language : language , name : annotationText , definition_html : definitionHtml , cpnat_type : 'cpnat:abstract' , } ) ; } } ) ; } var extension = { activate : ( superdesk ) => { const { gettext } = superdesk . localization ; return superdesk . privileges . getOwnPrivileges ( ) . then ( ( ) => ( { contributions : { editor3 : { annotationInputTabs : [ { label : gettext ( 'Annotations library' ) , component : getAnnotationInputWithKnowledgeBase ( superdesk ) , selectedByDefault : ( annotationText , mode ) => annotationFromLibraryTabSelectedByDefault ( superdesk , annotationText , mode ) , onAnnotationCreate : ( language , annotationText , definitionHtml ) => { return onAnnotationCreate ( superdesk , language , annotationText , definitionHtml ) ; } , } , ] , } , pages : superdesk . privileges . hasPrivilege ( 'concept_items' ) ? [ { title : gettext ( 'Annotations Library' ) , url : '/annotations-library' , component : getAnnotationsLibraryPage ( superdesk ) , privileges : [ 'concept_items' ] , } , ] : [ ] , } , } ) ) ; } , } ; export default extension ;