<commit_before>sirikata.ui(
    "SetMesh",
    function() {

SetMesh = {}; // External interface
var window; // Our UI window

/* toggles the window with the key combo ctrl + j */
var toggleVisible = function() {
    window.toggle();
};
SetMesh.toggleVisible = toggleVisible;

                  $('
' +
          '

' +
          '

' +
          '

' +
          '

' +
          '

' +
          '

' +
          '
<button id="prevButton">Prev</button>' + '<button id="nextButton">Next</button>' + '<input type = "checkbox" id="createNew">Create New Presence?</input>' +
         /* directions on how to use this tool */
          '
Select an object in the world, then click on a mesh thumbnail to set the mesh of selected object - or you may create a new mesh by first clicking the checkbox above.
' + '<input value="Enter Keyword" id="search"></input>' + '<button id="searchButton">search</button>' + '
' +
          '
').appendTo('body');

       window = new sirikata.ui.window(                     // (2)
           "#set-mesh",
           {
               autoOpen: false,
               width: 310,
               height: 360,
               modal: false
           }
        );

        /* Set Mesh Navigation buttons */
        sirikata.ui.button('#nextButton').click(loadNext);
        sirikata.ui.button('#prevButton').click(loadPrev);
        sirikata.ui.button('#searchButton').click(search);

        /* Set Mesh Thumbnail buttons */
        sirikata.ui.button('#img0').click(function() {
            setMesh('#img0', 0);
        });
        sirikata.ui.button('#img1').click(function() {
            setMesh('#img1', 1);
        });
        sirikata.ui.button('#img2').click(function() {
            setMesh('#img2', 2);
        });

        sirikata.ui.button('#img3').click(function() {
            setMesh('#img3', 3);
        });
        sirikata.ui.button('#img4').click(function() {
            setMesh('#img4', 4);
        });
        sirikata.ui.button('#img5').click(function() {
            setMesh('#img5', 5);
        });

        /*************************** variables ********************************/

        var nextStart = '';
        var currentMesh = null;
        var numChoices = 6;
        var searchResult = 0;
        displayArray = [];
        allMeshes = [];

        /* retrieving model information from open3dhub */
        while (true) {
            $.ajax({
                url: 'http://open3dhub.com/api/browse/' + nextStart,
                type: 'GET',
                dataType: 'json',
                async: false,
                success: allMeshesFunc,
                crossDomain: true
            });

            if (nextStart == null) break;
        }

        /* Function: allMeshesFunc
         *************************
         * Callback function for ajax request, pushes each thumbnail, full path, and title into a 2-dimensional array
         */
        function allMeshesFunc(dataGotten, status, xhr) {
            nextStart = dataGotten.next_start;
            for (var s in dataGotten.content_items) {
                if (typeof (dataGotten.content_items[s].metadata.types.original.thumbnail) != 'undefined') {
                    allMeshes.push([dataGotten.content_items[s].metadata.types.original.thumbnail, dataGotten.content_items[s].full_path, dataGotten.content_items[s].metadata.title]);
                }
            }
            loadNext();
        }

        /* Function: setMesh
        ********************
        * if an object in the world is selected, the object takes on the mesh of the thumbnail clicked afterward. if the "create new presence" option is checked,
        * then clicking a thumbnail creates an object with that mesh.
        */
        function setMesh(name, offset) {
            toggleBorder(offset);
            var string = (allMeshes[currentMesh + offset][1]);
            var str1 = string.substring(0, string.length - 2);
            var append = str1.substring(str1.lastIndexOf('/'), str1.length);
            var str2 = string.substring(string.length - 2, string.length);
            string = str1 + '/optimized' + str2 + append;
            string = "meerkat://" + string;

            if ($('#createNew').is(":checked")) {
                sirikata.event("createNewPres", string);
            } else sirikata.event("setmesh", string);

            var msg = "Mesh has been set to " + allMeshes[currentMesh + offset][2];
            $('#meshDescriptionText').text(msg);
        }

        /* Function: toggleBorder
         ************************
         * created a border around a thumbnail mesh, given what the offset of
         * the thumbnail is relative to the first one shown */
        function toggleBorder(offset) {
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                if (i == offset) $(name).attr("border", 5);
                else $(name).attr("border", 0);
            }
        }

        /* Function: toggleBorder
         ************************
         * removes border when another button is clicked
         */
        function removeBorders() {
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("border", 0);
            }
        }

        //Takes a string like this:
        // "d3308661de134382afafce26376c84c9d29a6bd319d9c3f3ac501d17f75f0e60"
        //turns it into this:
        //  http://open3dhub.com/download/d3308661de134382afafce26376c84c9d29a6bd319d9c3f3ac501d17f75f0e60
        function formSource(str) {
            return 'http://open3dhub.com/download/' + str;
        }

        /* Function: loadPrev
        *********************
        * loads the previous page of thumbnails
        */
        function loadPrev() {
            updateDisplayArray(0);
            removeBorders();
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }
        }

        /* Function: loadNext
         ********************
         * loads the next page of thumbnails
         */
        function loadNext() {
            updateDisplayArray(1);
            removeBorders();
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }

        }

        function searchTemp() {
            window.hide();
        }

    /* Function: levenshtein
     ***********************
     * Search function to find minimum edit distance
     * source info below
     */
    function levenshtein (s1, s2) {
    // Calculate Levenshtein distance between two strings
    //
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/levenshtein
    // +            original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +            bugfixed by: Onno Marsman
    // +             revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // + reimplemented by: Alexander M Beedie
    // *                example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
    // *                returns 1: 3
    if (s1 == s2) {
        return 0;
    }

    var s1_len = s1.length;
    var s2_len = s2.length;
    if (s1_len === 0) {
        return s2_len;
    }
    if (s2_len === 0) {
        return s1_len;
    }

    // BEGIN STATIC
    var split = false;
    try {
        split = !('0')[0];
    } catch (e) {
        split = true; // Earlier IE may not support access by string index
    }
    // END STATIC
    if (split) {
        s1 = s1.split('');
        s2 = s2.split('');
    }

    var v0 = new Array(s1_len + 1);
    var v1 = new Array(s1_len + 1);

    var s1_idx = 0,
        s2_idx = 0,
        cost = 0;
    for (s1_idx = 0; s1_idx < s1_len + 1; s1_idx++) {
        v0[s1_idx] = s1_idx;
    }
    var char_s1 = '',
        char_s2 = '';
    for (s2_idx = 1; s2_idx <= s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx = 0; s1_idx < s1_len; s1_idx++) {
            char_s1 = s1[s1_idx];
            cost = (char_s1 == char_s2) ? 0 : 1;
            var m_min = v0[s1_idx + 1] + 1;
            var b = v1[s1_idx] + 1;
            var c = v0[s1_idx] + cost;
            if (b < m_min) {
                m_min = b;
            }
            if (c < m_min) {
                m_min = c;
            }
            v1[s1_idx + 1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
    }
    return v0[s1_len];
    }

        /* Function: search
         ******************
         * finds the best search result and displays it
         */
        function search() {
            var searchVal = ($('#search').val()).toLowerCase();
            var i = 0;
            searchResult = currentMesh;
            var min = searchVal.length;
            for (i = 0; i < allMeshes.length; i++) {
                var editDist = levenshtein(searchVal, allMeshes[i][2], 0);
                if (editDist < min && (searchVal.charAt(0) == (allMeshes[i][2].charAt(0)).toLowerCase())) {
                    min = editDist;
                    searchResult = i;
                }
            }
            $('#meshDescriptionText').text("Search result: " + allMeshes[searchResult][2]);
            updateDisplayArray(2);
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }
            toggleBorder(0);
            $('#search').val('');

        }

        /* Function: updateDisplayArray
         ******************************
         * updates the array of thumbnail indexes to be displayed
         */
        function updateDisplayArray(condition) {
            var max = allMeshes.length;
            if (condition == 1) {
                if (currentMesh == null || currentMesh > (max - (2 * numChoices))) currentMesh = 0;
                else currentMesh += numChoices;
            } else if (condition == 0) {
                if (currentMesh == null || currentMesh < numChoices) currentMesh = max - numChoices;
                else currentMesh -= numChoices;
            } else if (condition == 2) currentMesh = searchResult;
            var count = 0;
            for (var i = currentMesh; i < currentMesh + numChoices; i++) {
               displayArray[count] = i;
               count++;
            }
        }

    }

);<commit_msg>Make setMesh UI more robust to errors from the CDN.<commit_after>sirikata.ui(
    "SetMesh",
    function() {

SetMesh = {}; // External interface
var window; // Our UI window

/* toggles the window with the key combo ctrl + j */
var toggleVisible = function() {
    window.toggle();
};
SetMesh.toggleVisible = toggleVisible;

                  $('
' +
          '

' +
          '

' +
          '

' +
          '

' +
          '

' +
          '

' +
          '
<button id="prevButton">Prev</button>' + '<button id="nextButton">Next</button>' + '<input type = "checkbox" id="createNew">Create New Presence?</input>' +
         /* directions on how to use this tool */
          '
Select an object in the world, then click on a mesh thumbnail to set the mesh of selected object - or you may create a new mesh by first clicking the checkbox above.
' + '<input value="Enter Keyword" id="search"></input>' + '<button id="searchButton">search</button>' + '
' +
          '
').appendTo('body');

       window = new sirikata.ui.window(                     // (2)
           "#set-mesh",
           {
               autoOpen: false,
               width: 310,
               height: 360,
               modal: false
           }
        );

        /* Set Mesh Navigation buttons */
        sirikata.ui.button('#nextButton').click(loadNext);
        sirikata.ui.button('#prevButton').click(loadPrev);
        sirikata.ui.button('#searchButton').click(search);

        /* Set Mesh Thumbnail buttons */
        sirikata.ui.button('#img0').click(function() {
            setMesh('#img0', 0);
        });
        sirikata.ui.button('#img1').click(function() {
            setMesh('#img1', 1);
        });
        sirikata.ui.button('#img2').click(function() {
            setMesh('#img2', 2);
        });

        sirikata.ui.button('#img3').click(function() {
            setMesh('#img3', 3);
        });
        sirikata.ui.button('#img4').click(function() {
            setMesh('#img4', 4);
        });
        sirikata.ui.button('#img5').click(function() {
            setMesh('#img5', 5);
        });

        /*************************** variables ********************************/

        var nextStart = '';
        var currentMesh = null;
        var numChoices = 6;
        var searchResult = 0;
        displayArray = [];
        allMeshes = [];

        /* retrieving model information from open3dhub */
        while (true) {
            $.ajax({
                url: 'http://open3dhub.com/api/browse/' + nextStart,
                type: 'GET',
                dataType: 'json',
                async: false,
                success: allMeshesFunc,
                crossDomain: true
            });

            if (nextStart == null) break;
        }

        /* Function: allMeshesFunc
         *************************
         * Callback function for ajax request, pushes each thumbnail, full path, and title into a 2-dimensional array
         */
        function allMeshesFunc(dataGotten, status, xhr) {
            if (!dataGotten) {
                nextStart = null;
                return;
            }
            nextStart = dataGotten.next_start;
            for (var s in dataGotten.content_items) {
                if (typeof (dataGotten.content_items[s].metadata.types.original.thumbnail) != 'undefined') {
                    allMeshes.push([dataGotten.content_items[s].metadata.types.original.thumbnail, dataGotten.content_items[s].full_path, dataGotten.content_items[s].metadata.title]);
                }
            }
            loadNext();
        }

        /* Function: setMesh
        ********************
        * if an object in the world is selected, the object takes on the mesh of the thumbnail clicked afterward. if the "create new presence" option is checked,
        * then clicking a thumbnail creates an object with that mesh.
        */
        function setMesh(name, offset) {
            toggleBorder(offset);
            var string = (allMeshes[currentMesh + offset][1]);
            var str1 = string.substring(0, string.length - 2);
            var append = str1.substring(str1.lastIndexOf('/'), str1.length);
            var str2 = string.substring(string.length - 2, string.length);
            string = str1 + '/optimized' + str2 + append;
            string = "meerkat://" + string;

            if ($('#createNew').is(":checked")) {
                sirikata.event("createNewPres", string);
            } else sirikata.event("setmesh", string);

            var msg = "Mesh has been set to " + allMeshes[currentMesh + offset][2];
            $('#meshDescriptionText').text(msg);
        }

        /* Function: toggleBorder
         ************************
         * created a border around a thumbnail mesh, given what the offset of
         * the thumbnail is relative to the first one shown */
        function toggleBorder(offset) {
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                if (i == offset) $(name).attr("border", 5);
                else $(name).attr("border", 0);
            }
        }

        /* Function: toggleBorder
         ************************
         * removes border when another button is clicked
         */
        function removeBorders() {
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("border", 0);
            }
        }

        //Takes a string like this:
        // "d3308661de134382afafce26376c84c9d29a6bd319d9c3f3ac501d17f75f0e60"
        //turns it into this:
        //  http://open3dhub.com/download/d3308661de134382afafce26376c84c9d29a6bd319d9c3f3ac501d17f75f0e60
        function formSource(str) {
            return 'http://open3dhub.com/download/' + str;
        }

        /* Function: loadPrev
        *********************
        * loads the previous page of thumbnails
        */
        function loadPrev() {
            updateDisplayArray(0);
            removeBorders();
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }
        }

        /* Function: loadNext
         ********************
         * loads the next page of thumbnails
         */
        function loadNext() {
            updateDisplayArray(1);
            removeBorders();
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }

        }

        function searchTemp() {
            window.hide();
        }

    /* Function: levenshtein
     ***********************
     * Search function to find minimum edit distance
     * source info below
     */
    function levenshtein (s1, s2) {
    // Calculate Levenshtein distance between two strings
    //
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/levenshtein
    // +            original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +            bugfixed by: Onno Marsman
    // +             revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // + reimplemented by: Alexander M Beedie
    // *                example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
    // *                returns 1: 3
    if (s1 == s2) {
        return 0;
    }

    var s1_len = s1.length;
    var s2_len = s2.length;
    if (s1_len === 0) {
        return s2_len;
    }
    if (s2_len === 0) {
        return s1_len;
    }

    // BEGIN STATIC
    var split = false;
    try {
        split = !('0')[0];
    } catch (e) {
        split = true; // Earlier IE may not support access by string index
    }
    // END STATIC
    if (split) {
        s1 = s1.split('');
        s2 = s2.split('');
    }

    var v0 = new Array(s1_len + 1);
    var v1 = new Array(s1_len + 1);

    var s1_idx = 0,
        s2_idx = 0,
        cost = 0;
    for (s1_idx = 0; s1_idx < s1_len + 1; s1_idx++) {
        v0[s1_idx] = s1_idx;
    }
    var char_s1 = '',
        char_s2 = '';
    for (s2_idx = 1; s2_idx <= s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx = 0; s1_idx < s1_len; s1_idx++) {
            char_s1 = s1[s1_idx];
            cost = (char_s1 == char_s2) ? 0 : 1;
            var m_min = v0[s1_idx + 1] + 1;
            var b = v1[s1_idx] + 1;
            var c = v0[s1_idx] + cost;
            if (b < m_min) {
                m_min = b;
            }
            if (c < m_min) {
                m_min = c;
            }
            v1[s1_idx + 1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
    }
    return v0[s1_len];
    }

        /* Function: search
         ******************
         * finds the best search result and displays it
         */
        function search() {
            var searchVal = ($('#search').val()).toLowerCase();
            var i = 0;
            searchResult = currentMesh;
            var min = searchVal.length;
            for (i = 0; i < allMeshes.length; i++) {
                var editDist = levenshtein(searchVal, allMeshes[i][2], 0);
                if (editDist < min && (searchVal.charAt(0) == (allMeshes[i][2].charAt(0)).toLowerCase())) {
                    min = editDist;
                    searchResult = i;
                }
            }
            $('#meshDescriptionText').text("Search result: " + allMeshes[searchResult][2]);
            updateDisplayArray(2);
            var prefix = "#img";
            for (var i = 0; i < numChoices; i++) {
                var name = prefix + i;
                $(name).attr("src", formSource(allMeshes[(displayArray[i])][0]));
            }
            toggleBorder(0);
            $('#search').val('');

        }

        /* Function: updateDisplayArray
         ******************************
         * updates the array of thumbnail indexes to be displayed
         */
        function updateDisplayArray(condition) {
            var max = allMeshes.length;
            if (condition == 1) {
                if (currentMesh == null || currentMesh > (max - (2 * numChoices))) currentMesh = 0;
                else currentMesh += numChoices;
            } else if (condition == 0) {
                if (currentMesh == null || currentMesh < numChoices) currentMesh = max - numChoices;
                else currentMesh -= numChoices;
            } else if (condition == 2) currentMesh = searchResult;
            var count = 0;
            for (var i = currentMesh; i < currentMesh + numChoices; i++) {
               displayArray[count] = i;
               count++;
            }
        }

    }

);<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

/* global WebAudioExtended, webkitRTCPeerConnection */

var audioElement = document.querySelector('audio');
var statusDiv = document.querySelector('div#status');

var startButton = document.querySelector('button#start');
var stopButton = document.querySelector('button#stop');
startButton.onclick = start;
stopButton.onclick = stop;

var renderLocallyCheckbox = document.querySelector('input#renderLocally');
renderLocallyCheckbox.onclick = toggleRenderLocally;

document.addEventListener('keydown', handleKeyDown, false);

var localStream;
var pc1;
var pc2;

var webAudio = new WebAudioExtended();
webAudio.loadSound('audio/Shamisen-C4.wav');

function trace(txt) {
  statusDiv.innerHTML += '
' + txt + '
';
}

function start() {
  webAudio.start();
  var constraints = {
    audio: true,
    video: false
  };
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(gotStreamFailed);
  startButton.disabled = true;
  stopButton.disabled = false;
}

function stop() {
  webAudio.stop();
  pc1.close();
  pc2.close();
  pc1 = null;
  pc2 = null;
  startButton.enabled = true;
  stopButton.enabled = false;
  renderLocallyCheckbox.disabled = true;
  localStream.stop();
}

function gotStream(stream) {
  renderLocallyCheckbox.disabled = false;
  var audioTracks = stream.getAudioTracks();
  if (audioTracks.length === 1) {
    console.log('gotStream({audio:true, video:false})');

    var filteredStream = webAudio.applyFilter(stream);

    var servers = null;
    pc1 = new webkitRTCPeerConnection(servers); // eslint-disable-line new-cap
    console.log('Created local peer connection object pc1');
    pc1.onicecandidate = iceCallback1;
    pc2 = new webkitRTCPeerConnection(servers); // eslint-disable-line new-cap
    console.log('Created remote peer connection object pc2');
    pc2.onicecandidate = iceCallback2;
    pc2.onaddstream = gotRemoteStream;

    pc1.addStream(filteredStream);
    pc1.createOffer(gotDescription1);

    stream.onended = function() {
      console.log('stream.onended');
      startButton.disabled = false;
      stopButton.disabled = true;
    };

    localStream = stream;
  } else {
    alert('The media stream contains an invalid amount of audio tracks.');
    stream.stop();
  }
}

function gotStreamFailed(error) {
  startButton.disabled = false;
  stopButton.disabled = true;
  alert('Failed to get access to local media. Error code: ' +
    error.code);
}

function forceOpus(sdp) {
  // Remove all other codecs (not the video codecs though).
  sdp = sdp.replace(/m=audio (\d+) RTP\/SAVPF.*\r\n/g,
      'm=audio $1 RTP/SAVPF 111\r\n');
  sdp = sdp.replace(/a=rtpmap:(?!111)\d{1,3} (?!VP8|red|ulpfec).*\r\n/g, '');
  return sdp;
}

function gotDescription1(desc) {
  console.log('Offer from pc1 \n' + desc.sdp);
  var modifiedOffer = new RTCSessionDescription({
    type: 'offer',
    sdp: forceOpus(desc.sdp)
  });
  pc1.setLocalDescription(modifiedOffer);
  console.log('Offer from pc1 \n' + modifiedOffer.sdp);
  pc2.setRemoteDescription(modifiedOffer);
  pc2.createAnswer(gotDescription2);
}

function gotDescription2(desc) {
  pc2.setLocalDescription(desc);
  console.log('Answer from pc2 \n' + desc.sdp);
  pc1.setRemoteDescription(desc);
}

function gotRemoteStream(e) {
  audioElement.srcObject = e.stream;
}

function iceCallback1(event) {
  if (event.candidate) {
    pc2.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    console.log('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    pc1.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    console.log('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function handleKeyDown() {
  webAudio.addEffect();
}

function toggleRenderLocally() {
  console.log('Render locally: ', renderLocallyCheckbox.checked);
  webAudio.renderLocally(renderLocallyCheckbox.checked);
}
<commit_msg>replace mediastream.stop with gettracks/track.stop<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

/* global WebAudioExtended, webkitRTCPeerConnection */

var audioElement = document.querySelector('audio');
var statusDiv = document.querySelector('div#status');

var startButton = document.querySelector('button#start');
var stopButton = document.querySelector('button#stop');
startButton.onclick = start;
stopButton.onclick = stop;

var renderLocallyCheckbox = document.querySelector('input#renderLocally');
renderLocallyCheckbox.onclick = toggleRenderLocally;

document.addEventListener('keydown', handleKeyDown, false);

var localStream;
var pc1;
var pc2;

var webAudio = new WebAudioExtended();
webAudio.loadSound('audio/Shamisen-C4.wav');

function trace(txt) {
  statusDiv.innerHTML += '
' + txt + '
';
}

function start() {
  webAudio.start();
  var constraints = {
    audio: true,
    video: false
  };
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(gotStreamFailed);
  startButton.disabled = true;
  stopButton.disabled = false;
}

function stop() {
  webAudio.stop();
  pc1.close();
  pc2.close();
  pc1 = null;
  pc2 = null;
  startButton.enabled = true;
  stopButton.enabled = false;
  renderLocallyCheckbox.disabled = true;
  localStream.getTracks().forEach(function(track) {
    track.stop();
  });
}

function gotStream(stream) {
  renderLocallyCheckbox.disabled = false;
  var audioTracks = stream.getAudioTracks();
  if (audioTracks.length === 1) {
    console.log('gotStream({audio:true, video:false})');

    var filteredStream = webAudio.applyFilter(stream);

    var servers = null;
    pc1 = new webkitRTCPeerConnection(servers); // eslint-disable-line new-cap
    console.log('Created local peer connection object pc1');
    pc1.onicecandidate = iceCallback1;
    pc2 = new webkitRTCPeerConnection(servers); // eslint-disable-line new-cap
    console.log('Created remote peer connection object pc2');
    pc2.onicecandidate = iceCallback2;
    pc2.onaddstream = gotRemoteStream;

    pc1.addStream(filteredStream);
    pc1.createOffer(gotDescription1);

    stream.onended = function() {
      console.log('stream.onended');
      startButton.disabled = false;
      stopButton.disabled = true;
    };

    localStream = stream;
  } else {
    alert('The media stream contains an invalid amount of audio tracks.');
    stream.stop();
  }
}

function gotStreamFailed(error) {
  startButton.disabled = false;
  stopButton.disabled = true;
  alert('Failed to get access to local media. Error code: ' +
    error.code);
}

function forceOpus(sdp) {
  // Remove all other codecs (not the video codecs though).
  sdp = sdp.replace(/m=audio (\d+) RTP\/SAVPF.*\r\n/g,
      'm=audio $1 RTP/SAVPF 111\r\n');
  sdp = sdp.replace(/a=rtpmap:(?!111)\d{1,3} (?!VP8|red|ulpfec).*\r\n/g, '');
  return sdp;
}

function gotDescription1(desc) {
  console.log('Offer from pc1 \n' + desc.sdp);
  var modifiedOffer = new RTCSessionDescription({
    type: 'offer',
    sdp: forceOpus(desc.sdp)
  });
  pc1.setLocalDescription(modifiedOffer);
  console.log('Offer from pc1 \n' + modifiedOffer.sdp);
  pc2.setRemoteDescription(modifiedOffer);
  pc2.createAnswer(gotDescription2);
}

function gotDescription2(desc) {
  pc2.setLocalDescription(desc);
  console.log('Answer from pc2 \n' + desc.sdp);
  pc1.setRemoteDescription(desc);
}

function gotRemoteStream(e) {
  audioElement.srcObject = e.stream;
}

function iceCallback1(event) {
  if (event.candidate) {
    pc2.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    console.log('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    pc1.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    console.log('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function handleKeyDown() {
  webAudio.addEffect();
}

function toggleRenderLocally() {
  console.log('Render locally: ', renderLocallyCheckbox.checked);
  webAudio.renderLocally(renderLocallyCheckbox.checked);
}
<|endoftext|>


<commit_before>// Load JS Library in JS
function getScript(url,success) {
  var script=document.createElement('script');
  script.src=url;
  var head=document.getElementsByTagName('head')[0],
  done=false;script.onload=script.onreadystatechange=function(){
    if(!done&&(!this.readyState||this.readyState=='loaded'||this.readyState=='complete')){
    done=true;success();script.onload=script.onreadystatechange=null;head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// Load Latest, Compressed jQuery
getScript('http://code.jquery.com/jquery-latest.min.js',function(){
  return win();
});

// Rek Scrubz
function win() {
  console.log($('div.nonHideableWords').text());
  chars = text.length;
  arrText = text.split(' ');
  arrLength = arrText.length;
  timeRemaining = (((chars/5)*60)/190)*1000;
  delay = timeRemaining/arrLength;
  for (var i = 0; i < arrLength; i++) {
    sleep(delay);
    $('.txtInput').val(arrText[i]).trigger({type : 'keypress', which : 32});
  }
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
<commit_msg>text =<commit_after>// Load JS Library in JS
function getScript(url,success) {
  var script=document.createElement('script');
  script.src=url;
  var head=document.getElementsByTagName('head')[0],
  done=false;script.onload=script.onreadystatechange=function(){
    if(!done&&(!this.readyState||this.readyState=='loaded'||this.readyState=='complete')){
    done=true;success();script.onload=script.onreadystatechange=null;head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// Load Latest, Compressed jQuery
getScript('http://code.jquery.com/jquery-latest.min.js',function(){
  return win();
});

// Rek Scrubz
function win() {
  text = $('div.nonHideableWords').text();
  chars = text.length;
  arrText = text.split(' ');
  arrLength = arrText.length;
  timeRemaining = (((chars/5)*60)/190)*1000;
  delay = timeRemaining/arrLength;
  for (var i = 0; i < arrLength; i++) {
    setTimeout(function() {
      alert("Hello");
    }, 3000);
    $('.txtInput').val(arrText[i]).trigger({type : 'keypress', which : 32});
  }
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
<|endoftext|>


<commit_before>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,
        INITIALIZED: 6,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            var $form = $(this);
            var $textarea = $form.find('textarea[name=error]');
            var $hidden = $form.find('input:hidden[name=has_errors]');
            $textarea.text("GNOME Shell Extensions cannot automatically detect any errors.").
                addClass('no-errors').attr('disabled', 'disabled');
            $hidden.val('');
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false,
                    'undo-uninstall-message': null});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED ||
                           oldState == ExtensionState.INITIALIZED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.INITIALIZED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                $elem.trigger('out-of-date');
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
                $elem.data('undo-uninstall-message').slideUp();
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            if (extensions && Object.keys(extensions).length) {
                var extensionValues = [];
                for (var uuid in extensions) {
                    extensionValues.push(extensions[uuid]);
                }

                extensionValues.sort(function(a, b) {
                    return a.name.localeCompare(b.name);
                });

                extensionValues.forEach(function(extension) {
                    var uuid = extension.uuid;

                    function reinstall() {
                        dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                        // If the user clicks "Install" we need to show that we
                        // installed it by reattaching the element, but we can't do
                        // that here -- the user might click "Cancel".
                        $elem.data('uninstalled', true);
                    }

                    function uninstall() {
                        dbusProxy.UninstallExtension(uuid).done(function(result) {
                            if (result) {
                                $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                                // Construct a dummy
 node as we need something
                                // to stuff everything else in...
                                var messageHTML = $("
You uninstalled
").
                                    append($('').text(extension.name)).
                                    append(". ").
                                    append($('', {'href': '#'}).text("Undo?")).html();

                                var $message = messages.addInfo(messageHTML);
                                $message.delegate('a', 'click', reinstall);
                                $elem.data('undo-uninstall-message', $message);
                            }
                        });
                    }

                    var $elem = $('
', {'class': 'extension'}).
                        append($('
', {'class': 'switch'})).
                        append($('', {'class': 'icon'})).
                        append($('
', {'class': 'extension-name'}).text(extension.name)).
                        append($('', {'class': 'author'})).
                        append($('
', {'class': 'description'}).text(extension.description));

                    $.ajax({
                        url: "/ajax/detail/",
                        dataType: "json",
                        data: { uuid: uuid },
                        type: "GET",
                    }).done(function(result) {
                        $elem.
                            find('span.author').text(" by ").append($('', {'href': "/accounts/profile/" + result.creator}).text(result.creator)).end().
                            find('img.icon').detach().end().
                            find('h3').html($('', {'href': result.link}).append($('', {'class': 'icon', 'src': result.icon})).append(extension.name)).end().
                            append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                            data('pk', result.pk);
                    });

                    // The DOM element's CSS styles won't be fully
                    // computed, so the switch will be incorrectly
                    // positioned -- wait a bit before adding them.
                    setTimeout(function() {
                        addExtensionSwitch(uuid, extension, $elem);
                    }, 0);

                    $container.append($elem);
                });
            } else {
                $container.append("You don't have any extensions installed.");
            }
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            var errorString;

            if (errors && errors.length) {
                errorString = errors.join('\n\n================\n\n');
            } else {
                errorString = "GNOME Shell Extensions did not detect any errors with this extension.";
            }

            var template = ("What's wrong?\n\n\n" +
                            "What have I tried?\n\n\n" +
                            "Automatically detected errors:\n\n" + errorString);

            $textarea.text(template);
        });
    };

    $.fn.addExtensionsSwitch = function () {
        var $extension = $(this);
        var uuid = $extension.data('uuid');

        $extension.bind('out-of-date', function() {
            messages.addError("This extension is incompatible with your version of GNOME.");
        });

        dbusProxy.GetExtensionInfo(uuid).done(function(meta) {
            addExtensionSwitch(uuid, meta, $(this));
        });
    };

});
<commit_msg>Fix typo<commit_after>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,
        INITIALIZED: 6,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            var $form = $(this);
            var $textarea = $form.find('textarea[name=error]');
            var $hidden = $form.find('input:hidden[name=has_errors]');
            $textarea.text("GNOME Shell Extensions cannot automatically detect any errors.").
                addClass('no-errors').attr('disabled', 'disabled');
            $hidden.val('');
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false,
                    'undo-uninstall-message': null});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED ||
                           oldState == ExtensionState.INITIALIZED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.INITIALIZED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                $elem.trigger('out-of-date');
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
                $elem.data('undo-uninstall-message').slideUp();
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            if (extensions && Object.keys(extensions).length) {
                var extensionValues = [];
                for (var uuid in extensions) {
                    extensionValues.push(extensions[uuid]);
                }

                extensionValues.sort(function(a, b) {
                    return a.name.localeCompare(b.name);
                });

                extensionValues.forEach(function(extension) {
                    var uuid = extension.uuid;

                    function reinstall() {
                        dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                        // If the user clicks "Install" we need to show that we
                        // installed it by reattaching the element, but we can't do
                        // that here -- the user might click "Cancel".
                        $elem.data('uninstalled', true);
                    }

                    function uninstall() {
                        dbusProxy.UninstallExtension(uuid).done(function(result) {
                            if (result) {
                                $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                                // Construct a dummy
 node as we need something
                                // to stuff everything else in...
                                var messageHTML = $("
You uninstalled
").
                                    append($('').text(extension.name)).
                                    append(". ").
                                    append($('', {'href': '#'}).text("Undo?")).html();

                                var $message = messages.addInfo(messageHTML);
                                $message.delegate('a', 'click', reinstall);
                                $elem.data('undo-uninstall-message', $message);
                            }
                        });
                    }

                    var $elem = $('
', {'class': 'extension'}).
                        append($('
', {'class': 'switch'})).
                        append($('', {'class': 'icon'})).
                        append($('
', {'class': 'extension-name'}).text(extension.name)).
                        append($('', {'class': 'author'})).
                        append($('
', {'class': 'description'}).text(extension.description));

                    $.ajax({
                        url: "/ajax/detail/",
                        dataType: "json",
                        data: { uuid: uuid },
                        type: "GET",
                    }).done(function(result) {
                        $elem.
                            find('span.author').text(" by ").append($('', {'href': "/accounts/profile/" + result.creator}).text(result.creator)).end().
                            find('img.icon').detach().end().
                            find('h3').html($('', {'href': result.link}).append($('', {'class': 'icon', 'src': result.icon})).append(extension.name)).end().
                            append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                            data('pk', result.pk);
                    });

                    // The DOM element's CSS styles won't be fully
                    // computed, so the switch will be incorrectly
                    // positioned -- wait a bit before adding them.
                    setTimeout(function() {
                        addExtensionSwitch(uuid, extension, $elem);
                    }, 0);

                    $container.append($elem);
                });
            } else {
                $container.append("You don't have any extensions installed.");
            }
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            var errorString;

            if (errors && errors.length) {
                errorString = errors.join('\n\n================\n\n');
            } else {
                errorString = "GNOME Shell Extensions did not detect any errors with this extension.";
            }

            var template = ("What's wrong?\n\n\n" +
                            "What have I tried?\n\n\n" +
                            "Automatically detected errors:\n\n" + errorString);

            $textarea.text(template);
        });
    };

    $.fn.addExtensionSwitch = function () {
        var $extension = $(this);
        var uuid = $extension.data('uuid');

        $extension.bind('out-of-date', function() {
            messages.addError("This extension is incompatible with your version of GNOME.");
        });

        dbusProxy.GetExtensionInfo(uuid).done(function(meta) {
            addExtensionSwitch(uuid, meta, $(this));
        });
    };

});
<|endoftext|>


<commit_before>define(['/customize/languageSelector.js',
        '/customize/translations/messages.js',
        '/customize/translations/messages.fr.js',
        '/bower_components/jquery/dist/jquery.min.js'], function(LS, Default, French) {
    var $ = window.jQuery;

    var map = {
        'fr': French
    };

    var defaultLanguage = 'en';

    var language = LS.getLanguage();

    var messages;

    if (!language || language === defaultLanguage || language === 'default' || !map[language]) {
        messages = Default;
    }
    else {
        // Add the translated keys to the returned object
        messages = $.extend(true, {}, Default, map[language]);
    }

    // Get keys with parameters
    messages._getKey = function (key, argArray) {
        if (!messages[key]) { return '?'; }
        var text = messages[key];
        return text.replace(/\{(\d+)\}/g, function (str, p1) {
            return argArray[p1] || null;
        });
    };

    messages._applyTranslation = function () {
        $('[data-localization]').each(function (i, e) {
            var $el = $(this);
            var key = $el.data('localization');
            $el.html(messages[key]);
        });
        $('[data-localization-title]').each(function (i, e) {
            var $el = $(this);
            var key = $el.data('localization-title');
            $el.attr('title', messages[key]);
        });
    };

    // Non translatable keys
    messages.initialState = [
        '
',
        'This is CryptPad, the zero knowledge realtime collaborative editor.',
        '
',
        'What you type here is encrypted so only people who have the link can access it.',
        '
',
        'Even the server cannot see what you type.',
        '
',
        '
',
        '',
        'What you see here, what you hear here, when you leave here, let it stay here',
        '',
        '
',
    ].join('');

    messages.codeInitialState = [
        '/*\n',
        '   This is CryptPad, the zero knowledge realtime collaborative editor.\n',
        '   What you type here is encrypted so only people who have the link can access it.\n',
        '   Even the server cannot see what you type.\n',
        '   What you see here, what you hear here, when you leave here, let it stay here.\n',
        '*/'
    ].join('');

    messages.slideInitialState = [
        '# CryptSlide\n',
        '* This is a zero knowledge realtime collaborative editor.\n',
        '* What you type here is encrypted so only people who have the link can access it.\n',
        '* Even the server cannot see what you type.\n',
        '* What you see here, what you hear here, when you leave here, let it stay here.\n',
        '\n',
        '---',
        '\n',
        '# How to use\n',
        '1. Write your slides content using markdown syntax\n',
        '2. Separate your slides with ---\n',
        '3. Click on the "Play" button to see the result'
    ].join('');

    return messages;
});
<commit_msg>add spanish translations to map. export a function which checks completion of translations<commit_after>define(['/customize/languageSelector.js',
        '/customize/translations/messages.js',
        '/customize/translations/messages.es.js',
        '/customize/translations/messages.fr.js',
        '/bower_components/jquery/dist/jquery.min.js'], function(LS, Default, Spanish, French) {
    var $ = window.jQuery;

    var map = {
        'fr': French,
        'es': Spanish,
    };

    var defaultLanguage = 'en';

    var language = LS.getLanguage();

    var messages;

    if (!language || language === defaultLanguage || language === 'default' || !map[language]) {
        messages = Default;
    }
    else {
        // Add the translated keys to the returned object
        messages = $.extend(true, {}, Default, map[language]);
    }

    messages._checkTranslationState = function () {
        var missing = [];
        Object.keys(map).forEach(function (code) {
            var translation = map[code];
            Object.keys(Default).forEach(function (k) {
                if (/^_/.test(k) || /nitialState$/.test(k)) { return; }
                if (!translation[k]) {
                    var warning = "key [" + k + "] is missing from translation [" + code + "]";
                    missing.push(warning);
                    console.log(warning);
                }
            });
        });
        return missing;
    };

    // Get keys with parameters
    messages._getKey = function (key, argArray) {
        if (!messages[key]) { return '?'; }
        var text = messages[key];
        return text.replace(/\{(\d+)\}/g, function (str, p1) {
            return argArray[p1] || null;
        });
    };

    messages._applyTranslation = function () {
        $('[data-localization]').each(function (i, e) {
            var $el = $(this);
            var key = $el.data('localization');
            $el.html(messages[key]);
        });
        $('[data-localization-title]').each(function (i, e) {
            var $el = $(this);
            var key = $el.data('localization-title');
            $el.attr('title', messages[key]);
        });
    };

    // Non translatable keys
    messages.initialState = [
        '
',
        'This is CryptPad, the zero knowledge realtime collaborative editor.',
        '
',
        'What you type here is encrypted so only people who have the link can access it.',
        '
',
        'Even the server cannot see what you type.',
        '
',
        '
',
        '',
        'What you see here, what you hear here, when you leave here, let it stay here',
        '',
        '
',
    ].join('');

    messages.codeInitialState = [
        '/*\n',
        '   This is CryptPad, the zero knowledge realtime collaborative editor.\n',
        '   What you type here is encrypted so only people who have the link can access it.\n',
        '   Even the server cannot see what you type.\n',
        '   What you see here, what you hear here, when you leave here, let it stay here.\n',
        '*/'
    ].join('');

    messages.slideInitialState = [
        '# CryptSlide\n',
        '* This is a zero knowledge realtime collaborative editor.\n',
        '* What you type here is encrypted so only people who have the link can access it.\n',
        '* Even the server cannot see what you type.\n',
        '* What you see here, what you hear here, when you leave here, let it stay here.\n',
        '\n',
        '---',
        '\n',
        '# How to use\n',
        '1. Write your slides content using markdown syntax\n',
        '2. Separate your slides with ---\n',
        '3. Click on the "Play" button to see the result'
    ].join('');

    return messages;
});
<|endoftext|>


<commit_before>var path = require('path');
var url = require('fast-url-parser');
var stacked = require('stacked');

// Middleware
var favicon = require('serve-favicon');
var redirects = require('redirects');
var router = require('static-router');
var cache = require('cache-control');
var cleanUrls = require('clean-urls');
var headers = require('set-headers');
var settle = require('settle');
var notFound = require('not-found');
var slashify = require('slashify');
var services = require('./middleware/services');
var protect = require('./middleware/protect');
var env = require('./middleware/env');

module.exports = function stacker (app, options) {
  options = options || {};

  return function (req, res, next) {

    // TODO: convert configure middleware to just be a method here
    // TODO: only run these middlewares if "req.config" exists

    var pack = stacked();
    var config = req.config || {};
    var settings = app.settings || {};
    var store = app.store || {};
    var cwd = settings.cwd || process.cwd();
    var root = config.root || './';
    var cwdRoot = path.resolve(cwd, root);
    var FAVICON_PATH = __dirname + '/templates/favicon.ico';

    // TODO: need a way to pass in a default error page for things like DIO
    var DEFAULT_ERROR_PAGE = __dirname + '/templates/not_found.html';
    var errorPage = (config.error_page)
      ? path.join(cwd, root, config.error_page)
      : DEFAULT_ERROR_PAGE;

    // // Services
    // pack.use(services({
    //   services: app.services,
    //   prefix: app.servicesRoutePrefix,
    //   config: req.config,
    //   track: app.track && app.track.indexOf('services') > -1 // TODO: test this
    // }));

    // if (config.redirects) pack.use(redirects(req.config.redirects));

    // Remove trailing slahs
    // pack.use(slashify({
    //   root: cwdRoot,
    //   index: config.index
    // }));

    // pack.use(protect(settings));

    // if (config.headers) pack.use(headers(config.headers));

    // if (config.cache_control) pack.use(cache(config.cache_control));

    pack.use(env(settings, app.localEnv));

    // if (config.clean_urls && config.clean_urls !== 'false' /* TODO: test this */) {
    //   pack.use(cleanUrls({
    //     root: path.resolve(cwd, root)
    //   }));
    // }

    // Serve static files
    pack.use(settle({
      root: cwdRoot,
      exists: (config.files) ? settings.isFile.bind(settings) : undefined,
      fullPath: (config.files) ? store.fullPath.bind(store, settings) : undefined,
    }));

    // Custom routes
    // if (config.routes) {
    //   pack.use(router(config.routes, {
    //     root: cwdRoot,
    //     index: config.index,
    //     exists: (settings && settings.isFile) ? settings.isFile.bind(settings) : null // TODO: test this
    //   }));
    // }

    // pack.use(favicon(FAVICON_PATH));

    /////////////////////////////////////////////////////////////

    // TODO: test this
    pack.use(notFound(errorPage));

    // pack.use(middleware.notFound(settings, app.store));
    // TODO: use this logic when passing in not found path

    // var DEFAULT_ERROR_PAGE = path.resolve(__dirname, '../../lib/templates/not_found.html');

    // res.statusCode = 404;
    // res.send(getErrorPage(req.config, settings), true, 404);

    // function getErrorPage (config, settings) {
    //   return (pathExists(config, settings))
    //     ? pathWithRoot(config, settings)
    //     : settings._defaults.error_page || DEFAULT_ERROR_PAGE;
    // }

    // function pathExists (config, settings) {
    //   if (!config || !config.error_page) return false;
    //   if (isUrl(config.error_page)) return true;

    //   // NOTE: If this becomes a bottleneck, convert
    //   // to async version of fs.exists()
    //   return settings.isFile(join(config.root, config.error_page));
    // }

    // function pathWithRoot (config, settings) {
    //   if (isUrl(config.error_page)) return config.error_page;
    //   return store.getPath(settings, join(
    //     '/',
    //     req.config.cwd || '/',
    //     req.config.root ||
    //     '/',
    //     config.error_page
    //   ));
    // }
    // /////////////////////////////////////////////////////////////////////////////

    if (options.testMode) return pack;

    pack(req, res, next);
  };
};<commit_msg>deps: use overrides<commit_after>var path = require('path');
var url = require('fast-url-parser');
var stacked = require('stacked');

// Middleware
var favicon = require('serve-favicon');
var redirects = require('redirects');
var router = require('static-router');
var cache = require('cache-control');
var cleanUrls = require('clean-urls');
var headers = require('set-headers');
var settle = require('settle');
var notFound = require('not-found');
var slashify = require('slashify');
var services = require('./middleware/services');
var protect = require('./middleware/protect');
var env = require('./middleware/env');

module.exports = function stacker (app, options) {
  options = options || {};

  return function (req, res, next) {

    // TODO: convert configure middleware to just be a method here
    // TODO: only run these middlewares if "req.config" exists

    var pack = stacked();
    var config = req.config || {};
    var settings = app.settings || {};
    var store = app.store || {};
    var cwd = settings.cwd || process.cwd();
    var root = config.root || './';
    var cwdRoot = path.resolve(cwd, root);
    var FAVICON_PATH = __dirname + '/templates/favicon.ico';

    // TODO: need a way to pass in a default error page for things like DIO
    var DEFAULT_ERROR_PAGE = __dirname + '/templates/not_found.html';
    var errorPage = (config.error_page)
      ? path.join(cwd, root, config.error_page)
      : DEFAULT_ERROR_PAGE;

    // // Services
    // pack.use(services({
    //   services: app.services,
    //   prefix: app.servicesRoutePrefix,
    //   config: req.config,
    //   track: app.track && app.track.indexOf('services') > -1 // TODO: test this
    // }));

    // if (config.redirects) pack.use(redirects(req.config.redirects));

    // Remove trailing slahs
    // pack.use(slashify({
    //   root: cwdRoot,
    //   index: config.index
    // }));

    // pack.use(protect(settings));

    // if (config.headers) pack.use(headers(config.headers));

    // if (config.cache_control) pack.use(cache(config.cache_control));

    pack.use(env(settings, app.localEnv));

    // if (config.clean_urls && config.clean_urls !== 'false' /* TODO: test this */) {
    //   pack.use(cleanUrls({
    //     root: path.resolve(cwd, root)
    //   }));
    // }

    // Serve static files
    pack.use(settle({
      root: cwdRoot,
      exists: (config.files) ? settings.isFile.bind(settings) : undefined,
      fullPath: (config.files) ? store.fullPath.bind(store, settings) : undefined
    }));

    // Custom routes
    // if (config.routes) {
    //   pack.use(router(config.routes, {
    //     root: cwdRoot,
    //     index: config.index,
    //     exists: (settings && settings.isFile) ? settings.isFile.bind(settings) : null // TODO: test this
    //   }));
    // }

    // pack.use(favicon(FAVICON_PATH));

    /////////////////////////////////////////////////////////////

    // TODO: test this
    pack.use(notFound(errorPage, {
      exists: (config.files) ? settings.isFile.bind(settings) : undefined,
      fullPath: (config.files) ? store.fullPath.bind(store, settings) : undefined
    }));

    // pack.use(middleware.notFound(settings, app.store));
    // TODO: use this logic when passing in not found path

    // var DEFAULT_ERROR_PAGE = path.resolve(__dirname, '../../lib/templates/not_found.html');

    // res.statusCode = 404;
    // res.send(getErrorPage(req.config, settings), true, 404);

    // function getErrorPage (config, settings) {
    //   return (pathExists(config, settings))
    //     ? pathWithRoot(config, settings)
    //     : settings._defaults.error_page || DEFAULT_ERROR_PAGE;
    // }

    // function pathExists (config, settings) {
    //   if (!config || !config.error_page) return false;
    //   if (isUrl(config.error_page)) return true;

    //   // NOTE: If this becomes a bottleneck, convert
    //   // to async version of fs.exists()
    //   return settings.isFile(join(config.root, config.error_page));
    // }

    // function pathWithRoot (config, settings) {
    //   if (isUrl(config.error_page)) return config.error_page;
    //   return store.getPath(settings, join(
    //     '/',
    //     req.config.cwd || '/',
    //     req.config.root ||
    //     '/',
    //     config.error_page
    //   ));
    // }
    // /////////////////////////////////////////////////////////////////////////////

    if (options.testMode) return pack;

    pack(req, res, next);
  };
};<|endoftext|>


<commit_before>;(function ($) {
    if (window.__dal__initListenerIsSet)
        return;

    $(document).on('autocompleteLightInitialize', '[data-autocomplete-light-function=select2]', function() {
        var element = $(this);

        // Templating helper
        function template(text, is_html) {
            if (is_html) {
                var $result = $('<span>');
                $result.html(text);
                return $result;
            } else {
                return text;
            }
        }

        function result_template(item) {
            return template(item.text,
                element.attr('data-html') !== undefined || element.attr('data-result-html') !== undefined
            );
        }

        function selected_template(item) {
            if (item.selected_text !== undefined) {
                return template(item.selected_text,
                    element.attr('data-html') !== undefined || element.attr('data-selected-html') !== undefined
                );
            } else {
                return result_template(item);
            }
            return
        }

        var ajax = null;
        if ($(this).attr('data-autocomplete-light-url')) {
            ajax = {
                url: $(this).attr('data-autocomplete-light-url'),
                dataType: 'json',
                delay: 250,

                data: function (params) {
                    var data = {
                        q: params.term, // search term
                        page: params.page,
                        create: element.attr('data-autocomplete-light-create') && !element.attr('data-tags'),
                        forward: yl.getForwards(element)
                    };

                    return data;
                },
                processResults: function (data, page) {
                    if (element.attr('data-tags')) {
                        $.each(data.results, function(index, value) {
                            value.id = value.text;
                        });
                    }

                    return data;
                },
                cache: true
            };
        }

        $(this).select2({
            tokenSeparators: element.attr('data-tags') ? [','] : null,
            debug: true,
            containerCssClass: ':all:',
            placeholder: element.attr('data-placeholder') || '',
            language: element.attr('data-autocomplete-light-language'),
            minimumInputLength: element.attr('data-minimum-input-length') || 0,
            allowClear: ! $(this).is('[required]'),
            templateResult: result_template,
            templateSelection: selected_template,
            ajax: ajax,
            tags: Boolean(element.attr('data-tags')),
        });

        $(this).on('select2:selecting', function (e) {
            var data = e.params.args.data;

            if (data.create_id !== true)
                return;

            e.preventDefault();

            var select = $(this);

            $.ajax({
                url: $(this).attr('data-autocomplete-light-url'),
                type: 'POST',
                dataType: 'json',
                data: {
                    text: data.id,
                    forward: yl.getForwards($(this))
                },
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
                },
                success: function(data, textStatus, jqXHR ) {
                    select.append(
                        $('<option>', {value: data.id, text: data.text, selected: true})
                    );
                    select.trigger('change');
                    select.select2('close');
                }
            });
        });

    });
    window.__dal__initListenerIsSet = true;
    $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() {
        window.__dal__initialize(this);
    });
})(yl.jQuery);
<commit_msg>Added create class to create option in result template<commit_after>;(function ($) {
    if (window.__dal__initListenerIsSet)
        return;

    $(document).on('autocompleteLightInitialize', '[data-autocomplete-light-function=select2]', function() {
        var element = $(this);

        // Templating helper
        function template(text, is_html) {
            if (is_html) {
                var $result = $('<span>');
                $result.html(text);
                return $result;
            } else {
                return text;
            }
        }

        function result_template(item) {
            var $opt = template(item.text,
                element.attr('data-html') !== undefined || element.attr('data-result-html') !== undefined
            );

            if ($opt.create_id) {
                result.addClass('dal-create');
            }
            return $opt
        }

        function selected_template(item) {
            if (item.selected_text !== undefined) {
                return template(item.selected_text,
                    element.attr('data-html') !== undefined || element.attr('data-selected-html') !== undefined
                );
            } else {
                return result_template(item);
            }
            return
        }

        var ajax = null;
        if ($(this).attr('data-autocomplete-light-url')) {
            ajax = {
                url: $(this).attr('data-autocomplete-light-url'),
                dataType: 'json',
                delay: 250,

                data: function (params) {
                    var data = {
                        q: params.term, // search term
                        page: params.page,
                        create: element.attr('data-autocomplete-light-create') && !element.attr('data-tags'),
                        forward: yl.getForwards(element)
                    };

                    return data;
                },
                processResults: function (data, page) {
                    if (element.attr('data-tags')) {
                        $.each(data.results, function(index, value) {
                            value.id = value.text;
                        });
                    }

                    return data;
                },
                cache: true
            };
        }

        $(this).select2({
            tokenSeparators: element.attr('data-tags') ? [','] : null,
            debug: true,
            containerCssClass: ':all:',
            placeholder: element.attr('data-placeholder') || '',
            language: element.attr('data-autocomplete-light-language'),
            minimumInputLength: element.attr('data-minimum-input-length') || 0,
            allowClear: ! $(this).is('[required]'),
            templateResult: result_template,
            templateSelection: selected_template,
            ajax: ajax,
            tags: Boolean(element.attr('data-tags')),
        });

        $(this).on('select2:selecting', function (e) {
            var data = e.params.args.data;

            if (data.create_id !== true)
                return;

            e.preventDefault();

            var select = $(this);

            $.ajax({
                url: $(this).attr('data-autocomplete-light-url'),
                type: 'POST',
                dataType: 'json',
                data: {
                    text: data.id,
                    forward: yl.getForwards($(this))
                },
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
                },
                success: function(data, textStatus, jqXHR ) {
                    select.append(
                        $('<option>', {value: data.id, text: data.text, selected: true})
                    );
                    select.trigger('change');
                    select.select2('close');
                }
            });
        });

    });
    window.__dal__initListenerIsSet = true;
    $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() {
        window.__dal__initialize(this);
    });
})(yl.jQuery);
<|endoftext|>


<commit_before>let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = function () {
    let rules = [];
    let extractPlugins = [];

    // Babel Compilation.
    rules.push({
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        use: [
            {
                loader: 'babel-loader',
                options: Config.babel()
            }
        ]
    });

    // TypeScript Compilation.
    if (Mix.isUsing('typeScript')) {
        rules.push({
            test: /\.tsx?$/,
            loader: 'ts-loader',
            exclude: /node_modules/,
        });

        extensions.push('.ts', '.tsx');
    }

    // CSS Compilation.
    rules.push({
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
    });

    // Add support for loading HTML files.
    rules.push({
        test: /\.html$/,
        loaders: ['html-loader']
    });

    // Add support for loading images.
    rules.push({
        test: /\.(png|jpe?g|gif)$/,
        loaders: [
            {
                loader: 'file-loader',
                options: {
                    name: path => {
                        if (! /node_modules|bower_components/.test(path)) {
                            return 'images/[name].[ext]?[hash]';
                        }

                        return 'images/vendor/' + path
                            .replace(/\\/g, '/')
                            .replace(
                                /((.*(node_modules|bower_components))|images|image|img|assets)\//g, ''
                            ) + '?[hash]';
                    },
                    publicPath: Config.resourceRoot
                }
            },

            {
                loader: 'img-loader',
                options: Config.imgLoaderOptions
            }
        ]
    });

    // Add support for loading fonts.
    rules.push({
        test: /\.(woff2?|ttf|eot|svg|otf)$/,
        loader: 'file-loader',
        options: {
            name: path => {
                if (! /node_modules|bower_components/.test(path)) {
                    return 'fonts/[name].[ext]?[hash]';
                }

                return 'fonts/vendor/' + path
                    .replace(/\\/g, '/')
                    .replace(
                        /((.*(node_modules|bower_components))|fonts|font|assets)\//g, ''
                    ) + '?[hash]';
            },
            publicPath: Config.resourceRoot
        }
    });

    // Add support for loading cursor files.
    rules.push({
        test: /\.(cur|ani)$/,
        loader: 'file-loader',
        options: {
            name: '[name].[ext]?[hash]',
            publicPath: Config.resourceRoot
        }
    });

    // Here, we'll filter through all CSS preprocessors that the user has requested.
    // For each one, we'll add a new Webpack rule and then prepare the necessary
    // extract plugin to extract the CSS into its file.
    Object.keys(Config.preprocessors).forEach(type => {
        if (type === 'fastSass') return;

        Config.preprocessors[type].forEach(preprocessor => {
            let outputPath = preprocessor.output.filePath.replace(Config.publicPath + path.sep, path.sep);

            tap(new ExtractTextPlugin(outputPath), extractPlugin => {
                let loaders = [
                    {
                        loader: 'css-loader',
                        options: {
                            url: Config.processCssUrls,
                            sourceMap: Mix.isUsing('sourcemaps'),
                            importLoaders: 1
                        }
                    },

                    {
                        loader: 'postcss-loader',
                        options: {
                            sourceMap: Mix.isUsing('sourcemaps'),
                            plugins: [
                                require('autoprefixer')
                            ].concat(Config.postCss)
                        }
                    },
                ];

                if (type === 'sass' && Config.processCssUrls) {
                    loaders.push({
                        loader: 'resolve-url-loader',
                        options: {
                            sourceMap: Mix.isUsing('sourcemaps')
                        }
                    });
                }

                loaders.push({
                    loader: `${type}-loader`,
                    options: Object.assign(
                        preprocessor.pluginOptions,
                        { sourceMap: (type === 'sass' && Config.processCssUrls) ? true : Mix.isUsing('sourcemaps') }
                    )
                });

                rules.push({
                    test: preprocessor.src.path(),
                    use: extractPlugin.extract({ use: loaders })
                });

                extractPlugins.push(extractPlugin);
            });
        });
    });

    // Vue Compilation.
    let vueExtractPlugin;

    if (Config.extractVueStyles) {
        vueExtractPlugin = extractPlugins.length ? extractPlugins[0] : new ExtractTextPlugin('vue-styles.css');
    }

    rules.push({
        test: /\.vue$/,
        loader: 'vue-loader',
        exclude: /(node_modules|bower_components)/,
        options: {
            // extractCSS: Config.extractVueStyles,
            loaders: Config.extractVueStyles ? {
                js: {
                    loader: 'babel-loader',
                    options: Config.babel()
                },

                scss: vueExtractPlugin.extract({
                    use: 'css-loader!sass-loader',
                    fallback: 'vue-style-loader'
                }),

                sass: vueExtractPlugin.extract({
                    use: 'css-loader!sass-loader?indentedSyntax',
                    fallback: 'vue-style-loader'
                }),

                css: vueExtractPlugin.extract({
                    use: 'css-loader',
                    fallback: 'vue-style-loader'
                }),

                stylus: vueExtractPlugin.extract({
                    use: 'css-loader!stylus-loader?paths[]=node_modules',
                    fallback: 'vue-style-loader'
                }),

                less: vueExtractPlugin.extract({
                    use: 'css-loader!less-loader',
                    fallback: 'vue-style-loader'
                }),
            } : {
                js: {
                    loader: 'babel-loader',
                    options: Config.babel()
                }
            },
            postcss: Config.postCss,
            preLoaders: Config.vue.preLoaders,
            postLoaders: Config.vue.postLoaders
        }
    });

    // If there were no existing extract text plugins to add our
    // Vue styles extraction too, we'll push a new one in.
    if (Config.extractVueStyles && ! extractPlugins.length) {
        extractPlugins.push(vueExtractPlugin);
    }

    return { rules, extractPlugins };
}
<commit_msg>Fix some sourcemap compile issues<commit_after>let webpack = require('webpack');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = function () {
    let rules = [];
    let extractPlugins = [];

    // Babel Compilation.
    rules.push({
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        use: [
            {
                loader: 'babel-loader',
                options: Config.babel()
            }
        ]
    });

    // TypeScript Compilation.
    if (Mix.isUsing('typeScript')) {
        rules.push({
            test: /\.tsx?$/,
            loader: 'ts-loader',
            exclude: /node_modules/,
        });

        extensions.push('.ts', '.tsx');
    }

    // CSS Compilation.
    rules.push({
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
    });

    // Add support for loading HTML files.
    rules.push({
        test: /\.html$/,
        loaders: ['html-loader']
    });

    // Add support for loading images.
    rules.push({
        test: /\.(png|jpe?g|gif)$/,
        loaders: [
            {
                loader: 'file-loader',
                options: {
                    name: path => {
                        if (! /node_modules|bower_components/.test(path)) {
                            return 'images/[name].[ext]?[hash]';
                        }

                        return 'images/vendor/' + path
                            .replace(/\\/g, '/')
                            .replace(
                                /((.*(node_modules|bower_components))|images|image|img|assets)\//g, ''
                            ) + '?[hash]';
                    },
                    publicPath: Config.resourceRoot
                }
            },

            {
                loader: 'img-loader',
                options: Config.imgLoaderOptions
            }
        ]
    });

    // Add support for loading fonts.
    rules.push({
        test: /\.(woff2?|ttf|eot|svg|otf)$/,
        loader: 'file-loader',
        options: {
            name: path => {
                if (! /node_modules|bower_components/.test(path)) {
                    return 'fonts/[name].[ext]?[hash]';
                }

                return 'fonts/vendor/' + path
                    .replace(/\\/g, '/')
                    .replace(
                        /((.*(node_modules|bower_components))|fonts|font|assets)\//g, ''
                    ) + '?[hash]';
            },
            publicPath: Config.resourceRoot
        }
    });

    // Add support for loading cursor files.
    rules.push({
        test: /\.(cur|ani)$/,
        loader: 'file-loader',
        options: {
            name: '[name].[ext]?[hash]',
            publicPath: Config.resourceRoot
        }
    });

    // Here, we'll filter through all CSS preprocessors that the user has requested.
    // For each one, we'll add a new Webpack rule and then prepare the necessary
    // extract plugin to extract the CSS into its file.
    Object.keys(Config.preprocessors).forEach(type => {
        if (type === 'fastSass') return;

        Config.preprocessors[type].forEach(preprocessor => {
            let outputPath = preprocessor.output.filePath.replace(Config.publicPath + path.sep, path.sep);

            tap(new ExtractTextPlugin(outputPath), extractPlugin => {
                let loaders = [
                    {
                        loader: 'css-loader',
                        options: {
                            url: Config.processCssUrls,
                            sourceMap: Mix.isUsing('sourcemaps'),
                            importLoaders: 1
                        }
                    },

                    {
                        loader: 'postcss-loader',
                        options: {
                            sourceMap: (type === 'sass' && Config.processCssUrls) ? true : Mix.isUsing('sourcemaps'),
                            plugins: [
                                require('autoprefixer')
                            ].concat(Config.postCss)
                        }
                    },
                ];

                if (type === 'sass' && Config.processCssUrls) {
                    loaders.push({
                        loader: 'resolve-url-loader',
                        options: {
                            sourceMap: true,
                            root: Mix.paths.root('node_modules')
                        }
                    });
                }

                loaders.push({
                    loader: `${type}-loader`,
                    options: Object.assign(
                        preprocessor.pluginOptions,
                        { sourceMap: (type === 'sass' && Config.processCssUrls) ? true : Mix.isUsing('sourcemaps') }
                    )
                });

                rules.push({
                    test: preprocessor.src.path(),
                    use: extractPlugin.extract({ use: loaders })
                });

                extractPlugins.push(extractPlugin);
            });
        });
    });

    // Vue Compilation.
    let vueExtractPlugin;

    if (Config.extractVueStyles) {
        vueExtractPlugin = extractPlugins.length ? extractPlugins[0] : new ExtractTextPlugin('vue-styles.css');
    }

    rules.push({
        test: /\.vue$/,
        loader: 'vue-loader',
        exclude: /(node_modules|bower_components)/,
        options: {
            // extractCSS: Config.extractVueStyles,
            loaders: Config.extractVueStyles ? {
                js: {
                    loader: 'babel-loader',
                    options: Config.babel()
                },

                scss: vueExtractPlugin.extract({
                    use: 'css-loader!sass-loader',
                    fallback: 'vue-style-loader'
                }),

                sass: vueExtractPlugin.extract({
                    use: 'css-loader!sass-loader?indentedSyntax',
                    fallback: 'vue-style-loader'
                }),

                css: vueExtractPlugin.extract({
                    use: 'css-loader',
                    fallback: 'vue-style-loader'
                }),

                stylus: vueExtractPlugin.extract({
                    use: 'css-loader!stylus-loader?paths[]=node_modules',
                    fallback: 'vue-style-loader'
                }),

                less: vueExtractPlugin.extract({
                    use: 'css-loader!less-loader',
                    fallback: 'vue-style-loader'
                }),
            } : {
                js: {
                    loader: 'babel-loader',
                    options: Config.babel()
                }
            },
            postcss: Config.postCss,
            preLoaders: Config.vue.preLoaders,
            postLoaders: Config.vue.postLoaders
        }
    });

    // If there were no existing extract text plugins to add our
    // Vue styles extraction too, we'll push a new one in.
    if (Config.extractVueStyles && ! extractPlugins.length) {
        extractPlugins.push(vueExtractPlugin);
    }

    return { rules, extractPlugins };
}
<|endoftext|>


<commit_before>import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'

function buildDistFile(filename) {
  return new Promise((resolve, reject) => {
    console.log(`Processing ./${filename}.css...`)

    fs.readFile(`./${filename}.css`, (err, css) => {
      if (err) throw err

      // return postcss([tailwind(), require('autoprefixer')])
      return postcss([tailwind()])
        .process(css, {
          from: `./${filename}.css`,
          to: `./dist/${filename}.css`,
          map: { inline: false },
        })
        .then(result => {
          fs.writeFileSync(`./dist/${filename}.css`, result.css)
          if (result.map) {
            fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
          }
          return result
        })
        .then(result => {
          const minified = new CleanCSS().minify(result.css)
          fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
        })
        .then(resolve)
        .catch(error => {
          console.log(error)
          reject()
        })
    })
  })
}

console.info('Building Tailwind!')

Promise.all([
  buildDistFile('preflight'),
  buildDistFile('components'),
  buildDistFile('utilities'),
  buildDistFile('tailwind'),
]).then(() => {
  console.log('Finished Building Tailwind!')
})
<commit_msg>Re-enable autoprefixer in build<commit_after>import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'

function buildDistFile(filename) {
  return new Promise((resolve, reject) => {
    console.log(`Processing ./${filename}.css...`)

    fs.readFile(`./${filename}.css`, (err, css) => {
      if (err) throw err

      return postcss([tailwind(), require('autoprefixer')])
        .process(css, {
          from: `./${filename}.css`,
          to: `./dist/${filename}.css`,
          map: { inline: false },
        })
        .then(result => {
          fs.writeFileSync(`./dist/${filename}.css`, result.css)
          if (result.map) {
            fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
          }
          return result
        })
        .then(result => {
          const minified = new CleanCSS().minify(result.css)
          fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
        })
        .then(resolve)
        .catch(error => {
          console.log(error)
          reject()
        })
    })
  })
}

console.info('Building Tailwind!')

Promise.all([
  buildDistFile('preflight'),
  buildDistFile('components'),
  buildDistFile('utilities'),
  buildDistFile('tailwind'),
]).then(() => {
  console.log('Finished Building Tailwind!')
})
<|endoftext|>