<commit_before>(function () {
    'use strict';

    angular
        .module('app')
        .factory('QuestionService', QuestionService);

    QuestionService.$inject = ['$timeout', '$filter', '$q'];

    function QuestionService($timeout, $filter, $q) {

        var service = {};

        service.GetAll = GetAll;
        service.GetByCategory = GetByCategory;

        function GetAll(){
            return [
                    {
                        name: 'Lifestyle'
                        questions: [
                            {
                                text: 'What do you do to stop your roommates eating your food?',
                                answers: [
                                    {text: 'Write your name on all your food, right down to individual yogurts.', points: 1},
                                    {text: 'Bring it up in conversation.', points: 2},
                                    {text: 'Lick it all. Lick everything. But don’t tell them.', points: 3},
                                    {text: 'Start eating their food.', points: 4}
                                ]
                            },
                            {
                                text: 'Someone is using your Wi-Fi instead of paying for their own. What do you do?',
                                answers: [
                                    {text: 'Let it go. Life’s too short.', points: 1},
                                    {text: 'Change the network name to “Not Your Wi-Fi” to drop them a hint.', points: 2},
                                    {text: 'Keep changing the password so they can’t keep logging in.', points: 3},
                                    {text: 'Get rid of it all together, and go live in the woods.', points: 4}
                                ]
                            },
                            {
                                text: 'Someone in front of you at the cinema is rocking their chair back and forth, annoying you. How do you deal with it?',
                                answers : [
                                    {text: 'Move seats.', points: 1},
                                    {text: 'Ask them to stop.', points: 2},
                                    {text: 'Keep kicking the back of their seat until they get the message.', points: 3},
                                    {text: 'Kick them in the head.', points: 4}
                                ]
                            },
                            {
                                text: 'Someone near you is chewing loudly. What do you do?',
                                answers : [
                                    {text: 'Nothing, but secretly start hating them.', points: 1},
                                    {text: 'Send them an email that uses the word ‘sorry,’ multiple times.', points: 2},
                                    {text: 'Ask them to be quieter.', points: 3},
                                    {text: 'Chew louder until they get the message.', points: 4},
                                    {text: 'Loudly play a YouTube video of someone chewing loudly.', points: 5},
                                    {text: 'Throw things at them.', points: 6}
                                ]
                            },
                            {
                                text: 'If you\'re in an argument, what\'s your go-to ending line?',
                                answers : [
                                    {text: '"You know what, I think you\'re right."', points: 1},
                                    {text: '"Let\'s sit down and talk this through"', points: 2},
                                    {text: 'No line, you go straight for the silent treatment.', points: 3},
                                    {text: '"Fine, I don\'t care!"', points: 4},
                                    {text: '"You\'d better comply, or else..."', points: 5}
                                ]
                            }
                        ]
                    },
                    {
                        name: 'Personality',
                        questions: [
                            {
                                text: 'You arrive at a house party but no one you know is there yet. What do you do?',
                                answers: [
                                    {text: 'Get the hell out of there and try again later', points: 1},
                                    {text: 'Go and hide in the toilet and text your friend telling them to get there urgently', points: 2},
                                    {text: 'Try to make yourself invisible by standing in the corner and staring at your phone', points: 3},
                                    {text: 'Loiter near the snack table and hope someone starts up a conversation with you', points: 4},
                                    {text: 'See if you can find the host and introduce yourself – it\'s only polite', points: 5},
                                    {text: 'Grab a drink and go and join a conversation – new friends aren\'t going to make themselves!', points: 6}
                                ]
                            },
                            {
                                text: 'Your phone rings but you don\'t recognise the number, what do you do?',
                                answers: [
                                    {text: 'Throw your phone into a river and emigrate to Peru', points: 1},
                                    {text: 'Let it ring out, there\'s no way you\'re speaking to some stranger', points: 2},
                                    {text: 'Quickly google the number to try and find out who it could be', points: 3},
                                    {text: 'Pick up, but only if you aren\'t doing anything', points: 4},
                                    {text: 'Pick it up, obviously – it might be important', points: 5}
                                ]
                            },
                            {
                                text: 'Your colleagues are having a light-hearted conversation round the table at the pub. You are...',
                                answers: [
                                    {text: 'At home watching Netflix on the sofa', points: 1},
                                    {text: 'Listening and feeling a little awkward, but not feeling confident enough to talk much', points: 2},
                                    {text: 'Talking when you feel comfortable, but mostly listening from the fringes', points: 3},
                                    {text: 'Chipping in with jokes quite often and taking control of the conversation when you can', points: 4},
                                    {text: 'Leading the conversation, and probably making people laugh in the process', points: 5}
                                ]
                            },
                            {
                                text: 'How do you like to spend your week nights?',
                                answers: [
                                    {text: 'At home relaxing, watching TV, on the internet or with a good book', points: 1},
                                    {text: 'It totally depends how I feel, some weeks I\'ll be really busy, others I just want to chill', points: 2},
                                    {text: 'I like to go out and see people once or twice a week when I can', points: 3},
                                    {text: 'I like to make as many plans as possible, being alone is boring', points: 4},
                                    {text: 'I go along with most plans because of my crippling fear of missing out', points: 5}
                                ]
                            },
                            {
                                text: 'How do you feel when making small talk?',
                                answers: [
                                    {text: 'Always extremely worried of what the other person thinks of me', points: 1},
                                    {text: 'A bit awkward, but I cope fine – it\'s a part of life', points: 2},
                                    {text: 'It always feels a little pointless, but it\'s not the worst thing in the world', points: 3},
                                    {text: 'It\'s OK, but I prefer to listen than to talk about myself', points: 4},
                                    {text: 'Great – it\'s always fun to get to know new people', points: 5}
                                ]
                            },
                        ]
                    },
                    {
                        name    : 'Nature',
                        questions: [
                            {
                                text: 'You go out to dinner with a friend. What are you ordering?',
                                answers: [
                                    {text: 'Whatever is the cheapest', points: 1},
                                    {text: 'Whatever seems to be the most nutritionally balanced', points: 2},
                                    {text: 'Something different from my friend, so we can share', points: 3},
                                    {text: 'Something I know I will like', points: 4},
                                    {text: 'Something I have never tried before', points: 5},
                                    {text: 'Whatever is the tastiest', points: 6}
                                ]
                            },
                            {
                                text: 'You get a flat tire on the highway. What is the very first thing you do?',
                                answers: [
                                    {text: 'Check for a spare', points: 1},
                                    {text: 'Google "how to change a tire"', points: 2},
                                    {text: 'Call a tow truck', points: 3},
                                    {text: 'Call a friend or family member for support', points: 4},
                                    {text: 'Punch the steering wheel', points: 5},
                                    {text: 'Scream', points: 6}
                                ]
                            },
                            {
                                text: 'Everyone should decide their college major based on...',
                                answers: [
                                    {text: 'Whatever opens up the most doors career-wise', points: 1},
                                    {text: 'Whatever ensures the most financial security', points: 2},
                                    {text: 'Their family\'s advice', points: 3},
                                    {text: 'Whatever leads to a job they will love', points: 4},
                                    {text: 'Whatever allows them to feel fulfilled', points: 5},
                                    {text: 'Whatever feels right', points: 6}
                                ]
                            },
                            {
                                text: 'What is the foundation of a solid romantic relationship?',
                                answers: [
                                    {text: 'Shared interests', points: 1},
                                    {text: 'Horoscope compatibility', points: 2},
                                    {text: 'Communication', points: 3},
                                    {text: 'Trust', points: 4},
                                    {text: 'Respect', points: 5},
                                    {text: 'Chemistry', points: 6}
                                ]
                            },
                            {
                                text: 'What version of yourself would you hate to see 10 years from now?',
                                answers: [
                                    {text: 'Someone financially struggling', points: 1},
                                    {text: 'Someone with no goals and no direction', points: 2},
                                    {text: 'Someone who works constantly with no time for themselves', points: 3},
                                    {text: 'Someone in the place I am now', points: 4},
                                    {text: 'Someone chronically dissatisfied with what they\'re doing', points: 5},
                                    {text: 'Someone who is single', points: 6}
                                ]
                            },
                        ]
                    }
                ];

        }

      function GetByCategory(categoryName) {
            var categoryQuestion = [];
            var allCategoriesAndQuestions = GetAll();
            allCategoriesAndQuestions.forEach(function(category){
                if(category.name == categoryName){
                    categoryQuestion = category.questions;
                }
            })

       }
    }
})();<commit_msg>line formatting<commit_after>(function () {
    'use strict';

    angular
        .module('app')
        .factory('QuestionService', QuestionService);

    QuestionService.$inject = ['$timeout', '$filter', '$q'];

    function QuestionService($timeout, $filter, $q) {

        var service = {};

        service.GetAll = GetAll;
        service.GetByCategory = GetByCategory;

        function GetAll() {
            return [
                {
                    name: 'Lifestyle',
                    questions: [
                        {
                            text: 'What do you do to stop your roommates eating your food?',
                            answers: [
                                {
                                    text: 'Write your name on all your food, right down to individual yogurts.',
                                    points: 1
                                },
                                {text: 'Bring it up in conversation.', points: 2},
                                {text: 'Lick it all. Lick everything. But don’t tell them.', points: 3},
                                {text: 'Start eating their food.', points: 4}
                            ]
                        },
                        {
                            text: 'Someone is using your Wi-Fi instead of paying for their own. What do you do?',
                            answers: [
                                {text: 'Let it go. Life’s too short.', points: 1},
                                {text: 'Change the network name to “Not Your Wi-Fi” to drop them a hint.', points: 2},
                                {text: 'Keep changing the password so they can’t keep logging in.', points: 3},
                                {text: 'Get rid of it all together, and go live in the woods.', points: 4}
                            ]
                        },
                        {
                            text: 'Someone in front of you at the cinema is rocking their chair back and forth, annoying you. How do you deal with it?',
                            answers: [
                                {text: 'Move seats.', points: 1},
                                {text: 'Ask them to stop.', points: 2},
                                {text: 'Keep kicking the back of their seat until they get the message.', points: 3},
                                {text: 'Kick them in the head.', points: 4}
                            ]
                        },
                        {
                            text: 'Someone near you is chewing loudly. What do you do?',
                            answers: [
                                {text: 'Nothing, but secretly start hating them.', points: 1},
                                {text: 'Send them an email that uses the word ‘sorry,’ multiple times.', points: 2},
                                {text: 'Ask them to be quieter.', points: 3},
                                {text: 'Chew louder until they get the message.', points: 4},
                                {text: 'Loudly play a YouTube video of someone chewing loudly.', points: 5},
                                {text: 'Throw things at them.', points: 6}
                            ]
                        },
                        {
                            text: 'If you\'re in an argument, what\'s your go-to ending line?',
                            answers: [
                                {text: '"You know what, I think you\'re right."', points: 1},
                                {text: '"Let\'s sit down and talk this through"', points: 2},
                                {text: 'No line, you go straight for the silent treatment.', points: 3},
                                {text: '"Fine, I don\'t care!"', points: 4},
                                {text: '"You\'d better comply, or else..."', points: 5}
                            ]
                        }
                    ]
                },
                {
                    name: 'Personality',
                    questions: [
                        {
                            text: 'You arrive at a house party but no one you know is there yet. What do you do?',
                            answers: [
                                {text: 'Get the hell out of there and try again later', points: 1},
                                {
                                    text: 'Go and hide in the toilet and text your friend telling them to get there urgently',
                                    points: 2
                                },
                                {
                                    text: 'Try to make yourself invisible by standing in the corner and staring at your phone',
                                    points: 3
                                },
                                {
                                    text: 'Loiter near the snack table and hope someone starts up a conversation with you',
                                    points: 4
                                },
                                {
                                    text: 'See if you can find the host and introduce yourself – it\'s only polite',
                                    points: 5
                                },
                                {
                                    text: 'Grab a drink and go and join a conversation – new friends aren\'t going to make themselves!',
                                    points: 6
                                }
                            ]
                        },
                        {
                            text: 'Your phone rings but you don\'t recognise the number, what do you do?',
                            answers: [
                                {text: 'Throw your phone into a river and emigrate to Peru', points: 1},
                                {text: 'Let it ring out, there\'s no way you\'re speaking to some stranger', points: 2},
                                {text: 'Quickly google the number to try and find out who it could be', points: 3},
                                {text: 'Pick up, but only if you aren\'t doing anything', points: 4},
                                {text: 'Pick it up, obviously – it might be important', points: 5}
                            ]
                        },
                        {
                            text: 'Your colleagues are having a light-hearted conversation round the table at the pub. You are...',
                            answers: [
                                {text: 'At home watching Netflix on the sofa', points: 1},
                                {
                                    text: 'Listening and feeling a little awkward, but not feeling confident enough to talk much',
                                    points: 2
                                },
                                {
                                    text: 'Talking when you feel comfortable, but mostly listening from the fringes',
                                    points: 3
                                },
                                {
                                    text: 'Chipping in with jokes quite often and taking control of the conversation when you can',
                                    points: 4
                                },
                                {
                                    text: 'Leading the conversation, and probably making people laugh in the process',
                                    points: 5
                                }
                            ]
                        },
                        {
                            text: 'How do you like to spend your week nights?',
                            answers: [
                                {text: 'At home relaxing, watching TV, on the internet or with a good book', points: 1},
                                {
                                    text: 'It totally depends how I feel, some weeks I\'ll be really busy, others I just want to chill',
                                    points: 2
                                },
                                {text: 'I like to go out and see people once or twice a week when I can', points: 3},
                                {text: 'I like to make as many plans as possible, being alone is boring', points: 4},
                                {
                                    text: 'I go along with most plans because of my crippling fear of missing out',
                                    points: 5
                                }
                            ]
                        },
                        {
                            text: 'How do you feel when making small talk?',
                            answers: [
                                {text: 'Always extremely worried of what the other person thinks of me', points: 1},
                                {text: 'A bit awkward, but I cope fine – it\'s a part of life', points: 2},
                                {
                                    text: 'It always feels a little pointless, but it\'s not the worst thing in the world',
                                    points: 3
                                },
                                {text: 'It\'s OK, but I prefer to listen than to talk about myself', points: 4},
                                {text: 'Great – it\'s always fun to get to know new people', points: 5}
                            ]
                        },
                    ]
                },
                {
                    name: 'Nature',
                    questions: [
                        {
                            text: 'You go out to dinner with a friend. What are you ordering?',
                            answers: [
                                {text: 'Whatever is the cheapest', points: 1},
                                {text: 'Whatever seems to be the most nutritionally balanced', points: 2},
                                {text: 'Something different from my friend, so we can share', points: 3},
                                {text: 'Something I know I will like', points: 4},
                                {text: 'Something I have never tried before', points: 5},
                                {text: 'Whatever is the tastiest', points: 6}
                            ]
                        },
                        {
                            text: 'You get a flat tire on the highway. What is the very first thing you do?',
                            answers: [
                                {text: 'Check for a spare', points: 1},
                                {text: 'Google "how to change a tire"', points: 2},
                                {text: 'Call a tow truck', points: 3},
                                {text: 'Call a friend or family member for support', points: 4},
                                {text: 'Punch the steering wheel', points: 5},
                                {text: 'Scream', points: 6}
                            ]
                        },
                        {
                            text: 'Everyone should decide their college major based on...',
                            answers: [
                                {text: 'Whatever opens up the most doors career-wise', points: 1},
                                {text: 'Whatever ensures the most financial security', points: 2},
                                {text: 'Their family\'s advice', points: 3},
                                {text: 'Whatever leads to a job they will love', points: 4},
                                {text: 'Whatever allows them to feel fulfilled', points: 5},
                                {text: 'Whatever feels right', points: 6}
                            ]
                        },
                        {
                            text: 'What is the foundation of a solid romantic relationship?',
                            answers: [
                                {text: 'Shared interests', points: 1},
                                {text: 'Horoscope compatibility', points: 2},
                                {text: 'Communication', points: 3},
                                {text: 'Trust', points: 4},
                                {text: 'Respect', points: 5},
                                {text: 'Chemistry', points: 6}
                            ]
                        },
                        {
                            text: 'What version of yourself would you hate to see 10 years from now?',
                            answers: [
                                {text: 'Someone financially struggling', points: 1},
                                {text: 'Someone with no goals and no direction', points: 2},
                                {text: 'Someone who works constantly with no time for themselves', points: 3},
                                {text: 'Someone in the place I am now', points: 4},
                                {text: 'Someone chronically dissatisfied with what they\'re doing', points: 5},
                                {text: 'Someone who is single', points: 6}
                            ]
                        }
                    ]
                }
            ];

        }

        function GetByCategory(categoryName) {
            var categoryQuestion = [];
            var allCategoriesAndQuestions = GetAll();
            allCategoriesAndQuestions.forEach(function (category) {
                if (category.name == categoryName) {
                    categoryQuestion = category.questions;
                }
            })

        }
    }
})();<|endoftext|>


<commit_before>// This is a modified version of https://github.com/stuartnelson3/blog/blob/master/public/js/script.js

function ImageUploadMarkdown (files) {
  var that = this

  this.init = function () {
    this.$textarea = $('.js-markdown-image-upload')

    this.addUploadPlaceholders()
    for (var i = 0; i < files.length; i++) {
      this.handleFileUpload(files[i])
    }
  }

  this.addUploadPlaceholders = function () {
    var placeholders = []
    for (var i = 0; i < files.length; i++) {
      var fileName = files[i].name
      placeholders.push(this.placeholderValue(fileName))
    }

    var selectionStart = this.$textarea[0].selectionStart
    var uploadsPlaceholder = placeholders.join('\r\n')
    this.$textarea.val(
      [this.$textarea.val().slice(0, selectionStart), uploadsPlaceholder, this.$textarea.val().slice(selectionStart)].join('')
    )
  }

  this.replaceImageMarkdownPlaceholder = function (newValue, fileName) {
    var oldPlaceholder = this.placeholderValue(fileName)
    this.$textarea.val(
      this.$textarea.val().replace(oldPlaceholder, newValue)
    )
  }

  this.placeholderValue = function (fileName) {
    return '![Uploading ' + fileName + '...]()'
  }

  this.handleFileUpload = function (file) {
    var formData = new FormData()
    formData.append('format', 'js')
    formData.append('file', file)

    formData.append('authenticity_token', $('meta[name="csrf-token"]').attr('content'))

    var request = new XMLHttpRequest()
    request.open('POST', '/uploads')

    request.onloadend = (function (fileName) {
      return function (e) {
        if (e.currentTarget.status === 201) {
          var filePath = e.currentTarget.response
          that.replaceImageMarkdownPlaceholder('![' + fileName + '](' + filePath + ')', fileName)
        } else {
          that.replaceImageMarkdownPlaceholder('', fileName)
          window.alert('File upload failure\n\n' + e.currentTarget.response)
        }
        that.$textarea.keyup()
      }
    }(file.name))

    request.send(formData)
  }

  return this
}

$(document).on('click', '.js-markdown-file-input-trigger', function () {
  $('.js-markdown-file-input').click()
})

$(document).on('change', '.js-markdown-file-input', function (e) {
  ImageUploadMarkdown(e.target.files).init()
})

$(document).on('drop', '.js-markdown-image-upload', function (e) {
  e.preventDefault()
  ImageUploadMarkdown(e.originalEvent.dataTransfer.files).init()
})
<commit_msg>Use == for checking XMLHttpRequest status<commit_after>// This is a modified version of https://github.com/stuartnelson3/blog/blob/master/public/js/script.js

function ImageUploadMarkdown (files) {
  var that = this

  this.init = function () {
    this.$textarea = $('.js-markdown-image-upload')

    this.addUploadPlaceholders()
    for (var i = 0; i < files.length; i++) {
      this.handleFileUpload(files[i])
    }
  }

  this.addUploadPlaceholders = function () {
    var placeholders = []
    for (var i = 0; i < files.length; i++) {
      var fileName = files[i].name
      placeholders.push(this.placeholderValue(fileName))
    }

    var selectionStart = this.$textarea[0].selectionStart
    var uploadsPlaceholder = placeholders.join('\r\n')
    this.$textarea.val(
      [this.$textarea.val().slice(0, selectionStart), uploadsPlaceholder, this.$textarea.val().slice(selectionStart)].join('')
    )
  }

  this.replaceImageMarkdownPlaceholder = function (newValue, fileName) {
    var oldPlaceholder = this.placeholderValue(fileName)
    this.$textarea.val(
      this.$textarea.val().replace(oldPlaceholder, newValue)
    )
  }

  this.placeholderValue = function (fileName) {
    return '![Uploading ' + fileName + '...]()'
  }

  this.handleFileUpload = function (file) {
    var formData = new FormData()
    formData.append('format', 'js')
    formData.append('file', file)

    formData.append('authenticity_token', $('meta[name="csrf-token"]').attr('content'))

    var request = new XMLHttpRequest()
    request.open('POST', '/uploads')

    request.onloadend = (function (fileName) {
      return function (e) {
        if (e.currentTarget.status == 201) { // eslint-disable-line eqeqeq
          var filePath = e.currentTarget.response
          that.replaceImageMarkdownPlaceholder('![' + fileName + '](' + filePath + ')', fileName)
        } else {
          that.replaceImageMarkdownPlaceholder('', fileName)
          window.alert('File upload failure\n\n' + e.currentTarget.response)
        }
        that.$textarea.keyup()
      }
    }(file.name))

    request.send(formData)
  }

  return this
}

$(document).on('click', '.js-markdown-file-input-trigger', function () {
  $('.js-markdown-file-input').click()
})

$(document).on('change', '.js-markdown-file-input', function (e) {
  ImageUploadMarkdown(e.target.files).init()
})

$(document).on('drop', '.js-markdown-image-upload', function (e) {
  e.preventDefault()
  ImageUploadMarkdown(e.originalEvent.dataTransfer.files).init()
})
<|endoftext|>


<commit_before>//= require can.jquery-all
//= require pbc/response
//= require pbc/system
//= require pbc/person

can.Control("CMS.Controllers.PBCModals", {
    defaults : {}
}, {
    init : function() {
        var content = $(".pbc-ca-content");
        content.collapse();
    }

    , ".add-document click" : function(el, ev) {
        this.selected_system_id = el.closest("[data-system-id]").data("system-id");
    }

    , ".documents-list li click" : function(el, ev) {
        var that = this
        , sys_id = this.selected_system_id;
        new CMS.Models.ObjectDocument({
            document_id : el.data("id")
            , system_id : this.selected_system_id
            , role : 'General Doc'
        })
        .save();
    }

    , '.pbc-add-response > a modal:success' : function(el, e, data) {
      var $this = $(el)
        , $input = $this.closest('.pbc-add-response').find('.pbc-system-search')
        , resp = new CMS.Models.Response()
        ;
      resp.attr({
        request_id: $(e.target).closest("[data-filter-id]").data("filter-id")
        , system_id: data.id
      });
      resp.save();

      $input.val('');
      $this.closest('.collapse').collapse('hide');
    }

    , 'a.system-edit modal:success' : function(el, e, data) {
      var $this = $(el)
        , response_id = $this.closest('li[data-id]').data('id')
        , response = CMS.Models.Response.findInCacheById(response_id)
        , system_id = response.attr('system_id')
        , system = CMS.Models.System.findInCacheById(response.attr('system_id'))
        ;
      system.attr(data);
    }

    , ".delete-reponse click" : function(el, ev) {
      this.selected_response_id = el.closest("[data-id]").data("id");
    }

    , "a[data-method=delete] click" : function(el, ev) {
      var modal = el.closest(".modal")
      , options = modal.data("modal_form").options;

      el.addClass("disabled");

      CMS.Models.Response.findInCacheById(options.id).destroy()
        .then(function() {
          modal.modal_form("hide");
        });
      ev.preventDefault();
      ev.stopPropagation();
    }

    , '.pbc-control > a modal:select' : function(el, e, control_data) {
        var request_id = el.closest('li[data-filter-id]').data('filter-id')
        ;

      $.post(
        '/requests/' + request_id,
        { _method: 'put'
        , 'request[control_id]': control_data.id
        }, function(data) {
          // FIXME: Brad, fix this if/when Requests are live-bound
          el.closest('.pbc-control').find('.item').text(control_data.slug);
            //find this control
            var $ca = $(".pbc-control-assessments .pbc-ca-item[data-type=ControlAssessment][data-control-id=" + control_data.id + "]");
            var type_name = el.closest('li[data-filter-type-name]').data("filter-type-name");

            // case 1: control exists -- no action needed
            if(!$ca.length) {
              // case 2: control does not exist
              $(".pbc-control-assessments").append(
                can.view(
                    "/pbc/control_assessment.mustache"
                    , $.extend({}, control_data, { type_name : type_name})
                ));
              $ca = $(".pbc-control-assessments .pbc-ca-item[data-control-id=" + control_data.id + "]");
            }
            var $oldParent = el.closest(".pbc-ca-item");
            el.closest(".pbc-requests > .main-item").detach().appendTo($ca.find(".pbc-requests"));
            //$ca.find(".pbc-ca-title .expander").addClass("in");
            var content = $ca.find(".pbc-ca-content");
            content.collapse().collapse("show");
            $ca.find("[data-toggle=#" + content.attr("id") + "]").addClass("in");
            // sweep for newly empty control assessments and delete.
            $(".pbc-control-assessments .pbc-ca-item:not(:has(.main-item))").remove();

            /*
            Due to request counts being removed by story 41602953, this code is not currently
             working or needed.  If request counts are restored, uncomment this block.  --BM
            var filtersmap = {
                "Documentation" : ".grcicon-document"
                , "Population Sample" : ".grcicon-populationsample"
                , "Interview" : ".grcicon-calendar"
            };

            var targetTextNode = $ca.find(".pbc-ca-title " + filtersmap[type_name])[0].nextSibling;
            targetTextNode.nodeValue = [" ", parseInt(targetTextNode.nodeValue) + 1, " "].join("");
            targetTextNode =  $oldParent.find(".pbc-ca-title " + filtersmap[type_name])[0].nextSibling;
            targetTextNode.nodeValue = [" ", parseInt(targetTextNode.nodeValue) - 1, " "].join("");
            */
        });
    }

    , '.pbc-control-select > a modal:select' : function(el, e, control_data) {
      var $this = $(el)

      $this.closest('.pbc-control-select').find('.item').text(control_data.slug);
      $("#request_control_id").val(control_data.id)
    }

    , ".items-list[id$=new] shown" : function(el, ev) {
        $("[data-target='#" + $(el).attr("id") + "']").closest("[data-toggle=modal]").hide()
        $(el).find("input[type=text]:first").focus();
    }

    , ".items-list[id$=new] hidden" : function(el, ev) {
        $("[data-target='#" + $(el).attr("id") + "']").closest("[data-toggle=modal]").show()
    }

});
<commit_msg>Add and remove necessary classes on control update.<commit_after>//= require can.jquery-all
//= require pbc/response
//= require pbc/system
//= require pbc/person

can.Control("CMS.Controllers.PBCModals", {
    defaults : {}
}, {
    init : function() {
        var content = $(".pbc-ca-content");
        content.collapse();
    }

    , ".add-document click" : function(el, ev) {
        this.selected_system_id = el.closest("[data-system-id]").data("system-id");
    }

    , ".documents-list li click" : function(el, ev) {
        var that = this
        , sys_id = this.selected_system_id;
        new CMS.Models.ObjectDocument({
            document_id : el.data("id")
            , system_id : this.selected_system_id
            , role : 'General Doc'
        })
        .save();
    }

    , '.pbc-add-response > a modal:success' : function(el, e, data) {
      var $this = $(el)
        , $input = $this.closest('.pbc-add-response').find('.pbc-system-search')
        , resp = new CMS.Models.Response()
        ;
      resp.attr({
        request_id: $(e.target).closest("[data-filter-id]").data("filter-id")
        , system_id: data.id
      });
      resp.save();

      $input.val('');
      $this.closest('.collapse').collapse('hide');
    }

    , 'a.system-edit modal:success' : function(el, e, data) {
      var $this = $(el)
        , response_id = $this.closest('li[data-id]').data('id')
        , response = CMS.Models.Response.findInCacheById(response_id)
        , system_id = response.attr('system_id')
        , system = CMS.Models.System.findInCacheById(response.attr('system_id'))
        ;
      system.attr(data);
    }

    , ".delete-reponse click" : function(el, ev) {
      this.selected_response_id = el.closest("[data-id]").data("id");
    }

    , "a[data-method=delete] click" : function(el, ev) {
      var modal = el.closest(".modal")
      , options = modal.data("modal_form").options;

      el.addClass("disabled");

      CMS.Models.Response.findInCacheById(options.id).destroy()
        .then(function() {
          modal.modal_form("hide");
        });
      ev.preventDefault();
      ev.stopPropagation();
    }

    , '.pbc-control > a modal:select' : function(el, e, control_data) {
        var request_id = el.closest('li[data-filter-id]').data('filter-id')
        ;

      $.post(
        '/requests/' + request_id,
        { _method: 'put'
        , 'request[control_id]': control_data.id
        }, function(data) {
          // FIXME: Brad, fix this if/when Requests are live-bound
          var $this = el.closest('.pbc-control').find('.item');
          $this.text(control_data.slug);
          $this.removeClass("error");
          $this.addClass("i-control");
            //find this control AND REMOVE ITS ERROR
            var $ca = $(".pbc-control-assessments .pbc-ca-item[data-type=ControlAssessment][data-control-id=" + control_data.id + "]");
            var type_name = el.closest('li[data-filter-type-name]').data("filter-type-name");

            // case 1: control exists -- no action needed
            if(!$ca.length) {
              // case 2: control does not exist
              $(".pbc-control-assessments").append(
                can.view(
                    "/pbc/control_assessment.mustache"
                    , $.extend({}, control_data, { type_name : type_name})
                ));
              $ca = $(".pbc-control-assessments .pbc-ca-item[data-control-id=" + control_data.id + "]");

            }
            var $oldParent = el.closest(".pbc-ca-item");
            el.closest(".pbc-requests > .main-item").detach().appendTo($ca.find(".pbc-requests"));
            //$ca.find(".pbc-ca-title .expander").addClass("in");
            var content = $ca.find(".pbc-ca-content");
            content.collapse().collapse("show");
            $ca.find("[data-toggle=#" + content.attr("id") + "]").addClass("in");
            // sweep for newly empty control assessments and delete.
            $(".pbc-control-assessments .pbc-ca-item:not(:has(.main-item))").remove();

            /*
            Due to request counts being removed by story 41602953, this code is not currently
             working or needed.  If request counts are restored, uncomment this block.  --BM
            var filtersmap = {
                "Documentation" : ".grcicon-document"
                , "Population Sample" : ".grcicon-populationsample"
                , "Interview" : ".grcicon-calendar"
            };

            var targetTextNode = $ca.find(".pbc-ca-title " + filtersmap[type_name])[0].nextSibling;
            targetTextNode.nodeValue = [" ", parseInt(targetTextNode.nodeValue) + 1, " "].join("");
            targetTextNode =  $oldParent.find(".pbc-ca-title " + filtersmap[type_name])[0].nextSibling;
            targetTextNode.nodeValue = [" ", parseInt(targetTextNode.nodeValue) - 1, " "].join("");
            */
        });
    }

    , '.pbc-control-select > a modal:select' : function(el, e, control_data) {
      var $this = $(el)

      $this.closest('.pbc-control-select').find('.item').text(control_data.slug);

      $("#request_control_id").val(control_data.id)
    }

    , ".items-list[id$=new] shown" : function(el, ev) {
        $("[data-target='#" + $(el).attr("id") + "']").closest("[data-toggle=modal]").hide()
        $(el).find("input[type=text]:first").focus();
    }

    , ".items-list[id$=new] hidden" : function(el, ev) {
        $("[data-target='#" + $(el).attr("id") + "']").closest("[data-toggle=modal]").show()
    }

});
<|endoftext|>


<commit_before>angular.module('ocWebGui.queue', ['ocWebGui.queue.service', 'ui.router', 'ocWebGui.shared.time', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('queue', {
        url: '/queue',
        templateUrl: 'queue/_queue.html',
        controller: 'QueueController',
        controllerAs: 'queue',
        navbarOverlay: true
      });
  })
  .controller('QueueController', function ($interval, $scope, Queue, $http) {
    var vm = this;
    vm.api = {};

    vm.options = {
      chart: {
        type: 'linePlusBarChart',
        height: 550,
        margin: {
          top: 30,
          right: 90,
          bottom: 60,
          left: 40
        },
        x: function (d) { return d.hour; },
        y: function (d) { return d.calls; },
        bars: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        lines: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        xAxis: {
          tickFormat: function (d) {
            return d3.format(',f')(d);
          },
          axisLabel: 'Kellonaika',
          showMaxMin: true
        },
        y1Axis: {
          ticks: 5
        },
        y2Axis: {
          ticks: 5,
          tickFormat: function (seconds) {
            var formatTime = d3.time.format("%H:%M");
            return formatTime(new Date(1864, 7, 7, 0, seconds));
          }
        },
        legend: {
          maxKeyLength: 100
        },
        duration: 500
      }
    };
    vm.data = [{
      'key': 'Puheluja tunnissa',
      'bar': true,
      'color': '#000000',
      'values': []
    }, {
      'key': 'Keskim. jonotusaika',
      'color': '#ff0000',
      'values': []
    }];

    function fetchContactStats() {
      $http.get('contacts/stats.json').then(function (response) {
        var data = response.data;
        var callsValues = data.calls_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });

        var queueValues = data.average_queue_duration_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });

        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }

        angular.extend(vm.stats, vm.stats, data);
        vm.data[0].values = callsValues;
        vm.data[1].values = queueValues;
        vm.options.chart.bars.yDomain[1] = getNearestTen(0);
        vm.options.chart.lines.yDomain[1] = getNearestTen(1);
      });
    }

    function fetchQueueStats() {
      $http.get('queue/stats.json').then(function (response) {
        var data = response.data;
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
      });
    }

    function getNearestTen(i) {
      var maxVal = d3.max(vm.data[i].values, function (x) { return x.calls; });
      if (maxVal == null) {
        return 0;
      }
      return Math.ceil(maxVal / 10) * 10;
    }

    vm.message = 'Jono';

    vm.queue = [];

    vm.date = new Date();

    function fetchData() {
      Queue.query(function (queue) {
        vm.queue = queue;
      });
      // Also update date/time
      vm.date = new Date();
    }
    var fetchDataInterval = $interval(fetchData, 5 * 1000);
    var fetchContactStatsInterval = $interval(fetchContactStats, 5 * 60 * 1000);
    var fetchQueueStatsInterval = $interval(fetchQueueStats, 5 * 60 * 1000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
      $interval.cancel(fetchContactStatsInterval);
      $interval.cancel(fetchQueueStatsInterval);
    });

    fetchData();
    fetchContactStats();
    fetchQueueStats();

  });
<commit_msg>fix bug when loading chart and setting ydomain when no data is available<commit_after>angular.module('ocWebGui.queue', ['ocWebGui.queue.service', 'ui.router', 'ocWebGui.shared.time', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('queue', {
        url: '/queue',
        templateUrl: 'queue/_queue.html',
        controller: 'QueueController',
        controllerAs: 'queue',
        navbarOverlay: true
      });
  })
  .controller('QueueController', function ($interval, $scope, Queue, $http) {
    var vm = this;
    vm.api = {};

    vm.options = {
      chart: {
        type: 'linePlusBarChart',
        height: 550,
        margin: {
          top: 30,
          right: 90,
          bottom: 60,
          left: 40
        },
        x: function (d) { return d.hour; },
        y: function (d) { return d.calls; },
        bars: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        lines: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        xAxis: {
          tickFormat: function (d) {
            return d3.format(',f')(d);
          },
          axisLabel: 'Kellonaika',
          showMaxMin: true
        },
        y1Axis: {
          ticks: 5
        },
        y2Axis: {
          ticks: 5,
          tickFormat: function (seconds) {
            var formatTime = d3.time.format("%H:%M");
            return formatTime(new Date(1864, 7, 7, 0, seconds));
          }
        },
        legend: {
          maxKeyLength: 100
        },
        duration: 500
      }
    };
    vm.data = [{
      'key': 'Puheluja tunnissa',
      'bar': true,
      'color': '#000000',
      'values': []
    }, {
      'key': 'Keskim. jonotusaika',
      'color': '#ff0000',
      'values': []
    }];

    function fetchContactStats() {
      $http.get('contacts/stats.json').then(function (response) {
        var data = response.data;
        var callsValues = data.calls_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });

        var queueValues = data.average_queue_duration_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });

        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }

        angular.extend(vm.stats, vm.stats, data);
        vm.data[0].values = callsValues;
        vm.data[1].values = queueValues;
        vm.options.chart.bars.yDomain[1] = getMaxValPlusOne(0);
        vm.options.chart.lines.yDomain[1] = getMaxValPlusOne(1);
      });
    }

    function fetchQueueStats() {
      $http.get('queue/stats.json').then(function (response) {
        var data = response.data;
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
      });
    }

    function getMaxValPlusOne(i) {
      var maxVal = d3.max(vm.data[i].values, function (x) { return x.calls; });
      if (maxVal == null) {
        return 0;
      }
      return maxVal + 1;
    }

    vm.message = 'Jono';

    vm.queue = [];

    vm.date = new Date();

    function fetchData() {
      Queue.query(function (queue) {
        vm.queue = queue;
      });
      // Also update date/time
      vm.date = new Date();
    }
    var fetchDataInterval = $interval(fetchData, 5 * 1000);
    var fetchContactStatsInterval = $interval(fetchContactStats, 5 * 60 * 1000);
    var fetchQueueStatsInterval = $interval(fetchQueueStats, 5 * 60 * 1000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
      $interval.cancel(fetchContactStatsInterval);
      $interval.cancel(fetchQueueStatsInterval);
    });

    fetchData();
    fetchContactStats();
    fetchQueueStats();

  });
<|endoftext|>


<commit_before>/**
 * Created by user on 22/11/16.
 */

app.controller('importationCtrl', function (CloudinaryClient, $scope,$http, $location, Auth) {

    // Scope methods
    /**
     * Import a workshop from a JSON file
     * @type {importer}
     */
    $scope.importer = importer;

    /**
     * Get inputs, create a json and post it
     * @type {getFields}
     */
    $scope.getFields = getFields;

    // Scope var
    $scope.inputStepTitle = "inputStepTitle";
    $scope.inputStepDuration = "inputStepDuration";
    $scope.stepsTextarea = "stepsTextarea";
    $scope.stepsTextareaAncre = "steps-textarea-ancre";
    $scope.photo = [];

    var cpt = 1;

    document.getElementById('inputPhotos').addEventListener('change', function(){
        for(var i = 0; i < this.files.length; i++){
            var reader = new FileReader();
            reader.onload = onLoadFunction;
            reader.readAsDataURL(this.files[i]);
        }
    }, false);

    function onLoadFunction(loadEvent) {
        $scope.$apply(function() {
            $scope.photo.push(loadEvent.target.result);
        });
    }
    if (!Auth.isConnected()) {
        $location.path("/");
        $scope.$emit('notify', {
            type: 'error',
            title: 'Vous n\'avez pas les autorisations d\'accéder à cette page'
        });
    }
    /**
     * Init a special text area (for the folklore here), in which you can formatting text
     */
    $('#folklore-textarea').wysihtml5({
        toolbar: {
            "font-styles": false, //Font styling, e.g. h1, h2, etc. Default true
            "link": false, //Button to insert a link. Default true
            "image": false, //Button to insert an image. Default true,
            "color": false, //Button to change color of font
            "blockquote": false, //Blockquote
            "fa": true // Font Awesome icons
        }
    });

    /**
     * Init a special text area (for the equipment here), in which you can formatting text
     */
    $('#equipment-textarea').wysihtml5({
        toolbar: {
            "font-styles": false,
            "link": false,
            "image": false,
            "color": false,
            "blockquote": false,
            "fa": true
        }
    });

    /**
     * Init a special text area (for the steps here), in which you can formatting text
     */
    $('#steps-textarea').wysihtml5({
        toolbar: {
            "font-styles": false,
            "link": false,
            "image": false,
            "color": false,
            "blockquote": false,
            "fa": true
        }
    });

    /**
     * Add more steps
     */
    $("body").on('click', '.add-more', function(){

        //modify the classes names, so we can get data for every new steps
        cpt++;
        $scope.inputStepTitle = "inputStepTitle-"+cpt;
        $scope.inputStepDuration = "inputStepDuration-"+cpt;
        $scope.stepsTextarea = "stepsTextarea-"+cpt;
        $scope.stepsTextareaAncre = "steps-textarea-ancre-"+cpt;
        $scope.$apply();

        var html = $(".copy").html();
        $(".after-add-more").after(html);

        //New special text area
        $('#stepsTextarea-'+cpt).wysihtml5({
            toolbar: {
                "font-styles": false,
                "link": false,
                "image": false,
                "color": false,
                "blockquote": false,
                "fa": true
            }
        });

        //Move classes as we need to
        $(".after-add-more").addClass("last-after-add-more-"+cpt);
        $(".after-add-more").removeClass("after-add-more");
        $(".control-group:first").addClass("after-add-more");
        $(".control-group:first").removeClass("control-group");

        if(cpt >= 3) {
            for(var i=0; i < document.getElementsByClassName("remove").length - 2; i++) {
                document.getElementsByClassName("remove")[i].style.display = "none";
            }
        }
    });

    /**
     * Remove steps (we can only remove the last one, so it's easier to get data)
     */
    $("body").on("click",".remove",function(){

        $(this).parents(".after-add-more").remove();
        $(".last-after-add-more-"+cpt).addClass("after-add-more");
        $(".last-after-add-more-"+cpt+" .remove").css("display", "table-cell");
        $(".last-after-add-more-"+cpt).removeClass("last-after-add-more-"+cpt);

        cpt--;
    });

    function prepareJSON(photo) {
        var json = {};
        var jsonContent = {};
        var educArray = [];
        json.title = document.getElementById('inputTitle').value;
        json.author = document.getElementById('inputAuthor').value;
        if(photo) {
            json.photo = photo;
        }
        json.duration = document.getElementById('inputDuration').value;
        json.synopsis = document.getElementById('inputSysnopsis').value;
        jsonContent.source = document.getElementById('inputSource').value;
        jsonContent.folklore = $('#folklore-textarea').val();
        jsonContent.equipment = $('#equipment-textarea').val();
        $(".labelCheckbox:checked").each(function(){
            educArray.push($(this).val());
        });

        jsonContent.educational_aims = educArray;

        var jsonArr = [];
        jsonArr.push({
            title: document.getElementById('inputStepTitle').value,
            description: $('#steps-textarea').val(),
            duration: document.getElementById('inputStepDuration').value
        });

        for (var y = 2; y <= cpt; y++) {
            jsonArr.push({
                title: document.getElementById('inputStepTitle-'+y).value,
                description: $('#stepsTextarea-'+y).val(),
                duration: document.getElementById('inputStepDuration-'+y).value
            });
        }

        jsonContent.steps = jsonArr;
        json.content = jsonContent;

        //Post
        //TODO vérifier les champs textes spéciaux
        //TODO requiere titre ajout step
        //TODO : required="required" au moins 1 sur les labels ?
        postJSON(json);

        window.top.window.scrollTo(0,0)
    }
    function getFields() {
        if ($scope.photo) {
            var reader = new FileReader();
            CloudinaryClient.uploadPhotos($scope.photo)
                .success(function(response) {
                    prepareJSON(response.data[0].filename);
                })
        } else {
            prepareJSON(null);
        }
    }

    function importer() {
        var fichier = document.getElementById('InputJSON').files[0];
        var lecture = new FileReader();
        lecture.onloadend = function (evenement) {
            var donnees = evenement.target.result;
            var type = fichier.name.split(".");

            //Check if the file is a JSON
            if(type[1] == "json") {

                var data = JSON.parse(donnees);

                //Check if the JSON file got what we expect in
                if( data.title && data.duration && data.synopsis && data.content.folklore && data.content.educational_aims && data.content.steps) {

                    //Post
                    postJSON(donnees);
                } else {
                    $scope.$emit('notify', {
                        type: 'error',
                        title: 'Format de l\'atelier incomptatible.',
                    });
                }
            }
            else {
                    $scope.$emit('notify', {
                        type: 'error',
                        title: 'L\'atelier doit être en format JSON.',
                    });
            }

        }
        lecture.readAsText(fichier, 'UTF-8')
    }

    /**
     * Post the json with the workshop on the server
     * @param donnees
     */
    function postJSON(donnees) {
        //Post
        var res = $http.post('/api/v1/catalogue', donnees);
        res.success(function(data, status, headers, config) {
            $scope.message = data;

            $scope.$emit('notify', {
                type: 'success',
                title: 'L\'atelier a bien été importé.',
                content: '/#/catalogue/'+data.data._id +'$$Lien vers votre atelier'
            });
        });
        res.error(function(data, status, headers, config) {
            $scope.$emit('notify', {
                type: 'error',
                title: 'L\'atelier n\'a pas pu être importé.',
            });
        });
    }
});<commit_msg>[DEV #95] Coucou Sauvage =D<commit_after>/**
 * Created by user on 22/11/16.
 */

app.controller('importationCtrl', function (CloudinaryClient, $scope,$http, $location, Auth) {

    // Scope methods
    /**
     * Import a workshop from a JSON file
     * @type {importer}
     */
    $scope.importer = importer;

    /**
     * Get inputs, create a json and post it
     * @type {getFields}
     */
    $scope.getFields = getFields;

    // Scope var
    $scope.inputStepTitle = "inputStepTitle";
    $scope.inputStepDuration = "inputStepDuration";
    $scope.stepsTextarea = "stepsTextarea";
    $scope.stepsTextareaAncre = "steps-textarea-ancre";
    $scope.photo = [];

    var cpt = 1;

    document.getElementById('inputPhotos').addEventListener('change', function(){
        for(var i = 0; i < this.files.length; i++){
            var reader = new FileReader();
            reader.onload = onLoadFunction;
            reader.readAsDataURL(this.files[i]);
        }
    }, false);

    function onLoadFunction(loadEvent) {
        $scope.$apply(function() {
            $scope.photo.push(loadEvent.target.result);
        });
    }
    if (!Auth.isConnected()) {
        $location.path("/");
        $scope.$emit('notify', {
            type: 'error',
            title: 'Vous n\'avez pas les autorisations d\'accéder à cette page'
        });
    }
    /**
     * Init a special text area (for the folklore here), in which you can formatting text
     */
    $('#folklore-textarea').wysihtml5({
        toolbar: {
            "font-styles": false, //Font styling, e.g. h1, h2, etc. Default true
            "link": false, //Button to insert a link. Default true
            "image": false, //Button to insert an image. Default true,
            "color": false, //Button to change color of font
            "blockquote": false, //Blockquote
            "fa": true // Font Awesome icons
        }
    });

    /**
     * Init a special text area (for the equipment here), in which you can formatting text
     */
    $('#equipment-textarea').wysihtml5({
        toolbar: {
            "font-styles": false,
            "link": false,
            "image": false,
            "color": false,
            "blockquote": false,
            "fa": true
        }
    });

    /**
     * Init a special text area (for the steps here), in which you can formatting text
     */
    $('#steps-textarea').wysihtml5({
        toolbar: {
            "font-styles": false,
            "link": false,
            "image": false,
            "color": false,
            "blockquote": false,
            "fa": true
        }
    });

    /**
     * Add more steps
     */
    $("body").on('click', '.add-more', function(){

        //modify the classes names, so we can get data for every new steps
        cpt++;
        $scope.inputStepTitle = "inputStepTitle-"+cpt;
        $scope.inputStepDuration = "inputStepDuration-"+cpt;
        $scope.stepsTextarea = "stepsTextarea-"+cpt;
        $scope.stepsTextareaAncre = "steps-textarea-ancre-"+cpt;
        $scope.$apply();

        var html = $(".copy").html();
        $(".after-add-more").after(html);

        //New special text area
        $('#stepsTextarea-'+cpt).wysihtml5({
            toolbar: {
                "font-styles": false,
                "link": false,
                "image": false,
                "color": false,
                "blockquote": false,
                "fa": true
            }
        });

        //Move classes as we need to
        $(".after-add-more").addClass("last-after-add-more-"+cpt);
        $(".after-add-more").removeClass("after-add-more");
        $(".control-group:first").addClass("after-add-more");
        $(".control-group:first").removeClass("control-group");

        if(cpt >= 3) {
            for(var i=0; i < document.getElementsByClassName("remove").length - 2; i++) {
                document.getElementsByClassName("remove")[i].style.display = "none";
            }
        }
    });

    /**
     * Remove steps (we can only remove the last one, so it's easier to get data)
     */
    $("body").on("click",".remove",function(){

        $(this).parents(".after-add-more").remove();
        $(".last-after-add-more-"+cpt).addClass("after-add-more");
        $(".last-after-add-more-"+cpt+" .remove").css("display", "table-cell");
        $(".last-after-add-more-"+cpt).removeClass("last-after-add-more-"+cpt);

        cpt--;
    });

    function prepareJSON(photo) {
        var json = {};
        var jsonContent = {};
        var educArray = [];
        json.title = document.getElementById('inputTitle').value;
        json.author = document.getElementById('inputAuthor').value;
        if(photo) {
            json.photo = photo;
        }
        json.duration = document.getElementById('inputDuration').value;
        json.synopsis = document.getElementById('inputSysnopsis').value;
        jsonContent.source = document.getElementById('inputSource').value;
        jsonContent.folklore = $('#folklore-textarea').val();
        jsonContent.equipment = $('#equipment-textarea').val();
        $(".labelCheckbox:checked").each(function(){
            educArray.push($(this).val());
        });

        jsonContent.educational_aims = educArray;

        var jsonArr = [];
        jsonArr.push({
            title: document.getElementById('inputStepTitle').value,
            description: $('#steps-textarea').val(),
            duration: document.getElementById('inputStepDuration').value
        });

        for (var y = 2; y <= cpt; y++) {
            jsonArr.push({
                title: document.getElementById('inputStepTitle-'+y).value,
                description: $('#stepsTextarea-'+y).val(),
                duration: document.getElementById('inputStepDuration-'+y).value
            });
        }

        jsonContent.steps = jsonArr;
        json.content = jsonContent;

        //Post
        //TODO vérifier les champs textes spéciaux
        //TODO requiere titre ajout step
        //TODO : required="required" au moins 1 sur les labels ?
        postJSON(json);

        window.top.window.scrollTo(0,0)
    }
    function getFields() {
        if ($scope.photo) {
            var reader = new FileReader();
            CloudinaryClient.uploadPhotos($scope.photo)
                .success(function(response) {
                    prepareJSON(response.data[0].filename);
                })
        } else {
            prepareJSON(null);
        }
    }
    function importer() {
        var fichier = document.getElementById('InputJSON').files[0];
        var lecture = new FileReader();
        lecture.onloadend = function (evenement) {
            var donnees = evenement.target.result;
            var type = fichier.name.split(".");

            //Check if the file is a JSON
            if(type[1] == "json") {

                var data = JSON.parse(donnees);

                if( data.title && data.duration && data.synopsis && data.content.folklore && data.content.educational_aims && data.content.steps) {
                    postJSON(donnees);
                } else {
                    $scope.$emit('notify', {
                        type: 'error',
                        title: 'Format de l\'atelier incomptatible.'
                    });
                }
            }
            else {
                    $scope.$emit('notify', {
                        type: 'error',
                        title: 'L\'atelier doit être en format JSON.'
                    });
            }
        };
        lecture.readAsText(fichier, 'UTF-8')
    }

    /**
     * Post the json with the workshop on the server
     * @param donnees
     */
    function postJSON(donnees) {
        //Post
        var res = $http.post('/api/v1/catalogue', donnees);
        res.success(function(data, status, headers, config) {
            $scope.message = data;

            $scope.$emit('notify', {
                type: 'success',
                title: 'L\'atelier a bien été importé.',
                content: '/#/catalogue/'+data.data._id +'$$Lien vers votre atelier'
            });
        });
        res.error(function(data, status, headers, config) {
            $scope.$emit('notify', {
                type: 'error',
                title: 'L\'atelier n\'a pas pu être importé.',
            });
        });
    }
});<|endoftext|>


<commit_before>define([
  'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dojo/dom-construct',
  'dijit/layout/BorderContainer', 'dijit/layout/StackContainer', 'dijit/layout/TabController', 'dijit/layout/ContentPane',
  'dijit/form/RadioButton', 'dijit/form/Textarea', 'dijit/form/TextBox', 'dijit/form/Button', 'dijit/form/Select',
  'dojox/widget/Standby', './ActionBar', './ContainerActionBar',
  './TranscriptomicsGeneGridContainer', './TranscriptomicsGeneFilterGrid', './TranscriptomicsGeneHeatmapContainer',
  './TranscriptomicsGeneHeatmapContainerNew', 'heatmap/dist/heatmap', 'dojo/dom-class'
], function (
  declare, lang, on, Topic, domConstruct,
  BorderContainer, TabContainer, StackController, ContentPane,
  RadioButton, TextArea, TextBox, Button, Select,
  Standby, ActionBar, ContainerActionBar,
  MainGridContainer, FilterGrid, HeatmapContainer,
  HeatmapContainerNew, Heatmap, domClass
) {

  return declare([BorderContainer], {
    gutters: false,
    state: null,
    tgState: null,
    loadingMask: null,
    apiServer: window.App.dataServiceURL,
    constructor: function (options) {
      // console.log(options);

      this.topicId = 'TranscriptomicsGene_' + options.id.split('_TranscriptomicsGene')[0];

      Topic.subscribe(this.topicId, lang.hitch(this, function () {
        // console.log("TranscriptomicsGeneContainer:", arguments);
        var key = arguments[0],
          value = arguments[1];

        switch (key) {
          case 'updateTgState':
            this.tgState = value;
            this.updateFilterPanel(value);
            break;
          case 'showLoadingMask':
            this.loadingMask.show();
            break;
          case 'hideLoadingMask':
            this.loadingMask.hide();
            break;
          case 'updateGenomeFilter':
            this.updateGenomeFilter(value);
            break;
          default:
            break;
        }
      }));
    },
    postCreate: function () {
      this.loadingMask = new Standby({
        target: this.id,
        image: '/public/js/p3/resources/images/spin.svg',
        color: '#efefef'
      });
      this.addChild(this.loadingMask);
      this.loadingMask.startup();

      this.loadingMask.show(); // this widget is opened by new window/tab
    },
    onSetState: function (attr, oldVal, state) {
      // console.log("TranscriptomicsGeneContainer set STATE. state: ", state);
      if (this.mainGridContainer) {
        this.mainGridContainer.set('state', state);
      }
      this._set('state', state);
    },

    visible: false,
    _setVisibleAttr: function (visible) {
      this.visible = visible;

      if (this.visible && !this._firstView) {
        this.onFirstView();
      }
      if (this.mainGridContainer) {
        this.mainGridContainer.set('visible', true);
      }
      if (this.heatmapContainer) {
        this.heatmapContainer.set('visible', true);
      }
      if (this.heatmapContainerNew) {
        this.heatmapContainerNew.set('visible', true);
      }
    },

    onFirstView: function () {
      if (this._firstView) {
        return;
      }

      var filterPanel = this._buildFilterPanel();

      this.tabContainer = new TabContainer({ region: 'center', id: this.id + '_TabContainer' });

      var tabController = new StackController({
        containerId: this.id + '_TabContainer',
        region: 'top',
        'class': 'TextTabButtons'
      });

      this.mainGridContainer = new MainGridContainer({
        title: 'Table',
        content: 'Transcriptomics Gene Table',
        state: this.state,
        topicId: this.topicId,
        apiServer: this.apiServer
      });

      this.heatmapContainerNew = new HeatmapContainerNew({
        title: 'Heatmap (new)',
        type: 'webGLHeatmap',
        topicId: this.topicId,
        content: 'Heatmap (new)'
      });

      this.heatmapContainer = new HeatmapContainer({
        title: 'Heatmap',
        topicId: this.topicId,
        content: 'Heatmap'
      });

      this.watch('state', lang.hitch(this, 'onSetState'));

      this.tabContainer.addChild(this.mainGridContainer);
      this.tabContainer.addChild(this.heatmapContainerNew);
      this.tabContainer.addChild(this.heatmapContainer);

      var self = this;
      this.tabContainer.watch('selectedChildWidget', function (name, oldTab, newTab) {
        if (newTab.type === 'webGLHeatmap') {
          self.heatmapContainerNew.update();
        }
      });

      this.addChild(tabController);
      this.addChild(this.tabContainer);
      this.addChild(filterPanel);

      this.inherited(arguments);
      this._firstView = true;
    },
    updateFilterPanel: function (tgState) {

      this.ta_keyword.set('value', tgState.keyword);
      this.filter_log_ratio.set('value', tgState.upFold || 0);
      this.filter_z_score.set('value', tgState.upZscore || 0);
    },
    _buildFilterPanel: function () {

      var filterPanel = new ContentPane({
        region: 'left',
        title: 'filter',
        content: 'Filter By',
        style: 'width:283px; overflow:auto',
        splitter: true,
        'class': 'filterPanel'
      });

      var filterGridDescriptor = new ContentPane({
        style: 'padding: 0',
        content: '

'
      });
      filterPanel.addChild(filterGridDescriptor);

      // genome list grid
      var filterGrid = new FilterGrid({
        'class': 'tgFilterGrid',
        topicId: this.topicId,
        state: this.state
      });
      filterPanel.addChild(filterGrid);

      // other filter items
      var otherFilterPanel = new ContentPane({
        region: 'bottom'
      });

      var select_genome_filter = this.filter_genome = new Select({
        name: 'selectGenomeFilter',
        options: [{ value: '', label: 'Select a genome to filter' }],
        style: 'width: 272px; margin: 5px 0'
      });
      var label_select_genome_filter = domConstruct.create('label', { innerHTML: 'Filer by Genome: ' });
      domConstruct.place(label_select_genome_filter, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_genome_filter.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var ta_keyword = this.ta_keyword = new TextArea({
        style: 'width:272px; min-height:75px; margin-bottom: 10px'
      });
      var label_keyword = domConstruct.create('label', { innerHTML: 'Filter by one or more keywords or locus tags' });
      domConstruct.place(label_keyword, otherFilterPanel.containerNode, 'last');
      domConstruct.place(ta_keyword.domNode, otherFilterPanel.containerNode, 'last');

      var select_log_ratio = this.filter_log_ratio = new Select({
        name: 'selectLogRatio',
        options: [{ value: 0, label: '0' }, { value: 0.5, label: '0.5' }, { value: 1, label: '1' },
          { value: 1.5, label: '1.5' }, { value: 2, label: '2' }, { value: 2.5, label: '2.5' },
          { value: 3, label: '3' }
        ],
        style: 'width: 80px; margin: 5px 0'
      });
      var label_select_log_ratio = domConstruct.create('label', { innerHTML: 'Filter by |Log Ratio|: ' });
      domConstruct.place(label_select_log_ratio, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_log_ratio.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var select_z_score = this.filter_z_score = new Select({
        name: 'selectZScore',
        options: [{ value: 0, label: '0' }, { value: 0.5, label: '0.5' }, { value: 1, label: '1' },
          { value: 1.5, label: '1.5' }, { value: 2, label: '2' }, { value: 2.5, label: '2.5' },
          { value: 3, label: '3' }
        ],
        style: 'width: 80px; margin: 5px 0'
      });
      var label_select_z_score = domConstruct.create('label', { innerHTML: 'Filter by |Z-score|: ' });
      domConstruct.place(label_select_z_score, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_z_score.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var defaultFilterValue = {
        keyword: '',
        filterGenome: null,
        clusterColumnOrder: [],
        upFold: 0,
        downFold: 0,
        upZscore: 0,
        downZscore: 0
      };

      var btn_submit = new Button({
        label: 'Filter',
        onClick: lang.hitch(this, function () {

          var filter = {};
          filter.filterGenome = select_genome_filter.get('value');
          filter.keyword = ta_keyword.get('value');

          var lr = parseFloat(select_log_ratio.get('value'));
          var zs = parseFloat(select_z_score.get('value'));

          !isNaN(lr) ? (filter.upFold = lr, filter.downFold = -lr) : {};
          !isNaN(zs) ? (filter.upZscore = zs, filter.downZscore = -zs) : {};

          this.tgState = lang.mixin(this.tgState, defaultFilterValue, filter);
          // console.log("filter tgState", this.tgState);

          Topic.publish(this.topicId, 'applyConditionFilter', this.tgState);
        })
      });
      domConstruct.place(btn_submit.domNode, otherFilterPanel.containerNode, 'last');

      filterPanel.addChild(otherFilterPanel);

      return filterPanel;
    },
    updateGenomeFilter: function (data) {
      this.filter_genome.addOption(data);
      // console.log(this.filter_genome, data);
    }
  });
});
<commit_msg>cleanup<commit_after>define([
  'dojo/_base/declare', 'dojo/_base/lang', 'dojo/topic', 'dojo/dom-construct',
  'dijit/layout/BorderContainer', 'dijit/layout/StackContainer', 'dijit/layout/TabController', 'dijit/layout/ContentPane',
  'dijit/form/Textarea', 'dijit/form/Button', 'dijit/form/Select', 'dojox/widget/Standby',
  './TranscriptomicsGeneGridContainer', './TranscriptomicsGeneFilterGrid', './TranscriptomicsGeneHeatmapContainer',
  './TranscriptomicsGeneHeatmapContainerNew'
], function (
  declare, lang, Topic, domConstruct,
  BorderContainer, TabContainer, StackController, ContentPane,
  TextArea, Button, Select, Standby,
  MainGridContainer, FilterGrid, HeatmapContainer,
  HeatmapContainerNew
) {

  return declare([BorderContainer], {
    gutters: false,
    state: null,
    tgState: null,
    loadingMask: null,
    apiServer: window.App.dataServiceURL,
    constructor: function (options) {
      // console.log(options);

      this.topicId = 'TranscriptomicsGene_' + options.id.split('_TranscriptomicsGene')[0];

      Topic.subscribe(this.topicId, lang.hitch(this, function () {
        // console.log("TranscriptomicsGeneContainer:", arguments);
        var key = arguments[0],
          value = arguments[1];

        switch (key) {
          case 'updateTgState':
            this.tgState = value;
            this.updateFilterPanel(value);
            break;
          case 'showLoadingMask':
            this.loadingMask.show();
            break;
          case 'hideLoadingMask':
            this.loadingMask.hide();
            break;
          case 'updateGenomeFilter':
            this.updateGenomeFilter(value);
            break;
          default:
            break;
        }
      }));
    },
    postCreate: function () {
      this.loadingMask = new Standby({
        target: this.id,
        image: '/public/js/p3/resources/images/spin.svg',
        color: '#efefef'
      });
      this.addChild(this.loadingMask);
      this.loadingMask.startup();

      this.loadingMask.show(); // this widget is opened by new window/tab
    },
    onSetState: function (attr, oldVal, state) {
      // console.log("TranscriptomicsGeneContainer set STATE. state: ", state);
      if (this.mainGridContainer) {
        this.mainGridContainer.set('state', state);
      }
      this._set('state', state);
    },

    visible: false,
    _setVisibleAttr: function (visible) {
      this.visible = visible;

      if (this.visible && !this._firstView) {
        this.onFirstView();
      }
      if (this.mainGridContainer) {
        this.mainGridContainer.set('visible', true);
      }
      if (this.heatmapContainer) {
        this.heatmapContainer.set('visible', true);
      }
      if (this.heatmapContainerNew) {
        this.heatmapContainerNew.set('visible', true);
      }
    },

    onFirstView: function () {
      if (this._firstView) {
        return;
      }

      var filterPanel = this._buildFilterPanel();

      this.tabContainer = new TabContainer({ region: 'center', id: this.id + '_TabContainer' });

      var tabController = new StackController({
        containerId: this.id + '_TabContainer',
        region: 'top',
        'class': 'TextTabButtons'
      });

      this.mainGridContainer = new MainGridContainer({
        title: 'Table',
        content: 'Transcriptomics Gene Table',
        state: this.state,
        topicId: this.topicId,
        apiServer: this.apiServer
      });

      this.heatmapContainerNew = new HeatmapContainerNew({
        title: 'Heatmap (new)',
        type: 'webGLHeatmap',
        topicId: this.topicId,
        content: 'Heatmap (new)'
      });

      this.heatmapContainer = new HeatmapContainer({
        title: 'Heatmap',
        topicId: this.topicId,
        content: 'Heatmap'
      });

      this.watch('state', lang.hitch(this, 'onSetState'));

      this.tabContainer.addChild(this.mainGridContainer);
      this.tabContainer.addChild(this.heatmapContainerNew);
      this.tabContainer.addChild(this.heatmapContainer);

      var self = this;
      this.tabContainer.watch('selectedChildWidget', function (name, oldTab, newTab) {
        if (newTab.type === 'webGLHeatmap') {
          self.heatmapContainerNew.update();
        }
      });

      this.addChild(tabController);
      this.addChild(this.tabContainer);
      this.addChild(filterPanel);

      this.inherited(arguments);
      this._firstView = true;
    },
    updateFilterPanel: function (tgState) {

      this.ta_keyword.set('value', tgState.keyword);
      this.filter_log_ratio.set('value', tgState.upFold || 0);
      this.filter_z_score.set('value', tgState.upZscore || 0);
    },
    _buildFilterPanel: function () {

      var filterPanel = new ContentPane({
        region: 'left',
        title: 'filter',
        content: 'Filter By',
        style: 'width:283px; overflow:auto',
        splitter: true,
        'class': 'filterPanel'
      });

      var filterGridDescriptor = new ContentPane({
        style: 'padding: 0',
        content: '

'
      });
      filterPanel.addChild(filterGridDescriptor);

      // genome list grid
      var filterGrid = new FilterGrid({
        'class': 'tgFilterGrid',
        topicId: this.topicId,
        state: this.state
      });
      filterPanel.addChild(filterGrid);

      // other filter items
      var otherFilterPanel = new ContentPane({
        region: 'bottom'
      });

      var select_genome_filter = this.filter_genome = new Select({
        name: 'selectGenomeFilter',
        options: [{ value: '', label: 'Select a genome to filter' }],
        style: 'width: 272px; margin: 5px 0'
      });
      var label_select_genome_filter = domConstruct.create('label', { innerHTML: 'Filer by Genome: ' });
      domConstruct.place(label_select_genome_filter, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_genome_filter.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var ta_keyword = this.ta_keyword = new TextArea({
        style: 'width:272px; min-height:75px; margin-bottom: 10px'
      });
      var label_keyword = domConstruct.create('label', { innerHTML: 'Filter by one or more keywords or locus tags' });
      domConstruct.place(label_keyword, otherFilterPanel.containerNode, 'last');
      domConstruct.place(ta_keyword.domNode, otherFilterPanel.containerNode, 'last');

      var select_log_ratio = this.filter_log_ratio = new Select({
        name: 'selectLogRatio',
        options: [{ value: 0, label: '0' }, { value: 0.5, label: '0.5' }, { value: 1, label: '1' },
          { value: 1.5, label: '1.5' }, { value: 2, label: '2' }, { value: 2.5, label: '2.5' },
          { value: 3, label: '3' }
        ],
        style: 'width: 80px; margin: 5px 0'
      });
      var label_select_log_ratio = domConstruct.create('label', { innerHTML: 'Filter by |Log Ratio|: ' });
      domConstruct.place(label_select_log_ratio, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_log_ratio.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var select_z_score = this.filter_z_score = new Select({
        name: 'selectZScore',
        options: [{ value: 0, label: '0' }, { value: 0.5, label: '0.5' }, { value: 1, label: '1' },
          { value: 1.5, label: '1.5' }, { value: 2, label: '2' }, { value: 2.5, label: '2.5' },
          { value: 3, label: '3' }
        ],
        style: 'width: 80px; margin: 5px 0'
      });
      var label_select_z_score = domConstruct.create('label', { innerHTML: 'Filter by |Z-score|: ' });
      domConstruct.place(label_select_z_score, otherFilterPanel.containerNode, 'last');
      domConstruct.place(select_z_score.domNode, otherFilterPanel.containerNode, 'last');
      domConstruct.place('
', otherFilterPanel.containerNode, 'last');

      var defaultFilterValue = {
        keyword: '',
        filterGenome: null,
        clusterColumnOrder: [],
        upFold: 0,
        downFold: 0,
        upZscore: 0,
        downZscore: 0
      };

      var btn_submit = new Button({
        label: 'Filter',
        onClick: lang.hitch(this, function () {

          var filter = {};
          filter.filterGenome = select_genome_filter.get('value');
          filter.keyword = ta_keyword.get('value');

          var lr = parseFloat(select_log_ratio.get('value'));
          var zs = parseFloat(select_z_score.get('value'));

          !isNaN(lr) ? (filter.upFold = lr, filter.downFold = -lr) : {};
          !isNaN(zs) ? (filter.upZscore = zs, filter.downZscore = -zs) : {};

          this.tgState = lang.mixin(this.tgState, defaultFilterValue, filter);
          // console.log("filter tgState", this.tgState);

          Topic.publish(this.topicId, 'applyConditionFilter', this.tgState);
        })
      });
      domConstruct.place(btn_submit.domNode, otherFilterPanel.containerNode, 'last');

      filterPanel.addChild(otherFilterPanel);

      return filterPanel;
    },
    updateGenomeFilter: function (data) {
      this.filter_genome.addOption(data);
      // console.log(this.filter_genome, data);
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    queryInterface.createTable('Documents', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      title: {
        type: Sequelize.STRING
      },
      accessType: {
        type: Sequelize.STRING
      },
      content: {
        type: Sequelize.TEXT
      },
      owner: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      userId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        references: {
          model: 'Users',
          key: 'id',
          as: 'userId',
        },
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    queryInterface.dropTable('Documents');
  }
};
<commit_msg>Modify createdAt and updatedAt field type to dateonly<commit_after>'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    queryInterface.createTable('Documents', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      title: {
        type: Sequelize.STRING
      },
      accessType: {
        type: Sequelize.STRING
      },
      content: {
        type: Sequelize.TEXT
      },
      owner: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATEONLY
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATEONLY
      },
      userId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        references: {
          model: 'Users',
          key: 'id',
          as: 'userId',
        },
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    queryInterface.dropTable('Documents');
  }
};
<|endoftext|>


<commit_before>import React, {useContext} from 'react';
import {StyleSheet, Text, Image, Platform, View, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';
import {NavigationBar, useNavigated} from 'navigation-react-native';
import Tweets from './Tweets';

export default ({tweet: {account: {id: accountId, name, username, logo},
  text, time, retweets, likes, replies}}) => {
  const {stateNavigator} = useContext(NavigationContext);
  useNavigated(() => {
    if (Platform.OS === 'web') document.title = 'Tweet';
  });
  return (
    <>
      <NavigationBar
        title="Tweet"
        navigationImage={require('./arrow.png')}
        barTintColor="#fff"
        tintColor={Platform.OS !== 'ios' ? "deepskyblue" : null}
        navigationHref={stateNavigator.historyManager.getHref(
          stateNavigator.getNavigationBackLink(1)
        )}
        onNavigationPress={(e) => {
          if (Platform.OS !== 'web')
            stateNavigator.navigateBack(1);
          else {
            if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return;
            e.preventDefault()
            history.back();
          }
        }} />
      <Tweets
        tweets={replies}
        renderHeader={(
          <View>
            <View style={styles.heading}>
              <TouchableHighlight
                underlayColor="white"
                accessibilityRole="link"
                href={stateNavigator.historyManager.getHref(
                  stateNavigator.getNavigationLink('timeline', {id: accountId})
                )}
                onPress={(e) => {
                  if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return
                  e.preventDefault()
                  stateNavigator.navigate('timeline', {id: accountId});
              }}>
                <Image style={styles.logo} source={logo} />
              </TouchableHighlight>
              <View style={styles.details}>
                <Text style={styles.name}>{name}</Text>
                <Text>{username}</Text>
              </View>
            </View>
            <Text style={styles.text}>{text}</Text>
            <Text style={styles.time}>{time}</Text>
            <View style={styles.interactions}>
              <Text style={styles.count}>{retweets}</Text>
              <Text style={styles.interaction}>RETWEETS</Text>
              <Text style={styles.count}>{likes}</Text>
              <Text style={styles.interaction}>LIKES</Text>
            </View>
          </View>
        )} />
    </>
  );
};

const styles = StyleSheet.create({
  heading: {
    flexDirection: 'row',
    marginTop: 20,
    marginBottom: 10,
  },
  logo: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 12,
  },
  name: {
    fontWeight: 'bold',
    marginTop: 5,
    marginBottom: 2,
  },
  text: {
    fontSize: 18,
  },
  time: {
    color: '#657786',
    paddingTop: 12,
    paddingBottom: 10,
    fontSize: 13,
  },
  interactions: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#ccd6dd',
    paddingTop: 12,
    paddingBottom: 12,
  },
  count: {
    fontWeight: 'bold',
    fontSize: 13,
    marginRight: 5,
  },
  interaction: {
    color: '#657786',
    fontSize: 13,
    marginRight: 10,
  },
});
<commit_msg>Tweaked format<commit_after>import React, {useContext} from 'react';
import {StyleSheet, Text, Image, Platform, View, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';
import {NavigationBar, useNavigated} from 'navigation-react-native';
import Tweets from './Tweets';

export default ({tweet: {account: {id: accountId, name, username, logo},
  text, time, retweets, likes, replies}}) => {
  const {stateNavigator} = useContext(NavigationContext);
  useNavigated(() => {
    if (Platform.OS === 'web') document.title = 'Tweet';
  });
  return (
    <>
      <NavigationBar
        title="Tweet"
        navigationImage={require('./arrow.png')}
        barTintColor="#fff"
        tintColor={Platform.OS !== 'ios' ? "deepskyblue" : null}
        navigationHref={stateNavigator.historyManager.getHref(
          stateNavigator.getNavigationBackLink(1)
        )}
        onNavigationPress={(e) => {
          if (Platform.OS !== 'web')
            stateNavigator.navigateBack(1);
          else {
            if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return;
            e.preventDefault();
            history.back();
          }
        }} />
      <Tweets
        tweets={replies}
        renderHeader={(
          <View>
            <View style={styles.heading}>
              <TouchableHighlight
                underlayColor="white"
                accessibilityRole="link"
                href={stateNavigator.historyManager.getHref(
                  stateNavigator.getNavigationLink('timeline', {id: accountId})
                )}
                onPress={(e) => {
                  if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return;
                  e.preventDefault();
                  stateNavigator.navigate('timeline', {id: accountId});
              }}>
                <Image style={styles.logo} source={logo} />
              </TouchableHighlight>
              <View style={styles.details}>
                <Text style={styles.name}>{name}</Text>
                <Text>{username}</Text>
              </View>
            </View>
            <Text style={styles.text}>{text}</Text>
            <Text style={styles.time}>{time}</Text>
            <View style={styles.interactions}>
              <Text style={styles.count}>{retweets}</Text>
              <Text style={styles.interaction}>RETWEETS</Text>
              <Text style={styles.count}>{likes}</Text>
              <Text style={styles.interaction}>LIKES</Text>
            </View>
          </View>
        )} />
    </>
  );
};

const styles = StyleSheet.create({
  heading: {
    flexDirection: 'row',
    marginTop: 20,
    marginBottom: 10,
  },
  logo: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 12,
  },
  name: {
    fontWeight: 'bold',
    marginTop: 5,
    marginBottom: 2,
  },
  text: {
    fontSize: 18,
  },
  time: {
    color: '#657786',
    paddingTop: 12,
    paddingBottom: 10,
    fontSize: 13,
  },
  interactions: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#ccd6dd',
    paddingTop: 12,
    paddingBottom: 12,
  },
  count: {
    fontWeight: 'bold',
    fontSize: 13,
    marginRight: 5,
  },
  interaction: {
    color: '#657786',
    fontSize: 13,
    marginRight: 10,
  },
});
<|endoftext|>