diff --git a/CourseEditorOperations.php b/CourseEditorOperations.php index 020f62b..9217f87 100644 --- a/CourseEditorOperations.php +++ b/CourseEditorOperations.php @@ -1,242 +1,228 @@ type) { case 'fromTopic': self::createNewCourseFromTopic($operation->params); break; case 'fromDepartment': self::createNewCourseFromDepartment($operation->params); break; } //FIXME Must be a serius return object and error handling return "ok"; } private function createCourseMetadata($topic, $title, $description){ $topic = ($topic === null ? $title : $topic); $pageTitle = MWNamespace::getCanonicalName(NS_COURSEMETADATA) . ':' . $title; $metadata = "
" . $topic . "
\r\n"; if($description !== '' && $description !== null){ $metadata .= "
" . $description . "
\r\n"; } $resultCreateMetadataPage = CourseEditorUtils::editWrapper($pageTitle, $metadata , null, null); //FIXME Return an object with results in order to display error to the user } private function createNewCourseFromDepartment($params){ $department = $params[0]; $title = $params[1]; $description = $params[2]; $namespace = $params[3]; if($department != null && $title != null && $namespace != null){ $compareResult = strcmp($namespace, 'NS_COURSE'); $namespaceCostant = ($compareResult == 0 ? NS_COURSE : NS_USER); $pageTitle = MWNamespace::getCanonicalName($namespaceCostant) . ':'; if($namespaceCostant == NS_USER){ self::createPrivateCourse($pageTitle, null, $title, $description); }else{ self::createPublicCourseFromDepartment($pageTitle, $department, $title, $description); } } } private function createNewCourseFromTopic($params){ $topic = $params[0]; $title = $params[1]; $description = $params[2]; $namespace = $params[3]; if($topic != null && $title != null && $namespace != null){ $compareResult = strcmp($namespace, 'NS_COURSE'); $namespaceCostant = ($compareResult === 0 ? NS_COURSE : NS_USER); $pageTitle = MWNamespace::getCanonicalName($namespaceCostant) . ':'; if($namespaceCostant == NS_USER){ self::createPrivateCourse($pageTitle, $topic, $title, $description); }else{ self::createPublicCourseFromTopic($pageTitle, $topic, $title, $description); } } } private function createPrivateCourse($pageTitle, $topic, $title, $description){ $context = CourseEditorUtils::getRequestContext(); $user = $context->getUser(); $userPage = $pageTitle . $user->getName(); $titleWithUser = $user->getName() . '/' . $title; $pageTitle = $userPage . "/" . $title; $resultCreateCourse = CourseEditorUtils::editWrapper($pageTitle, "{{CCourse}}", null, null); $resultCreateMetadataPage = self::createCourseMetadata($topic, $titleWithUser, $description); $textToPrepend = "{{Course|" . $title . "|" . $user->getName() . "}}"; $resultPrependToUserPage = CourseEditorUtils::editWrapper($userPage, null, $textToPrepend, null); //FIXME Return an object with results in order to display error to the user } private function createPublicCourseFromTopic($pageTitle, $topic, $title, $description){ $pageTitle .= $title; $resultCreateCourse = CourseEditorUtils::editWrapper($pageTitle, "{{CCourse}}", null, null); $topicCourses = CourseEditorUtils::getTopicCourses($topic); $text = $topicCourses . "{{Course|" . $title . "}}}}"; - /*if(sizeof($topicCourse) > 0){ - $text = $topicCourses[1][0] . "{{Course|" . $title; - }else { - $text = "{{Topic|" . "{{Course|" . $title; - } - if($description !== "" && $description !== null){ - $text .= "|" . $description . "}}}}"; - }else { - $text .= "}}}}"; - }*/ $resultCreateMetadataPage = self::createCourseMetadata($topic, $title, $description); $resultAppendToTopic = CourseEditorUtils::editWrapper($topic, $text, null, null); //FIXME Return an object with results in order to display error to the user } private function createPublicCourseFromDepartment($pageTitle, $department, $title, $description){ $pageTitle .= $title; $resultCreateCourse = CourseEditorUtils::editWrapper($pageTitle, "{{CCourse}}", null, null); $text = "{{Topic|" . "{{Course|" . $title . "}}}}"; - /*if($description !== "" && $description !== null){ - $text .= "|" . $description . "}}}}"; - }else { - $text .= "}}}}"; - }*/ $listElementText = "\r\n* [[" . $title . "]]"; $resultCreateMetadataPage = self::createCourseMetadata(null, $title, $description); $resultAppendToTopic = CourseEditorUtils::editWrapper($title, $text, null, null); $resultAppendToDepartment = CourseEditorUtils::editWrapper($department, null, null, $listElementText); //FIXME Return an object with results in order to display error to the user } public static function applyCourseOp($courseName, $operation){ $value = json_decode($operation); switch ($value->action) { case 'rename': $sectionName = $value->elementName; $newSectionName = $value->newElementName; $chapters = CourseEditorUtils::getChapters($courseName . '/' .$sectionName); $newSectionText = ""; foreach ($chapters as $chapter) { $newSectionText .= "* [[" . $courseName . "/" . $newSectionName . "/" . $chapter ."|". $chapter ."]]\r\n"; } $pageTitle = $courseName . "/" . $sectionName; $newPageTitle = $courseName . '/' . $newSectionName; $resultMove = CourseEditorUtils::moveWrapper($pageTitle, $newPageTitle); $resultEdit = CourseEditorUtils::editWrapper($newPageTitle, $newSectionText, null, null); $apiResult = array($resultMove, $resultEdit); CourseEditorUtils::setComposedOperationSuccess($value, $apiResult); break; case 'delete': $user = CourseEditorUtils::getRequestContext()->getUser(); $sectionName = $value->elementName; $chapters = CourseEditorUtils::getChapters($courseName . '/' . $sectionName); $title = Title::newFromText( $courseName . '/' . $sectionName, $defaultNamespace=NS_MAIN ); if(!$title->userCan('delete', $user, 'secure')){ $resultChapters = true; $pageTitle = $courseName . '/' . $sectionName; $prependText = "\r\n{{DeleteMe}}"; $resultSection = CourseEditorUtils::editWrapper($pageTitle, null, $prependText, null); foreach ($chapters as $chapter) { $pageTitle = $courseName . '/' . $sectionName . '/' . $chapter; $prependText = "\r\n{{DeleteMe}}"; $resultChapters = CourseEditorUtils::editWrapper($pageTitle, null, $prependText, null); } }else { $resultChapters = true; foreach ($chapters as $chapter) { $pageTitle = $courseName . '/' . $sectionName . '/' . $chapter; $resultChapters = CourseEditorUtils::deleteWrapper($pageTitle); } $pageTitle = $courseName . '/' . $sectionName; $resultSection = CourseEditorUtils::deleteWrapper($pageTitle); } $apiResult = array($resultSection, $resultChapters); CourseEditorUtils::setComposedOperationSuccess($value, $apiResult); break; case 'add': $sectionName = $value->elementName; $pageTitle = $courseName . '/' . $sectionName; $text = ""; $apiResult = CourseEditorUtils::editWrapper($pageTitle, $text, null, null); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; case 'update': - $newCourseText = "{{CCourse}}\r\n"; + $newCourseText = "{{CCourse|\r\n"; $newSectionsArray = json_decode($value->elementsList); foreach ($newSectionsArray as $section) { $newCourseText .= "{{SSection|" . $section ."}}\r\n"; } + $newCourseText .= "}}" $categories = CourseEditorUtils::getCategories($courseName); if(sizeof($categories) > 0){ foreach ($categories as $category) { $newCourseText .= "\r\n[[" . $category['title'] . "]]"; } } $apiResult = CourseEditorUtils::editWrapper($courseName, $newCourseText, null, null); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; } return json_encode($value); } public static function applySectionOp($sectionName, $operation){ $context = CourseEditorUtils::getRequestContext(); $value = json_decode($operation); switch ($value->action) { case 'rename': $chapterName = $value->elementName; $newChapterName = $value->newElementName; $from = $sectionName . '/' . $chapterName; $to = $sectionName . '/' . $newChapterName; $apiResult = CourseEditorUtils::moveWrapper($from, $to); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; case 'delete': $user = $context->getUser(); $chapterName = $value->elementName; $title = Title::newFromText($sectionName . '/' . $chapterName, $defaultNamespace=NS_MAIN); if(!$title->userCan('delete', $user, 'secure')){ $pageTitle = $sectionName . '/' . $chapterName; $prependText = "\r\n{{DeleteMe}}"; $apiResult = CourseEditorUtils::editWrapper($pageTitle, null, $prependText, null); }else { $pageTitle = $sectionName . '/' . $chapterName; $apiResult = CourseEditorUtils::deleteWrapper($pageTitle); } CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; case 'add': $chapterName = $value->elementName; $pageTitle = $sectionName . '/' . $chapterName; $text = ""; $apiResult = CourseEditorUtils::editWrapper($pageTitle, $text, null, null); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; case 'update': $newSectionText = ""; $newChaptersArray = json_decode($value->elementsList); foreach ($newChaptersArray as $chapter) { $newSectionText .= "* [[" . $sectionName . "/" . $chapter ."|". $chapter ."]]\r\n"; } $apiResult = CourseEditorUtils::editWrapper($sectionName, $newSectionText); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; case 'purge': $explodedString = explode("/", $sectionName); $pageToBePurged = (sizeof($explodedString) > 2 ? $explodedString[0] . "/" . $explodedString[1] : $explodedString[0]); $apiResult = CourseEditorUtils::purgeWrapper($pageToBePurged); CourseEditorUtils::setSingleOperationSuccess($value, $apiResult); break; } return json_encode($value); } } diff --git a/CourseEditorTemplates.php b/CourseEditorTemplates.php index 9177865..9b65428 100644 --- a/CourseEditorTemplates.php +++ b/CourseEditorTemplates.php @@ -1,137 +1,152 @@ data['section']; ?>

-
+
+
  


data['course']; ?>

+
+
  


data['topic']){ $topic = $this->data['topic']; ?>
data['department']){ $department = $this->data['department']; ?>
getContent( Revision::RAW ); $text = ContentHandler::getContentText( $content ); $textNoNewLines = trim(preg_replace('/\n+/', '', $text)); $regex = "/({{Topic|.+)}}.*$/"; preg_match_all($regex, $textNoNewLines, $matches, PREG_PATTERN_ORDER); return $matches[1][0]; } /** * This method is a workaround (read it HACK) to check the API results. * MediaWiki ApiResult object is not "standard" but if an error/exception * occurs the result variable is a string. */ public static function setSingleOperationSuccess(&$operation, $result){ $isSuccess = true; if (is_string($result)) { $isSuccess = false; } $operation->success = $isSuccess; } /** * This method is a workaround (read it HACK) to check the API results. * MediaWiki ApiResult object is not "standard" but if an error/exception * occurs the result variable is a string. */ public static function setComposedOperationSuccess(&$operation, $result){ $isSuccess = true; if (is_string($result[0]) || is_string($result[1])) { $isSuccess = false; } $operation->success = $isSuccess; } public static function getRequestContext(){ if(self::$requestContext == null) { $context = new RequestContext(); self::$requestContext = $context; } return self::$requestContext; } public static function getCategories($courseName){ try { $api = new ApiMain( new DerivativeRequest( self::getRequestContext()->getRequest(), array( 'action' => 'query', 'titles' => $courseName, 'prop' => 'categories' ) ), true ); $api->execute(); $results = $api->getResult()->getResultData(null, array('Strip' => 'all')); $page = reset($results['query']['pages']); return $page['categories']; } catch(UsageException $e){ return $e->getMessage(); } } public static function getChapters($sectionName){ $title = Title::newFromText($sectionName, $defaultNamespace=NS_MAIN ); $page = WikiPage::factory( $title ); $content = $page->getContent( Revision::RAW ); $text = ContentHandler::getContentText( $content ); $regex = "/\*\s*\[{2}([^|]*)\|?([^\]]*)\]{2}\s*/"; preg_match_all($regex, $text, $matches, PREG_PATTERN_ORDER); return $matches[2]; } public static function getSections($courseName){ $title = Title::newFromText( $courseName, $defaultNamespace=NS_MAIN ); $page = WikiPage::factory( $title ); $content = $page->getContent( Revision::RAW ); $text = ContentHandler::getContentText( $content ); $regex = "/\{{2}SSection\|(.*)\}{2}/"; preg_match_all($regex, $text, $matches, PREG_PATTERN_ORDER); return $matches[1]; } public static function deleteWrapper($title){ $context = self::getRequestContext(); try { $user = $context->getUser(); $token = $user->getEditToken(); $api = new ApiMain( new DerivativeRequest( $context->getRequest(), array( 'action' => 'delete', 'title' => $title, 'token' => $token ), true ), true ); $api->execute(); return $api->getResult()->getResultData(null, array('Strip' => 'all')); } catch(UsageException $e){ return $e->getMessage(); } } public static function purgeWrapper($titles){ $context = self::getRequestContext(); try { $api = new ApiMain( new DerivativeRequest( $context->getRequest(), array( 'action' => 'purge', 'titles' => $titles, 'forcerecursivelinkupdate' => true ), true ), true ); $api->execute(); return $api->getResult()->getResultData(null, array('Strip' => 'all')); } catch(UsageException $e){ return $e->getMessage(); } } public static function editWrapper($title, $text, $textToPrepend, $textToAppend){ $context = self::getRequestContext(); try { $user = $context->getUser(); $token = $user->getEditToken(); //$token = $this->getCsrfToken(); $api = new ApiMain( new DerivativeRequest( $context->getRequest(), array( 'action' => 'edit', 'title' => $title, 'text' => $text, // automatically override text 'prependtext' => $textToPrepend, // automatically override text 'appendtext' => $textToAppend, 'notminor' => true, 'token' => $token ), true ), true ); $api->execute(); return $api->getResult()->getResultData(null, array('Strip' => 'all')); } catch(UsageException $e){ return $e->getMessage(); } } public static function moveWrapper($from, $to){ $context = self::getRequestContext(); try { $user = $context->getUser(); $token = $user->getEditToken(); $api = new ApiMain( new DerivativeRequest( $context->getRequest(), array( 'action' => 'move', 'from' => $from, 'to' => $to, 'noredirect' => true, 'movetalk' => true, 'movesubpages' => true, 'token' => $token ), true ), true ); $api->execute(); return $api->getResult()->getResultData(null, array('Strip' => 'all')); } catch(UsageException $e){ return $e->getMessage(); } } - - public static function generateRandomCourseId(){ - $randomCourseId = ''; - $switchToChar = true; - $random = 0; - for ($i=0; $i < 6; $i++) { - $random = mt_rand(48, 57); - if($switchToChar){ - $random += 49; - $randomCourseId .= chr($random); - $switchToChar = false; - }else { - $randomCourseId .= chr($random); - $switchToChar = true; - } - } - return $randomCourseId; - } } diff --git a/i18n/en.json b/i18n/en.json index 9dce80a..c11bc53 100644 --- a/i18n/en.json +++ b/i18n/en.json @@ -1,36 +1,37 @@ { "courseeditor" : "Course editor", "courseeditor-add-new-section" : "Add a new section", "courseeditor-save-course": "Save course", "courseeditor-add-new-chapter" : "Add New Chapter", "courseeditor-save-section" : "Save Section", "courseeditor-cancel" : "Cancel", "courseeditor-edit-dialog" : "Edit", "courseeditor-rename" : "Rename", "courseeditor-organize-chapters" : "You can organize, add and delete chapters", "courseeditor-organize-sections" : "You can organize, add and delete sections", "courseeditor-input-department-label" : "Department:", "courseeditor-input-topic-label" : "Topic:", "courseeditor-input-course-label" : "Title:", "courseeditor-input-course-placeholder" : "Insert the title of the course", "courseeditor-input-description-label" : "Description:", "courseeditor-input-description-placeholder" : "Insert a description", "courseeditor-alert-message" : "Hey, there is a course with the same title yet!
Choose another title or start to contribute immediately to the existing course.", "courseeditor-validate-form" : "Please, insert a topic and a name", "courseeditor-radiobutton-namespace" : "Do you want to creatre a private course in your personal page or a public one?", "courseeditor-radiobutton-namespace-private" : "Private", "courseeditor-radiobutton-namespace-public" : "Public", "courseeditor-message-dialog-title" : "Oops...", "courseeditor-message-dialog-message" : "There's an element in the recycle bin with the same name, what do you want to do?", "courseeditor-message-dialog-cancel" : "Cancel", "courseeditor-message-dialog-restore" : "Restore", "courseeditor-message-dialog-create-new" : "Create new", + "courseeditor-alert-message-existing-element" : "There is already an element with the same name. Please, enter a different one.", "courseeditor-recycle-bin" : "Recycle bin", "courseeditor-error-operation" : "Sorry, something went wrong! :(
", "courseeditor-error-operation-action-add" : "Add", "courseeditor-error-operation-action-rename" : "Rename", "courseeditor-error-operation-action-delete" : "Delete", "courseeditor-error-operation-action-purge" : "Purge", "courseeditor-error-operation-action-update" : "Update", "courseeditor-error-operation-fail" : " fails!" } diff --git a/i18n/it.json b/i18n/it.json index a716909..aca5a5e 100644 --- a/i18n/it.json +++ b/i18n/it.json @@ -1,36 +1,37 @@ { "courseeditor" : "Editor di corsi", "courseeditor-add-new-section" : "Aggiungi una nuova sezione", "courseeditor-save-course": "Salva corso", "courseeditor-add-new-chapter" : "Aggiungi un nuovo capitolo", "courseeditor-save-section" : "Salva sezione", "courseeditor-cancel" : "Cancella", "courseeditor-edit-dialog" : "Modifica", "courseeditor-rename" : "Rinomina", "courseeditor-organize-chapters" : "Qui puoi organizzare, aggiungere e rimuovere capitoli", "courseeditor-organize-sections" : "Qui puoi organizzare, aggiungere e rimuovere sezioni", "courseeditor-input-department-label" : "Dipartmento:", "courseeditor-input-topic-label" : "Argomento:", "courseeditor-input-course-label" : "Titolo:", "courseeditor-input-course-placeholder" : "Inserisci il titolo del corso", "courseeditor-input-description-label" : "Descrizione:", "courseeditor-input-description-placeholder" : "Insersci la descrizione", "courseeditor-alert-message" : "Ehi, c'è un corso con lo stesso titolo!
Scegli un altro titolo o inizia a contribuire subito al corso esitente.
", "courseeditor-validate-form" : "Inserisci l'argomento e il corso!", "courseeditor-radiobutton-namespace" : "Vuoi creare un corso privato nella tua pagina personale o uno pubblico?", "courseeditor-radiobutton-namespace-private" : "Privato", "courseeditor-radiobutton-namespace-public" : "Pubblico", "courseeditor-message-dialog-title" : "Ops...", "courseeditor-message-dialog-message" : "C'è un elemento nel cestino con lo stesso nome, cosa vuoi fare?", "courseeditor-message-dialog-cancel" : "Indietro", "courseeditor-message-dialog-restore" : "Ripristina", "courseeditor-message-dialog-create-new" : "Crea nuovo", + "courseeditor-alert-message-existing-element" : "È già presente un elemento con lo stesso nome. Per favore, inserire un nome diverso.", "courseeditor-recycle-bin" : "Cestino", "courseeditor-error-operation" : "Scusa, qualcosa è andato storto! :(
", "courseeditor-error-operation-action-add" : "Aggiungi", "courseeditor-error-operation-action-rename" : "Rinomina ", "courseeditor-error-operation-action-delete" : "Elimina", "courseeditor-error-operation-action-purge" : "Purga", "courseeditor-error-operation-action-update" : "Aggiorna", "courseeditor-error-operation-fail" : " fallito!" } diff --git a/modules/commonFunctions.js b/modules/commonFunctions.js index 5081b40..bed3e44 100644 --- a/modules/commonFunctions.js +++ b/modules/commonFunctions.js @@ -1,319 +1,338 @@ /* Create a gloabal windowManager to open dialogs and append it to the body*/ var windowManager = new OO.ui.WindowManager(); $('body').append( windowManager.$element ); /******** UTIL METHODS ********/ /** * Init handlers * @param {DraggableGroupWidget} [draggableWidget] * @param {TextInputWidget} [textInputWidget] * @param {Array} [editStack] */ var initHandlers = function(draggableWidget, textInputWidget, editStack){ $('.deleteElementIcon').click(function(){ deleteElement(draggableWidget, $(this).parent().text(), editStack); }); $('.editElementIcon').click(function(){ editElement(draggableWidget, $(this).parent().text(), editStack); }); $('.oo-ui-inputWidget-input').attr('id', 'addElement'); $('#addElement').blur(function(){ + $('#alert').hide(); addElement(draggableWidget, textInputWidget.getValue(), editStack); textInputWidget.setValue(''); }); $('#addElement').keypress(function(keypressed) { if(keypressed.which === 13) { addElement(draggableWidget, textInputWidget.getValue(), editStack); textInputWidget.setValue(''); } }); }; /** * Find the index of a deleted element in the editStack * @param {String} [elementName] * @param {Array} [editStack] */ var findIndexOfDeletedElement = function(editStack, elementName) { for (var i = 0; i < editStack.length; i++) { if (editStack[i]['action'] === 'delete' && editStack[i]['elementName'] === elementName) { return i; } } return null; }; +/** + * Find the index of already added or renamed element in the editStack + * @param {String} [elementName] + * @param {DraggableWidget} [draggableWidget] + * @return boolean + */ +var elementExist = function(draggableWidget, elementName) { + var items = draggableWidget.getItems(); + for (var item in items) { + if (items[item].data === elementName) { + return true; + } + } + return false; +}; + /** * Create a drag item, its handlers on edit and remove icons and append it to * to the draggableWidget. * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var createDragItem = function(draggableWidget, elementName, editStack){ //Create item and icons var dragItem = new DraggableHandledItemWidget( { data: elementName, icon: 'menu', label: elementName } ); var iconDelete = $(""); var iconEdit = $(""); //Append icons and add the item to draggableWidget dragItem.$label.append(iconDelete, iconEdit); draggableWidget.addItems([dragItem]); //Create handlers $(iconDelete).click(function(){ deleteElement(draggableWidget, $(this).parent().text(), editStack); }); $(iconEdit).click(function(){ editElement(draggableWidget, $(this).parent().text(), editStack); }); }; /** * Create a button list group item, its handler on undo and append it to * to the RecycleBin list group. * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var createRecycleBinItem = function(draggableWidget, elementName, editStack){ //Create item and icon var liButton = $('
  •   ' + elementName +'
  • '); var undoDeleteIcon = $(''); //Append icon and add the item to the list liButton.prepend(undoDeleteIcon); $('.list-group').append(liButton); //Create handler $(undoDeleteIcon).click(function(){ var elementToRestore = $(this).parent().attr('id'); restoreElement(draggableWidget, elementToRestore, editStack); }); } /******** HELPER METHODS ********/ var dequeue = function(queueName){ $(document).dequeue(queueName); }; /** * Delete a element from the draggableWidget and add a item to the * RecycleBin list. * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var deleteElement = function(draggableWidget, elementName, editStack){ var elementToRemove = draggableWidget.getItemFromData(elementName); draggableWidget.removeItems([elementToRemove]); editStack.push({ action: 'delete', elementName: elementName }); createRecycleBinItem(draggableWidget, elementName, editStack); }; /** * Restore a element from the RecycleBin and remove its deletion * from the editStack * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var restoreElement = function(draggableWidget, elementName, editStack){ createDragItem(draggableWidget, elementName, editStack); editStack.splice(editStack.indexOf({action: 'delete', element: elementName})); $('li[id="' + elementName + '"]').remove(); }; /** * Add a element to the draggableWidget automatically if its name isn't * in the RecycleBin list, otherwise open a MessageDialog and ask to the user * if he/she prefer to restore the element or create a new one. * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var addElement = function(draggableWidget, elementName, editStack){ if($.trim(elementName).length !== 0){ - if(findIndexOfDeletedElement(editStack, elementName) === null){ - createDragItem(draggableWidget, elementName, editStack); - editStack.push({ - action: 'add', - elementName: elementName - }); - }else { + if(findIndexOfDeletedElement(editStack, elementName) !== null){ var messageDialog = new OO.ui.MessageDialog(); windowManager.addWindows( [ messageDialog ] ); windowManager.openWindow( messageDialog, { title: OO.ui.deferMsg('courseeditor-message-dialog-title'), message: OO.ui.deferMsg('courseeditor-message-dialog-message'), actions: [ { action: 'reject', label: OO.ui.deferMsg('courseeditor-message-dialog-cancel'), flags: 'safe' }, { action: 'restore', label: OO.ui.deferMsg('courseeditor-message-dialog-restore') }, { action: 'confirm', label: OO.ui.deferMsg('courseeditor-message-dialog-create-new'), flags: [ 'primary', 'constructive' ] } ] } ).then( function ( opened ) { opened.then( function ( closing, data ) { if ( data && data.action === 'restore' ) { restoreElement(draggableWidget, elementName, editStack); } else if(data && data.action === 'confirm') { createDragItem(draggableWidget, elementName, editStack); editStack.push({ action: 'add', elementName: elementName }); } } ); } ); + }else if (elementExist(draggableWidget, elementName)) { + $('#alert').show(); + }else { + createDragItem(draggableWidget, elementName, editStack); + editStack.push({ + action: 'add', + elementName: elementName + }); } } }; /** * Rename a element * @param {DraggableGroupWidget} [draggableWidget] * @param {String} [elementName] * @param {Array} [editStack] */ var editElement = function(draggableWidget, elementName, editStack){ var dialog = new EditDialog(draggableWidget, elementName, editStack); windowManager.addWindows( [ dialog ] ); windowManager.openWindow( dialog ); }; /******** OO.UI OBJECTS ********/ var progressBar = new OO.ui.ProgressBarWidget(); function ProgressDialog( config ) { ProgressDialog.parent.call( this, config ); }; OO.inheritClass( ProgressDialog, OO.ui.Dialog ); ProgressDialog.static.escapable = false; ProgressDialog.prototype.initialize = function () { ProgressDialog.parent.prototype.initialize.call( this ); this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); this.content.$element.append(progressBar.$element); this.$body.append( this.content.$element ); }; ProgressDialog.prototype.getBodyHeight = function () { return this.content.$element.outerHeight( true ); }; /****** Draggable Widget ******/ /** * Draggable group widget containing drag/drop items * * @param {Object} [config] Configuration options */ function DraggableGroupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor DraggableGroupWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.DraggableGroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); } /* Setup */ OO.inheritClass( DraggableGroupWidget, OO.ui.Widget ); OO.mixinClass( DraggableGroupWidget, OO.ui.mixin.DraggableGroupElement ); /** * Drag/drop items with custom handle * * @param {Object} [config] Configuration options */ function DraggableHandledItemWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor DraggableHandledItemWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.DraggableElement.call( this, $.extend( { $handle: this.$icon }, config ) ); } /* Setup */ OO.inheritClass( DraggableHandledItemWidget, OO.ui.DecoratedOptionWidget ); OO.mixinClass( DraggableHandledItemWidget, OO.ui.mixin.DraggableElement ); /****** Edit Dialog ******/ /* Create a dialog */ function EditDialog(draggableWidget, elementName, editStack, config ) { EditDialog.parent.call( this, config ); this.draggableWidget = draggableWidget; this.elementName = elementName; this.editStack = editStack; this.textInputWidget = new OO.ui.TextInputWidget($.extend( { validate: 'non-empty' }, config ) ); this.textInputWidget.setValue(elementName); } /* Inheritance */ OO.inheritClass( EditDialog, OO.ui.ProcessDialog ); /* Static Properties */ EditDialog.static.title = OO.ui.deferMsg( 'courseeditor-edit-dialog' ); EditDialog.static.actions = [ { action: 'save', label: OO.ui.deferMsg( 'courseeditor-rename' ), flags: 'primary' }, { label: OO.ui.deferMsg( 'courseeditor-cancel' ), flags: 'safe' } ]; /* Initialize the dialog elements */ EditDialog.prototype.initialize = function () { EditDialog.parent.prototype.initialize.apply( this, arguments ); this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); this.content.$element.append(this.textInputWidget.$element ); this.$body.append( this.content.$element ); }; /* Define actions */ EditDialog.prototype.getActionProcess = function ( action ) { var dialog = this; if ( action === 'save' ) { return new OO.ui.Process( function () { var newElementName = dialog.textInputWidget.getValue(); var items = dialog.draggableWidget.getItems(); items.filter(function(element) { if(element.data === dialog.elementName){ element.setData(newElementName); element.setLabel(newElementName); var iconDelete = $(""); var iconEdit = $(""); element.$label.append(iconDelete, iconEdit); $(iconDelete).click(function(){ deleteElement(dialog.draggableWidget, $(this).parent().text(), dialog.editStack); }); $(iconEdit).click(function(){ editElement(dialog.draggableWidget, $(this).parent().text(), dialog.editStack); }); dialog.editStack.push({ action: 'rename', elementName: dialog.elementName, newElementName: newElementName }) } }); dialog.close( { action: action } ); } ); } return EditDialog.parent.prototype.getActionProcess.call( this, action ); };