Developers Club geek daily blog

2 years, 11 months ago
Online compilation on the static website, the recipe for beginners
You wrote several years the project and now want to attract users? I have an idle time as barchelor fried eggs with bacon, the recipe especially for you.

For preparation of the simple website it is required to you:
  • repository on GitHub — 1 piece
  • ready html a template, for giving of a pleasant type — 1 piece
  • piece fresh kompilirushchegosya C ++ a code — at least 1 code line
  • ready javascript sauces from shop — ~ 500Kb
  • pictures and animashka to taste

Change any components, experiment and prepare the websites for favourite language!



We prepare a hosting


In this example for a hosting I will use GitHub. Yes, it allows not only to work with repositories, but also gives an opportunity to publish the websites for the project. Everything that needs to be made, it to create a branch of gh-pages and to zakommitit there the index.html file with the website:
# Прим: здесь и далее не забывайте заменять user на ваше имя в GitHub,
# а repository на имя вашего репозитория.

# Клонируем наш репозиторий в локальную папку:
git clone github.com/user/repository.git

# Создаем ветку gh-pages
cd repository
git checkout --orphan gh-pages

# Удаляем всё лишнее
git rm -rf .

# Создаём и коммитим index.html
echo "Test" > index.html
git add index.html
git commit -a -m "Testing gh-pages"

# Закидываем изменения обратно на GitHub
git push origin gh-pages

Now your page is available to the address http (s)://user.github.io/repository/. Certainly, at desire, you can select other hosting.

We decorate html dish with a statics


Online compilation on the static website, the recipe for beginners
It is a high time to fill the website with something useful. We find a template, pleasant for html eye, in the Internet and we shower it on our hosting.
# Закидываем наш html шаблон в репозиторий:
cp -rf ../folder_with_template/* ./

Cook cunnings
Selecting a template it is worth paying attention to at once whether it is displayed correctly on mobile devices. It becomes very simply: you change page scale (Ctrl + +). The template at a big scale has to look good and the horizontal scroll bar should not appear.

Now the most difficult and creative part of a dish. It is necessary to fill a ready template with contents, to add the description of the project, documentation and other useful things.

At the end, we do not forget everything to zakommitit and to send to GitHub:
git add *
git commit -m "Added some content"
git push


We prepare meat a code


For marinade we need jQuery and the Ace editor written on javascript. It is possible to do also without these components, or to replace them with something other. Personally I tried several editors and Ace.js seemed to me the most convenient and functional. From shortcomings at it big weight ~ 500Kb.

We select the town on the page where we will place online compilation. We add to the right place:
<div id="code">
    ... your code goes here ...
</div>

We do not forget to add CSS and loading of javascript:
<style type="text/css" media="screen">
    #code { 
         width: 100%;
         float:left;
         min-height:100px;
         overflow: hidden;
     }
</style>

<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/ace/ace.js"></script>

Now it is necessary to configure our editor:
<script>
    var code;
    
    $(function() {
        code = ace.edit("code");                      // созадем редактор из элемента с id="code"
        code.setTheme("ace/theme/textmate");          // выбираем тему оформления для подсветки синтаксиса
        code.getSession().setMode("ace/mode/c_cpp");  // говорим что код надо подсвечивать как C++ код
        code.setShowPrintMargin(false);               // опционально: убираем вертикальную границу в 80 сиволов
        code.setOptions({
            maxLines: Infinity,                       // опционально: масштабировать редактор вертикально по размеру кода
            fontSize: "12pt",                         // опционально: размер шрифта ставим побольше
        });
        code.$blockScrolling = Infinity;              // отключаем устаревшие, не поддерживаемые фишки редактора
    });
</script>

Cook cunnings
Always there is a wish to avoid situations of copying of a code from a repository on the page of documentation. If not to do it, then the chance that the code in a repository and on the page is desynchronized is big. Then on your wonderful page there will be an expired product, and users will begin to complain.

With GitHub it is rather simple to avoid it, the benefit it allows cross-origin resource sharing. That is you can request from the static page on http(s)://user.github.io/repository/resources, for example with raw.githubusercontent.com. Just add $blockScrolling code. following later = Infinity;
$.get("https://raw.githubusercontent.com/user/repository/master/" + "path_to_source_file_in_repo.cpp", function(data) {
    code.setValue(data);    // обновляем содержимое редактора полученными данными
    code.clearSelection();  // опционально: снимаем выделение строк в редакторе
});

The advanced culinary specialists can independently add error checking and an output of the corresponding message to the user.

As a result you have to see your code in the editor with beautiful syntax highlighting:
Online compilation on the static website, the recipe for beginners

We fry bacon a code


So, now we should add the button for compilation of a code and the place for a result output to our page:
<button id="run" onclick='run();'>Run</button> 

<p>Output:</p><pre id="output">Waiting...</pre>

About online compilation we will be helped by the Coliru service:
function run() {
    // Комманда для компиляции на удаленном сервере
    var cmd = "g++ -Wall main.cpp -o main_prog &&echo 'Compilation: SUCCESS."
        + " Program output is:\n' &&./main_prog &&echo \"\nExit code: $?\"";

    var output = $("#output");
    output.text('');
    var to_compile = {
        "src": code.getValue(),
        "cmd": cmd,
    };

    output.text("Executing... Please wait.");

    $.ajax({
        url: "http://coliru.stacked-crooked.com/compile",
        type: "POST",
        data: JSON.stringify(to_compile),
        contentType:"text/plain; charset=utf-8",
        dataType: "text"
    }).done(function(data) {
        output.text(data);
    }).fail(function(data) {
        output.text("Server error: " + data);
    });
};

Why Coliru was selected?
Services for online of compilation divorced quite a lot, but the majority of them has no external API, or this API is not documented. Coliru was the first service compilation online With ++ a code which at me earned.


We allow to try a dish to friends


There were finishing touches, cherry on our fried eggs our cake! If we started all this for involvement of users, then a reasonable step will be to add social buttons.

It is possible to use SocialLikes plug-in
<link rel="stylesheet" href="social-likes_flat.css">
<meta property="og:title" content="Your Title"/>
<meta property="og:image" content="Your logo"/>
<link rel="canonical" href="https://user.github.io/repository/">
<meta property="og:url" content="https://user.github.io/repository/"/>
<meta property="og:site_name" content="Your repository name"/>
<meta property="og:type" content="website"/>
<meta property="og:description" content="Your short description"/>
...
<script src="social-likes.min.js"></script>
...

<div class="social-likes right" data-counters="no">
    <div class="facebook" title="Share on Facebook">Facebook</div>
    <div class="twitter" title="Share on Twitter">Twitter</div>
    <div class="plusone" title="Share on Google+">Google+</div>
    <div class="vkontakte" title="Share on VK">VK</div>
    <div class="odnoklassniki" title="Share on Odnoklassniki">Odnoklassniki</div>
    <div class="mailru" title="Share on MyWorld">MyWorld</div>
</div>


It is ready! It was necessary to force to polaykat cunning and deception people you. For example to write to them: "Hi, Vasya. Whether check, please, social buttons work for me!".

Instead of a result


The turned-out dish can be modified on your taste. Instead of GitHub it is possible to use any services which were pleasant to you, Coliru is able to compile also About a code (it is possible that other languages are also supported). Services for online of compilation are available quite a lot if to look, then it is possible to find similar services and for your favourite language.

I hope this mini-recipe to someone it will be useful and will add interactivity to your projects.

The result in my case looks here so: apolukhin.github.io/Boost-Cookbook-4880OS

P.S.: If it is not difficult, check please whether social buttons work.

This article is a translation of the original post at habrahabr.ru/post/270141/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: sysmagazine.com@gmail.com.

We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus