Extending Atlassian Confluence and JIRA with Speakeasy

    What for?





    Anyone who has ever been interested in the issue of “fitting” JIRA , Confluence, or another Atlassian product to himself knows that there is an Atlassian SDK for these purposes .



    And the one who delved into this SDK at least once imagines how much time and small gray boxes should be spent to get into all this, especially if there is no older comrade who is on the right path.




    It’s especially disappointing when, at the height of work on an important project, with a catastrophic lack of time, one of the clients asks to screw some small thing in Confluence or hide some link in JIRA. And clients have to be asked to wait, what they have a habit of being offended by. And the problem is aggravated by the fact that the client often has its own full-time programmers, who, unfortunately, cannot help with anything, because They don’t have knowledge in developing plug-ins for Atlassian products and this experience will not work in a couple of days.



    Apparently, the Atlassian guys also understand this, which is why they presented Speakeasy technology to users and administrators . The technology itself is no longer new - the presentation of its early beta was dedicated to Codegeist 2011 , a competition for plug-in developers, but only now it seems that more or less stable versions are coming out that you can be afraid to install in the production system.



    Speakeasy, unlike the Atlassian SDK, allows you to customize only what the user sees - change pages by adding JavaScript, markup or styles to them. But this is done much easier than using the SDK. The Firefox add-on Greasemonkey does something similar , but here we are not limited to one browser and do not force the user to install something else there specifically.



    Who needs this?


    Although it is tempting to call Speakeasy a mass technology that will allow any user to customize JIRA and Confluence, obviously this is not entirely true. In most cases (but not always) you will need basic JavaScript programming skills and HTML + CSS layouts. But for this you do not need to read the docks on the Atlassian SDK! And this, for a minute, hundreds of interesting and intriguing pages in English.



    Therefore, among the people who can get profit from Speakeasy, I would rank:


    • Developers, and even more so web developers. These people almost immediately, without any additional training, can start making extensions using Speakeasy.
    • Administrators Administrators, often also know how to program and will be able to make some kind of extension for their favorite users. And considering that when using Speakeasy, the users themselves decide whether to use any extension or not, we get a huge space for maneuvering between their mutually exclusive wishes.
    • Managers will no longer be sad after the developer’s phrase “Yes, I’ll do such a thing, but it will take two weeks to learn the SDK and I will conduct experiments for another month”, and with a clear (or almost clean) conscience they will say “You don’t need to learn anything! Go do it right away, dear! ”


    And immediately to the battle!


    Let's create some simple but useful extensions from scratch. All examples are for Confluence 3.5, as the latest version 4.0 has not yet gone so much to the people. But almost all of the following will be adequate for the 4th version. Accordingly, there will be no fundamental differences in the development of the extension for JIRA.



    Example 0, which is not an example at all - Installing Speakeasy


    For starters, you still need an administrator to install Speakeasy on the server and distribute the necessary rights.



    Fresh and not very versions of Speakeasy are distributed in Plugin Exchange and in the corresponding maven repository .



    After the plug-in is installed, you should decide which user groups will have the right to create their extensions, and which user groups will be able to include these extensions for themselves (Administration - Plugins - Manage Existing - Speakeasy Plugin - Configure).



    It should be noted separately that by default, the administrator is not allowed to include extensions on Speakeasy. This is obviously done for security reasons. But on the test system, the setting “Allow administrators to enable extensions” can be turned on.



    Example 1 - Historical


    In this example, we’ll add a link to the page’s history to a prominent place so as not to crawl behind it every time in the drop-down menu.



    We go to the page with Speakeasy extensions.




    Click the Install link and in the dialog that appears, select the use of the Wizard, and in the Wizard itself, enter a unique identifier for the extension, its name and description.




    After that, an extension with such “parameters” and standard test content will be created and installed. Using the “More - Edit” button, we find ourselves in a simple but useful web-editor where we can program a couple of lines of our extension.





    We are interested in the main.js file, because it should contain the main logic in JavaScript.



    /**
    * @context page
    */
    var $ = require('speakeasy/jquery').jQuery;
    $(document).ready(function() {
     var href = $('a#action-view-history-link').attr('href');
     $('a#view-change-link').after(", view history");
    });
    


    Writing such lines will not be difficult for anyone who knows JS and jQuery, but those who are not friends with JavaScript can write similar code using google. Separately, I only mention the entry "@context page" in the comments. It indicates in which contexts (read, page types) this script should be run. Now we are only interested in wiki pages, and a list of contexts can be found on this page .



    And here is what we get as a result:




    Example 2 - Informative


    Modifying something in the standard UI is great, and even better when we can fill the modified UI with some new information.



    For information, you can use all the features of JavaScript / JQuery - REST, SOAP, XML-RPC. The benefit of Confluence and JIRA such interfaces have .



    Let's try to use the simplest REST-interface, on which you can only get information about various entities from Confluence. We request the date the page was created to organically place it in the standard Confluence interface next to the date of the last editing.



    The code in this case looks like this:


    /**
    * @context page
    */
    var $ = require('speakeasy/jquery').jQuery;
    $(document).ready(function() {
     var pageId = $('input#pageId').attr('value');
     var serviceUrl = '/rest/prototype/1/content/' + pageId + '.json';
     $.getJSON( serviceUrl, function(data) {
       $('li.page-metadata-modification-info a:first').after(" on " + data.createdDate.friendly);
     });
    });
    


    And here is the modified UI:




    Because Since all the scripts work out when the page loads, the user does not notice any “flickers” like “there was no date and suddenly appeared”.



    Example 3 - Punctual


    Speakeasy extensions also include some Atlassian product-specific stuff. Among them is working with WebItem . In simple terms, you have the opportunity to add your menu items to the pages, next to the standard items.



    To do this, inside the extension is the web-items.json file, which describes the menu item you need. Let's go straight to the example:



    [
       {   "section" : "system.content.action/primary",
           "label"   : "Revert",
           "url"     : "",
           "cssName" : "stiltsoft-web-item",
           "weight"  : 25
       }
    ]
    


    This creates a new item called Revert in the Tools menu. The URL parameter can be set to the address you need, but I did a little trickier and did not set the URL, but added JavaScript logic to this item (see below).



    The item itself is needed to quickly roll back to the previous page revision, and the JavaScript code, accordingly, calculates the number of this revision:



    /**
    * @context atl.general
    */
    var $ = require('speakeasy/jquery').jQuery;
    $(document).ready(function() {
       var pageId = $('input#pageId').attr('value');
       var revision = $("meta[name='page-version']").attr('content');    
       $('a.revert-web-item').attr('href','/pages/revertpagebacktoversion.action?pageId='+pageId+'&version='+(revision-1));
    });
    


    This item looks like this:




    Example 4 - Interactive


    SpeakEasy developers didn’t forget about those who like to create beautiful interfaces. Speakeasy itself includes the ability to create a beautiful dialog, in the style of Confluence / JIRA itself, using the openOnePanelDialog method. This is how it looks in the code:



    /**
    * The main module
    *
    * @context atl.general
    */
    var $ = require('speakeasy/jquery').jQuery;
    var dialog = require('speakeasy/dialog');
    $(document).ready(function() {
       $('span#title-text').after("View source");
     $('a#stiltsoft-view-source').click(function(){
       var url=$('a#action-view-source-link').attr('href');
       $.get(url,function(data){
         dialog.openOnePanelDialog(
         {
           'header':'Page source',
           'content':$(data).find('div#content'),
           'submitLabel':'OK',
           'cancelClass':'stiltsoft-cancel',
           'submit':function(dialog,callback){
             callback.success();
           }
         });    
       }         
     );
       return false;
     });
    });
    


    Этот код добавляет к заголовку страницы ссылочку View Source, которая, собственно, и выводит красивый диалог с исходным кодом страницы. В расширении было еще немного магии с CSS, чтобы скрыть лишние кнопки диалога, но для примера это не самое важное.



    Примерно вот так, это выглядит на экране:




    Для тех, кому одного диалога не достаточно, стоит обратиться к библиотеке AUI (Atlassian User Interface). Это полностью клиентская JavaScript-библиотека, содержащая все те основные элементы (диалоги, попапы, выпадающие меню и т.п.), из которых собирается интерфейс продуктов Atlassian. Поэтому ваше расширение, использующее AUI, не будет отличаться по внешнему виду от остального интерфейса.



    Чтобы сразу “окунуться” в эту технологию, советую посетить AUI Demo, AUI Sandbox и немного поиграться с элементами там присутствующими.



    Пример 5 — Волшебный


    Самые ленивые из нас могут воспользоваться специальным Firefox-плагином (созданном на основе platypus), который позволяет визуально вносить изменения в страницу, а затем сохранять получившиеся изменения в виде SpeakEasy-расширения.



    И, конечно же, лучше один раз увидеть. Видео от разработчиков:




    Что дальше?


    Speakeasy technology continues to evolve, although, I must say, there is nothing supernatural in it. But there is a convenient and useful. Whether Speakeasy will become a “standard” technology for Atlassian products and whether it will go in standard delivery will show the time and activity of the writers' expansion. But this does not stop us from making our lives a little easier today :)


    Also popular now: